[
  {
    "path": ".gitignore",
    "content": "# Runtime data\npids\n*.pid\n*.seed\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n\n# Compiled binary addons (http://nodejs.org/api/addons.html)\nbuild/Release\nbuild\n\n# Dependency directory\nnode_modules\nbower_components\n\n# Editors\n.idea\n*.iml\n\n# OS metadata\n.DS_Store\nThumbs.db\n"
  },
  {
    "path": ".npmignore",
    "content": ".idea\nbuild\nexamples\nnode_modules\ntest\n.travis.yml\nkarma.conf.js\nrollup.config.js\ntslint.json\n"
  },
  {
    "path": ".publishrc",
    "content": "{\n  \"validations\": {\n    \"vulnerableDependencies\": true,\n    \"uncommittedChanges\": true,\n    \"untrackedFiles\": true,\n    \"sensitiveData\": true,\n    \"branch\": \"master\",\n    \"gitTag\": true\n  },\n  \"confirm\": true,\n  \"publishTag\": \"latest\",\n  \"prePublishScript\": \"npm run build\"\n}"
  },
  {
    "path": ".travis.yml",
    "content": "language: node_js\n\nnode_js:\n  - \"6.1\"\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2016 Sahat Yalkabov\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "![Project Logo](http://i.imgur.com/yutNy7x.jpg)\n\n# [Satellizer](https://github.com/sahat/satellizer/)\n\n[![Donate](https://img.shields.io/badge/paypal-donate-blue.svg)](https://paypal.me/sahat)\n[![Join the chat at https://gitter.im/sahat/satellizer](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/sahat/satellizer?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n[![Build Status](http://img.shields.io/travis/sahat/satellizer.svg?style=flat)](https://travis-ci.org/sahat/satellizer)\n[![npm version](https://badge.fury.io/js/satellizer.svg)](https://badge.fury.io/js/satellizer)\n[![Book session on Codementor](https://cdn.codementor.io/badges/book_session_github.svg)](https://www.codementor.io/sahatyalkabov?utm_source=github&utm_medium=button&utm_term=sahatyalkabov&utm_campaign=github)\n[![OpenCollective](https://opencollective.com/satellizer/backers/badge.svg)](#backers)\n[![OpenCollective](https://opencollective.com/satellizer/sponsors/badge.svg)](#sponsors)\n\n[**Live Demo**](https://satellizer-sahat.rhcloud.com)\n\n---\n\n**Satellizer** is a simple to use, end-to-end, token-based authentication module\nfor [AngularJS](http://angularjs.org) with built-in support for Google, Facebook,\nLinkedIn, Twitter, Instagram, GitHub, Bitbucket, Yahoo, Twitch, Microsoft (Windows Live) OAuth providers, as well as Email\nand Password sign-in. However, you are not limited to the sign-in options above, in fact\nyou can add any *OAuth 1.0* or *OAuth 2.0* provider by passing provider-specific information\nin the app *config* block.\n\n![Screenshot](https://lh4.googleusercontent.com/-0UUIecT-3N4/U-LQJkd75iI/AAAAAAAAEZY/YN3Oe-eUPGc/w1676-h1158-no/satellizer.png)\n\n## Backers\nSupport us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/satellizer#backer)]\n\n<a href=\"https://opencollective.com/satellizer/backer/0/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/0/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/1/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/1/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/2/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/2/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/3/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/3/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/4/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/4/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/5/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/5/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/6/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/6/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/7/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/7/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/8/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/8/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/9/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/9/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/10/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/10/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/11/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/11/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/12/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/12/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/13/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/13/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/14/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/14/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/15/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/15/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/16/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/16/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/17/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/17/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/18/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/18/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/19/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/19/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/20/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/20/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/21/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/21/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/22/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/22/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/23/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/23/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/24/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/24/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/25/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/25/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/26/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/26/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/27/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/27/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/28/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/28/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/backer/29/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/backer/29/avatar.svg\"></a>\n\n## Sponsors\nBecome a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/satellizer#sponsor)]\n\n<a href=\"https://opencollective.com/satellizer/sponsor/0/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/0/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/1/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/1/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/2/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/2/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/3/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/3/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/4/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/4/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/5/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/5/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/6/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/6/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/7/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/7/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/8/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/8/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/9/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/9/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/10/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/10/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/11/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/11/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/12/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/12/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/13/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/13/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/14/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/14/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/15/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/15/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/16/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/16/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/17/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/17/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/18/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/18/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/19/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/19/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/20/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/20/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/21/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/21/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/22/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/22/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/23/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/23/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/24/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/24/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/25/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/25/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/26/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/26/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/27/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/27/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/28/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/28/avatar.svg\"></a>\n<a href=\"https://opencollective.com/satellizer/sponsor/29/website\" target=\"_blank\"><img src=\"https://opencollective.com/satellizer/sponsor/29/avatar.svg\"></a>\n\n## Table of Contents\n\n- [Installation](#installation)\n - [Requirements for Mobile Apps](#requirements-for-mobile-apps)\n- [Usage](#usage)\n- [Configuration](#configuration)\n- [Browser Support](#browser-support)\n- [Authentication Flow](#authentication-flow)\n - [Login with Email and Password](#-login-with-email-and-password)\n - [Login with OAuth 1.0](#-login-with-oauth-10)\n - [Login with OAuth 2.0](#-login-with-oauth-20)\n - [Logout](#-log-out)\n- [Obtaining OAuth Keys](#obtaining-oauth-keys)\n- [API Reference](#api-reference)\n- [FAQ](#faq)\n- [Community Resources](#community-resources)\n- [Backers](#backers)\n- [Sponsors](#sponsors)\n- [Credits](#credits)\n- [License](#license)\n\n## Installation\n\n#### <img src=\"https://upload.wikimedia.org/wikipedia/commons/e/e2/Google_Chrome_icon_%282011%29.svg\" height=\"22\" align=\"top\"> Browser\n\n```html\n<script src=\"angular.js\"></script>\n<script src=\"satellizer.js\"></script>\n```\n```html\n<!-- Satellizer CDN -->\n<script src=\"https://cdn.jsdelivr.net/satellizer/0.15.5/satellizer.min.js\"></script>\n```\n\n#### <img src=\"https://upload.wikimedia.org/wikipedia/commons/d/db/Npm-logo.svg\" height=\"22\" align=\"top\"> NPM\n\n```\n$ npm install satellizer\n```\n\n#### <img src=\"https://bower.io/img/bower-logo.svg\" height=\"22\" align=\"top\"> Bower\n\n```\n$ bower install satellizer\n```\n\n### Requirements for Mobile Apps\n\nWith any Cordova mobile apps or any framework that uses Cordova, such as [Ionic Framework](http://ionicframework.com/), you will need to add [cordova-plugin-inappbrowser](https://cordova.apache.org/docs/en/3.0.0/cordova/inappbrowser/inappbrowser.html) plugin:\n\n```\n$ cordova plugin add cordova-plugin-inappbrowser\n```\n\nMake sure that **inAppBrowser** is listed in your project:\n\n```\n$ cordova plugins\ncordova-plugin-console 1.0.2 \"Console\"\ncordova-plugin-device 1.1.1 \"Device\"\ncordova-plugin-inappbrowser 1.3.0 \"InAppBrowser\"\ncordova-plugin-splashscreen 3.2.0 \"Splashscreen\"\ncordova-plugin-statusbar 2.1.1 \"StatusBar\"\ncordova-plugin-whitelist 1.2.1 \"Whitelist\"\nionic-plugin-keyboard 1.0.8 \"Keyboard\"\n```\n\n## Usage\n\n**Step 1. App Module**\n```js\nangular.module('MyApp', ['satellizer'])\n  .config(function($authProvider) {\n\n    $authProvider.facebook({\n      clientId: 'Facebook App ID'\n    });\n\n    // Optional: For client-side use (Implicit Grant), set responseType to 'token' (default: 'code')\n    $authProvider.facebook({\n      clientId: 'Facebook App ID',\n      responseType: 'token'\n    });\n\n    $authProvider.google({\n      clientId: 'Google Client ID'\n    });\n\n    $authProvider.github({\n      clientId: 'GitHub Client ID'\n    });\n\n    $authProvider.linkedin({\n      clientId: 'LinkedIn Client ID'\n    });\n\n    $authProvider.instagram({\n      clientId: 'Instagram Client ID'\n    });\n\n    $authProvider.yahoo({\n      clientId: 'Yahoo Client ID / Consumer Key'\n    });\n\n    $authProvider.live({\n      clientId: 'Microsoft Client ID'\n    });\n\n    $authProvider.twitch({\n      clientId: 'Twitch Client ID'\n    });\n\n    $authProvider.bitbucket({\n      clientId: 'Bitbucket Client ID'\n    });\n\n    $authProvider.spotify({\n      clientId: 'Spotify Client ID'\n    });\n\n    // No additional setup required for Twitter\n\n    $authProvider.oauth2({\n      name: 'foursquare',\n      url: '/auth/foursquare',\n      clientId: 'Foursquare Client ID',\n      redirectUri: window.location.origin,\n      authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate',\n    });\n\n  });\n```\n\n**Step 2. Controller**\n```js\nangular.module('MyApp')\n  .controller('LoginCtrl', function($scope, $auth) {\n\n    $scope.authenticate = function(provider) {\n      $auth.authenticate(provider);\n    };\n\n  });\n```\n\n**Step 3. Template**\n```html\n<button ng-click=\"authenticate('facebook')\">Sign in with Facebook</button>\n<button ng-click=\"authenticate('google')\">Sign in with Google</button>\n<button ng-click=\"authenticate('github')\">Sign in with GitHub</button>\n<button ng-click=\"authenticate('linkedin')\">Sign in with LinkedIn</button>\n<button ng-click=\"authenticate('instagram')\">Sign in with Instagram</button>\n<button ng-click=\"authenticate('twitter')\">Sign in with Twitter</button>\n<button ng-click=\"authenticate('foursquare')\">Sign in with Foursquare</button>\n<button ng-click=\"authenticate('yahoo')\">Sign in with Yahoo</button>\n<button ng-click=\"authenticate('live')\">Sign in with Windows Live</button>\n<button ng-click=\"authenticate('twitch')\">Sign in with Twitch</button>\n<button ng-click=\"authenticate('bitbucket')\">Sign in with Bitbucket</button>\n<button ng-click=\"authenticate('spotify')\">Sign in with Spotify</button>\n```\n\n**Note:** For server-side usage please refer to the [**examples**](https://github.com/sahat/satellizer/tree/master/examples/server)\ndirectory.\n\n## Configuration\n\nBelow is a complete listing of all default configuration options.\n\n```js\n$authProvider.httpInterceptor = function() { return true; },\n$authProvider.withCredentials = false;\n$authProvider.tokenRoot = null;\n$authProvider.baseUrl = '/';\n$authProvider.loginUrl = '/auth/login';\n$authProvider.signupUrl = '/auth/signup';\n$authProvider.unlinkUrl = '/auth/unlink/';\n$authProvider.tokenName = 'token';\n$authProvider.tokenPrefix = 'satellizer';\n$authProvider.tokenHeader = 'Authorization';\n$authProvider.tokenType = 'Bearer';\n$authProvider.storageType = 'localStorage';\n\n// Facebook\n$authProvider.facebook({\n  name: 'facebook',\n  url: '/auth/facebook',\n  authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n  redirectUri: window.location.origin + '/',\n  requiredUrlParams: ['display', 'scope'],\n  scope: ['email'],\n  scopeDelimiter: ',',\n  display: 'popup',\n  oauthType: '2.0',\n  popupOptions: { width: 580, height: 400 }\n});\n\n// Google\n$authProvider.google({\n  url: '/auth/google',\n  authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n  redirectUri: window.location.origin,\n  requiredUrlParams: ['scope'],\n  optionalUrlParams: ['display'],\n  scope: ['profile', 'email'],\n  scopePrefix: 'openid',\n  scopeDelimiter: ' ',\n  display: 'popup',\n  oauthType: '2.0',\n  popupOptions: { width: 452, height: 633 }\n});\n\n// GitHub\n$authProvider.github({\n  url: '/auth/github',\n  authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n  redirectUri: window.location.origin,\n  optionalUrlParams: ['scope'],\n  scope: ['user:email'],\n  scopeDelimiter: ' ',\n  oauthType: '2.0',\n  popupOptions: { width: 1020, height: 618 }\n});\n\n// Instagram\n$authProvider.instagram({\n  name: 'instagram',\n  url: '/auth/instagram',\n  authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n  redirectUri: window.location.origin,\n  requiredUrlParams: ['scope'],\n  scope: ['basic'],\n  scopeDelimiter: '+',\n  oauthType: '2.0'\n});\n\n// LinkedIn\n$authProvider.linkedin({\n  url: '/auth/linkedin',\n  authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n  redirectUri: window.location.origin,\n  requiredUrlParams: ['state'],\n  scope: ['r_emailaddress'],\n  scopeDelimiter: ' ',\n  state: 'STATE',\n  oauthType: '2.0',\n  popupOptions: { width: 527, height: 582 }\n});\n\n// Twitter\n$authProvider.twitter({\n  url: '/auth/twitter',\n  authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n  redirectUri: window.location.origin,\n  oauthType: '1.0',\n  popupOptions: { width: 495, height: 645 }\n});\n\n// Twitch\n$authProvider.twitch({\n  url: '/auth/twitch',\n  authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n  redirectUri: window.location.origin,\n  requiredUrlParams: ['scope'],\n  scope: ['user_read'],\n  scopeDelimiter: ' ',\n  display: 'popup',\n  oauthType: '2.0',\n  popupOptions: { width: 500, height: 560 }\n});\n\n// Windows Live\n$authProvider.live({\n  url: '/auth/live',\n  authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n  redirectUri: window.location.origin,\n  requiredUrlParams: ['display', 'scope'],\n  scope: ['wl.emails'],\n  scopeDelimiter: ' ',\n  display: 'popup',\n  oauthType: '2.0',\n  popupOptions: { width: 500, height: 560 }\n});\n\n// Yahoo\n$authProvider.yahoo({\n  url: '/auth/yahoo',\n  authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n  redirectUri: window.location.origin,\n  scope: [],\n  scopeDelimiter: ',',\n  oauthType: '2.0',\n  popupOptions: { width: 559, height: 519 }\n});\n\n// Bitbucket\n$authProvider.bitbucket({\n  url: '/auth/bitbucket',\n  authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n  redirectUri: window.location.origin + '/',\n  optionalUrlParams: ['scope'],\n  scope: ['email'],\n  scopeDelimiter: ' ',\n  oauthType: '2.0',\n  popupOptions: { width: 1020, height: 618 }\n});\n\n// Spotify\n$authProvider.spotify({\n  url: '/auth/spotify',\n  authorizationEndpoint: 'https://accounts.spotify.com/authorize',\n  redirectUri: window.location.origin,\n  optionalUrlParams: ['state'],\n  requiredUrlParams: ['scope'],\n  scope: ['user-read-email'],\n  scopePrefix: '',\n  scopeDelimiter: ',',\n  oauthType: '2.0',\n  popupOptions: { width: 500, height: 530 }\n});\n\n// Generic OAuth 2.0\n$authProvider.oauth2({\n  name: null,\n  url: null,\n  clientId: null,\n  redirectUri: null,\n  authorizationEndpoint: null,\n  defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n  requiredUrlParams: null,\n  optionalUrlParams: null,\n  scope: null,\n  scopePrefix: null,\n  scopeDelimiter: null,\n  state: null,\n  oauthType: null,\n  popupOptions: null,\n  responseType: 'code',\n  responseParams: {\n    code: 'code',\n    clientId: 'clientId',\n    redirectUri: 'redirectUri'\n  }\n});\n\n// Generic OAuth 1.0\n$authProvider.oauth1({\n  name: null,\n  url: null,\n  authorizationEndpoint: null,\n  redirectUri: null,\n  oauthType: null,\n  popupOptions: null\n});\n```\n\n## Browser Support\n\n<table>\n  <tbody>\n    <tr>\n      <td><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/Internet_Explorer_9_icon.svg/2000px-Internet_Explorer_9_icon.svg.png\" height=\"35\"></td>\n      <td><img src=\"http://vignette1.wikia.nocookie.net/unanything/images/f/ff/Microsoft_Edge_logo_svg.png/revision/latest?cb=20150728233335\" height=\"35\"></td>\n      <td><img src=\"http://img4.wikia.nocookie.net/__cb20140907211937/logopedia/images/b/b6/Chrome_new_logo.png\" height=\"35\"></td>\n      <td><img src=\"http://media.idownloadblog.com/wp-content/uploads/2014/06/Safari-logo-OS-X-Yosemite.png\" height=\"35\"></td>\n      <td><img src=\"https://mozorg.cdn.mozilla.net/media/img/styleguide/identity/firefox/guidelines-logo.7ea045a4e288.png\" height=\"35\"></td>\n      <td><img src=\"http://upload.wikimedia.org/wikipedia/commons/d/d4/Opera_browser_logo_2013.png\" height=\"35\"></td>\n    </tr>\n    <tr>\n      <td align=\"center\">9+</td>\n      <td align=\"center\">✓</td>\n      <td align=\"center\">✓</td>\n      <td align=\"center\">✓</td>\n      <td align=\"center\">✓</td>\n      <td align=\"center\">✓</td>\n    </tr>\n  </tbody>\n</table>\n\n## Authentication Flow\n\nSatellizer relies on *token-based authentication* using\n[JSON Web Tokens](https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/)\ninstead of cookies.\n\nAdditionally, **authorization** (obtaining user's information with their permission) and **authentication** (application sign-in) requires sever-side implementation. See provided [examples](https://github.com/sahat/satellizer/tree/master/examples/server) implemented in multiple languages for your convenience. In other words, you cannot just launch your AngularJS application and expect everything to work. The only exception is when you use *OAuth 2.0 Implicit Grant* (client-side) authorization by setting `responseType: 'token'` in provider's [configuration](https://github.com/sahat/satellizer#configuration).\n\n### <img height=\"34\" align=\"top\" src=\"http://tech-lives.com/wp-content/uploads/2012/03/Lock-icon.png\"> Login with Email and Password\n\n1. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Enter your email and password into the login form.\n2. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** On form submit call `$auth.login()` with email and password.\n3. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Send a `POST` request to `/auth/login`.\n4. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Check if email exists, if not - return `401`.\n5. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Check if password is correct, if not - return `401`.\n6. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Create a JSON Web Token and send it back to the client.\n7. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Parse the token and save it to *Local Storage* for subsequent\nuse after page reload.\n\n\n### <img height=\"34\" align=\"top\" src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d2/Oauth_logo.svg/180px-Oauth_logo.svg.png\"> Login with OAuth 1.0\n\n1. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Open an **empty** popup window via `$auth.authenticate('provider name')`.\n2. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Unlike OAuth 2.0, with OAuth 1.0 you cannot go directly to the authorization\nscreen without a valid `request_token`.\n3. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** The OAuth 1.0 flow starts with an empty **POST** request to */auth/provider*.\n4. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Obtain and return `request_token`for the authorization popup.\n5. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Set the URL location of a popup to the `authorizationEndpoint` with a valid `request_token` query parameter, as well as popup options for height and width. This will redirect a user to the authorization screen. After this point, the flow is very similar to OAuth 2.0.\n6. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Sign in with your username and password if necessary, then authorize\nthe application.\n7. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Send a *POST* request back to the */auth/provider* with\n`oauth_token` and `oauth_verifier` query parameters.\n8. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Do an OAuth-signed `POST` request to the */access_token* URL since we now have `oauth_token` and\n`oauth_verifier` parameters.\n10. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Look up the user by their unique *Provider ID*. If user already\nexists, grab the existing user, otherwise create a new user account.\n11. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Create a JSON Web Token and send it back to the client.\n12. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Parse the token and save it to *Local Storage* for subsequent\nuse after page reload.\n\n\n### <img height=\"34\" align=\"top\" src=\"https://getkong.org/assets/images/icons/plugins/oauth2-authentication.png\"> Login with OAuth 2.0\n\n1. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Open a popup window via `$auth.authenticate('provider name')`.\n2. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Sign in with that provider, if necessary, then authorize the application.\n3. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** After successful authorization, the popup is redirected back to\nyour app, e.g. *http://localhost:3000*,  with the `code` (authorization code)\nquery string parameter.\n4. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** The `code` parameter is sent back to the  parent window that opened the popup.\n5. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Parent window closes the popup and sends a **POST**\nrequest to */auth/provider* with`code` parameter.\n6. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** *Authorization code* is exchanged for *access token*.\n7. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** User information is retrived using the *access token* from **Step 6**.\n8. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** Look up the user by their unique *Provider ID*. If user already\nexists, grab the existing user, otherwise create a new user account.\n9. <img height=\"24\" align=\"top\" src=\"http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/256/Places-network-server-database-icon.png\"> **Server:** In both cases of Step 8, create a JSON Web Token and send it back to the client.\n10. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Parse the token and save it to *Local Storage* for subsequent\nuse after page reload.\n\n### <img height=\"34\" align=\"top\" src=\"http://i.imgur.com/S5Ei6Rj.png\"> Log out\n1. <img height=\"24\" align=\"top\" src=\"https://i.ytimg.com/i/bn1OgGei-DV7aSRo_HaAiw/mq1.jpg?v=4f8f2cc9\"> **Client:** Remove token from Local Storage.\n\n**Note:** To learn more about JSON Web Tokens visit <img src=\"http://jwt.io/img/pic_logo.svg\" height=\"22\" align=\"top\"> [JWT.io](http://jwt.io/).\n\n## Obtaining OAuth Keys\n\n<img src=\"https://camo.githubusercontent.com/204e6b07369021b5b9eb7d228d051aca72a457ef/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f7468756d622f322f32662f476f6f676c655f323031355f6c6f676f2e7376672f3130303070782d476f6f676c655f323031355f6c6f676f2e7376672e706e67\" width=\"150\">\n- Visit [Google Developer Console](https://console.developers.google.com/iam-admin/projects)\n- Click **CREATE PROJECT** button\n- Enter *Project Name*, then click **CREATE**\n- Then select *APIs & auth* from the sidebar and click on *Credentials* tab\n- Click **CREATE NEW CLIENT ID** button\n - **Application Type**: Web Application\n - **Authorized Javascript origins**: *http://localhost:3000*\n - **Authorized redirect URI**: *http://localhost:3000*\n\n**Note:** Make sure you have turned on **Contacts API** and **Google+ API** in the *APIs* tab.\n\n<hr>\n\n<img src=\"http://www.doit.ba/img/facebook.jpg\" width=\"150\">\n- Visit [Facebook Developers](https://developers.facebook.com/)\n- Click **Apps > Create a New App** in the navigation bar\n- Enter *Display Name*, then choose a category, then click **Create app**\n- Click on *Settings* on the sidebar, then click **+ Add Platform**\n- Select **Website**\n- Enter *http://localhost:3000* for *Site URL*\n\n<hr>\n\n<img src=\"https://g.twimg.com/Twitter_logo_blue.png\" height=\"70\">\n- Sign in at [https://apps.twitter.com](https://apps.twitter.com/)\n- Click on **Create New App**\n- Enter your *Application Name*, *Description* and *Website*\n- For **Callback URL**: *http://127.0.0.1:3000*\n- Go to **Settings** tab\n- Under *Application Type* select **Read and Write** access\n- Check the box **Allow this application to be used to Sign in with Twitter**\n- Click **Update this Twitter's applications settings**\n\n<hr>\n\n<img src=\"http://blogs.unity3d.com/wp-content/uploads/2013/12/New-Microsoft-Logo.png\" width=\"150\">\n- Visit [Live Connect App Management](http://go.microsoft.com/fwlink/p/?LinkId=193157).\n- Click on **Create application**\n- Enter an *Application name*, then click on **I accept** button\n- Go to **API Settings** tab\n- Enter a *Redirect URL*\n- Click **Save**\n- Go to **App Settings** tab to get *Client ID* and *Client Secret*\n\n> **Note:** Microsoft does not consider `localhost` or `127.0.0.1` to be a valid URL.\nAs a workaround for local development add `127.0.0.1 mylocalwebsite.net` to **/etc/hosts** file\nand specify `mylocalwebsite.net` as your *Redirect URL* in the **API Settings** tab.\n\n<img src=\"https://camo.githubusercontent.com/7318ebef474f99229892e6bf052f0117ca86f0e4/68747470733a2f2f6769746875622e676c6f62616c2e73736c2e666173746c792e6e65742f696d616765732f6d6f64756c65732f6c6f676f735f706167652f4769744875622d4c6f676f2e706e67\" width=\"150\">\n- Visit [https://github.com/settings/profile](https://github.com/settings/profile)\n- Select **Applications** in the left panel\n- Go to **Developer applications** tab, then click on the **Register new application** button\n - **Application name**: Your app name\n - **Homepage URL**: *http://localhost:3000*\n - **Authorization callback URL**: *http://localhost:3000*\n- Click on the **Register application** button\n\n<img\nsrc=\"http://i.imgur.com/qCkAeZl.png\"\nwidth=\"150\" />\n- Visit\n[https://developer.spotify.com](https://developer.spotify.com)\n- Select **My Apps** on the top menu\n- Select **Create an App** on the right side\n - **Application Name**: Your app name\n - **Application Description**: Your app Description\n- Click **Create**\n- Fill out the following:\n - **Redirect URIs**: *http://localhost:3000*\n- Click **Save**\n\n<hr>\n\n## API Reference\n\n- [`$auth.login(user, [options])`](#authloginuser-options)\n- [`$auth.signup(user, [options])`](#authsignupuser-options)\n- [`$auth.authenticate(name, [userData])`](#authauthenticatename-userdata)\n- [`$auth.logout()`](#authlogout)\n- [`$auth.isAuthenticated()`](#authisauthenticated)\n- [`$auth.link(name, [userData])`](#authlinkname-userdata)\n- [`$auth.unlink(name, [options])`](#authunlinkname-options)\n- [`$auth.getToken()`](#authgettoken)\n- [`$auth.getPayload()`](#authgetpayload)\n- [`$auth.setToken(token)`](#authsettokentoken)\n- [`$auth.removeToken()`](#authremovetoken)\n- [`$auth.setStorageType(type)`](#authsetstoragetypetype)\n\n#### `$auth.login(user, [options])`\n\nSign in using Email and Password.\n\n##### Parameters\n\n| Param                    | Type     | Details\n| ------------------------ | -------- | ---------------------------------------------------------------------------------------\n| **user**                 | `Object` | JavaScript object containing user information.\n| **options** *(optional)* | `Object` | HTTP config object. See [`$http(config)`](https://docs.angularjs.org/api/ng/service/$http) docs.\n\n##### Returns\n\n- **response** - The HTTP response object from the server.\n\n##### Usage\n\n```js\nvar user = {\n  email: $scope.email,\n  password: $scope.password\n};\n\n$auth.login(user)\n  .then(function(response) {\n    // Redirect user here after a successful log in.\n  })\n  .catch(function(response) {\n    // Handle errors here, such as displaying a notification\n    // for invalid email and/or password.\n  });\n```\n\n<hr>\n\n#### `$auth.signup(user, [options])`\n\nCreate a new account with Email and Password.\n\n##### Parameters\n\n| Param                    | Type     | Details\n| ------------------------ | -------- | ---------------------------------------------------------------------------------------\n| **user**                 | `Object` | JavaScript object containing user information.\n| **options** *(optional)* | `Object` | HTTP config object. See [`$http(config)`](https://docs.angularjs.org/api/ng/service/$http) docs.\n\n##### Returns\n\n- **response** - The HTTP response object from the server.\n\n##### Usage\n\n```js\nvar user = {\n  firstName: $scope.firstName,\n  lastName: $scope.lastName,\n  email: $scope.email,\n  password: $scope.password\n};\n\n$auth.signup(user)\n  .then(function(response) {\n    // Redirect user here to login page or perhaps some other intermediate page\n    // that requires email address verification before any other part of the site\n    // can be accessed.\n  })\n  .catch(function(response) {\n    // Handle errors here.\n  });\n```\n\n<hr>\n\n#### `$auth.authenticate(name, [userData])`\n\nStarts the OAuth 1.0 or the OAuth 2.0 authorization flow by opening a popup window. If used client side, [`responseType: \"token\"`](#authentication-flow) is required in the provider setup to get the actual access token.\n\n##### Parameters\n\n| Param                     | Type     | Details\n| ------------------------- | -------- | --------------------------------------------------------------------------------\n| **name**                  | `String` | One of the built-in or custom OAuth provider names created via `$authProvider.oauth1()` or `$authProvider.oauth2()`.\n| **userData** *(optional)* | `Object` | If you need to send additional data to the server along with `code`, `clientId` and `redirectUri` (OAuth 2.0) or `oauth_token` and `oauth_verifier` (OAuth 1.0).\n\n##### Returns\n\n- **response** - The HTTP response object from the server.\n\n##### Usage\n\n```js\n$auth.authenticate('google')\n  .then(function(response) {\n    // Signed in with Google.\n  })\n  .catch(function(response) {\n    // Something went wrong.\n  });\n```\n\n<hr>\n\n#### `$auth.logout()`\n\nDeletes a token from Local Storage (or Session Storage).\n\n##### Usage\n\n```js\n$auth.logout();\n```\n\n<hr>\n\n#### `$auth.isAuthenticated()`\n\nChecks authentication status of a user.\n\n| State                                  | True     | False\n| -------------------------------------- | -------- | -------\n| No token in Local Storage              |          | ✓\n| Token present, but not a valid JWT     | ✓        |\n| JWT present without [`exp`]((http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#expDef))              | ✓        |\n| JWT present with [`exp`]((http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#expDef)) and not expired | ✓        |\n| JWT present with [`exp`]((http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#expDef)) and expired     |          | ✓\n\n##### Usage\n\n```js\n// Controller\n$scope.isAuthenticated = function() {\n  return $auth.isAuthenticated();\n};\n```\n\n```html\n<!-- Template -->\n<ul ng-if=\"!isAuthenticated()\">\n  <li><a href=\"/login\">Login</a></li>\n  <li><a href=\"/signup\">Sign up</a></li>\n</ul>\n<ul ng-if=\"isAuthenticated()\">\n  <li><a href=\"/logout\">Logout</a></li>\n</ul>\n```\n\n<hr>\n\n#### `$auth.link(name, [userData])`\n\nAlias for [`$auth.authenticate(name, [userData])`](#authauthenticatename-userdata).\n\n:bulb: **Note:** Account linking (and merging) business logic is handled entirely on the server.\n\n##### Usage\n\n```js\n// Controller\n$scope.link = function(provider) {\n  $auth.link(provider)\n    .then(function(response) {\n      // You have successfully linked an account.\n    })\n    .catch(function(response) {\n      // Handle errors here.\n    });\n};\n```\n\n```html\n<!-- Template -->\n<button ng-click=\"link('facebook')\">\n  Connect Facebook Account\n</button>\n```\n<hr>\n\n#### `$auth.unlink(name, [options])`\n\nUnlinks an OAuth provider.\n\nBy default, sends a POST request to `/auth/unlink` with the `{ provider: name }` data object.\n\n##### Parameters\n\n| Param                     | Type     | Details\n| ------------------------- | -------- | --------------------------------------------------------------------------------\n| **name**                  | `String` | One of the built-in or custom OAuth provider names created via `$authProvider.oauth1()` or `$authProvider.oauth2()`.\n| **options** *(optional)*  | `Object` | HTTP config object. See [`$http(config)`](https://docs.angularjs.org/api/ng/service/$http) docs.\n\n\n##### Returns\n\n- **response** - The HTTP response object from the server.\n\n##### Usage\n\n```js\n$auth.unlink('github')\n  .then(function(response) {\n    // You have unlinked a GitHub account.\n  })\n  .catch(function(response) {\n    // Handle errors here.\n  });\n```\n\n<hr>\n\n#### `$auth.getToken()`\n\nReturns a token from Local Storage (or Session Storage).\n\n```js\n$auth.getToken();\n// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEyMzQ1Njc4OTAsIm5hbWUiOiJKb2huIERvZSJ9.kRkUHzvZMWXjgB4zkO3d6P1imkdp0ogebLuxnTCiYUU\n```\n\n<hr>\n\n#### `$auth.getPayload()`\n\nReturns a JWT Claims Set, i.e. the middle part of a JSON Web Token.\n\n##### Usage\n\n```js\n$auth.getPayload();\n// { exp: 1414978281, iat: 1413765081, userId: \"544457a3eb129ee822a38fdd\" }\n```\n\n<hr>\n\n#### `$auth.setToken(token)`\n\nSaves a JWT or an access token to Local Storage / Session Storage.\n\n##### Parameters\n\n| Param                    | Type     | Details\n| ------------------------ | -------- | ---------------------------------------------------------------------------------------\n| **token**                | `Object` | An object that takes a JWT (`response.data[config.tokenName]`) or an access token (`response.access_token`).\n\n<hr>\n\n#### `$auth.removeToken()`\n\nRemoves a token from Local Storage / Session Storage. Used internally by [`$auth.logout()`](#authlogout).\n\n##### Usage\n\n```js\n$auth.removeToken();\n```\n\n<hr>\n\n#### `$auth.setStorageType(type)`\n\nSets storage type to Local Storage or Session Storage.\n\n##### Parameters\n\n| Param                    | Type     | Details\n| ------------------------ | -------- | -------------------------------------------------------\n| **type**                 | `String` | Accepts `'localStorage'` and `'sessionStorage'` values.\n\n##### Usage\n\n```js\n$auth.setStorageType('sessionStorage');\n```\n\n## FAQ\n\n#### :question: How do I set `offline_access`?\n\n```js\n$authProvider.google({\n  optionalUrlParams: ['access_type'],\n  accessType: 'offline'\n});\n```\n\n#### :question: Can I change `redirectUri` to something other than base URL?\n\nBy default, `redirectUri` is set to `window.location.origin` (protocol, hostname, port number of a URL) for all OAuth providers. This `redirectUri` must match *exactly* the URL¹ specified in your OAuth app settings.\n\n**Facebook (example)**\n![](http://i.imgur.com/eaykgcZ.png)\n\n\nHowever, you can set `redirectUri` to any URL *path* you desire. For instance, you may follow the naming convention of [Passport.js](http://passportjs.org/):\n```js\n// Note: Must be absolute path.\nwindow.location.origin + '/auth/facebook/facebook/callback'\nwindow.location.origin + '/auth/facebook/google/callback'\n...\n```\n\nUsing the example above, a popup window will be redirected to `http://localhost:3000/auth/facebook/callback?code=YOUR_AUTHORIZATION_CODE` after a successful Facebook authorization. To avoid potential 404 errors, create server routes for each `redirectUri` URL that return **200 OK**. Or alternatively, you may render a custom template with a loading spinner. For the moment, a popup will not stay long enough to see that custom template, due to 20ms interval polling, but in the future I may add support for overriding this polling interval value.\n\nAs far as Satellizer is concerned, it does not matter what is the value of `redirectUri` as long as it matches URL in your OAuth app settings. Satellizer's primary concern is to read URL query/hash parameters, then close a popup.\n\n¹ **Note:** Depending on the OAuth provider, it may be called *Site URL*, *Callback URL*, *Redirect URL*, and so on.\n\n#### :question: How can I send a token in a format other than `Authorization: Bearer <token>`?\nIf you are unable to send a token to your server in the following format - `Authorization: Bearer <token>`, then use\n**`$authProvider.tokenHeader`** and **`$authProvider.tokenType`** config options to change the header format. The default values are `Authorization` and `Bearer`, respectively.\n\nFor example, if you need to use `Authorization: Basic` header, this is where you change it.\n\n#### :question: How can I avoid sending Authorization header on all HTTP requests?\nBy default, once user is authenticated, JWT will be sent on every request. If you would like to prevent that, you could use `skipAuthorization` option in your `$http` request. For example:\n\n```js\n$http({\n  method: 'GET',\n  url: '/api/endpoint',\n  skipAuthorization: true  // `Authorization: Bearer <token>` will not be sent on this request.\n});\n```\n\n#### :question: Is there a way to dynamically change `localStorage` to `sessionStorage`?\nYes, you can toggle between [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionstorage) via the following Satellizer methods:\n- `$auth.setStorageType('sessionStorage');`\n- `$auth.setStorageType('localStorage');`\n\n#### :question: I am having a problem with Ionic authentication on iOS 9.\nFirst, check what kind of error you are getting by opening the Web Inspector from **Develop > Simulator > index.html** menu.\nIf you have configured everything correctly, chances are you running into the following error:\n\n> Failed to load resource: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.\n\nFollow instructions on this [StackOverflow post](http://stackoverflow.com/questions/32631184/the-resource-could-not-be-loaded-because-the-app-transport-security-policy-requi) by adding `NSAppTransportSecurity` to *info.plist*. That should fix the problem.\n\n## Community Resources\n\n### Tutorials\n- Ionic JWT auth with Facebook using Node.js ([Part 1](http://blog.grossman.io/ionic-jwt-auth-with-facebook-using-nodejs-part-1/) and [Part 2](http://blog.grossman.io/ionic-jwt-auth-with-facebook-using-nodejs-part-2-2/))\n- [Build an Instagram clone with AngularJS, Satellizer, Node.js and MongoDB](https://hackhands.com/building-instagram-clone-angularjs-satellizer-nodejs-mongodb/)\n\n\n## Credits\n\n| Contribution               | User\n| -------------------------- | --------------------------------------\n| Dropwizard (Java) Example  | [Alice Chen](https://github.com/chena)\n| Go Example                 | [Salim Alami](https://github.com/celrenheit)\n| Ruby on Rails Example      | [Simonas Gildutis](https://github.com/simonasdev)\n| Ionic Framework Example    | [Dimitris Bozelos](https://github.com/krystalcode)\n\nAdditionally, I would like to thank all other contributors who have reported\nbugs, submitted pull requests and suggested new features!\n\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2016 Sahat Yalkabov\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n"
  },
  {
    "path": "bower.json",
    "content": "{\n  \"name\": \"satellizer\",\n  \"main\": \"dist/satellizer.js\",\n  \"homepage\": \"https://github.com/sahat/satellizer\",\n  \"ignore\": [\n    \"examples\",\n    \"src\",\n    \"test\",\n    \"typings\",\n    \".gitignore\",\n    \".npmignore\",\n    \"karma.conf.js\",\n    \"rollup.config.js\",\n    \"tsconfig.json\",\n    \"tslint.json\",\n    \"typings.json\"\n  ],\n  \"dependencies\": {\n    \"angular\": \"1.3.0 - 1.5.x\"\n  }\n}\n"
  },
  {
    "path": "dist/satellizer.js",
    "content": "/**\n * Satellizer 0.15.5\n * (c) 2016 Sahat Yalkabov \n * License: MIT \n */\n\n(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n    typeof define === 'function' && define.amd ? define(factory) :\n    (global.satellizer = factory());\n}(this, function () { 'use strict';\n\n    var Config = (function () {\n        function Config() {\n            this.baseUrl = '/';\n            this.loginUrl = '/auth/login';\n            this.signupUrl = '/auth/signup';\n            this.unlinkUrl = '/auth/unlink/';\n            this.tokenName = 'token';\n            this.tokenPrefix = 'satellizer';\n            this.tokenHeader = 'Authorization';\n            this.tokenType = 'Bearer';\n            this.storageType = 'localStorage';\n            this.tokenRoot = null;\n            this.withCredentials = false;\n            this.providers = {\n                facebook: {\n                    name: 'facebook',\n                    url: '/auth/facebook',\n                    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ',',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 580, height: 400 }\n                },\n                google: {\n                    name: 'google',\n                    url: '/auth/google',\n                    authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    optionalUrlParams: ['display', 'state'],\n                    scope: ['profile', 'email'],\n                    scopePrefix: 'openid',\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 452, height: 633 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                },\n                github: {\n                    name: 'github',\n                    url: '/auth/github',\n                    authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['scope'],\n                    scope: ['user:email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1020, height: 618 }\n                },\n                instagram: {\n                    name: 'instagram',\n                    url: '/auth/instagram',\n                    authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['basic'],\n                    scopeDelimiter: '+',\n                    oauthType: '2.0'\n                },\n                linkedin: {\n                    name: 'linkedin',\n                    url: '/auth/linkedin',\n                    authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['state'],\n                    scope: ['r_emailaddress'],\n                    scopeDelimiter: ' ',\n                    state: 'STATE',\n                    oauthType: '2.0',\n                    popupOptions: { width: 527, height: 582 }\n                },\n                twitter: {\n                    name: 'twitter',\n                    url: '/auth/twitter',\n                    authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n                    redirectUri: window.location.origin,\n                    oauthType: '1.0',\n                    popupOptions: { width: 495, height: 645 }\n                },\n                twitch: {\n                    name: 'twitch',\n                    url: '/auth/twitch',\n                    authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['user_read'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                live: {\n                    name: 'live',\n                    url: '/auth/live',\n                    authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['wl.emails'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                yahoo: {\n                    name: 'yahoo',\n                    url: '/auth/yahoo',\n                    authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n                    redirectUri: window.location.origin,\n                    scope: [],\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 559, height: 519 }\n                },\n                bitbucket: {\n                    name: 'bitbucket',\n                    url: '/auth/bitbucket',\n                    authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1028, height: 529 }\n                },\n                spotify: {\n                    name: 'spotify',\n                    url: '/auth/spotify',\n                    authorizationEndpoint: 'https://accounts.spotify.com/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['state'],\n                    requiredUrlParams: ['scope'],\n                    scope: ['user-read-email'],\n                    scopePrefix: '',\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 530 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                }\n            };\n            this.httpInterceptor = function () { return true; };\n        }\n        Object.defineProperty(Config, \"getConstant\", {\n            get: function () {\n                return new Config();\n            },\n            enumerable: true,\n            configurable: true\n        });\n        return Config;\n    }());\n    ;\n\n    var AuthProvider = (function () {\n        function AuthProvider(SatellizerConfig) {\n            this.SatellizerConfig = SatellizerConfig;\n        }\n        Object.defineProperty(AuthProvider.prototype, \"baseUrl\", {\n            get: function () { return this.SatellizerConfig.baseUrl; },\n            set: function (value) { this.SatellizerConfig.baseUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"loginUrl\", {\n            get: function () { return this.SatellizerConfig.loginUrl; },\n            set: function (value) { this.SatellizerConfig.loginUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"signupUrl\", {\n            get: function () { return this.SatellizerConfig.signupUrl; },\n            set: function (value) { this.SatellizerConfig.signupUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"unlinkUrl\", {\n            get: function () { return this.SatellizerConfig.unlinkUrl; },\n            set: function (value) { this.SatellizerConfig.unlinkUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenRoot\", {\n            get: function () { return this.SatellizerConfig.tokenRoot; },\n            set: function (value) { this.SatellizerConfig.tokenRoot = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenName\", {\n            get: function () { return this.SatellizerConfig.tokenName; },\n            set: function (value) { this.SatellizerConfig.tokenName = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenPrefix\", {\n            get: function () { return this.SatellizerConfig.tokenPrefix; },\n            set: function (value) { this.SatellizerConfig.tokenPrefix = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenHeader\", {\n            get: function () { return this.SatellizerConfig.tokenHeader; },\n            set: function (value) { this.SatellizerConfig.tokenHeader = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenType\", {\n            get: function () { return this.SatellizerConfig.tokenType; },\n            set: function (value) { this.SatellizerConfig.tokenType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"withCredentials\", {\n            get: function () { return this.SatellizerConfig.withCredentials; },\n            set: function (value) { this.SatellizerConfig.withCredentials = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"storageType\", {\n            get: function () { return this.SatellizerConfig.storageType; },\n            set: function (value) { this.SatellizerConfig.storageType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"httpInterceptor\", {\n            get: function () { return this.SatellizerConfig.httpInterceptor; },\n            set: function (value) {\n                if (typeof value === 'function') {\n                    this.SatellizerConfig.httpInterceptor = value;\n                }\n                else {\n                    this.SatellizerConfig.httpInterceptor = function () { return value; };\n                }\n            },\n            enumerable: true,\n            configurable: true\n        });\n        AuthProvider.prototype.facebook = function (options) {\n            angular.extend(this.SatellizerConfig.providers.facebook, options);\n        };\n        AuthProvider.prototype.google = function (options) {\n            angular.extend(this.SatellizerConfig.providers.google, options);\n        };\n        AuthProvider.prototype.github = function (options) {\n            angular.extend(this.SatellizerConfig.providers.github, options);\n        };\n        AuthProvider.prototype.instagram = function (options) {\n            angular.extend(this.SatellizerConfig.providers.instagram, options);\n        };\n        AuthProvider.prototype.linkedin = function (options) {\n            angular.extend(this.SatellizerConfig.providers.linkedin, options);\n        };\n        AuthProvider.prototype.twitter = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitter, options);\n        };\n        AuthProvider.prototype.twitch = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitch, options);\n        };\n        AuthProvider.prototype.live = function (options) {\n            angular.extend(this.SatellizerConfig.providers.live, options);\n        };\n        AuthProvider.prototype.yahoo = function (options) {\n            angular.extend(this.SatellizerConfig.providers.yahoo, options);\n        };\n        AuthProvider.prototype.bitbucket = function (options) {\n            angular.extend(this.SatellizerConfig.providers.bitbucket, options);\n        };\n        AuthProvider.prototype.spotify = function (options) {\n            angular.extend(this.SatellizerConfig.providers.spotify, options);\n        };\n        AuthProvider.prototype.oauth1 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '1.0'\n            });\n        };\n        AuthProvider.prototype.oauth2 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '2.0'\n            });\n        };\n        AuthProvider.prototype.$get = function (SatellizerShared, SatellizerLocal, SatellizerOAuth) {\n            return {\n                login: function (user, options) { return SatellizerLocal.login(user, options); },\n                signup: function (user, options) { return SatellizerLocal.signup(user, options); },\n                logout: function () { return SatellizerShared.logout(); },\n                authenticate: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                link: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                unlink: function (name, options) { return SatellizerOAuth.unlink(name, options); },\n                isAuthenticated: function () { return SatellizerShared.isAuthenticated(); },\n                getPayload: function () { return SatellizerShared.getPayload(); },\n                getToken: function () { return SatellizerShared.getToken(); },\n                setToken: function (token) { return SatellizerShared.setToken({ access_token: token }); },\n                removeToken: function () { return SatellizerShared.removeToken(); },\n                setStorageType: function (type) { return SatellizerShared.setStorageType(type); }\n            };\n        };\n        AuthProvider.$inject = ['SatellizerConfig'];\n        return AuthProvider;\n    }());\n    AuthProvider.prototype.$get.$inject = ['SatellizerShared', 'SatellizerLocal', 'SatellizerOAuth'];\n\n    function joinUrl(baseUrl, url) {\n        if (/^(?:[a-z]+:)?\\/\\//i.test(url)) {\n            return url;\n        }\n        var joined = [baseUrl, url].join('/');\n        var normalize = function (str) {\n            return str\n                .replace(/[\\/]+/g, '/')\n                .replace(/\\/\\?/g, '?')\n                .replace(/\\/\\#/g, '#')\n                .replace(/\\:\\//g, '://');\n        };\n        return normalize(joined);\n    }\n    function getFullUrlPath(location) {\n        var isHttps = location.protocol === 'https:';\n        return location.protocol + '//' + location.hostname +\n            ':' + (location.port || (isHttps ? '443' : '80')) +\n            (/^\\//.test(location.pathname) ? location.pathname : '/' + location.pathname);\n    }\n    function parseQueryString(str) {\n        var obj = {};\n        var key;\n        var value;\n        angular.forEach((str || '').split('&'), function (keyValue) {\n            if (keyValue) {\n                value = keyValue.split('=');\n                key = decodeURIComponent(value[0]);\n                obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;\n            }\n        });\n        return obj;\n    }\n    function decodeBase64(str) {\n        var buffer;\n        if (typeof module !== 'undefined' && module.exports) {\n            try {\n                buffer = require('buffer').Buffer;\n            }\n            catch (err) {\n            }\n        }\n        var fromCharCode = String.fromCharCode;\n        var re_btou = new RegExp([\n            '[\\xC0-\\xDF][\\x80-\\xBF]',\n            '[\\xE0-\\xEF][\\x80-\\xBF]{2}',\n            '[\\xF0-\\xF7][\\x80-\\xBF]{3}'\n        ].join('|'), 'g');\n        var cb_btou = function (cccc) {\n            switch (cccc.length) {\n                case 4:\n                    var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n                        | ((0x3f & cccc.charCodeAt(1)) << 12)\n                        | ((0x3f & cccc.charCodeAt(2)) << 6)\n                        | (0x3f & cccc.charCodeAt(3));\n                    var offset = cp - 0x10000;\n                    return (fromCharCode((offset >>> 10) + 0xD800)\n                        + fromCharCode((offset & 0x3FF) + 0xDC00));\n                case 3:\n                    return fromCharCode(((0x0f & cccc.charCodeAt(0)) << 12)\n                        | ((0x3f & cccc.charCodeAt(1)) << 6)\n                        | (0x3f & cccc.charCodeAt(2)));\n                default:\n                    return fromCharCode(((0x1f & cccc.charCodeAt(0)) << 6)\n                        | (0x3f & cccc.charCodeAt(1)));\n            }\n        };\n        var btou = function (b) {\n            return b.replace(re_btou, cb_btou);\n        };\n        var _decode = buffer ? function (a) {\n            return (a.constructor === buffer.constructor\n                ? a : new buffer(a, 'base64')).toString();\n        }\n            : function (a) {\n                return btou(atob(a));\n            };\n        return _decode(String(str).replace(/[-_]/g, function (m0) {\n            return m0 === '-' ? '+' : '/';\n        })\n            .replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n    }\n\n    var Shared = (function () {\n        function Shared($q, $window, SatellizerConfig, SatellizerStorage) {\n            this.$q = $q;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerStorage = SatellizerStorage;\n            var _a = this.SatellizerConfig, tokenName = _a.tokenName, tokenPrefix = _a.tokenPrefix;\n            this.prefixedTokenName = tokenPrefix ? [tokenPrefix, tokenName].join('_') : tokenName;\n        }\n        Shared.prototype.getToken = function () {\n            return this.SatellizerStorage.get(this.prefixedTokenName);\n        };\n        Shared.prototype.getPayload = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token && token.split('.').length === 3) {\n                try {\n                    var base64Url = token.split('.')[1];\n                    var base64 = base64Url.replace('-', '+').replace('_', '/');\n                    return JSON.parse(decodeBase64(base64));\n                }\n                catch (e) {\n                }\n            }\n        };\n        Shared.prototype.setToken = function (response) {\n            var tokenRoot = this.SatellizerConfig.tokenRoot;\n            var tokenName = this.SatellizerConfig.tokenName;\n            var accessToken = response && response.access_token;\n            var token;\n            if (accessToken) {\n                if (angular.isObject(accessToken) && angular.isObject(accessToken.data)) {\n                    response = accessToken;\n                }\n                else if (angular.isString(accessToken)) {\n                    token = accessToken;\n                }\n            }\n            if (!token && response) {\n                var tokenRootData = tokenRoot && tokenRoot.split('.').reduce(function (o, x) { return o[x]; }, response.data);\n                token = tokenRootData ? tokenRootData[tokenName] : response.data && response.data[tokenName];\n            }\n            if (token) {\n                this.SatellizerStorage.set(this.prefixedTokenName, token);\n            }\n        };\n        Shared.prototype.removeToken = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n        };\n        Shared.prototype.isAuthenticated = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token) {\n                if (token.split('.').length === 3) {\n                    try {\n                        var base64Url = token.split('.')[1];\n                        var base64 = base64Url.replace('-', '+').replace('_', '/');\n                        var exp = JSON.parse(this.$window.atob(base64)).exp;\n                        if (typeof exp === 'number') {\n                            return Math.round(new Date().getTime() / 1000) < exp;\n                        }\n                    }\n                    catch (e) {\n                        return true; // Pass: Non-JWT token that looks like JWT\n                    }\n                }\n                return true; // Pass: All other tokens\n            }\n            return false; // Fail: No token at all\n        };\n        Shared.prototype.logout = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n            return this.$q.when();\n        };\n        Shared.prototype.setStorageType = function (type) {\n            this.SatellizerConfig.storageType = type;\n        };\n        Shared.$inject = ['$q', '$window', 'SatellizerConfig', 'SatellizerStorage'];\n        return Shared;\n    }());\n\n    var Local = (function () {\n        function Local($http, SatellizerConfig, SatellizerShared) {\n            this.$http = $http;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n        }\n        Local.prototype.login = function (user, options) {\n            var _this = this;\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.loginUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options).then(function (response) {\n                _this.SatellizerShared.setToken(response);\n                return response;\n            });\n        };\n        Local.prototype.signup = function (user, options) {\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.signupUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options);\n        };\n        Local.$inject = ['$http', 'SatellizerConfig', 'SatellizerShared'];\n        return Local;\n    }());\n\n    var Popup = (function () {\n        function Popup($interval, $window, $q) {\n            this.$interval = $interval;\n            this.$window = $window;\n            this.$q = $q;\n            this.popup = null;\n            this.defaults = {\n                redirectUri: null\n            };\n        }\n        Popup.prototype.stringifyOptions = function (options) {\n            var parts = [];\n            angular.forEach(options, function (value, key) {\n                parts.push(key + '=' + value);\n            });\n            return parts.join(',');\n        };\n        Popup.prototype.open = function (url, name, popupOptions, redirectUri, dontPoll) {\n            var width = popupOptions.width || 500;\n            var height = popupOptions.height || 500;\n            var options = this.stringifyOptions({\n                width: width,\n                height: height,\n                top: this.$window.screenY + ((this.$window.outerHeight - height) / 2.5),\n                left: this.$window.screenX + ((this.$window.outerWidth - width) / 2)\n            });\n            var popupName = this.$window['cordova'] || this.$window.navigator.userAgent.indexOf('CriOS') > -1 ? '_blank' : name;\n            this.popup = this.$window.open(url, popupName, options);\n            if (this.popup && this.popup.focus) {\n                this.popup.focus();\n            }\n            if (dontPoll) {\n                return;\n            }\n            if (this.$window['cordova']) {\n                return this.eventListener(redirectUri);\n            }\n            else {\n                if (url === 'about:blank') {\n                    this.popup.location = url;\n                }\n                return this.polling(redirectUri);\n            }\n        };\n        Popup.prototype.polling = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var redirectUriParser = document.createElement('a');\n                redirectUriParser.href = redirectUri;\n                var redirectUriPath = getFullUrlPath(redirectUriParser);\n                var polling = _this.$interval(function () {\n                    if (!_this.popup || _this.popup.closed || _this.popup.closed === undefined) {\n                        _this.$interval.cancel(polling);\n                        reject(new Error('The popup window was closed'));\n                    }\n                    try {\n                        var popupWindowPath = getFullUrlPath(_this.popup.location);\n                        if (popupWindowPath === redirectUriPath) {\n                            if (_this.popup.location.search || _this.popup.location.hash) {\n                                var query = parseQueryString(_this.popup.location.search.substring(1).replace(/\\/$/, ''));\n                                var hash = parseQueryString(_this.popup.location.hash.substring(1).replace(/[\\/$]/, ''));\n                                var params = angular.extend({}, query, hash);\n                                if (params.error) {\n                                    reject(new Error(params.error));\n                                }\n                                else {\n                                    resolve(params);\n                                }\n                            }\n                            else {\n                                reject(new Error('OAuth redirect has occurred but no query or hash parameters were found. ' +\n                                    'They were either not set during the redirect, or were removed—typically by a ' +\n                                    'routing library—before Satellizer could read it.'));\n                            }\n                            _this.$interval.cancel(polling);\n                            _this.popup.close();\n                        }\n                    }\n                    catch (error) {\n                    }\n                }, 500);\n            });\n        };\n        Popup.prototype.eventListener = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                _this.popup.addEventListener('loadstart', function (event) {\n                    if (event.url.indexOf(redirectUri) !== 0) {\n                        return;\n                    }\n                    var parser = document.createElement('a');\n                    parser.href = event.url;\n                    if (parser.search || parser.hash) {\n                        var query = parseQueryString(parser.search.substring(1).replace(/\\/$/, ''));\n                        var hash = parseQueryString(parser.hash.substring(1).replace(/[\\/$]/, ''));\n                        var params = angular.extend({}, query, hash);\n                        if (params.error) {\n                            reject(new Error(params.error));\n                        }\n                        else {\n                            resolve(params);\n                        }\n                        _this.popup.close();\n                    }\n                });\n                _this.popup.addEventListener('loaderror', function () {\n                    reject(new Error('Authorization failed'));\n                });\n                _this.popup.addEventListener('exit', function () {\n                    reject(new Error('The popup window was closed'));\n                });\n            });\n        };\n        Popup.$inject = ['$interval', '$window', '$q'];\n        return Popup;\n    }());\n\n    var OAuth1 = (function () {\n        function OAuth1($http, $window, SatellizerConfig, SatellizerPopup) {\n            this.$http = $http;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.defaults = {\n                name: null,\n                url: null,\n                authorizationEndpoint: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                redirectUri: null,\n                requiredUrlParams: null,\n                defaultUrlParams: null,\n                oauthType: '1.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        ;\n        OAuth1.prototype.init = function (options, userData) {\n            var _this = this;\n            angular.extend(this.defaults, options);\n            var name = options.name, popupOptions = options.popupOptions;\n            var redirectUri = this.defaults.redirectUri;\n            // Should open an empty popup and wait until request token is received\n            if (!this.$window['cordova']) {\n                this.SatellizerPopup.open('about:blank', name, popupOptions, redirectUri, true);\n            }\n            return this.getRequestToken().then(function (response) {\n                return _this.openPopup(options, response).then(function (popupResponse) {\n                    return _this.exchangeForToken(popupResponse, userData);\n                });\n            });\n        };\n        OAuth1.prototype.openPopup = function (options, response) {\n            var url = [options.authorizationEndpoint, this.buildQueryString(response.data)].join('?');\n            var redirectUri = this.defaults.redirectUri;\n            if (this.$window['cordova']) {\n                return this.SatellizerPopup.open(url, options.name, options.popupOptions, redirectUri);\n            }\n            else {\n                this.SatellizerPopup.popup.location = url;\n                return this.SatellizerPopup.polling(redirectUri);\n            }\n        };\n        OAuth1.prototype.getRequestToken = function () {\n            var url = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(url, this.defaults);\n        };\n        OAuth1.prototype.exchangeForToken = function (oauthData, userData) {\n            var payload = angular.extend({}, userData, oauthData);\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth1.prototype.buildQueryString = function (obj) {\n            var str = [];\n            angular.forEach(obj, function (value, key) {\n                str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n            });\n            return str.join('&');\n        };\n        OAuth1.$inject = ['$http', '$window', 'SatellizerConfig', 'SatellizerPopup'];\n        return OAuth1;\n    }());\n\n    var OAuth2 = (function () {\n        function OAuth2($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.defaults = {\n                name: null,\n                url: null,\n                clientId: null,\n                authorizationEndpoint: null,\n                redirectUri: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                state: null,\n                requiredUrlParams: null,\n                defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n                responseType: 'code',\n                responseParams: {\n                    code: 'code',\n                    clientId: 'clientId',\n                    redirectUri: 'redirectUri'\n                },\n                oauthType: '2.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        OAuth2.camelCase = function (name) {\n            return name.replace(/([\\:\\-\\_]+(.))/g, function (_, separator, letter, offset) {\n                return offset ? letter.toUpperCase() : letter;\n            });\n        };\n        OAuth2.prototype.init = function (options, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                angular.extend(_this.defaults, options);\n                var stateName = _this.defaults.name + '_state';\n                var _a = _this.defaults, name = _a.name, state = _a.state, popupOptions = _a.popupOptions, redirectUri = _a.redirectUri, responseType = _a.responseType;\n                if (typeof state === 'function') {\n                    _this.SatellizerStorage.set(stateName, state());\n                }\n                else if (typeof state === 'string') {\n                    _this.SatellizerStorage.set(stateName, state);\n                }\n                var url = [_this.defaults.authorizationEndpoint, _this.buildQueryString()].join('?');\n                _this.SatellizerPopup.open(url, name, popupOptions, redirectUri).then(function (oauth) {\n                    if (responseType === 'token' || !url) {\n                        return resolve(oauth);\n                    }\n                    if (oauth.state && oauth.state !== _this.SatellizerStorage.get(stateName)) {\n                        return reject(new Error('The value returned in the state parameter does not match the state value from your original ' +\n                            'authorization code request.'));\n                    }\n                    resolve(_this.exchangeForToken(oauth, userData));\n                }).catch(function (error) { return reject(error); });\n            });\n        };\n        OAuth2.prototype.exchangeForToken = function (oauthData, userData) {\n            var _this = this;\n            var payload = angular.extend({}, userData);\n            angular.forEach(this.defaults.responseParams, function (value, key) {\n                switch (key) {\n                    case 'code':\n                        payload[value] = oauthData.code;\n                        break;\n                    case 'clientId':\n                        payload[value] = _this.defaults.clientId;\n                        break;\n                    case 'redirectUri':\n                        payload[value] = _this.defaults.redirectUri;\n                        break;\n                    default:\n                        payload[value] = oauthData[key];\n                }\n            });\n            if (oauthData.state) {\n                payload.state = oauthData.state;\n            }\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ?\n                joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) :\n                this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth2.prototype.buildQueryString = function () {\n            var _this = this;\n            var keyValuePairs = [];\n            var urlParamsCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];\n            angular.forEach(urlParamsCategories, function (paramsCategory) {\n                angular.forEach(_this.defaults[paramsCategory], function (paramName) {\n                    var camelizedName = OAuth2.camelCase(paramName);\n                    var paramValue = angular.isFunction(_this.defaults[paramName]) ? _this.defaults[paramName]() : _this.defaults[camelizedName];\n                    if (paramName === 'redirect_uri' && !paramValue) {\n                        return;\n                    }\n                    if (paramName === 'state') {\n                        var stateName = _this.defaults.name + '_state';\n                        paramValue = encodeURIComponent(_this.SatellizerStorage.get(stateName));\n                    }\n                    if (paramName === 'scope' && Array.isArray(paramValue)) {\n                        paramValue = paramValue.join(_this.defaults.scopeDelimiter);\n                        if (_this.defaults.scopePrefix) {\n                            paramValue = [_this.defaults.scopePrefix, paramValue].join(_this.defaults.scopeDelimiter);\n                        }\n                    }\n                    keyValuePairs.push([paramName, paramValue]);\n                });\n            });\n            return keyValuePairs.map(function (pair) { return pair.join('='); }).join('&');\n        };\n        OAuth2.$inject = ['$http', '$window', '$timeout', '$q', 'SatellizerConfig', 'SatellizerPopup', 'SatellizerStorage'];\n        return OAuth2;\n    }());\n\n    var OAuth = (function () {\n        function OAuth($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage, SatellizerShared, SatellizerOAuth1, SatellizerOAuth2) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerOAuth1 = SatellizerOAuth1;\n            this.SatellizerOAuth2 = SatellizerOAuth2;\n        }\n        OAuth.prototype.authenticate = function (name, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var provider = _this.SatellizerConfig.providers[name];\n                var oauth = null;\n                switch (provider.oauthType) {\n                    case '1.0':\n                        oauth = new OAuth1(_this.$http, _this.$window, _this.SatellizerConfig, _this.SatellizerPopup);\n                        break;\n                    case '2.0':\n                        oauth = new OAuth2(_this.$http, _this.$window, _this.$timeout, _this.$q, _this.SatellizerConfig, _this.SatellizerPopup, _this.SatellizerStorage);\n                        break;\n                    default:\n                        return reject(new Error('Invalid OAuth Type'));\n                }\n                return oauth.init(provider, userData).then(function (response) {\n                    if (provider.url) {\n                        _this.SatellizerShared.setToken(response);\n                    }\n                    resolve(response);\n                }).catch(function (error) {\n                    reject(error);\n                });\n            });\n        };\n        OAuth.prototype.unlink = function (provider, httpOptions) {\n            if (httpOptions === void 0) { httpOptions = {}; }\n            httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);\n            httpOptions.data = { provider: provider } || httpOptions.data;\n            httpOptions.method = httpOptions.method || 'POST';\n            httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(httpOptions);\n        };\n        OAuth.$inject = [\n            '$http',\n            '$window',\n            '$timeout',\n            '$q',\n            'SatellizerConfig',\n            'SatellizerPopup',\n            'SatellizerStorage',\n            'SatellizerShared',\n            'SatellizerOAuth1',\n            'SatellizerOAuth2'\n        ];\n        return OAuth;\n    }());\n\n    var Storage = (function () {\n        function Storage($window, SatellizerConfig) {\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.memoryStore = {};\n        }\n        Storage.prototype.get = function (key) {\n            try {\n                return this.$window[this.SatellizerConfig.storageType].getItem(key);\n            }\n            catch (e) {\n                return this.memoryStore[key];\n            }\n        };\n        Storage.prototype.set = function (key, value) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].setItem(key, value);\n            }\n            catch (e) {\n                this.memoryStore[key] = value;\n            }\n        };\n        Storage.prototype.remove = function (key) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].removeItem(key);\n            }\n            catch (e) {\n                delete this.memoryStore[key];\n            }\n        };\n        Storage.$inject = ['$window', 'SatellizerConfig'];\n        return Storage;\n    }());\n\n    var Interceptor = (function () {\n        function Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            var _this = this;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerStorage = SatellizerStorage;\n            this.request = function (config) {\n                if (config['skipAuthorization']) {\n                    return config;\n                }\n                if (_this.SatellizerShared.isAuthenticated() && _this.SatellizerConfig.httpInterceptor()) {\n                    var tokenName = _this.SatellizerConfig.tokenPrefix ?\n                        [_this.SatellizerConfig.tokenPrefix, _this.SatellizerConfig.tokenName].join('_') : _this.SatellizerConfig.tokenName;\n                    var token = _this.SatellizerStorage.get(tokenName);\n                    if (_this.SatellizerConfig.tokenHeader && _this.SatellizerConfig.tokenType) {\n                        token = _this.SatellizerConfig.tokenType + ' ' + token;\n                    }\n                    config.headers[_this.SatellizerConfig.tokenHeader] = token;\n                }\n                return config;\n            };\n        }\n        Interceptor.Factory = function (SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            return new Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage);\n        };\n        Interceptor.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n        return Interceptor;\n    }());\n    Interceptor.Factory.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n\n    var HttpProviderConfig = (function () {\n        function HttpProviderConfig($httpProvider) {\n            this.$httpProvider = $httpProvider;\n            $httpProvider.interceptors.push(Interceptor.Factory);\n        }\n        HttpProviderConfig.$inject = ['$httpProvider'];\n        return HttpProviderConfig;\n    }());\n\n    angular.module('satellizer', [])\n        .provider('$auth', ['SatellizerConfig', function (SatellizerConfig) { return new AuthProvider(SatellizerConfig); }])\n        .constant('SatellizerConfig', Config.getConstant)\n        .service('SatellizerShared', Shared)\n        .service('SatellizerLocal', Local)\n        .service('SatellizerPopup', Popup)\n        .service('SatellizerOAuth', OAuth)\n        .service('SatellizerOAuth2', OAuth2)\n        .service('SatellizerOAuth1', OAuth1)\n        .service('SatellizerStorage', Storage)\n        .service('SatellizerInterceptor', Interceptor)\n        .config(['$httpProvider', function ($httpProvider) { return new HttpProviderConfig($httpProvider); }]);\n    var ng1 = 'satellizer';\n\n    return ng1;\n\n}));\n//# sourceMappingURL=satellizer.js.map\n"
  },
  {
    "path": "examples/client/app.js",
    "content": "angular.module('MyApp', ['ngResource', 'ngMessages', 'ngAnimate', 'toastr', 'ui.router', 'satellizer'])\n  .config(function($stateProvider, $urlRouterProvider, $authProvider) {\n\n    /**\n     * Helper auth functions\n     */\n    var skipIfLoggedIn = ['$q', '$auth', function($q, $auth) {\n      var deferred = $q.defer();\n      if ($auth.isAuthenticated()) {\n        deferred.reject();\n      } else {\n        deferred.resolve();\n      }\n      return deferred.promise;\n    }];\n\n    var loginRequired = ['$q', '$location', '$auth', function($q, $location, $auth) {\n      var deferred = $q.defer();\n      if ($auth.isAuthenticated()) {\n        deferred.resolve();\n      } else {\n        $location.path('/login');\n      }\n      return deferred.promise;\n    }];\n\n    /**\n     * App routes\n     */\n    $stateProvider\n      .state('home', {\n        url: '/',\n        controller: 'HomeCtrl',\n        templateUrl: 'partials/home.html'\n      })\n      .state('login', {\n        url: '/login',\n        templateUrl: 'partials/login.html',\n        controller: 'LoginCtrl',\n        resolve: {\n          skipIfLoggedIn: skipIfLoggedIn\n        }\n      })\n      .state('signup', {\n        url: '/signup',\n        templateUrl: 'partials/signup.html',\n        controller: 'SignupCtrl',\n        resolve: {\n          skipIfLoggedIn: skipIfLoggedIn\n        }\n      })\n      .state('logout', {\n        url: '/logout',\n        template: null,\n        controller: 'LogoutCtrl'\n      })\n      .state('profile', {\n        url: '/profile',\n        templateUrl: 'partials/profile.html',\n        controller: 'ProfileCtrl',\n        resolve: {\n          loginRequired: loginRequired\n        }\n      });\n    $urlRouterProvider.otherwise('/');\n\n    /**\n     *  Satellizer config\n     */\n    $authProvider.facebook({\n      clientId: '603122136500203'\n    });\n\n    $authProvider.google({\n      clientId: 'YOUR_GOOGLE_CLIENT_ID'\n    });\n\n    $authProvider.github({\n      clientId: 'YOUR_GITHUB_CLIENT_ID'\n    });\n\n    $authProvider.linkedin({\n      clientId: 'YOUR_LINKEDIN_CLIENT_ID'\n    });\n\n    $authProvider.instagram({\n      clientId: 'YOUR_INSTAGRAM_CLIENT_ID'\n    });\n\n    $authProvider.yahoo({\n      clientId: 'YOUR_YAHOO_CLIENT_ID'\n    });\n\n    $authProvider.live({\n      clientId: 'YOUR_MICROSOFT_CLIENT_ID'\n    });\n\n    $authProvider.twitch({\n      clientId: 'YOUR_TWITCH_CLIENT_ID'\n    });\n\n    $authProvider.bitbucket({\n      clientId: 'YOUR_BITBUCKET_CLIENT_ID'\n    });\n\n    $authProvider.spotify({\n      clientId: 'YOUR_SPOTIFY_CLIENT_ID'\n    });\n\n    $authProvider.twitter({\n      url: '/auth/twitter'\n    });\n\n    $authProvider.oauth2({\n      name: 'foursquare',\n      url: '/auth/foursquare',\n      clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',\n      redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,\n      authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate'\n    });\n  });\n"
  },
  {
    "path": "examples/client/controllers/home.js",
    "content": "angular.module('MyApp')\n  .controller('HomeCtrl', function($scope, $http) {\n    $http.jsonp('https://api.github.com/repos/sahat/satellizer?callback=JSON_CALLBACK')\n      .success(function(data) {\n        if (data) {\n          if (data.data.stargazers_count) {\n            $scope.stars = data.data.stargazers_count;\n          }\n          if (data.data.forks) {\n            $scope.forks = data.data.forks;\n          }\n          if (data.data.open_issues) {\n            $scope.issues = data.data.open_issues;\n          }\n        }\n      });\n  });\n"
  },
  {
    "path": "examples/client/controllers/login.js",
    "content": "angular.module('MyApp')\n  .controller('LoginCtrl', function($scope, $location, $auth, toastr) {\n    $scope.login = function() {\n      $auth.login($scope.user)\n        .then(function() {\n          toastr.success('You have successfully signed in!');\n          $location.path('/');\n        })\n        .catch(function(error) {\n          toastr.error(error.data.message, error.status);\n        });\n    };\n    $scope.authenticate = function(provider) {\n      $auth.authenticate(provider)\n        .then(function() {\n          toastr.success('You have successfully signed in with ' + provider + '!');\n          $location.path('/');\n        })\n        .catch(function(error) {\n          if (error.message) {\n            // Satellizer promise reject error.\n            toastr.error(error.message);\n          } else if (error.data) {\n            // HTTP response error from server\n            toastr.error(error.data.message, error.status);\n          } else {\n            toastr.error(error);\n          }\n        });\n    };\n  });\n"
  },
  {
    "path": "examples/client/controllers/logout.js",
    "content": "angular.module('MyApp')\n  .controller('LogoutCtrl', function($location, $auth, toastr) {\n    if (!$auth.isAuthenticated()) { return; }\n    $auth.logout()\n      .then(function() {\n        toastr.info('You have been logged out');\n        $location.path('/');\n      });\n  });"
  },
  {
    "path": "examples/client/controllers/navbar.js",
    "content": "angular.module('MyApp')\n  .controller('NavbarCtrl', function($scope, $auth) {\n    $scope.isAuthenticated = function() {\n      return $auth.isAuthenticated();\n    };\n  });\n"
  },
  {
    "path": "examples/client/controllers/profile.js",
    "content": "angular.module('MyApp')\n  .controller('ProfileCtrl', function($scope, $auth, toastr, Account) {\n    $scope.getProfile = function() {\n      Account.getProfile()\n        .then(function(response) {\n          $scope.user = response.data;\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message, response.status);\n        });\n    };\n    $scope.updateProfile = function() {\n      Account.updateProfile($scope.user)\n        .then(function() {\n          toastr.success('Profile has been updated');\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message, response.status);\n        });\n    };\n    $scope.link = function(provider) {\n      $auth.link(provider)\n        .then(function() {\n          toastr.success('You have successfully linked a ' + provider + ' account');\n          $scope.getProfile();\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message, response.status);\n        });\n    };\n    $scope.unlink = function(provider) {\n      $auth.unlink(provider)\n        .then(function() {\n          toastr.info('You have unlinked a ' + provider + ' account');\n          $scope.getProfile();\n        })\n        .catch(function(response) {\n          toastr.error(response.data ? response.data.message : 'Could not unlink ' + provider + ' account', response.status);\n        });\n    };\n\n    $scope.getProfile();\n  });\n"
  },
  {
    "path": "examples/client/controllers/signup.js",
    "content": "angular.module('MyApp')\n  .controller('SignupCtrl', function($scope, $location, $auth, toastr) {\n    $scope.signup = function() {\n      $auth.signup($scope.user)\n        .then(function(response) {\n          $auth.setToken(response);\n          $location.path('/');\n          toastr.info('You have successfully created a new account and have been signed-in');\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message);\n        });\n    };\n  });"
  },
  {
    "path": "examples/client/directives/passwordMatch.js",
    "content": "angular.module('MyApp')\n  .directive('passwordMatch', function() {\n    return {\n      require: 'ngModel',\n      scope: {\n        otherModelValue: '=passwordMatch'\n      },\n      link: function(scope, element, attributes, ngModel) {\n        ngModel.$validators.compareTo = function(modelValue) {\n          return modelValue === scope.otherModelValue;\n        };\n        scope.$watch('otherModelValue', function() {\n          ngModel.$validate();\n        });\n      }\n    };\n  });\n\n"
  },
  {
    "path": "examples/client/directives/passwordStrength.js",
    "content": "angular.module('MyApp')\n  .directive('passwordStrength', function() {\n    return {\n      restrict: 'A',\n      require: 'ngModel',\n      link: function(scope, element, attrs, ngModel) {\n        var indicator = element.children();\n        var dots = Array.prototype.slice.call(indicator.children());\n        var weakest = dots.slice(-1)[0];\n        var weak = dots.slice(-2);\n        var strong = dots.slice(-3);\n        var strongest = dots.slice(-4);\n\n        element.after(indicator);\n\n        element.bind('keyup', function() {\n          var matches = {\n                positive: {},\n                negative: {}\n              },\n              counts = {\n                positive: {},\n                negative: {}\n              },\n              tmp,\n              strength = 0,\n              letters = 'abcdefghijklmnopqrstuvwxyz',\n              numbers = '01234567890',\n              symbols = '\\\\!@#$%&/()=?¿',\n              strValue;\n\n          angular.forEach(dots, function(el) {\n            el.style.backgroundColor = '#ebeef1';\n          });\n          \n          if (ngModel.$viewValue) {\n            // Increase strength level\n            matches.positive.lower = ngModel.$viewValue.match(/[a-z]/g);\n            matches.positive.upper = ngModel.$viewValue.match(/[A-Z]/g);\n            matches.positive.numbers = ngModel.$viewValue.match(/\\d/g);\n            matches.positive.symbols = ngModel.$viewValue.match(/[$-/:-?{-~!^_`\\[\\]]/g);\n            matches.positive.middleNumber = ngModel.$viewValue.slice(1, -1).match(/\\d/g);\n            matches.positive.middleSymbol = ngModel.$viewValue.slice(1, -1).match(/[$-/:-?{-~!^_`\\[\\]]/g);\n\n            counts.positive.lower = matches.positive.lower ? matches.positive.lower.length : 0;\n            counts.positive.upper = matches.positive.upper ? matches.positive.upper.length : 0;\n            counts.positive.numbers = matches.positive.numbers ? matches.positive.numbers.length : 0;\n            counts.positive.symbols = matches.positive.symbols ? matches.positive.symbols.length : 0;\n\n            counts.positive.numChars = ngModel.$viewValue.length;\n            tmp += (counts.positive.numChars >= 8) ? 1 : 0;\n\n            counts.positive.requirements = (tmp >= 3) ? tmp : 0;\n            counts.positive.middleNumber = matches.positive.middleNumber ? matches.positive.middleNumber.length : 0;\n            counts.positive.middleSymbol = matches.positive.middleSymbol ? matches.positive.middleSymbol.length : 0;\n\n            // Decrease strength level\n            matches.negative.consecLower = ngModel.$viewValue.match(/(?=([a-z]{2}))/g);\n            matches.negative.consecUpper = ngModel.$viewValue.match(/(?=([A-Z]{2}))/g);\n            matches.negative.consecNumbers = ngModel.$viewValue.match(/(?=(\\d{2}))/g);\n            matches.negative.onlyNumbers = ngModel.$viewValue.match(/^[0-9]*$/g);\n            matches.negative.onlyLetters = ngModel.$viewValue.match(/^([a-z]|[A-Z])*$/g);\n\n            counts.negative.consecLower = matches.negative.consecLower ? matches.negative.consecLower.length : 0;\n            counts.negative.consecUpper = matches.negative.consecUpper ? matches.negative.consecUpper.length : 0;\n            counts.negative.consecNumbers = matches.negative.consecNumbers ? matches.negative.consecNumbers.length : 0;\n\n            // Calculations\n            strength += counts.positive.numChars * 4;\n            if (counts.positive.upper) {\n              strength += (counts.positive.numChars - counts.positive.upper) * 2;\n            }\n            if (counts.positive.lower) {\n              strength += (counts.positive.numChars - counts.positive.lower) * 2;\n            }\n            if (counts.positive.upper || counts.positive.lower) {\n              strength += counts.positive.numbers * 4;\n            }\n            strength += counts.positive.symbols * 6;\n            strength += (counts.positive.middleSymbol + counts.positive.middleNumber) * 2;\n            strength += counts.positive.requirements * 2;\n\n            strength -= counts.negative.consecLower * 2;\n            strength -= counts.negative.consecUpper * 2;\n            strength -= counts.negative.consecNumbers * 2;\n\n            if (matches.negative.onlyNumbers) {\n              strength -= counts.positive.numChars;\n            }\n            if (matches.negative.onlyLetters) {\n              strength -= counts.positive.numChars;\n            }\n\n            strength = Math.max(0, Math.min(100, Math.round(strength)));\n\n            if (strength > 85) {\n              angular.forEach(strongest, function(el) {\n                el.style.backgroundColor = '#008cdd';\n              });\n            } else if (strength > 65) {\n              angular.forEach(strong, function(el) {\n                el.style.backgroundColor = '#6ead09';\n              });\n            } else if (strength > 30) {\n              angular.forEach(weak, function(el) {\n                el.style.backgroundColor = '#e09115';\n              });\n            } else {\n              weakest.style.backgroundColor = '#e01414';\n            }\n          }\n        });\n      },\n      template: '<span class=\"password-strength-indicator\"><span></span><span></span><span></span><span></span></span>'\n    };\n  });"
  },
  {
    "path": "examples/client/index.html",
    "content": "<!DOCTYPE html>\n<html ng-app=\"MyApp\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n  <title>Satellizer</title>\n  <link href=\"favicon.png\" rel=\"shortcut icon\">\n  <link href=\"//fonts.googleapis.com/css?family=Roboto|Montserrat:400,700|Open+Sans:400,300,600\" rel=\"stylesheet\">\n  <link href=\"//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n  <link href=\"//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css\" rel=\"stylesheet\">\n  <link href=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n  <link href=\"//cdn.jsdelivr.net/animatecss/3.2.0/animate.css\" rel=\"stylesheet\">\n  <link href=\"/stylesheets/angular-toastr.css\" rel=\"stylesheet\">\n  <link href=\"/stylesheets/styles.css\" rel=\"stylesheet\">\n</head>\n<body>\n<div ng-controller=\"NavbarCtrl\" class=\"navbar navbar-default navbar-static-top\">\n  <div class=\"navbar-header\">\n    <a class=\"navbar-brand\" href=\"/\"><i class=\"ion-ios7-pulse-strong\"></i> Satellizer</a>\n  </div>\n  <ul class=\"nav navbar-nav\">\n    <li><a href=\"/#/\">Home</a></li>\n    <li ng-if=\"isAuthenticated()\"><a href=\"/#/profile\">Profile</a></li>\n  </ul>\n  <ul ng-if=\"!isAuthenticated()\" class=\"nav navbar-nav pull-right\">\n    <li><a href=\"/#/login\">Login</a></li>\n    <li><a href=\"/#/signup\">Sign up</a></li>\n  </ul>\n  <ul ng-if=\"isAuthenticated()\" class=\"nav navbar-nav pull-right\">\n    <li><a href=\"/#/logout\">Logout</a></li>\n  </ul>\n</div>\n\n<div ui-view></div>\n\n<!-- Third-party Libraries -->\n<script src=\"/vendor/angular.js\"></script>\n<script src=\"/vendor/angular-animate.js\"></script>\n<script src=\"/vendor/angular-messages.js\"></script>\n<script src=\"/vendor/angular-resource.js\"></script>\n<script src=\"/vendor/angular-sanitize.js\"></script>\n<script src=\"/vendor/angular-ui-router.js\"></script>\n<script src=\"/vendor/angular-toastr.tpls.js\"></script>\n<script src=\"/vendor/satellizer.js\"></script>\n\n<!-- Application Code -->\n<script src=\"/app.js\"></script>\n<script src=\"/directives/passwordStrength.js\"></script>\n<script src=\"/directives/passwordMatch.js\"></script>\n<script src=\"/controllers/home.js\"></script>\n<script src=\"/controllers/login.js\"></script>\n<script src=\"/controllers/signup.js\"></script>\n<script src=\"/controllers/logout.js\"></script>\n<script src=\"/controllers/profile.js\"></script>\n<script src=\"/controllers/navbar.js\"></script>\n<script src=\"/services/account.js\"></script>\n</body>\n</html>\n"
  },
  {
    "path": "examples/client/partials/home.html",
    "content": "<div class=\"container\">\n  <div class=\"panel panel-default\">\n    <div class=\"panel-heading\">Home Page</div>\n    <div class=\"panel-body\">\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <h2>Heading</h2>\n          <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus,\n            tellus ac cursus commodo, tortor mauris condimentum nibh, ut\n            fermentum massa justo sit amet risus. Etiam porta sem malesuada\n            magna mollis euismod. Donec sed odio dui.</p>\n          <p><a class=\"btn btn-primary\" href=\"#\">View details »</a></p>\n        </div>\n        <div class=\"col-sm-6\">\n          <h2>Heading</h2>\n          <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus,\n            tellus ac cursus commodo, tortor mauris condimentum nibh, ut\n            fermentum massa justo sit amet risus. Etiam porta sem malesuada\n            magna mollis euismod. Donec sed odio dui.</p>\n          <p><a class=\"btn btn-primary\" href=\"#\">View details »</a></p>\n        </div>\n      </div>\n    </div>\n    <div class=\"panel-footer text-center\">\n      <ul class=\"list-inline\">\n        <li><i class=\"ion-star\"></i> {{stars | number}} stars</li>\n        <li><i class=\"ion-fork-repo\"></i> {{forks | number}} forks</li>\n        <li><i class=\"ion-pull-request\"></i> {{issues | number}} issues</li>\n      </ul>\n    </div>\n  </div>\n</div>\n<div class=\"text-center\">\n  <a class=\"btn btn-default\" href=\"https://github.com/sahat/satellizer\"><i class=\"ion-social-github\"></i> GitHub project</a>\n  <a class=\"btn btn-default\" href=\"https://github.com/sahat/satellizer/issues/new\"><i class=\"ion-bug\"></i> Report issue</a>\n</div>\n</div>"
  },
  {
    "path": "examples/client/partials/login.html",
    "content": "<div class=\"container\">\n  <div class=\"row\">\n    <div class=\"center-form panel\">\n      <div class=\"panel-body\">\n        <h2 class=\"text-center\">Log in</h2>\n        <form method=\"post\" ng-submit=\"login()\" name=\"loginForm\">\n          <div class=\"form-group has-feedback\">\n            <input class=\"form-control input-lg\" type=\"text\" name=\"email\" ng-model=\"user.email\" placeholder=\"Email\" required autofocus>\n            <span class=\"ion-at form-control-feedback\"></span>\n          </div>\n          <div class=\"form-group has-feedback\">\n            <input class=\"form-control input-lg\" type=\"password\" name=\"password\" ng-model=\"user.password\" placeholder=\"Password\" required>\n            <span class=\"ion-key form-control-feedback\"></span>\n          </div>\n          <button type=\"submit\" ng-disabled=\"loginForm.$invalid\" class=\"btn btn-lg  btn-block btn-success\">Log in</button>\n          <br/>\n          <p class=\"text-center text-muted\">\n            <small>Don't have an account yet? <a href=\"/#/signup\">Sign up</a></small>\n          </p>\n          <div class=\"signup-or-separator\">\n            <h6 class=\"text\">or</h6>\n            <hr>\n          </div>\n        </form>\n        <button class=\"btn btn-block btn-facebook\" ng-click=\"authenticate('facebook')\">\n          <i class=\"ion-social-facebook\"></i> Sign in with Facebook\n        </button>\n        <button class=\"btn btn-block btn-google-plus\" ng-click=\"authenticate('google')\">\n          <span class=\"ion-social-googleplus\"></span>Sign in with Google\n        </button>\n        <button class=\"btn btn-block btn-linkedin\" ng-click=\"authenticate('linkedin')\">\n          <i class=\"ion-social-linkedin\"></i> Sign in with LinkedIn\n        </button>\n        <button class=\"btn btn-block btn-instagram\" ng-click=\"authenticate('instagram')\">\n          <i class=\"ion-social-instagram\"></i> Sign in with Instagram\n        </button>\n        <button class=\"btn btn-block btn-twitter\" ng-click=\"authenticate('twitter')\">\n          <i class=\"ion-social-twitter\"></i> Sign in with Twitter\n        </button>\n        <button class=\"btn btn-block btn-foursquare\" ng-click=\"authenticate('foursquare')\">\n          <i class=\"fa fa-foursquare\"></i> Sign in with Foursquare\n        </button>\n        <button class=\"btn btn-block btn-github\" ng-click=\"authenticate('github')\">\n          <i class=\"ion-social-github\"></i> Sign in with GitHub\n        </button>\n        <button class=\"btn btn-block btn-bitbucket\" ng-click=\"authenticate('bitbucket')\">\n          <i class=\"fa fa-bitbucket\"></i> Sign in with Bitbucket\n        </button>\n        <button class=\"btn btn-block btn-yahoo\" ng-click=\"authenticate('yahoo')\">\n          <i class=\"ion-social-yahoo\"></i> Sign in with Yahoo\n        </button>\n        <button class=\"btn btn-block btn-live\" ng-click=\"authenticate('live')\">\n          <i class=\"ion-social-windows\"></i> Sign in with Windows Live\n        </button>\n        <button class=\"btn btn-block btn-twitch\" ng-click=\"authenticate('twitch')\">\n          <i class=\"ion-social-twitch\"></i> Sign in with Twitch\n        </button>\n        <button class=\"btn btn-block btn-spotify\" ng-click=\"authenticate('spotify')\">\n          <i class=\"fa fa-spotify\"></i> Sign in with Spotify\n        </button>\n      </div>\n    </div>\n  </div>\n</div>\n"
  },
  {
    "path": "examples/client/partials/profile.html",
    "content": "<div class=\"container\">\n  <div class=\"panel panel-default\">\n    <div class=\"panel-heading\">Profile</div>\n    <div class=\"panel-body\">\n      <legend><i class=\"ion-clipboard\"></i> Edit My Profile</legend>\n      <form method=\"post\" ng-submit=\"updateProfile()\">\n        <div class=\"form-group\">\n          <label class=\"control-label\">Profile Picture</label>\n          <img class=\"profile-picture\" ng-src=\"{{user.picture || 'https://placehold.it/100x100'}}\">\n        </div>\n        <div class=\"form-group\">\n          <label class=\"control-label\"><i class=\"ion-person\"></i> Display Name</label>\n          <input type=\"text\" class=\"form-control\" ng-model=\"user.displayName\" />\n        </div>\n        <div class=\"form-group\">\n          <label class=\"control-label\"><i class=\"ion-at\"></i> Email Address</label>\n          <input type=\"email\" class=\"form-control\" ng-model=\"user.email\" />\n        </div>\n        <button class=\"btn btn-lg btn-success\">Update Information</button>\n      </form>\n    </div>\n  </div>\n\n  <div class=\"panel panel-default\">\n    <div class=\"panel-heading\">Accounts</div>\n    <div class=\"panel-body\">\n      <legend><i class=\"ion-link\"></i> Linked Accounts</legend>\n      <div class=\"btn-group-vertical\">\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.facebook\" ng-click=\"unlink('facebook')\">\n          <i class=\"ion-social-facebook\"></i> Unlink Facebook Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.facebook\" ng-click=\"link('facebook')\">\n          <i class=\"ion-social-facebook\"></i> Link Facebook Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.google\" ng-click=\"unlink('google')\">\n          <i class=\"ion-social-googleplus\"></i> Unlink Google Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.google\" ng-click=\"link('google')\">\n          <i class=\"ion-social-googleplus\"></i> Link Google Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.linkedin\" ng-click=\"unlink('linkedin')\">\n          <i class=\"ion-social-linkedin\"></i> Unlink LinkedIn Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.linkedin\" ng-click=\"link('linkedin')\">\n          <i class=\"ion-social-linkedin\"></i> Link LinkedIn Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.twitter\" ng-click=\"unlink('twitter')\">\n          <i class=\"ion-social-twitter\"></i> Unlink Twitter Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.twitter\" ng-click=\"link('twitter')\">\n          <i class=\"ion-social-twitter\"></i> Link Twitter Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.github\" ng-click=\"unlink('github')\">\n          <i class=\"ion-social-github\"></i> Unlink GitHub Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.github\" ng-click=\"link('github')\">\n          <i class=\"ion-social-github\"></i> Link GitHub Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.instagram\" ng-click=\"unlink('instagram')\">\n          <i class=\"ion-social-instagram\"></i> Unlink Instagram Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.instagram\" ng-click=\"link('instagram')\">\n          <i class=\"ion-social-instagram\"></i> Link Instagram Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.foursquare\" ng-click=\"unlink('foursquare')\">\n          <i class=\"ion-social-foursquare\"></i> Unlink Foursquare Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.foursquare\" ng-click=\"link('foursquare')\">\n          <i class=\"ion-social-foursquare\"></i> Link Foursquare Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.yahoo\" ng-click=\"unlink('yahoo')\">\n          <i class=\"ion-social-yahoo\"></i> Unlink Yahoo Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.yahoo\" ng-click=\"link('yahoo')\">\n          <i class=\"ion-social-yahoo\"></i> Link Yahoo Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.live\" ng-click=\"unlink('live')\">\n          <i class=\"ion-social-windows\"></i> Unlink Windows Live Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.live\" ng-click=\"link('live')\">\n          <i class=\"ion-social-windows\"></i> Link Windows Live Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.twitch\" ng-click=\"unlink('twitch')\">\n          <i class=\"ion-social-twitch\"></i> Unlink Twitch Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.twitch\" ng-click=\"link('twitch')\">\n          <i class=\"ion-social-twitch\"></i> Link Twitch Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.bitbucket\" ng-click=\"unlink('bitbucket')\">\n          <i class=\"fa fa-bitbucket\"></i> Unlink Bitbucket Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.bitbucket\" ng-click=\"link('bitbucket')\">\n          <i class=\"fa fa-bitbucket\"></i> Link Bitbucket Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.spotify\" ng-click=\"unlink('spotify')\">\n          <i class=\"fa fa-spotify\"></i> Unlink Spotify Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.spotify\" ng-click=\"link('spotify')\">\n          <i class=\"fa fa-spotify\"></i> Link Spotify Account\n        </button>\n\n      </div>\n    </div>\n  </div>\n</div>\n"
  },
  {
    "path": "examples/client/partials/signup.html",
    "content": "<div class=\"container\">\n  <div class=\"row\">\n    <div class=\"center-form panel\">\n      <div class=\"panel-body\">\n        <h2 class=\"text-center\">Sign up</h2>\n        <form method=\"post\" ng-submit=\"signup()\" name=\"signupForm\">\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.displayName.$invalid && signupForm.displayName.$dirty }\">\n            <input class=\"form-control input-lg\" type=\"text\" name=\"displayName\" ng-model=\"user.displayName\" placeholder=\"Name\" required autofocus>\n            <span class=\"ion-person form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.displayName.$dirty\" ng-messages=\"signupForm.displayName.$error\">\n              <div ng-message=\"required\">You must enter your name.</div>\n            </div>\n          </div>\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.email.$invalid && signupForm.email.$dirty }\">\n            <input class=\"form-control input-lg\" type=\"email\" id=\"email\" name=\"email\" ng-model=\"user.email\" placeholder=\"Email\" required>\n            <span class=\"ion-at form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.email.$dirty\" ng-messages=\"signupForm.email.$error\">\n              <div ng-message=\"required\">Your email address is required.</div>\n              <div ng-message=\"pattern\">Your email address is invalid.</div>\n            </div>\n          </div>\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.password.$invalid && signupForm.password.$dirty }\">\n            <input password-strength class=\"form-control input-lg\" type=\"password\" name=\"password\" ng-model=\"user.password\" placeholder=\"Password\" required>\n            <span class=\"ion-key form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.password.$dirty\" ng-messages=\"signupForm.password.$error\">\n              <div ng-message=\"required\">Password is required.</div>\n            </div>\n          </div>\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.confirmPassword.$invalid && signupForm.confirmPassword.$dirty }\">\n            <input password-match=\"user.password\" class=\"form-control input-lg\" type=\"password\" name=\"confirmPassword\" ng-model=\"confirmPassword\" placeholder=\"Confirm Password\">\n            <span class=\"ion-key form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.confirmPassword.$dirty\" ng-messages=\"signupForm.confirmPassword.$error\">\n              <div ng-message=\"compareTo\">Password must match.</div>\n            </div>\n          </div>\n          <p class=\"text-center text-muted\"><small>By clicking on Sign up, you agree to <a href=\"#\">terms & conditions</a> and <a href=\"#\">privacy policy</a></small></p>\n          <button type=\"submit\" ng-disabled=\"signupForm.$invalid\" class=\"btn btn-lg btn-block btn-primary\">Sign up</button>\n          <br/>\n          <p class=\"text-center text-muted\">Already have an account? <a href=\"/#/login\">Log in now</a></p>\n        </form>\n      </div>\n    </div>\n  </div>\n</div>"
  },
  {
    "path": "examples/client/services/account.js",
    "content": "angular.module('MyApp')\n  .factory('Account', function($http) {\n    return {\n      getProfile: function() {\n        return $http.get('/api/me');\n      },\n      updateProfile: function(profileData) {\n        return $http.put('/api/me', profileData);\n      }\n    };\n  });"
  },
  {
    "path": "examples/client/stylesheets/angular-toastr.css",
    "content": ".toast-title {\n  font-weight: bold;\n}\n.toast-message {\n  word-wrap: break-word;\n}\n.toast-message a,\n.toast-message label {\n  color: #ffffff;\n}\n.toast-message a:hover {\n  color: #cccccc;\n  text-decoration: none;\n}\n.toast-close-button {\n  position: relative;\n  right: -0.3em;\n  top: -0.3em;\n  float: right;\n  font-size: 20px;\n  font-weight: bold;\n  color: #ffffff;\n  -webkit-text-shadow: 0 1px 0 #ffffff;\n  text-shadow: 0 1px 0 #ffffff;\n  opacity: 0.8;\n}\n.toast-close-button:hover,\n.toast-close-button:focus {\n  color: #000000;\n  text-decoration: none;\n  cursor: pointer;\n  opacity: 0.4;\n}\n/*Additional properties for button version\n iOS requires the button element instead of an anchor tag.\n If you want the anchor version, it requires `href=\"#\"`.*/\nbutton.toast-close-button {\n  padding: 0;\n  cursor: pointer;\n  background: transparent;\n  border: 0;\n  -webkit-appearance: none;\n}\n.toast-top-center {\n  top: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-bottom-center {\n  bottom: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-top-full-width {\n  top: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-bottom-full-width {\n  bottom: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-top-left {\n  top: 12px;\n  left: 12px;\n}\n.toast-top-right {\n  top: 12px;\n  right: 12px;\n}\n.toast-bottom-right {\n  right: 12px;\n  bottom: 12px;\n}\n.toast-bottom-left {\n  bottom: 12px;\n  left: 12px;\n}\n#toast-container {\n  position: fixed;\n  z-index: 999999;\n  /*overrides*/\n}\n#toast-container * {\n  -moz-box-sizing: border-box;\n  -webkit-box-sizing: border-box;\n  box-sizing: border-box;\n}\n#toast-container > div {\n  position: relative;\n  overflow: hidden;\n  margin: 0 0 6px;\n  padding: 15px 15px 15px 50px;\n  width: 300px;\n  -moz-border-radius: 3px 3px 3px 3px;\n  -webkit-border-radius: 3px 3px 3px 3px;\n  border-radius: 3px 3px 3px 3px;\n  background-position: 15px center;\n  background-repeat: no-repeat;\n  -moz-box-shadow: 0 0 12px #999999;\n  -webkit-box-shadow: 0 0 12px #999999;\n  box-shadow: 0 0 12px #999999;\n  color: #ffffff;\n  opacity: 0.8;\n}\n#toast-container > :hover {\n  -moz-box-shadow: 0 0 12px #000000;\n  -webkit-box-shadow: 0 0 12px #000000;\n  box-shadow: 0 0 12px #000000;\n  opacity: 1;\n  cursor: pointer;\n}\n#toast-container > .toast-info {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGwSURBVEhLtZa9SgNBEMc9sUxxRcoUKSzSWIhXpFMhhYWFhaBg4yPYiWCXZxBLERsLRS3EQkEfwCKdjWJAwSKCgoKCcudv4O5YLrt7EzgXhiU3/4+b2ckmwVjJSpKkQ6wAi4gwhT+z3wRBcEz0yjSseUTrcRyfsHsXmD0AmbHOC9Ii8VImnuXBPglHpQ5wwSVM7sNnTG7Za4JwDdCjxyAiH3nyA2mtaTJufiDZ5dCaqlItILh1NHatfN5skvjx9Z38m69CgzuXmZgVrPIGE763Jx9qKsRozWYw6xOHdER+nn2KkO+Bb+UV5CBN6WC6QtBgbRVozrahAbmm6HtUsgtPC19tFdxXZYBOfkbmFJ1VaHA1VAHjd0pp70oTZzvR+EVrx2Ygfdsq6eu55BHYR8hlcki+n+kERUFG8BrA0BwjeAv2M8WLQBtcy+SD6fNsmnB3AlBLrgTtVW1c2QN4bVWLATaIS60J2Du5y1TiJgjSBvFVZgTmwCU+dAZFoPxGEEs8nyHC9Bwe2GvEJv2WXZb0vjdyFT4Cxk3e/kIqlOGoVLwwPevpYHT+00T+hWwXDf4AJAOUqWcDhbwAAAAASUVORK5CYII=\") !important;\n}\n#toast-container > .toast-error {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII=\") !important;\n}\n#toast-container > .toast-success {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==\") !important;\n}\n#toast-container > .toast-warning {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII=\") !important;\n}\n#toast-container.toast-top-center > div,\n#toast-container.toast-bottom-center > div {\n  width: 300px;\n  margin: auto;\n}\n#toast-container.toast-top-full-width > div,\n#toast-container.toast-bottom-full-width > div {\n  width: 96%;\n  margin: auto;\n}\n.toast {\n  background-color: #030303;\n}\n.toast-success {\n  background-color: #51a351;\n}\n.toast-error {\n  background-color: #bd362f;\n}\n.toast-info {\n  background-color: #2f96b4;\n}\n.toast-warning {\n  background-color: #f89406;\n}\n.toast-progress {\n  position: absolute;\n  left: 0;\n  bottom: 0;\n  height: 4px;\n  background-color: #000000;\n  opacity: 0.4;\n}\n/*Animations*/\n.toast {\n  opacity: 1 !important;\n}\n.toast.ng-enter {\n  opacity: 0 !important;\n  transition: opacity .3s linear;\n}\n.toast.ng-enter.ng-enter-active {\n  opacity: 1 !important;\n}\n.toast.ng-leave {\n  opacity: 1;\n  transition: opacity .3s linear;\n}\n.toast.ng-leave.ng-leave-active {\n  opacity: 0 !important;\n}\n/*Responsive Design*/\n@media all and (max-width: 240px) {\n  #toast-container > div {\n    padding: 8px 8px 8px 50px;\n    width: 11em;\n  }\n  #toast-container .toast-close-button {\n    right: -0.2em;\n    top: -0.2em;\n  }\n}\n@media all and (min-width: 241px) and (max-width: 480px) {\n  #toast-container > div {\n    padding: 8px 8px 8px 50px;\n    width: 18em;\n  }\n  #toast-container .toast-close-button {\n    right: -0.2em;\n    top: -0.2em;\n  }\n}\n@media all and (min-width: 481px) and (max-width: 768px) {\n  #toast-container > div {\n    padding: 15px 15px 15px 50px;\n    width: 25em;\n  }\n}\n"
  },
  {
    "path": "examples/client/stylesheets/styles.css",
    "content": "body {\n  font-family: 'Open Sans', sans-serif;\n  background: #e4e7ec;\n}\n\nh1, h2, h3, h4, h5, h6 {\n  font-family: 'Montserrat', sans-serif;\n  font-weight: bold;\n}\n\na {\n  color: #000;\n}\n\nul {\n  margin-bottom: 0;\n}\n\n.list-inline > li {\n  padding-left: 15px;\n  padding-right: 15px;\n}\n\n.text-muted {\n  color: #90939a;\n}\n\n.navbar {\n  border: 0;\n  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .26);\n}\n\n.navbar-header {\n  float: left;\n  padding-left: 15px;\n}\n\n.navbar-nav {\n  float: left;\n  margin: 0;\n}\n\n.navbar-nav > li {\n  float: left;\n}\n\n.navbar-nav > li > a {\n  padding: 15px;\n}\n\n.navbar-default {\n  color: #fff;\n  background: #fff;\n}\n\n.navbar-default .navbar-brand {\n  color: #333;\n  background-color: #ffe939;\n}\n\n.navbar-default .navbar-brand:hover {\n  color: #ffe939;\n  background-color: #333;\n}\n\n.navbar-brand {\n  margin-left: -15px;\n  transition: 0.25s all;\n}\n\n.panel {\n  border-color: #cfd9D7;\n  border-radius: 2px;\n  box-shadow: 0 8px 17px rgba(0, 0, 0, .2);\n}\n\n.panel-default > .panel-heading {\n  font-size: 85%;\n  font-weight: bold;\n  color: #444;\n  text-transform: uppercase;\n  background-color: #f6f6f6;\n  border-color: #cfd9db;\n}\n\n.form-control {\n  border-radius: 0;\n}\n\n.center-form {\n  width: 330px;\n  margin: 12% auto;\n}\n\n.signup-or-separator {\n  position: relative;\n  height: 34px;\n  text-align: center;\n  background: none;\n}\n\n.signup-or-separator hr {\n  width: 90%;\n  margin: -16px auto 10px auto;\n  border-top: 1px solid #dce0e0;\n}\n\n.signup-or-separator .text {\n  display: inline-block;\n  padding: 8px;\n  margin: 0;\n  background-color: #fff;\n}\n\n.has-feedback .form-control-feedback {\n  top: 0;\n  left: 0;\n  width: 46px;\n  height: 46px;\n  line-height: 46px;\n  color: #555;\n}\n\n.password-strength-indicator {\n  position: absolute;\n  top: 10px;\n  right: 0;\n  width: 5px;\n  padding: 0 15px;\n}\n\n.password-strength-indicator span {\n  display: block;\n  width: 5px;\n  height: 5px;\n  margin-bottom: 2px;\n  background: #ebeef1;\n  border-radius: 5px;\n}\n\n[class^='ion-'] {\n  font-size: 1.2em;\n}\n\n.has-feedback .form-control {\n  padding-left: 42.5px;\n}\n\n.alert-material {\n  position: fixed;\n  right: 12px;\n  bottom: 12px;\n  z-index: 1;\n  display: inline-block;\n  min-height: 48px;\n  padding: 13px 24px 12px;\n  font-family: 'Roboto', sans-serif;\n  color: #f1f1f1;\n  cursor: default;\n  background: #323232;\n  border-radius: 2px;\n  outline: none;\n  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);\n}\n\n.profile-picture {\n  height: 100px;\n  display: block;\n}\n\n.btn {\n  font-weight: bold;\n  border-radius: 2px;\n  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .26);\n}\n\n.btn-primary {\n  background-color: #4285f4;\n}\n\n.btn-primary:hover {\n  background-color: #3367d6;\n}\n\n.btn-success {\n  background-color: #0f9d58;\n}\n\n.btn-success:hover {\n  background-color: #196c4a;\n}\n\n.btn-danger {\n  background-color: #db4437;\n}\n\n.btn-danger:hover {\n  background-color: #b04c3b;\n}\n\n.btn-group-vertical .btn {\n  margin-bottom: 10px;\n}\n\n.btn-group-vertical > .btn:first-child:not(:last-child) {\n  border-radius: 2px;\n}\n\n.btn-group-vertical > .btn:not(:first-child):not(:last-child) {\n  border-radius: 2px;\n}\n\n.btn-group-vertical > .btn:last-child:not(:first-child) {\n  border-radius: 2px;\n}\n\n.btn-lg {\n  font-size: 14px;\n}\n\n.btn [class^='ion-'] {\n  margin-right: 5px;\n}\n\n.btn .fa {\n  margin-right: 5px;\n}\n\n/*********************\n* Social Buttons\n*********************/\n\n.btn-google-plus {\n  color: #fff;\n  background-color: #dd4b39;\n  border: 1px solid #d54331;\n}\n\n.btn-google-plus:hover,\n.btn-google-plus:focus {\n  color: #fff;\n  background-color: #cb3927;\n}\n\n.btn-facebook {\n  color: #fff;\n  background-color: #3b5998;\n  border: 1px solid #335190;\n}\n\n.btn-facebook:hover,\n.btn-facebook:focus {\n  color: #fff;\n  background-color: #294786;\n}\n\n.btn-linkedin {\n  color: #fff;\n  background-color: #007bb6;\n  border: 1px solid #0073ae;\n}\n\n.btn-linkedin:hover,\n.btn-linkedin:focus {\n  color: #fff;\n  background-color: #0069a4;\n}\n\n.btn-twitter {\n  color: #fff;\n  background-color: #00aced;\n  border: 1px solid #009fdb;\n}\n\n.btn-twitter:hover,\n.btn-twitter:focus {\n  color: #fff;\n  background-color: #0090c7;\n}\n\n.btn-foursquare {\n  color: #fff;\n  background-color: #f94877;\n  border: 1px solid #f8215a;\n}\n\n.btn-foursquare:hover,\n.btn-foursquare:focus {\n  color: #fff;\n  background-color: #f71752;\n}\n\n.btn-github {\n  color: #fff;\n  background-color: #444;\n  border: 1px solid #3b3b3b;\n}\n\n.btn-github:hover,\n.btn-github:focus {\n  color: #fff;\n  background-color: #303030;\n}\n\n.btn-instagram {\n  color: #fff;\n  background-color: #3f729b;\n}\n\n.btn-instagram:hover,\n.btn-instagram:focus {\n  color: #fff;\n  background-color: #305777;\n}\n\n.btn-yahoo {\n  color: #fff;\n  background-color: #720e9e;\n}\n\n.btn-yahoo:hover,\n.btn-yahoo:focus {\n  color: #fff;\n  background-color: #600e85;\n}\n\n.btn-live {\n  color: #fff;\n  background-color: #2672ec;\n}\n\n.btn-live:hover,\n.btn-live:focus {\n  color: #fff;\n  background-color: #125acd;\n}\n\n.btn-twitch {\n  color: #fff;\n  background-color: #6441a5;\n}\n\n.btn-twitch:hover,\n.btn-twitch:focus {\n  color: #fff;\n  background-color: #7550ba;\n}\n\n.btn-bitbucket {\n  color: #fff;\n  background-color: #10375e;\n}\n\n.btn-bitbucket:hover,\n.btn-bitbucket:focus {\n  color: #fff;\n  background-color: #0d2c4a;\n}\n\n.btn-spotify {\n  color: #fff;\n  background-color: #2ebd59;\n}\n\n.btn-spotify:hover,\n.btn-spotify:focus {\n  color: #fff;\n  background-color: #29a34e;\n}\n\n/*********************\n* Animations\n*********************/\n\n.fadeZoom.ng-enter {\n  -webkit-animation-duration: 0.6s, 0.2s;\n  -moz-animation-duration: 0.2s, 0.2s;\n  -ms-animation-duration: 0.2s, 0.2s;\n  animation-duration: 0.2, 0.2s;\n  -webkit-animation-name: fadeIn, zoomIn;\n  -moz-animation-name: fadeIn, zoomIn;\n  -ms-animation-name: fadeIn, zoomIn;\n  animation-name: fadeIn, zoomIn;\n}\n\n.fadeZoomFadeDown.ng-enter {\n  -webkit-animation-duration: 0.2s, 0.2s;\n  -moz-animation-duration: 0.2s, 0.2s;\n  -ms-animation-duration: 0.2s, 0.2s;\n  animation-duration: 0.2s, 0.2s;\n  -webkit-animation-name: fadeIn, zoomIn;\n  -moz-animation-name: fadeIn, zoomIn;\n  -ms-animation-name: fadeIn, zoomIn;\n  animation-name: fadeIn, zoomIn;\n}\n\n.fadeZoomFadeDown.ng-leave {\n  -webkit-animation: fadeOutDown 0.2s;\n  -moz-animation: fadeOutDown 0.2s;\n  -ms-animation: fadeOutDown 0.2s;\n  animation: fadeOutDown 0.2s;\n}\n\n@-webkit-keyframes zoomIn {\n  0% {\n    opacity: 0;\n    -webkit-transform: scale3d(0.8, 0.8, 0.8);\n    -moz-transform: scale3d(0.8, 0.8, 0.8);\n    -ms-transform: scale3d(0.8, 0.8, 0.8);\n    transform: scale3d(0.8, 0.8, 0.8);\n  }\n\n  50% {\n    opacity: 1;\n  }\n}\n\n@keyframes zoomIn {\n  0% {\n    opacity: 0;\n    -webkit-transform: scale3d(0.8, 0.8, 0.8);\n    -moz-transform: scale3d(0.8, 0.8, 0.8);\n    -ms-transform: scale3d(0.8, 0.8, 0.8);\n    transform: scale3d(0.8, 0.8, 0.8);\n  }\n\n  50% {\n    opacity: 1;\n  }\n}\n"
  },
  {
    "path": "examples/client/vendor/angular-animate.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* jshint ignore:start */\nvar noop        = angular.noop;\nvar extend      = angular.extend;\nvar jqLite      = angular.element;\nvar forEach     = angular.forEach;\nvar isArray     = angular.isArray;\nvar isString    = angular.isString;\nvar isObject    = angular.isObject;\nvar isUndefined = angular.isUndefined;\nvar isDefined   = angular.isDefined;\nvar isFunction  = angular.isFunction;\nvar isElement   = angular.isElement;\n\nvar ELEMENT_NODE = 1;\nvar COMMENT_NODE = 8;\n\nvar ADD_CLASS_SUFFIX = '-add';\nvar REMOVE_CLASS_SUFFIX = '-remove';\nvar EVENT_CLASS_PREFIX = 'ng-';\nvar ACTIVE_CLASS_SUFFIX = '-active';\n\nvar NG_ANIMATE_CLASSNAME = 'ng-animate';\nvar NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';\n\n// Detect proper transitionend/animationend event names.\nvar CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;\n\n// If unprefixed events are not supported but webkit-prefixed are, use the latter.\n// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.\n// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`\n// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.\n// Register both events in case `window.onanimationend` is not supported because of that,\n// do the same for `transitionend` as Safari is likely to exhibit similar behavior.\n// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit\n// therefore there is no reason to test anymore for other vendor prefixes:\n// http://caniuse.com/#search=transition\nif (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) {\n  CSS_PREFIX = '-webkit-';\n  TRANSITION_PROP = 'WebkitTransition';\n  TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';\n} else {\n  TRANSITION_PROP = 'transition';\n  TRANSITIONEND_EVENT = 'transitionend';\n}\n\nif (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) {\n  CSS_PREFIX = '-webkit-';\n  ANIMATION_PROP = 'WebkitAnimation';\n  ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';\n} else {\n  ANIMATION_PROP = 'animation';\n  ANIMATIONEND_EVENT = 'animationend';\n}\n\nvar DURATION_KEY = 'Duration';\nvar PROPERTY_KEY = 'Property';\nvar DELAY_KEY = 'Delay';\nvar TIMING_KEY = 'TimingFunction';\nvar ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';\nvar ANIMATION_PLAYSTATE_KEY = 'PlayState';\nvar SAFE_FAST_FORWARD_DURATION_VALUE = 9999;\n\nvar ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;\nvar ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;\nvar TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;\nvar TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;\n\nvar isPromiseLike = function(p) {\n  return p && p.then ? true : false;\n};\n\nfunction assertArg(arg, name, reason) {\n  if (!arg) {\n    throw ngMinErr('areq', \"Argument '{0}' is {1}\", (name || '?'), (reason || \"required\"));\n  }\n  return arg;\n}\n\nfunction mergeClasses(a,b) {\n  if (!a && !b) return '';\n  if (!a) return b;\n  if (!b) return a;\n  if (isArray(a)) a = a.join(' ');\n  if (isArray(b)) b = b.join(' ');\n  return a + ' ' + b;\n}\n\nfunction packageStyles(options) {\n  var styles = {};\n  if (options && (options.to || options.from)) {\n    styles.to = options.to;\n    styles.from = options.from;\n  }\n  return styles;\n}\n\nfunction pendClasses(classes, fix, isPrefix) {\n  var className = '';\n  classes = isArray(classes)\n      ? classes\n      : classes && isString(classes) && classes.length\n          ? classes.split(/\\s+/)\n          : [];\n  forEach(classes, function(klass, i) {\n    if (klass && klass.length > 0) {\n      className += (i > 0) ? ' ' : '';\n      className += isPrefix ? fix + klass\n                            : klass + fix;\n    }\n  });\n  return className;\n}\n\nfunction removeFromArray(arr, val) {\n  var index = arr.indexOf(val);\n  if (val >= 0) {\n    arr.splice(index, 1);\n  }\n}\n\nfunction stripCommentsFromElement(element) {\n  if (element instanceof jqLite) {\n    switch (element.length) {\n      case 0:\n        return [];\n        break;\n\n      case 1:\n        // there is no point of stripping anything if the element\n        // is the only element within the jqLite wrapper.\n        // (it's important that we retain the element instance.)\n        if (element[0].nodeType === ELEMENT_NODE) {\n          return element;\n        }\n        break;\n\n      default:\n        return jqLite(extractElementNode(element));\n        break;\n    }\n  }\n\n  if (element.nodeType === ELEMENT_NODE) {\n    return jqLite(element);\n  }\n}\n\nfunction extractElementNode(element) {\n  if (!element[0]) return element;\n  for (var i = 0; i < element.length; i++) {\n    var elm = element[i];\n    if (elm.nodeType == ELEMENT_NODE) {\n      return elm;\n    }\n  }\n}\n\nfunction $$addClass($$jqLite, element, className) {\n  forEach(element, function(elm) {\n    $$jqLite.addClass(elm, className);\n  });\n}\n\nfunction $$removeClass($$jqLite, element, className) {\n  forEach(element, function(elm) {\n    $$jqLite.removeClass(elm, className);\n  });\n}\n\nfunction applyAnimationClassesFactory($$jqLite) {\n  return function(element, options) {\n    if (options.addClass) {\n      $$addClass($$jqLite, element, options.addClass);\n      options.addClass = null;\n    }\n    if (options.removeClass) {\n      $$removeClass($$jqLite, element, options.removeClass);\n      options.removeClass = null;\n    }\n  }\n}\n\nfunction prepareAnimationOptions(options) {\n  options = options || {};\n  if (!options.$$prepared) {\n    var domOperation = options.domOperation || noop;\n    options.domOperation = function() {\n      options.$$domOperationFired = true;\n      domOperation();\n      domOperation = noop;\n    };\n    options.$$prepared = true;\n  }\n  return options;\n}\n\nfunction applyAnimationStyles(element, options) {\n  applyAnimationFromStyles(element, options);\n  applyAnimationToStyles(element, options);\n}\n\nfunction applyAnimationFromStyles(element, options) {\n  if (options.from) {\n    element.css(options.from);\n    options.from = null;\n  }\n}\n\nfunction applyAnimationToStyles(element, options) {\n  if (options.to) {\n    element.css(options.to);\n    options.to = null;\n  }\n}\n\nfunction mergeAnimationOptions(element, target, newOptions) {\n  var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');\n  var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');\n  var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);\n\n  if (newOptions.preparationClasses) {\n    target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);\n    delete newOptions.preparationClasses;\n  }\n\n  // noop is basically when there is no callback; otherwise something has been set\n  var realDomOperation = target.domOperation !== noop ? target.domOperation : null;\n\n  extend(target, newOptions);\n\n  // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.\n  if (realDomOperation) {\n    target.domOperation = realDomOperation;\n  }\n\n  if (classes.addClass) {\n    target.addClass = classes.addClass;\n  } else {\n    target.addClass = null;\n  }\n\n  if (classes.removeClass) {\n    target.removeClass = classes.removeClass;\n  } else {\n    target.removeClass = null;\n  }\n\n  return target;\n}\n\nfunction resolveElementClasses(existing, toAdd, toRemove) {\n  var ADD_CLASS = 1;\n  var REMOVE_CLASS = -1;\n\n  var flags = {};\n  existing = splitClassesToLookup(existing);\n\n  toAdd = splitClassesToLookup(toAdd);\n  forEach(toAdd, function(value, key) {\n    flags[key] = ADD_CLASS;\n  });\n\n  toRemove = splitClassesToLookup(toRemove);\n  forEach(toRemove, function(value, key) {\n    flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;\n  });\n\n  var classes = {\n    addClass: '',\n    removeClass: ''\n  };\n\n  forEach(flags, function(val, klass) {\n    var prop, allow;\n    if (val === ADD_CLASS) {\n      prop = 'addClass';\n      allow = !existing[klass];\n    } else if (val === REMOVE_CLASS) {\n      prop = 'removeClass';\n      allow = existing[klass];\n    }\n    if (allow) {\n      if (classes[prop].length) {\n        classes[prop] += ' ';\n      }\n      classes[prop] += klass;\n    }\n  });\n\n  function splitClassesToLookup(classes) {\n    if (isString(classes)) {\n      classes = classes.split(' ');\n    }\n\n    var obj = {};\n    forEach(classes, function(klass) {\n      // sometimes the split leaves empty string values\n      // incase extra spaces were applied to the options\n      if (klass.length) {\n        obj[klass] = true;\n      }\n    });\n    return obj;\n  }\n\n  return classes;\n}\n\nfunction getDomNode(element) {\n  return (element instanceof angular.element) ? element[0] : element;\n}\n\nfunction applyGeneratedPreparationClasses(element, event, options) {\n  var classes = '';\n  if (event) {\n    classes = pendClasses(event, EVENT_CLASS_PREFIX, true);\n  }\n  if (options.addClass) {\n    classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));\n  }\n  if (options.removeClass) {\n    classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));\n  }\n  if (classes.length) {\n    options.preparationClasses = classes;\n    element.addClass(classes);\n  }\n}\n\nfunction clearGeneratedClasses(element, options) {\n  if (options.preparationClasses) {\n    element.removeClass(options.preparationClasses);\n    options.preparationClasses = null;\n  }\n  if (options.activeClasses) {\n    element.removeClass(options.activeClasses);\n    options.activeClasses = null;\n  }\n}\n\nfunction blockTransitions(node, duration) {\n  // we use a negative delay value since it performs blocking\n  // yet it doesn't kill any existing transitions running on the\n  // same element which makes this safe for class-based animations\n  var value = duration ? '-' + duration + 's' : '';\n  applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);\n  return [TRANSITION_DELAY_PROP, value];\n}\n\nfunction blockKeyframeAnimations(node, applyBlock) {\n  var value = applyBlock ? 'paused' : '';\n  var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;\n  applyInlineStyle(node, [key, value]);\n  return [key, value];\n}\n\nfunction applyInlineStyle(node, styleTuple) {\n  var prop = styleTuple[0];\n  var value = styleTuple[1];\n  node.style[prop] = value;\n}\n\nfunction concatWithSpace(a,b) {\n  if (!a) return b;\n  if (!b) return a;\n  return a + ' ' + b;\n}\n\nvar $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {\n  var queue, cancelFn;\n\n  function scheduler(tasks) {\n    // we make a copy since RAFScheduler mutates the state\n    // of the passed in array variable and this would be difficult\n    // to track down on the outside code\n    queue = queue.concat(tasks);\n    nextTick();\n  }\n\n  queue = scheduler.queue = [];\n\n  /* waitUntilQuiet does two things:\n   * 1. It will run the FINAL `fn` value only when an uncancelled RAF has passed through\n   * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.\n   *\n   * The motivation here is that animation code can request more time from the scheduler\n   * before the next wave runs. This allows for certain DOM properties such as classes to\n   * be resolved in time for the next animation to run.\n   */\n  scheduler.waitUntilQuiet = function(fn) {\n    if (cancelFn) cancelFn();\n\n    cancelFn = $$rAF(function() {\n      cancelFn = null;\n      fn();\n      nextTick();\n    });\n  };\n\n  return scheduler;\n\n  function nextTick() {\n    if (!queue.length) return;\n\n    var items = queue.shift();\n    for (var i = 0; i < items.length; i++) {\n      items[i]();\n    }\n\n    if (!cancelFn) {\n      $$rAF(function() {\n        if (!cancelFn) nextTick();\n      });\n    }\n  }\n}];\n\nvar $$AnimateChildrenDirective = [function() {\n  return function(scope, element, attrs) {\n    var val = attrs.ngAnimateChildren;\n    if (angular.isString(val) && val.length === 0) { //empty attribute\n      element.data(NG_ANIMATE_CHILDREN_DATA, true);\n    } else {\n      attrs.$observe('ngAnimateChildren', function(value) {\n        value = value === 'on' || value === 'true';\n        element.data(NG_ANIMATE_CHILDREN_DATA, value);\n      });\n    }\n  };\n}];\n\nvar ANIMATE_TIMER_KEY = '$$animateCss';\n\n/**\n * @ngdoc service\n * @name $animateCss\n * @kind object\n *\n * @description\n * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes\n * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT\n * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or\n * directives to create more complex animations that can be purely driven using CSS code.\n *\n * Note that only browsers that support CSS transitions and/or keyframe animations are capable of\n * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).\n *\n * ## Usage\n * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that\n * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,\n * any automatic control over cancelling animations and/or preventing animations from being run on\n * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to\n * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger\n * the CSS animation.\n *\n * The example below shows how we can create a folding animation on an element using `ng-if`:\n *\n * ```html\n * <!-- notice the `fold-animation` CSS class -->\n * <div ng-if=\"onOff\" class=\"fold-animation\">\n *   This element will go BOOM\n * </div>\n * <button ng-click=\"onOff=true\">Fold In</button>\n * ```\n *\n * Now we create the **JavaScript animation** that will trigger the CSS transition:\n *\n * ```js\n * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n *       var height = element[0].offsetHeight;\n *       return $animateCss(element, {\n *         from: { height:'0px' },\n *         to: { height:height + 'px' },\n *         duration: 1 // one second\n *       });\n *     }\n *   }\n * }]);\n * ```\n *\n * ## More Advanced Uses\n *\n * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks\n * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.\n *\n * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,\n * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with\n * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order\n * to provide a working animation that will run in CSS.\n *\n * The example below showcases a more advanced version of the `.fold-animation` from the example above:\n *\n * ```js\n * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n *       var height = element[0].offsetHeight;\n *       return $animateCss(element, {\n *         addClass: 'red large-text pulse-twice',\n *         easing: 'ease-out',\n *         from: { height:'0px' },\n *         to: { height:height + 'px' },\n *         duration: 1 // one second\n *       });\n *     }\n *   }\n * }]);\n * ```\n *\n * Since we're adding/removing CSS classes then the CSS transition will also pick those up:\n *\n * ```css\n * /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,\n * the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/\n * .red { background:red; }\n * .large-text { font-size:20px; }\n *\n * /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/\n * .pulse-twice {\n *   animation: 0.5s pulse linear 2;\n *   -webkit-animation: 0.5s pulse linear 2;\n * }\n *\n * @keyframes pulse {\n *   from { transform: scale(0.5); }\n *   to { transform: scale(1.5); }\n * }\n *\n * @-webkit-keyframes pulse {\n *   from { -webkit-transform: scale(0.5); }\n *   to { -webkit-transform: scale(1.5); }\n * }\n * ```\n *\n * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.\n *\n * ## How the Options are handled\n *\n * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation\n * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline\n * styles using the `from` and `to` properties.\n *\n * ```js\n * var animator = $animateCss(element, {\n *   from: { background:'red' },\n *   to: { background:'blue' }\n * });\n * animator.start();\n * ```\n *\n * ```css\n * .rotating-animation {\n *   animation:0.5s rotate linear;\n *   -webkit-animation:0.5s rotate linear;\n * }\n *\n * @keyframes rotate {\n *   from { transform: rotate(0deg); }\n *   to { transform: rotate(360deg); }\n * }\n *\n * @-webkit-keyframes rotate {\n *   from { -webkit-transform: rotate(0deg); }\n *   to { -webkit-transform: rotate(360deg); }\n * }\n * ```\n *\n * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is\n * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition\n * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition\n * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied\n * and spread across the transition and keyframe animation.\n *\n * ## What is returned\n *\n * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually\n * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are\n * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:\n *\n * ```js\n * var animator = $animateCss(element, { ... });\n * ```\n *\n * Now what do the contents of our `animator` variable look like:\n *\n * ```js\n * {\n *   // starts the animation\n *   start: Function,\n *\n *   // ends (aborts) the animation\n *   end: Function\n * }\n * ```\n *\n * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.\n * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and stlyes may have been\n * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties\n * and that changing them will not reconfigure the parameters of the animation.\n *\n * ### runner.done() vs runner.then()\n * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the\n * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.\n * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`\n * unless you really need a digest to kick off afterwards.\n *\n * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss\n * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).\n * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.\n *\n * @param {DOMElement} element the element that will be animated\n * @param {object} options the animation-related options that will be applied during the animation\n *\n * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied\n * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)\n * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).\n * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).\n * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).\n * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.\n * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.\n * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.\n * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.\n * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`\n * is provided then the animation will be skipped entirely.\n * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is\n * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value\n * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same\n * CSS delay value.\n * * `stagger` - A numeric time value representing the delay between successively animated elements\n * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})\n * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a\n * * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)\n * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occuring on the classes being added and removed.)\n * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once\n *    the animation is closed. This is useful for when the styles are used purely for the sake of\n *    the animation and do not have a lasting visual effect on the element (e.g. a colapse and open animation).\n *    By default this value is set to `false`.\n *\n * @return {object} an object with start and end methods and details about the animation.\n *\n * * `start` - The method to start the animation. This will return a `Promise` when called.\n * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.\n */\nvar ONE_SECOND = 1000;\nvar BASE_TEN = 10;\n\nvar ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;\nvar CLOSING_TIME_BUFFER = 1.5;\n\nvar DETECT_CSS_PROPERTIES = {\n  transitionDuration:      TRANSITION_DURATION_PROP,\n  transitionDelay:         TRANSITION_DELAY_PROP,\n  transitionProperty:      TRANSITION_PROP + PROPERTY_KEY,\n  animationDuration:       ANIMATION_DURATION_PROP,\n  animationDelay:          ANIMATION_DELAY_PROP,\n  animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY\n};\n\nvar DETECT_STAGGER_CSS_PROPERTIES = {\n  transitionDuration:      TRANSITION_DURATION_PROP,\n  transitionDelay:         TRANSITION_DELAY_PROP,\n  animationDuration:       ANIMATION_DURATION_PROP,\n  animationDelay:          ANIMATION_DELAY_PROP\n};\n\nfunction getCssKeyframeDurationStyle(duration) {\n  return [ANIMATION_DURATION_PROP, duration + 's'];\n}\n\nfunction getCssDelayStyle(delay, isKeyframeAnimation) {\n  var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;\n  return [prop, delay + 's'];\n}\n\nfunction computeCssStyles($window, element, properties) {\n  var styles = Object.create(null);\n  var detectedStyles = $window.getComputedStyle(element) || {};\n  forEach(properties, function(formalStyleName, actualStyleName) {\n    var val = detectedStyles[formalStyleName];\n    if (val) {\n      var c = val.charAt(0);\n\n      // only numerical-based values have a negative sign or digit as the first value\n      if (c === '-' || c === '+' || c >= 0) {\n        val = parseMaxTime(val);\n      }\n\n      // by setting this to null in the event that the delay is not set or is set directly as 0\n      // then we can still allow for zegative values to be used later on and not mistake this\n      // value for being greater than any other negative value.\n      if (val === 0) {\n        val = null;\n      }\n      styles[actualStyleName] = val;\n    }\n  });\n\n  return styles;\n}\n\nfunction parseMaxTime(str) {\n  var maxValue = 0;\n  var values = str.split(/\\s*,\\s*/);\n  forEach(values, function(value) {\n    // it's always safe to consider only second values and omit `ms` values since\n    // getComputedStyle will always handle the conversion for us\n    if (value.charAt(value.length - 1) == 's') {\n      value = value.substring(0, value.length - 1);\n    }\n    value = parseFloat(value) || 0;\n    maxValue = maxValue ? Math.max(value, maxValue) : value;\n  });\n  return maxValue;\n}\n\nfunction truthyTimingValue(val) {\n  return val === 0 || val != null;\n}\n\nfunction getCssTransitionDurationStyle(duration, applyOnlyDuration) {\n  var style = TRANSITION_PROP;\n  var value = duration + 's';\n  if (applyOnlyDuration) {\n    style += DURATION_KEY;\n  } else {\n    value += ' linear all';\n  }\n  return [style, value];\n}\n\nfunction createLocalCacheLookup() {\n  var cache = Object.create(null);\n  return {\n    flush: function() {\n      cache = Object.create(null);\n    },\n\n    count: function(key) {\n      var entry = cache[key];\n      return entry ? entry.total : 0;\n    },\n\n    get: function(key) {\n      var entry = cache[key];\n      return entry && entry.value;\n    },\n\n    put: function(key, value) {\n      if (!cache[key]) {\n        cache[key] = { total: 1, value: value };\n      } else {\n        cache[key].total++;\n      }\n    }\n  };\n}\n\n// we do not reassign an already present style value since\n// if we detect the style property value again we may be\n// detecting styles that were added via the `from` styles.\n// We make use of `isDefined` here since an empty string\n// or null value (which is what getPropertyValue will return\n// for a non-existing style) will still be marked as a valid\n// value for the style (a falsy value implies that the style\n// is to be removed at the end of the animation). If we had a simple\n// \"OR\" statement then it would not be enough to catch that.\nfunction registerRestorableStyles(backup, node, properties) {\n  forEach(properties, function(prop) {\n    backup[prop] = isDefined(backup[prop])\n        ? backup[prop]\n        : node.style.getPropertyValue(prop);\n  });\n}\n\nvar $AnimateCssProvider = ['$animateProvider', function($animateProvider) {\n  var gcsLookup = createLocalCacheLookup();\n  var gcsStaggerLookup = createLocalCacheLookup();\n\n  this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',\n               '$$forceReflow', '$sniffer', '$$rAFScheduler', '$animate',\n       function($window,   $$jqLite,   $$AnimateRunner,   $timeout,\n                $$forceReflow,   $sniffer,   $$rAFScheduler, $animate) {\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    var parentCounter = 0;\n    function gcsHashFn(node, extraClasses) {\n      var KEY = \"$$ngAnimateParentKey\";\n      var parentNode = node.parentNode;\n      var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);\n      return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;\n    }\n\n    function computeCachedCssStyles(node, className, cacheKey, properties) {\n      var timings = gcsLookup.get(cacheKey);\n\n      if (!timings) {\n        timings = computeCssStyles($window, node, properties);\n        if (timings.animationIterationCount === 'infinite') {\n          timings.animationIterationCount = 1;\n        }\n      }\n\n      // we keep putting this in multiple times even though the value and the cacheKey are the same\n      // because we're keeping an interal tally of how many duplicate animations are detected.\n      gcsLookup.put(cacheKey, timings);\n      return timings;\n    }\n\n    function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {\n      var stagger;\n\n      // if we have one or more existing matches of matching elements\n      // containing the same parent + CSS styles (which is how cacheKey works)\n      // then staggering is possible\n      if (gcsLookup.count(cacheKey) > 0) {\n        stagger = gcsStaggerLookup.get(cacheKey);\n\n        if (!stagger) {\n          var staggerClassName = pendClasses(className, '-stagger');\n\n          $$jqLite.addClass(node, staggerClassName);\n\n          stagger = computeCssStyles($window, node, properties);\n\n          // force the conversion of a null value to zero incase not set\n          stagger.animationDuration = Math.max(stagger.animationDuration, 0);\n          stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);\n\n          $$jqLite.removeClass(node, staggerClassName);\n\n          gcsStaggerLookup.put(cacheKey, stagger);\n        }\n      }\n\n      return stagger || {};\n    }\n\n    var cancelLastRAFRequest;\n    var rafWaitQueue = [];\n    function waitUntilQuiet(callback) {\n      rafWaitQueue.push(callback);\n      $$rAFScheduler.waitUntilQuiet(function() {\n        gcsLookup.flush();\n        gcsStaggerLookup.flush();\n\n        // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.\n        // PLEASE EXAMINE THE `$$forceReflow` service to understand why.\n        var pageWidth = $$forceReflow();\n\n        // we use a for loop to ensure that if the queue is changed\n        // during this looping then it will consider new requests\n        for (var i = 0; i < rafWaitQueue.length; i++) {\n          rafWaitQueue[i](pageWidth);\n        }\n        rafWaitQueue.length = 0;\n      });\n    }\n\n    function computeTimings(node, className, cacheKey) {\n      var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);\n      var aD = timings.animationDelay;\n      var tD = timings.transitionDelay;\n      timings.maxDelay = aD && tD\n          ? Math.max(aD, tD)\n          : (aD || tD);\n      timings.maxDuration = Math.max(\n          timings.animationDuration * timings.animationIterationCount,\n          timings.transitionDuration);\n\n      return timings;\n    }\n\n    return function init(element, options) {\n      var restoreStyles = {};\n      var node = getDomNode(element);\n      if (!node\n          || !node.parentNode\n          || !$animate.enabled()) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      options = prepareAnimationOptions(options);\n\n      var temporaryStyles = [];\n      var classes = element.attr('class');\n      var styles = packageStyles(options);\n      var animationClosed;\n      var animationPaused;\n      var animationCompleted;\n      var runner;\n      var runnerHost;\n      var maxDelay;\n      var maxDelayTime;\n      var maxDuration;\n      var maxDurationTime;\n\n      if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      var method = options.event && isArray(options.event)\n            ? options.event.join(' ')\n            : options.event;\n\n      var isStructural = method && options.structural;\n      var structuralClassName = '';\n      var addRemoveClassName = '';\n\n      if (isStructural) {\n        structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);\n      } else if (method) {\n        structuralClassName = method;\n      }\n\n      if (options.addClass) {\n        addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);\n      }\n\n      if (options.removeClass) {\n        if (addRemoveClassName.length) {\n          addRemoveClassName += ' ';\n        }\n        addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);\n      }\n\n      // there may be a situation where a structural animation is combined together\n      // with CSS classes that need to resolve before the animation is computed.\n      // However this means that there is no explicit CSS code to block the animation\n      // from happening (by setting 0s none in the class name). If this is the case\n      // we need to apply the classes before the first rAF so we know to continue if\n      // there actually is a detected transition or keyframe animation\n      if (options.applyClassesEarly && addRemoveClassName.length) {\n        applyAnimationClasses(element, options);\n      }\n\n      var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();\n      var fullClassName = classes + ' ' + preparationClasses;\n      var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);\n      var hasToStyles = styles.to && Object.keys(styles.to).length > 0;\n      var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;\n\n      // there is no way we can trigger an animation if no styles and\n      // no classes are being applied which would then trigger a transition,\n      // unless there a is raw keyframe value that is applied to the element.\n      if (!containsKeyframeAnimation\n           && !hasToStyles\n           && !preparationClasses) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      var cacheKey, stagger;\n      if (options.stagger > 0) {\n        var staggerVal = parseFloat(options.stagger);\n        stagger = {\n          transitionDelay: staggerVal,\n          animationDelay: staggerVal,\n          transitionDuration: 0,\n          animationDuration: 0\n        };\n      } else {\n        cacheKey = gcsHashFn(node, fullClassName);\n        stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);\n      }\n\n      if (!options.$$skipPreparationClasses) {\n        $$jqLite.addClass(element, preparationClasses);\n      }\n\n      var applyOnlyDuration;\n\n      if (options.transitionStyle) {\n        var transitionStyle = [TRANSITION_PROP, options.transitionStyle];\n        applyInlineStyle(node, transitionStyle);\n        temporaryStyles.push(transitionStyle);\n      }\n\n      if (options.duration >= 0) {\n        applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;\n        var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);\n\n        // we set the duration so that it will be picked up by getComputedStyle later\n        applyInlineStyle(node, durationStyle);\n        temporaryStyles.push(durationStyle);\n      }\n\n      if (options.keyframeStyle) {\n        var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];\n        applyInlineStyle(node, keyframeStyle);\n        temporaryStyles.push(keyframeStyle);\n      }\n\n      var itemIndex = stagger\n          ? options.staggerIndex >= 0\n              ? options.staggerIndex\n              : gcsLookup.count(cacheKey)\n          : 0;\n\n      var isFirst = itemIndex === 0;\n\n      // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY\n      // without causing any combination of transitions to kick in. By adding a negative delay value\n      // it forces the setup class' transition to end immediately. We later then remove the negative\n      // transition delay to allow for the transition to naturally do it's thing. The beauty here is\n      // that if there is no transition defined then nothing will happen and this will also allow\n      // other transitions to be stacked on top of each other without any chopping them out.\n      if (isFirst && !options.skipBlocking) {\n        blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);\n      }\n\n      var timings = computeTimings(node, fullClassName, cacheKey);\n      var relativeDelay = timings.maxDelay;\n      maxDelay = Math.max(relativeDelay, 0);\n      maxDuration = timings.maxDuration;\n\n      var flags = {};\n      flags.hasTransitions          = timings.transitionDuration > 0;\n      flags.hasAnimations           = timings.animationDuration > 0;\n      flags.hasTransitionAll        = flags.hasTransitions && timings.transitionProperty == 'all';\n      flags.applyTransitionDuration = hasToStyles && (\n                                        (flags.hasTransitions && !flags.hasTransitionAll)\n                                         || (flags.hasAnimations && !flags.hasTransitions));\n      flags.applyAnimationDuration  = options.duration && flags.hasAnimations;\n      flags.applyTransitionDelay    = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);\n      flags.applyAnimationDelay     = truthyTimingValue(options.delay) && flags.hasAnimations;\n      flags.recalculateTimingStyles = addRemoveClassName.length > 0;\n\n      if (flags.applyTransitionDuration || flags.applyAnimationDuration) {\n        maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;\n\n        if (flags.applyTransitionDuration) {\n          flags.hasTransitions = true;\n          timings.transitionDuration = maxDuration;\n          applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;\n          temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));\n        }\n\n        if (flags.applyAnimationDuration) {\n          flags.hasAnimations = true;\n          timings.animationDuration = maxDuration;\n          temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));\n        }\n      }\n\n      if (maxDuration === 0 && !flags.recalculateTimingStyles) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      if (options.delay != null) {\n        var delayStyle = parseFloat(options.delay);\n\n        if (flags.applyTransitionDelay) {\n          temporaryStyles.push(getCssDelayStyle(delayStyle));\n        }\n\n        if (flags.applyAnimationDelay) {\n          temporaryStyles.push(getCssDelayStyle(delayStyle, true));\n        }\n      }\n\n      // we need to recalculate the delay value since we used a pre-emptive negative\n      // delay value and the delay value is required for the final event checking. This\n      // property will ensure that this will happen after the RAF phase has passed.\n      if (options.duration == null && timings.transitionDuration > 0) {\n        flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;\n      }\n\n      maxDelayTime = maxDelay * ONE_SECOND;\n      maxDurationTime = maxDuration * ONE_SECOND;\n      if (!options.skipBlocking) {\n        flags.blockTransition = timings.transitionDuration > 0;\n        flags.blockKeyframeAnimation = timings.animationDuration > 0 &&\n                                       stagger.animationDelay > 0 &&\n                                       stagger.animationDuration === 0;\n      }\n\n      if (options.from) {\n        if (options.cleanupStyles) {\n          registerRestorableStyles(restoreStyles, node, Object.keys(options.from));\n        }\n        applyAnimationFromStyles(element, options);\n      }\n\n      if (flags.blockTransition || flags.blockKeyframeAnimation) {\n        applyBlocking(maxDuration);\n      } else if (!options.skipBlocking) {\n        blockTransitions(node, false);\n      }\n\n      // TODO(matsko): for 1.5 change this code to have an animator object for better debugging\n      return {\n        $$willAnimate: true,\n        end: endFn,\n        start: function() {\n          if (animationClosed) return;\n\n          runnerHost = {\n            end: endFn,\n            cancel: cancelFn,\n            resume: null, //this will be set during the start() phase\n            pause: null\n          };\n\n          runner = new $$AnimateRunner(runnerHost);\n\n          waitUntilQuiet(start);\n\n          // we don't have access to pause/resume the animation\n          // since it hasn't run yet. AnimateRunner will therefore\n          // set noop functions for resume and pause and they will\n          // later be overridden once the animation is triggered\n          return runner;\n        }\n      };\n\n      function endFn() {\n        close();\n      }\n\n      function cancelFn() {\n        close(true);\n      }\n\n      function close(rejected) { // jshint ignore:line\n        // if the promise has been called already then we shouldn't close\n        // the animation again\n        if (animationClosed || (animationCompleted && animationPaused)) return;\n        animationClosed = true;\n        animationPaused = false;\n\n        if (!options.$$skipPreparationClasses) {\n          $$jqLite.removeClass(element, preparationClasses);\n        }\n        $$jqLite.removeClass(element, activeClasses);\n\n        blockKeyframeAnimations(node, false);\n        blockTransitions(node, false);\n\n        forEach(temporaryStyles, function(entry) {\n          // There is only one way to remove inline style properties entirely from elements.\n          // By using `removeProperty` this works, but we need to convert camel-cased CSS\n          // styles down to hyphenated values.\n          node.style[entry[0]] = '';\n        });\n\n        applyAnimationClasses(element, options);\n        applyAnimationStyles(element, options);\n\n        if (Object.keys(restoreStyles).length) {\n          forEach(restoreStyles, function(value, prop) {\n            value ? node.style.setProperty(prop, value)\n                  : node.style.removeProperty(prop);\n          });\n        }\n\n        // the reason why we have this option is to allow a synchronous closing callback\n        // that is fired as SOON as the animation ends (when the CSS is removed) or if\n        // the animation never takes off at all. A good example is a leave animation since\n        // the element must be removed just after the animation is over or else the element\n        // will appear on screen for one animation frame causing an overbearing flicker.\n        if (options.onDone) {\n          options.onDone();\n        }\n\n        // if the preparation function fails then the promise is not setup\n        if (runner) {\n          runner.complete(!rejected);\n        }\n      }\n\n      function applyBlocking(duration) {\n        if (flags.blockTransition) {\n          blockTransitions(node, duration);\n        }\n\n        if (flags.blockKeyframeAnimation) {\n          blockKeyframeAnimations(node, !!duration);\n        }\n      }\n\n      function closeAndReturnNoopAnimator() {\n        runner = new $$AnimateRunner({\n          end: endFn,\n          cancel: cancelFn\n        });\n\n        // should flush the cache animation\n        waitUntilQuiet(noop);\n        close();\n\n        return {\n          $$willAnimate: false,\n          start: function() {\n            return runner;\n          },\n          end: endFn\n        };\n      }\n\n      function start() {\n        if (animationClosed) return;\n        if (!node.parentNode) {\n          close();\n          return;\n        }\n\n        var startTime, events = [];\n\n        // even though we only pause keyframe animations here the pause flag\n        // will still happen when transitions are used. Only the transition will\n        // not be paused since that is not possible. If the animation ends when\n        // paused then it will not complete until unpaused or cancelled.\n        var playPause = function(playAnimation) {\n          if (!animationCompleted) {\n            animationPaused = !playAnimation;\n            if (timings.animationDuration) {\n              var value = blockKeyframeAnimations(node, animationPaused);\n              animationPaused\n                  ? temporaryStyles.push(value)\n                  : removeFromArray(temporaryStyles, value);\n            }\n          } else if (animationPaused && playAnimation) {\n            animationPaused = false;\n            close();\n          }\n        };\n\n        // checking the stagger duration prevents an accidently cascade of the CSS delay style\n        // being inherited from the parent. If the transition duration is zero then we can safely\n        // rely that the delay value is an intential stagger delay style.\n        var maxStagger = itemIndex > 0\n                         && ((timings.transitionDuration && stagger.transitionDuration === 0) ||\n                            (timings.animationDuration && stagger.animationDuration === 0))\n                         && Math.max(stagger.animationDelay, stagger.transitionDelay);\n        if (maxStagger) {\n          $timeout(triggerAnimationStart,\n                   Math.floor(maxStagger * itemIndex * ONE_SECOND),\n                   false);\n        } else {\n          triggerAnimationStart();\n        }\n\n        // this will decorate the existing promise runner with pause/resume methods\n        runnerHost.resume = function() {\n          playPause(true);\n        };\n\n        runnerHost.pause = function() {\n          playPause(false);\n        };\n\n        function triggerAnimationStart() {\n          // just incase a stagger animation kicks in when the animation\n          // itself was cancelled entirely\n          if (animationClosed) return;\n\n          applyBlocking(false);\n\n          forEach(temporaryStyles, function(entry) {\n            var key = entry[0];\n            var value = entry[1];\n            node.style[key] = value;\n          });\n\n          applyAnimationClasses(element, options);\n          $$jqLite.addClass(element, activeClasses);\n\n          if (flags.recalculateTimingStyles) {\n            fullClassName = node.className + ' ' + preparationClasses;\n            cacheKey = gcsHashFn(node, fullClassName);\n\n            timings = computeTimings(node, fullClassName, cacheKey);\n            relativeDelay = timings.maxDelay;\n            maxDelay = Math.max(relativeDelay, 0);\n            maxDuration = timings.maxDuration;\n\n            if (maxDuration === 0) {\n              close();\n              return;\n            }\n\n            flags.hasTransitions = timings.transitionDuration > 0;\n            flags.hasAnimations = timings.animationDuration > 0;\n          }\n\n          if (flags.applyAnimationDelay) {\n            relativeDelay = typeof options.delay !== \"boolean\" && truthyTimingValue(options.delay)\n                  ? parseFloat(options.delay)\n                  : relativeDelay;\n\n            maxDelay = Math.max(relativeDelay, 0);\n            timings.animationDelay = relativeDelay;\n            delayStyle = getCssDelayStyle(relativeDelay, true);\n            temporaryStyles.push(delayStyle);\n            node.style[delayStyle[0]] = delayStyle[1];\n          }\n\n          maxDelayTime = maxDelay * ONE_SECOND;\n          maxDurationTime = maxDuration * ONE_SECOND;\n\n          if (options.easing) {\n            var easeProp, easeVal = options.easing;\n            if (flags.hasTransitions) {\n              easeProp = TRANSITION_PROP + TIMING_KEY;\n              temporaryStyles.push([easeProp, easeVal]);\n              node.style[easeProp] = easeVal;\n            }\n            if (flags.hasAnimations) {\n              easeProp = ANIMATION_PROP + TIMING_KEY;\n              temporaryStyles.push([easeProp, easeVal]);\n              node.style[easeProp] = easeVal;\n            }\n          }\n\n          if (timings.transitionDuration) {\n            events.push(TRANSITIONEND_EVENT);\n          }\n\n          if (timings.animationDuration) {\n            events.push(ANIMATIONEND_EVENT);\n          }\n\n          startTime = Date.now();\n          var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;\n          var endTime = startTime + timerTime;\n\n          var animationsData = element.data(ANIMATE_TIMER_KEY) || [];\n          var setupFallbackTimer = true;\n          if (animationsData.length) {\n            var currentTimerData = animationsData[0];\n            setupFallbackTimer = endTime > currentTimerData.expectedEndTime;\n            if (setupFallbackTimer) {\n              $timeout.cancel(currentTimerData.timer);\n            } else {\n              animationsData.push(close);\n            }\n          }\n\n          if (setupFallbackTimer) {\n            var timer = $timeout(onAnimationExpired, timerTime, false);\n            animationsData[0] = {\n              timer: timer,\n              expectedEndTime: endTime\n            };\n            animationsData.push(close);\n            element.data(ANIMATE_TIMER_KEY, animationsData);\n          }\n\n          element.on(events.join(' '), onAnimationProgress);\n          if (options.to) {\n            if (options.cleanupStyles) {\n              registerRestorableStyles(restoreStyles, node, Object.keys(options.to));\n            }\n            applyAnimationToStyles(element, options);\n          }\n        }\n\n        function onAnimationExpired() {\n          var animationsData = element.data(ANIMATE_TIMER_KEY);\n\n          // this will be false in the event that the element was\n          // removed from the DOM (via a leave animation or something\n          // similar)\n          if (animationsData) {\n            for (var i = 1; i < animationsData.length; i++) {\n              animationsData[i]();\n            }\n            element.removeData(ANIMATE_TIMER_KEY);\n          }\n        }\n\n        function onAnimationProgress(event) {\n          event.stopPropagation();\n          var ev = event.originalEvent || event;\n          var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();\n\n          /* Firefox (or possibly just Gecko) likes to not round values up\n           * when a ms measurement is used for the animation */\n          var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));\n\n          /* $manualTimeStamp is a mocked timeStamp value which is set\n           * within browserTrigger(). This is only here so that tests can\n           * mock animations properly. Real events fallback to event.timeStamp,\n           * or, if they don't, then a timeStamp is automatically created for them.\n           * We're checking to see if the timeStamp surpasses the expected delay,\n           * but we're using elapsedTime instead of the timeStamp on the 2nd\n           * pre-condition since animations sometimes close off early */\n          if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {\n            // we set this flag to ensure that if the transition is paused then, when resumed,\n            // the animation will automatically close itself since transitions cannot be paused.\n            animationCompleted = true;\n            close();\n          }\n        }\n      }\n    };\n  }];\n}];\n\nvar $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {\n  $$animationProvider.drivers.push('$$animateCssDriver');\n\n  var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';\n  var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';\n\n  var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';\n  var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';\n\n  function isDocumentFragment(node) {\n    return node.parentNode && node.parentNode.nodeType === 11;\n  }\n\n  this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',\n       function($animateCss,   $rootScope,   $$AnimateRunner,   $rootElement,   $sniffer,   $$jqLite,   $document) {\n\n    // only browsers that support these properties can render animations\n    if (!$sniffer.animations && !$sniffer.transitions) return noop;\n\n    var bodyNode = $document[0].body;\n    var rootNode = getDomNode($rootElement);\n\n    var rootBodyElement = jqLite(\n      // this is to avoid using something that exists outside of the body\n      // we also special case the doc fragement case because our unit test code\n      // appends the $rootElement to the body after the app has been bootstrapped\n      isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode\n    );\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    return function initDriverFn(animationDetails) {\n      return animationDetails.from && animationDetails.to\n          ? prepareFromToAnchorAnimation(animationDetails.from,\n                                         animationDetails.to,\n                                         animationDetails.classes,\n                                         animationDetails.anchors)\n          : prepareRegularAnimation(animationDetails);\n    };\n\n    function filterCssClasses(classes) {\n      //remove all the `ng-` stuff\n      return classes.replace(/\\bng-\\S+\\b/g, '');\n    }\n\n    function getUniqueValues(a, b) {\n      if (isString(a)) a = a.split(' ');\n      if (isString(b)) b = b.split(' ');\n      return a.filter(function(val) {\n        return b.indexOf(val) === -1;\n      }).join(' ');\n    }\n\n    function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {\n      var clone = jqLite(getDomNode(outAnchor).cloneNode(true));\n      var startingClasses = filterCssClasses(getClassVal(clone));\n\n      outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);\n      inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);\n\n      clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);\n\n      rootBodyElement.append(clone);\n\n      var animatorIn, animatorOut = prepareOutAnimation();\n\n      // the user may not end up using the `out` animation and\n      // only making use of the `in` animation or vice-versa.\n      // In either case we should allow this and not assume the\n      // animation is over unless both animations are not used.\n      if (!animatorOut) {\n        animatorIn = prepareInAnimation();\n        if (!animatorIn) {\n          return end();\n        }\n      }\n\n      var startingAnimator = animatorOut || animatorIn;\n\n      return {\n        start: function() {\n          var runner;\n\n          var currentAnimation = startingAnimator.start();\n          currentAnimation.done(function() {\n            currentAnimation = null;\n            if (!animatorIn) {\n              animatorIn = prepareInAnimation();\n              if (animatorIn) {\n                currentAnimation = animatorIn.start();\n                currentAnimation.done(function() {\n                  currentAnimation = null;\n                  end();\n                  runner.complete();\n                });\n                return currentAnimation;\n              }\n            }\n            // in the event that there is no `in` animation\n            end();\n            runner.complete();\n          });\n\n          runner = new $$AnimateRunner({\n            end: endFn,\n            cancel: endFn\n          });\n\n          return runner;\n\n          function endFn() {\n            if (currentAnimation) {\n              currentAnimation.end();\n            }\n          }\n        }\n      };\n\n      function calculateAnchorStyles(anchor) {\n        var styles = {};\n\n        var coords = getDomNode(anchor).getBoundingClientRect();\n\n        // we iterate directly since safari messes up and doesn't return\n        // all the keys for the coods object when iterated\n        forEach(['width','height','top','left'], function(key) {\n          var value = coords[key];\n          switch (key) {\n            case 'top':\n              value += bodyNode.scrollTop;\n              break;\n            case 'left':\n              value += bodyNode.scrollLeft;\n              break;\n          }\n          styles[key] = Math.floor(value) + 'px';\n        });\n        return styles;\n      }\n\n      function prepareOutAnimation() {\n        var animator = $animateCss(clone, {\n          addClass: NG_OUT_ANCHOR_CLASS_NAME,\n          delay: true,\n          from: calculateAnchorStyles(outAnchor)\n        });\n\n        // read the comment within `prepareRegularAnimation` to understand\n        // why this check is necessary\n        return animator.$$willAnimate ? animator : null;\n      }\n\n      function getClassVal(element) {\n        return element.attr('class') || '';\n      }\n\n      function prepareInAnimation() {\n        var endingClasses = filterCssClasses(getClassVal(inAnchor));\n        var toAdd = getUniqueValues(endingClasses, startingClasses);\n        var toRemove = getUniqueValues(startingClasses, endingClasses);\n\n        var animator = $animateCss(clone, {\n          to: calculateAnchorStyles(inAnchor),\n          addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,\n          removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,\n          delay: true\n        });\n\n        // read the comment within `prepareRegularAnimation` to understand\n        // why this check is necessary\n        return animator.$$willAnimate ? animator : null;\n      }\n\n      function end() {\n        clone.remove();\n        outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);\n        inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);\n      }\n    }\n\n    function prepareFromToAnchorAnimation(from, to, classes, anchors) {\n      var fromAnimation = prepareRegularAnimation(from, noop);\n      var toAnimation = prepareRegularAnimation(to, noop);\n\n      var anchorAnimations = [];\n      forEach(anchors, function(anchor) {\n        var outElement = anchor['out'];\n        var inElement = anchor['in'];\n        var animator = prepareAnchoredAnimation(classes, outElement, inElement);\n        if (animator) {\n          anchorAnimations.push(animator);\n        }\n      });\n\n      // no point in doing anything when there are no elements to animate\n      if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;\n\n      return {\n        start: function() {\n          var animationRunners = [];\n\n          if (fromAnimation) {\n            animationRunners.push(fromAnimation.start());\n          }\n\n          if (toAnimation) {\n            animationRunners.push(toAnimation.start());\n          }\n\n          forEach(anchorAnimations, function(animation) {\n            animationRunners.push(animation.start());\n          });\n\n          var runner = new $$AnimateRunner({\n            end: endFn,\n            cancel: endFn // CSS-driven animations cannot be cancelled, only ended\n          });\n\n          $$AnimateRunner.all(animationRunners, function(status) {\n            runner.complete(status);\n          });\n\n          return runner;\n\n          function endFn() {\n            forEach(animationRunners, function(runner) {\n              runner.end();\n            });\n          }\n        }\n      };\n    }\n\n    function prepareRegularAnimation(animationDetails) {\n      var element = animationDetails.element;\n      var options = animationDetails.options || {};\n\n      if (animationDetails.structural) {\n        options.event = animationDetails.event;\n        options.structural = true;\n        options.applyClassesEarly = true;\n\n        // we special case the leave animation since we want to ensure that\n        // the element is removed as soon as the animation is over. Otherwise\n        // a flicker might appear or the element may not be removed at all\n        if (animationDetails.event === 'leave') {\n          options.onDone = options.domOperation;\n        }\n      }\n\n      // We assign the preparationClasses as the actual animation event since\n      // the internals of $animateCss will just suffix the event token values\n      // with `-active` to trigger the animation.\n      if (options.preparationClasses) {\n        options.event = concatWithSpace(options.event, options.preparationClasses);\n      }\n\n      var animator = $animateCss(element, options);\n\n      // the driver lookup code inside of $$animation attempts to spawn a\n      // driver one by one until a driver returns a.$$willAnimate animator object.\n      // $animateCss will always return an object, however, it will pass in\n      // a flag as a hint as to whether an animation was detected or not\n      return animator.$$willAnimate ? animator : null;\n    }\n  }];\n}];\n\n// TODO(matsko): use caching here to speed things up for detection\n// TODO(matsko): add documentation\n//  by the time...\n\nvar $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {\n  this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',\n       function($injector,   $$AnimateRunner,   $$jqLite) {\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n         // $animateJs(element, 'enter');\n    return function(element, event, classes, options) {\n      // the `classes` argument is optional and if it is not used\n      // then the classes will be resolved from the element's className\n      // property as well as options.addClass/options.removeClass.\n      if (arguments.length === 3 && isObject(classes)) {\n        options = classes;\n        classes = null;\n      }\n\n      options = prepareAnimationOptions(options);\n      if (!classes) {\n        classes = element.attr('class') || '';\n        if (options.addClass) {\n          classes += ' ' + options.addClass;\n        }\n        if (options.removeClass) {\n          classes += ' ' + options.removeClass;\n        }\n      }\n\n      var classesToAdd = options.addClass;\n      var classesToRemove = options.removeClass;\n\n      // the lookupAnimations function returns a series of animation objects that are\n      // matched up with one or more of the CSS classes. These animation objects are\n      // defined via the module.animation factory function. If nothing is detected then\n      // we don't return anything which then makes $animation query the next driver.\n      var animations = lookupAnimations(classes);\n      var before, after;\n      if (animations.length) {\n        var afterFn, beforeFn;\n        if (event == 'leave') {\n          beforeFn = 'leave';\n          afterFn = 'afterLeave'; // TODO(matsko): get rid of this\n        } else {\n          beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);\n          afterFn = event;\n        }\n\n        if (event !== 'enter' && event !== 'move') {\n          before = packageAnimations(element, event, options, animations, beforeFn);\n        }\n        after  = packageAnimations(element, event, options, animations, afterFn);\n      }\n\n      // no matching animations\n      if (!before && !after) return;\n\n      function applyOptions() {\n        options.domOperation();\n        applyAnimationClasses(element, options);\n      }\n\n      return {\n        start: function() {\n          var closeActiveAnimations;\n          var chain = [];\n\n          if (before) {\n            chain.push(function(fn) {\n              closeActiveAnimations = before(fn);\n            });\n          }\n\n          if (chain.length) {\n            chain.push(function(fn) {\n              applyOptions();\n              fn(true);\n            });\n          } else {\n            applyOptions();\n          }\n\n          if (after) {\n            chain.push(function(fn) {\n              closeActiveAnimations = after(fn);\n            });\n          }\n\n          var animationClosed = false;\n          var runner = new $$AnimateRunner({\n            end: function() {\n              endAnimations();\n            },\n            cancel: function() {\n              endAnimations(true);\n            }\n          });\n\n          $$AnimateRunner.chain(chain, onComplete);\n          return runner;\n\n          function onComplete(success) {\n            animationClosed = true;\n            applyOptions();\n            applyAnimationStyles(element, options);\n            runner.complete(success);\n          }\n\n          function endAnimations(cancelled) {\n            if (!animationClosed) {\n              (closeActiveAnimations || noop)(cancelled);\n              onComplete(cancelled);\n            }\n          }\n        }\n      };\n\n      function executeAnimationFn(fn, element, event, options, onDone) {\n        var args;\n        switch (event) {\n          case 'animate':\n            args = [element, options.from, options.to, onDone];\n            break;\n\n          case 'setClass':\n            args = [element, classesToAdd, classesToRemove, onDone];\n            break;\n\n          case 'addClass':\n            args = [element, classesToAdd, onDone];\n            break;\n\n          case 'removeClass':\n            args = [element, classesToRemove, onDone];\n            break;\n\n          default:\n            args = [element, onDone];\n            break;\n        }\n\n        args.push(options);\n\n        var value = fn.apply(fn, args);\n        if (value) {\n          if (isFunction(value.start)) {\n            value = value.start();\n          }\n\n          if (value instanceof $$AnimateRunner) {\n            value.done(onDone);\n          } else if (isFunction(value)) {\n            // optional onEnd / onCancel callback\n            return value;\n          }\n        }\n\n        return noop;\n      }\n\n      function groupEventedAnimations(element, event, options, animations, fnName) {\n        var operations = [];\n        forEach(animations, function(ani) {\n          var animation = ani[fnName];\n          if (!animation) return;\n\n          // note that all of these animations will run in parallel\n          operations.push(function() {\n            var runner;\n            var endProgressCb;\n\n            var resolved = false;\n            var onAnimationComplete = function(rejected) {\n              if (!resolved) {\n                resolved = true;\n                (endProgressCb || noop)(rejected);\n                runner.complete(!rejected);\n              }\n            };\n\n            runner = new $$AnimateRunner({\n              end: function() {\n                onAnimationComplete();\n              },\n              cancel: function() {\n                onAnimationComplete(true);\n              }\n            });\n\n            endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {\n              var cancelled = result === false;\n              onAnimationComplete(cancelled);\n            });\n\n            return runner;\n          });\n        });\n\n        return operations;\n      }\n\n      function packageAnimations(element, event, options, animations, fnName) {\n        var operations = groupEventedAnimations(element, event, options, animations, fnName);\n        if (operations.length === 0) {\n          var a,b;\n          if (fnName === 'beforeSetClass') {\n            a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');\n            b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');\n          } else if (fnName === 'setClass') {\n            a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');\n            b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');\n          }\n\n          if (a) {\n            operations = operations.concat(a);\n          }\n          if (b) {\n            operations = operations.concat(b);\n          }\n        }\n\n        if (operations.length === 0) return;\n\n        // TODO(matsko): add documentation\n        return function startAnimation(callback) {\n          var runners = [];\n          if (operations.length) {\n            forEach(operations, function(animateFn) {\n              runners.push(animateFn());\n            });\n          }\n\n          runners.length ? $$AnimateRunner.all(runners, callback) : callback();\n\n          return function endFn(reject) {\n            forEach(runners, function(runner) {\n              reject ? runner.cancel() : runner.end();\n            });\n          };\n        };\n      }\n    };\n\n    function lookupAnimations(classes) {\n      classes = isArray(classes) ? classes : classes.split(' ');\n      var matches = [], flagMap = {};\n      for (var i=0; i < classes.length; i++) {\n        var klass = classes[i],\n            animationFactory = $animateProvider.$$registeredAnimations[klass];\n        if (animationFactory && !flagMap[klass]) {\n          matches.push($injector.get(animationFactory));\n          flagMap[klass] = true;\n        }\n      }\n      return matches;\n    }\n  }];\n}];\n\nvar $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {\n  $$animationProvider.drivers.push('$$animateJsDriver');\n  this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {\n    return function initDriverFn(animationDetails) {\n      if (animationDetails.from && animationDetails.to) {\n        var fromAnimation = prepareAnimation(animationDetails.from);\n        var toAnimation = prepareAnimation(animationDetails.to);\n        if (!fromAnimation && !toAnimation) return;\n\n        return {\n          start: function() {\n            var animationRunners = [];\n\n            if (fromAnimation) {\n              animationRunners.push(fromAnimation.start());\n            }\n\n            if (toAnimation) {\n              animationRunners.push(toAnimation.start());\n            }\n\n            $$AnimateRunner.all(animationRunners, done);\n\n            var runner = new $$AnimateRunner({\n              end: endFnFactory(),\n              cancel: endFnFactory()\n            });\n\n            return runner;\n\n            function endFnFactory() {\n              return function() {\n                forEach(animationRunners, function(runner) {\n                  // at this point we cannot cancel animations for groups just yet. 1.5+\n                  runner.end();\n                });\n              };\n            }\n\n            function done(status) {\n              runner.complete(status);\n            }\n          }\n        };\n      } else {\n        return prepareAnimation(animationDetails);\n      }\n    };\n\n    function prepareAnimation(animationDetails) {\n      // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations\n      var element = animationDetails.element;\n      var event = animationDetails.event;\n      var options = animationDetails.options;\n      var classes = animationDetails.classes;\n      return $$animateJs(element, event, classes, options);\n    }\n  }];\n}];\n\nvar NG_ANIMATE_ATTR_NAME = 'data-ng-animate';\nvar NG_ANIMATE_PIN_DATA = '$ngAnimatePin';\nvar $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {\n  var PRE_DIGEST_STATE = 1;\n  var RUNNING_STATE = 2;\n\n  var rules = this.rules = {\n    skip: [],\n    cancel: [],\n    join: []\n  };\n\n  function isAllowed(ruleType, element, currentAnimation, previousAnimation) {\n    return rules[ruleType].some(function(fn) {\n      return fn(element, currentAnimation, previousAnimation);\n    });\n  }\n\n  function hasAnimationClasses(options, and) {\n    options = options || {};\n    var a = (options.addClass || '').length > 0;\n    var b = (options.removeClass || '').length > 0;\n    return and ? a && b : a || b;\n  }\n\n  rules.join.push(function(element, newAnimation, currentAnimation) {\n    // if the new animation is class-based then we can just tack that on\n    return !newAnimation.structural && hasAnimationClasses(newAnimation.options);\n  });\n\n  rules.skip.push(function(element, newAnimation, currentAnimation) {\n    // there is no need to animate anything if no classes are being added and\n    // there is no structural animation that will be triggered\n    return !newAnimation.structural && !hasAnimationClasses(newAnimation.options);\n  });\n\n  rules.skip.push(function(element, newAnimation, currentAnimation) {\n    // why should we trigger a new structural animation if the element will\n    // be removed from the DOM anyway?\n    return currentAnimation.event == 'leave' && newAnimation.structural;\n  });\n\n  rules.skip.push(function(element, newAnimation, currentAnimation) {\n    // if there is an ongoing current animation then don't even bother running the class-based animation\n    return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;\n  });\n\n  rules.cancel.push(function(element, newAnimation, currentAnimation) {\n    // there can never be two structural animations running at the same time\n    return currentAnimation.structural && newAnimation.structural;\n  });\n\n  rules.cancel.push(function(element, newAnimation, currentAnimation) {\n    // if the previous animation is already running, but the new animation will\n    // be triggered, but the new animation is structural\n    return currentAnimation.state === RUNNING_STATE && newAnimation.structural;\n  });\n\n  rules.cancel.push(function(element, newAnimation, currentAnimation) {\n    var nO = newAnimation.options;\n    var cO = currentAnimation.options;\n\n    // if the exact same CSS class is added/removed then it's safe to cancel it\n    return (nO.addClass && nO.addClass === cO.removeClass) || (nO.removeClass && nO.removeClass === cO.addClass);\n  });\n\n  this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',\n               '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',\n       function($$rAF,   $rootScope,   $rootElement,   $document,   $$HashMap,\n                $$animation,   $$AnimateRunner,   $templateRequest,   $$jqLite,   $$forceReflow) {\n\n    var activeAnimationsLookup = new $$HashMap();\n    var disabledElementsLookup = new $$HashMap();\n    var animationsEnabled = null;\n\n    function postDigestTaskFactory() {\n      var postDigestCalled = false;\n      return function(fn) {\n        // we only issue a call to postDigest before\n        // it has first passed. This prevents any callbacks\n        // from not firing once the animation has completed\n        // since it will be out of the digest cycle.\n        if (postDigestCalled) {\n          fn();\n        } else {\n          $rootScope.$$postDigest(function() {\n            postDigestCalled = true;\n            fn();\n          });\n        }\n      };\n    }\n\n    // Wait until all directive and route-related templates are downloaded and\n    // compiled. The $templateRequest.totalPendingRequests variable keeps track of\n    // all of the remote templates being currently downloaded. If there are no\n    // templates currently downloading then the watcher will still fire anyway.\n    var deregisterWatch = $rootScope.$watch(\n      function() { return $templateRequest.totalPendingRequests === 0; },\n      function(isEmpty) {\n        if (!isEmpty) return;\n        deregisterWatch();\n\n        // Now that all templates have been downloaded, $animate will wait until\n        // the post digest queue is empty before enabling animations. By having two\n        // calls to $postDigest calls we can ensure that the flag is enabled at the\n        // very end of the post digest queue. Since all of the animations in $animate\n        // use $postDigest, it's important that the code below executes at the end.\n        // This basically means that the page is fully downloaded and compiled before\n        // any animations are triggered.\n        $rootScope.$$postDigest(function() {\n          $rootScope.$$postDigest(function() {\n            // we check for null directly in the event that the application already called\n            // .enabled() with whatever arguments that it provided it with\n            if (animationsEnabled === null) {\n              animationsEnabled = true;\n            }\n          });\n        });\n      }\n    );\n\n    var callbackRegistry = {};\n\n    // remember that the classNameFilter is set during the provider/config\n    // stage therefore we can optimize here and setup a helper function\n    var classNameFilter = $animateProvider.classNameFilter();\n    var isAnimatableClassName = !classNameFilter\n              ? function() { return true; }\n              : function(className) {\n                return classNameFilter.test(className);\n              };\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    function normalizeAnimationOptions(element, options) {\n      return mergeAnimationOptions(element, options, {});\n    }\n\n    function findCallbacks(element, event) {\n      var targetNode = getDomNode(element);\n\n      var matches = [];\n      var entries = callbackRegistry[event];\n      if (entries) {\n        forEach(entries, function(entry) {\n          if (entry.node.contains(targetNode)) {\n            matches.push(entry.callback);\n          }\n        });\n      }\n\n      return matches;\n    }\n\n    return {\n      on: function(event, container, callback) {\n        var node = extractElementNode(container);\n        callbackRegistry[event] = callbackRegistry[event] || [];\n        callbackRegistry[event].push({\n          node: node,\n          callback: callback\n        });\n      },\n\n      off: function(event, container, callback) {\n        var entries = callbackRegistry[event];\n        if (!entries) return;\n\n        callbackRegistry[event] = arguments.length === 1\n            ? null\n            : filterFromRegistry(entries, container, callback);\n\n        function filterFromRegistry(list, matchContainer, matchCallback) {\n          var containerNode = extractElementNode(matchContainer);\n          return list.filter(function(entry) {\n            var isMatch = entry.node === containerNode &&\n                            (!matchCallback || entry.callback === matchCallback);\n            return !isMatch;\n          });\n        }\n      },\n\n      pin: function(element, parentElement) {\n        assertArg(isElement(element), 'element', 'not an element');\n        assertArg(isElement(parentElement), 'parentElement', 'not an element');\n        element.data(NG_ANIMATE_PIN_DATA, parentElement);\n      },\n\n      push: function(element, event, options, domOperation) {\n        options = options || {};\n        options.domOperation = domOperation;\n        return queueAnimation(element, event, options);\n      },\n\n      // this method has four signatures:\n      //  () - global getter\n      //  (bool) - global setter\n      //  (element) - element getter\n      //  (element, bool) - element setter<F37>\n      enabled: function(element, bool) {\n        var argCount = arguments.length;\n\n        if (argCount === 0) {\n          // () - Global getter\n          bool = !!animationsEnabled;\n        } else {\n          var hasElement = isElement(element);\n\n          if (!hasElement) {\n            // (bool) - Global setter\n            bool = animationsEnabled = !!element;\n          } else {\n            var node = getDomNode(element);\n            var recordExists = disabledElementsLookup.get(node);\n\n            if (argCount === 1) {\n              // (element) - Element getter\n              bool = !recordExists;\n            } else {\n              // (element, bool) - Element setter\n              bool = !!bool;\n              if (!bool) {\n                disabledElementsLookup.put(node, true);\n              } else if (recordExists) {\n                disabledElementsLookup.remove(node);\n              }\n            }\n          }\n        }\n\n        return bool;\n      }\n    };\n\n    function queueAnimation(element, event, options) {\n      var node, parent;\n      element = stripCommentsFromElement(element);\n      if (element) {\n        node = getDomNode(element);\n        parent = element.parent();\n      }\n\n      options = prepareAnimationOptions(options);\n\n      // we create a fake runner with a working promise.\n      // These methods will become available after the digest has passed\n      var runner = new $$AnimateRunner();\n\n      // this is used to trigger callbacks in postDigest mode\n      var runInNextPostDigestOrNow = postDigestTaskFactory();\n\n      if (isArray(options.addClass)) {\n        options.addClass = options.addClass.join(' ');\n      }\n\n      if (options.addClass && !isString(options.addClass)) {\n        options.addClass = null;\n      }\n\n      if (isArray(options.removeClass)) {\n        options.removeClass = options.removeClass.join(' ');\n      }\n\n      if (options.removeClass && !isString(options.removeClass)) {\n        options.removeClass = null;\n      }\n\n      if (options.from && !isObject(options.from)) {\n        options.from = null;\n      }\n\n      if (options.to && !isObject(options.to)) {\n        options.to = null;\n      }\n\n      // there are situations where a directive issues an animation for\n      // a jqLite wrapper that contains only comment nodes... If this\n      // happens then there is no way we can perform an animation\n      if (!node) {\n        close();\n        return runner;\n      }\n\n      var className = [node.className, options.addClass, options.removeClass].join(' ');\n      if (!isAnimatableClassName(className)) {\n        close();\n        return runner;\n      }\n\n      var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;\n\n      // this is a hard disable of all animations for the application or on\n      // the element itself, therefore  there is no need to continue further\n      // past this point if not enabled\n      var skipAnimations = !animationsEnabled || disabledElementsLookup.get(node);\n      var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};\n      var hasExistingAnimation = !!existingAnimation.state;\n\n      // there is no point in traversing the same collection of parent ancestors if a followup\n      // animation will be run on the same element that already did all that checking work\n      if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {\n        skipAnimations = !areAnimationsAllowed(element, parent, event);\n      }\n\n      if (skipAnimations) {\n        close();\n        return runner;\n      }\n\n      if (isStructural) {\n        closeChildAnimations(element);\n      }\n\n      var newAnimation = {\n        structural: isStructural,\n        element: element,\n        event: event,\n        close: close,\n        options: options,\n        runner: runner\n      };\n\n      if (hasExistingAnimation) {\n        var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);\n        if (skipAnimationFlag) {\n          if (existingAnimation.state === RUNNING_STATE) {\n            close();\n            return runner;\n          } else {\n            mergeAnimationOptions(element, existingAnimation.options, options);\n            return existingAnimation.runner;\n          }\n        }\n\n        var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);\n        if (cancelAnimationFlag) {\n          if (existingAnimation.state === RUNNING_STATE) {\n            // this will end the animation right away and it is safe\n            // to do so since the animation is already running and the\n            // runner callback code will run in async\n            existingAnimation.runner.end();\n          } else if (existingAnimation.structural) {\n            // this means that the animation is queued into a digest, but\n            // hasn't started yet. Therefore it is safe to run the close\n            // method which will call the runner methods in async.\n            existingAnimation.close();\n          } else {\n            // this will merge the new animation options into existing animation options\n            mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);\n            return existingAnimation.runner;\n          }\n        } else {\n          // a joined animation means that this animation will take over the existing one\n          // so an example would involve a leave animation taking over an enter. Then when\n          // the postDigest kicks in the enter will be ignored.\n          var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);\n          if (joinAnimationFlag) {\n            if (existingAnimation.state === RUNNING_STATE) {\n              normalizeAnimationOptions(element, options);\n            } else {\n              applyGeneratedPreparationClasses(element, isStructural ? event : null, options);\n\n              event = newAnimation.event = existingAnimation.event;\n              options = mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);\n\n              //we return the same runner since only the option values of this animation will\n              //be fed into the `existingAnimation`.\n              return existingAnimation.runner;\n            }\n          }\n        }\n      } else {\n        // normalization in this case means that it removes redundant CSS classes that\n        // already exist (addClass) or do not exist (removeClass) on the element\n        normalizeAnimationOptions(element, options);\n      }\n\n      // when the options are merged and cleaned up we may end up not having to do\n      // an animation at all, therefore we should check this before issuing a post\n      // digest callback. Structural animations will always run no matter what.\n      var isValidAnimation = newAnimation.structural;\n      if (!isValidAnimation) {\n        // animate (from/to) can be quickly checked first, otherwise we check if any classes are present\n        isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)\n                            || hasAnimationClasses(newAnimation.options);\n      }\n\n      if (!isValidAnimation) {\n        close();\n        clearElementAnimationState(element);\n        return runner;\n      }\n\n      // the counter keeps track of cancelled animations\n      var counter = (existingAnimation.counter || 0) + 1;\n      newAnimation.counter = counter;\n\n      markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);\n\n      $rootScope.$$postDigest(function() {\n        var animationDetails = activeAnimationsLookup.get(node);\n        var animationCancelled = !animationDetails;\n        animationDetails = animationDetails || {};\n\n        // if addClass/removeClass is called before something like enter then the\n        // registered parent element may not be present. The code below will ensure\n        // that a final value for parent element is obtained\n        var parentElement = element.parent() || [];\n\n        // animate/structural/class-based animations all have requirements. Otherwise there\n        // is no point in performing an animation. The parent node must also be set.\n        var isValidAnimation = parentElement.length > 0\n                                && (animationDetails.event === 'animate'\n                                    || animationDetails.structural\n                                    || hasAnimationClasses(animationDetails.options));\n\n        // this means that the previous animation was cancelled\n        // even if the follow-up animation is the same event\n        if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {\n          // if another animation did not take over then we need\n          // to make sure that the domOperation and options are\n          // handled accordingly\n          if (animationCancelled) {\n            applyAnimationClasses(element, options);\n            applyAnimationStyles(element, options);\n          }\n\n          // if the event changed from something like enter to leave then we do\n          // it, otherwise if it's the same then the end result will be the same too\n          if (animationCancelled || (isStructural && animationDetails.event !== event)) {\n            options.domOperation();\n            runner.end();\n          }\n\n          // in the event that the element animation was not cancelled or a follow-up animation\n          // isn't allowed to animate from here then we need to clear the state of the element\n          // so that any future animations won't read the expired animation data.\n          if (!isValidAnimation) {\n            clearElementAnimationState(element);\n          }\n\n          return;\n        }\n\n        // this combined multiple class to addClass / removeClass into a setClass event\n        // so long as a structural event did not take over the animation\n        event = !animationDetails.structural && hasAnimationClasses(animationDetails.options, true)\n            ? 'setClass'\n            : animationDetails.event;\n\n        markElementAnimationState(element, RUNNING_STATE);\n        var realRunner = $$animation(element, event, animationDetails.options);\n\n        realRunner.done(function(status) {\n          close(!status);\n          var animationDetails = activeAnimationsLookup.get(node);\n          if (animationDetails && animationDetails.counter === counter) {\n            clearElementAnimationState(getDomNode(element));\n          }\n          notifyProgress(runner, event, 'close', {});\n        });\n\n        // this will update the runner's flow-control events based on\n        // the `realRunner` object.\n        runner.setHost(realRunner);\n        notifyProgress(runner, event, 'start', {});\n      });\n\n      return runner;\n\n      function notifyProgress(runner, event, phase, data) {\n        runInNextPostDigestOrNow(function() {\n          var callbacks = findCallbacks(element, event);\n          if (callbacks.length) {\n            // do not optimize this call here to RAF because\n            // we don't know how heavy the callback code here will\n            // be and if this code is buffered then this can\n            // lead to a performance regression.\n            $$rAF(function() {\n              forEach(callbacks, function(callback) {\n                callback(element, phase, data);\n              });\n            });\n          }\n        });\n        runner.progress(event, phase, data);\n      }\n\n      function close(reject) { // jshint ignore:line\n        clearGeneratedClasses(element, options);\n        applyAnimationClasses(element, options);\n        applyAnimationStyles(element, options);\n        options.domOperation();\n        runner.complete(!reject);\n      }\n    }\n\n    function closeChildAnimations(element) {\n      var node = getDomNode(element);\n      var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');\n      forEach(children, function(child) {\n        var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));\n        var animationDetails = activeAnimationsLookup.get(child);\n        switch (state) {\n          case RUNNING_STATE:\n            animationDetails.runner.end();\n            /* falls through */\n          case PRE_DIGEST_STATE:\n            if (animationDetails) {\n              activeAnimationsLookup.remove(child);\n            }\n            break;\n        }\n      });\n    }\n\n    function clearElementAnimationState(element) {\n      var node = getDomNode(element);\n      node.removeAttribute(NG_ANIMATE_ATTR_NAME);\n      activeAnimationsLookup.remove(node);\n    }\n\n    function isMatchingElement(nodeOrElmA, nodeOrElmB) {\n      return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);\n    }\n\n    function areAnimationsAllowed(element, parentElement, event) {\n      var bodyElement = jqLite($document[0].body);\n      var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';\n      var rootElementDetected = isMatchingElement(element, $rootElement);\n      var parentAnimationDetected = false;\n      var animateChildren;\n\n      var parentHost = element.data(NG_ANIMATE_PIN_DATA);\n      if (parentHost) {\n        parentElement = parentHost;\n      }\n\n      while (parentElement && parentElement.length) {\n        if (!rootElementDetected) {\n          // angular doesn't want to attempt to animate elements outside of the application\n          // therefore we need to ensure that the rootElement is an ancestor of the current element\n          rootElementDetected = isMatchingElement(parentElement, $rootElement);\n        }\n\n        var parentNode = parentElement[0];\n        if (parentNode.nodeType !== ELEMENT_NODE) {\n          // no point in inspecting the #document element\n          break;\n        }\n\n        var details = activeAnimationsLookup.get(parentNode) || {};\n        // either an enter, leave or move animation will commence\n        // therefore we can't allow any animations to take place\n        // but if a parent animation is class-based then that's ok\n        if (!parentAnimationDetected) {\n          parentAnimationDetected = details.structural || disabledElementsLookup.get(parentNode);\n        }\n\n        if (isUndefined(animateChildren) || animateChildren === true) {\n          var value = parentElement.data(NG_ANIMATE_CHILDREN_DATA);\n          if (isDefined(value)) {\n            animateChildren = value;\n          }\n        }\n\n        // there is no need to continue traversing at this point\n        if (parentAnimationDetected && animateChildren === false) break;\n\n        if (!rootElementDetected) {\n          // angular doesn't want to attempt to animate elements outside of the application\n          // therefore we need to ensure that the rootElement is an ancestor of the current element\n          rootElementDetected = isMatchingElement(parentElement, $rootElement);\n          if (!rootElementDetected) {\n            parentHost = parentElement.data(NG_ANIMATE_PIN_DATA);\n            if (parentHost) {\n              parentElement = parentHost;\n            }\n          }\n        }\n\n        if (!bodyElementDetected) {\n          // we also need to ensure that the element is or will be apart of the body element\n          // otherwise it is pointless to even issue an animation to be rendered\n          bodyElementDetected = isMatchingElement(parentElement, bodyElement);\n        }\n\n        parentElement = parentElement.parent();\n      }\n\n      var allowAnimation = !parentAnimationDetected || animateChildren;\n      return allowAnimation && rootElementDetected && bodyElementDetected;\n    }\n\n    function markElementAnimationState(element, state, details) {\n      details = details || {};\n      details.state = state;\n\n      var node = getDomNode(element);\n      node.setAttribute(NG_ANIMATE_ATTR_NAME, state);\n\n      var oldValue = activeAnimationsLookup.get(node);\n      var newValue = oldValue\n          ? extend(oldValue, details)\n          : details;\n      activeAnimationsLookup.put(node, newValue);\n    }\n  }];\n}];\n\nvar $$AnimateAsyncRunFactory = ['$$rAF', function($$rAF) {\n  var waitQueue = [];\n\n  function waitForTick(fn) {\n    waitQueue.push(fn);\n    if (waitQueue.length > 1) return;\n    $$rAF(function() {\n      for (var i = 0; i < waitQueue.length; i++) {\n        waitQueue[i]();\n      }\n      waitQueue = [];\n    });\n  }\n\n  return function() {\n    var passed = false;\n    waitForTick(function() {\n      passed = true;\n    });\n    return function(callback) {\n      passed ? callback() : waitForTick(callback);\n    };\n  };\n}];\n\nvar $$AnimateRunnerFactory = ['$q', '$sniffer', '$$animateAsyncRun',\n                      function($q,   $sniffer,   $$animateAsyncRun) {\n\n  var INITIAL_STATE = 0;\n  var DONE_PENDING_STATE = 1;\n  var DONE_COMPLETE_STATE = 2;\n\n  AnimateRunner.chain = function(chain, callback) {\n    var index = 0;\n\n    next();\n    function next() {\n      if (index === chain.length) {\n        callback(true);\n        return;\n      }\n\n      chain[index](function(response) {\n        if (response === false) {\n          callback(false);\n          return;\n        }\n        index++;\n        next();\n      });\n    }\n  };\n\n  AnimateRunner.all = function(runners, callback) {\n    var count = 0;\n    var status = true;\n    forEach(runners, function(runner) {\n      runner.done(onProgress);\n    });\n\n    function onProgress(response) {\n      status = status && response;\n      if (++count === runners.length) {\n        callback(status);\n      }\n    }\n  };\n\n  function AnimateRunner(host) {\n    this.setHost(host);\n\n    this._doneCallbacks = [];\n    this._runInAnimationFrame = $$animateAsyncRun();\n    this._state = 0;\n  }\n\n  AnimateRunner.prototype = {\n    setHost: function(host) {\n      this.host = host || {};\n    },\n\n    done: function(fn) {\n      if (this._state === DONE_COMPLETE_STATE) {\n        fn();\n      } else {\n        this._doneCallbacks.push(fn);\n      }\n    },\n\n    progress: noop,\n\n    getPromise: function() {\n      if (!this.promise) {\n        var self = this;\n        this.promise = $q(function(resolve, reject) {\n          self.done(function(status) {\n            status === false ? reject() : resolve();\n          });\n        });\n      }\n      return this.promise;\n    },\n\n    then: function(resolveHandler, rejectHandler) {\n      return this.getPromise().then(resolveHandler, rejectHandler);\n    },\n\n    'catch': function(handler) {\n      return this.getPromise()['catch'](handler);\n    },\n\n    'finally': function(handler) {\n      return this.getPromise()['finally'](handler);\n    },\n\n    pause: function() {\n      if (this.host.pause) {\n        this.host.pause();\n      }\n    },\n\n    resume: function() {\n      if (this.host.resume) {\n        this.host.resume();\n      }\n    },\n\n    end: function() {\n      if (this.host.end) {\n        this.host.end();\n      }\n      this._resolve(true);\n    },\n\n    cancel: function() {\n      if (this.host.cancel) {\n        this.host.cancel();\n      }\n      this._resolve(false);\n    },\n\n    complete: function(response) {\n      var self = this;\n      if (self._state === INITIAL_STATE) {\n        self._state = DONE_PENDING_STATE;\n        self._runInAnimationFrame(function() {\n          self._resolve(response);\n        });\n      }\n    },\n\n    _resolve: function(response) {\n      if (this._state !== DONE_COMPLETE_STATE) {\n        forEach(this._doneCallbacks, function(fn) {\n          fn(response);\n        });\n        this._doneCallbacks.length = 0;\n        this._state = DONE_COMPLETE_STATE;\n      }\n    }\n  };\n\n  return AnimateRunner;\n}];\n\nvar $$AnimationProvider = ['$animateProvider', function($animateProvider) {\n  var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';\n\n  var drivers = this.drivers = [];\n\n  var RUNNER_STORAGE_KEY = '$$animationRunner';\n\n  function setRunner(element, runner) {\n    element.data(RUNNER_STORAGE_KEY, runner);\n  }\n\n  function removeRunner(element) {\n    element.removeData(RUNNER_STORAGE_KEY);\n  }\n\n  function getRunner(element) {\n    return element.data(RUNNER_STORAGE_KEY);\n  }\n\n  this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',\n       function($$jqLite,   $rootScope,   $injector,   $$AnimateRunner,   $$HashMap,   $$rAFScheduler) {\n\n    var animationQueue = [];\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    function sortAnimations(animations) {\n      var tree = { children: [] };\n      var i, lookup = new $$HashMap();\n\n      // this is done first beforehand so that the hashmap\n      // is filled with a list of the elements that will be animated\n      for (i = 0; i < animations.length; i++) {\n        var animation = animations[i];\n        lookup.put(animation.domNode, animations[i] = {\n          domNode: animation.domNode,\n          fn: animation.fn,\n          children: []\n        });\n      }\n\n      for (i = 0; i < animations.length; i++) {\n        processNode(animations[i]);\n      }\n\n      return flatten(tree);\n\n      function processNode(entry) {\n        if (entry.processed) return entry;\n        entry.processed = true;\n\n        var elementNode = entry.domNode;\n        var parentNode = elementNode.parentNode;\n        lookup.put(elementNode, entry);\n\n        var parentEntry;\n        while (parentNode) {\n          parentEntry = lookup.get(parentNode);\n          if (parentEntry) {\n            if (!parentEntry.processed) {\n              parentEntry = processNode(parentEntry);\n            }\n            break;\n          }\n          parentNode = parentNode.parentNode;\n        }\n\n        (parentEntry || tree).children.push(entry);\n        return entry;\n      }\n\n      function flatten(tree) {\n        var result = [];\n        var queue = [];\n        var i;\n\n        for (i = 0; i < tree.children.length; i++) {\n          queue.push(tree.children[i]);\n        }\n\n        var remainingLevelEntries = queue.length;\n        var nextLevelEntries = 0;\n        var row = [];\n\n        for (i = 0; i < queue.length; i++) {\n          var entry = queue[i];\n          if (remainingLevelEntries <= 0) {\n            remainingLevelEntries = nextLevelEntries;\n            nextLevelEntries = 0;\n            result.push(row);\n            row = [];\n          }\n          row.push(entry.fn);\n          entry.children.forEach(function(childEntry) {\n            nextLevelEntries++;\n            queue.push(childEntry);\n          });\n          remainingLevelEntries--;\n        }\n\n        if (row.length) {\n          result.push(row);\n        }\n\n        return result;\n      }\n    }\n\n    // TODO(matsko): document the signature in a better way\n    return function(element, event, options) {\n      options = prepareAnimationOptions(options);\n      var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;\n\n      // there is no animation at the current moment, however\n      // these runner methods will get later updated with the\n      // methods leading into the driver's end/cancel methods\n      // for now they just stop the animation from starting\n      var runner = new $$AnimateRunner({\n        end: function() { close(); },\n        cancel: function() { close(true); }\n      });\n\n      if (!drivers.length) {\n        close();\n        return runner;\n      }\n\n      setRunner(element, runner);\n\n      var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));\n      var tempClasses = options.tempClasses;\n      if (tempClasses) {\n        classes += ' ' + tempClasses;\n        options.tempClasses = null;\n      }\n\n      animationQueue.push({\n        // this data is used by the postDigest code and passed into\n        // the driver step function\n        element: element,\n        classes: classes,\n        event: event,\n        structural: isStructural,\n        options: options,\n        beforeStart: beforeStart,\n        close: close\n      });\n\n      element.on('$destroy', handleDestroyedElement);\n\n      // we only want there to be one function called within the post digest\n      // block. This way we can group animations for all the animations that\n      // were apart of the same postDigest flush call.\n      if (animationQueue.length > 1) return runner;\n\n      $rootScope.$$postDigest(function() {\n        var animations = [];\n        forEach(animationQueue, function(entry) {\n          // the element was destroyed early on which removed the runner\n          // form its storage. This means we can't animate this element\n          // at all and it already has been closed due to destruction.\n          if (getRunner(entry.element)) {\n            animations.push(entry);\n          } else {\n            entry.close();\n          }\n        });\n\n        // now any future animations will be in another postDigest\n        animationQueue.length = 0;\n\n        var groupedAnimations = groupAnimations(animations);\n        var toBeSortedAnimations = [];\n\n        forEach(groupedAnimations, function(animationEntry) {\n          toBeSortedAnimations.push({\n            domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),\n            fn: function triggerAnimationStart() {\n              // it's important that we apply the `ng-animate` CSS class and the\n              // temporary classes before we do any driver invoking since these\n              // CSS classes may be required for proper CSS detection.\n              animationEntry.beforeStart();\n\n              var startAnimationFn, closeFn = animationEntry.close;\n\n              // in the event that the element was removed before the digest runs or\n              // during the RAF sequencing then we should not trigger the animation.\n              var targetElement = animationEntry.anchors\n                  ? (animationEntry.from.element || animationEntry.to.element)\n                  : animationEntry.element;\n\n              if (getRunner(targetElement)) {\n                var operation = invokeFirstDriver(animationEntry);\n                if (operation) {\n                  startAnimationFn = operation.start;\n                }\n              }\n\n              if (!startAnimationFn) {\n                closeFn();\n              } else {\n                var animationRunner = startAnimationFn();\n                animationRunner.done(function(status) {\n                  closeFn(!status);\n                });\n                updateAnimationRunners(animationEntry, animationRunner);\n              }\n            }\n          });\n        });\n\n        // we need to sort each of the animations in order of parent to child\n        // relationships. This ensures that the child classes are applied at the\n        // right time.\n        $$rAFScheduler(sortAnimations(toBeSortedAnimations));\n      });\n\n      return runner;\n\n      // TODO(matsko): change to reference nodes\n      function getAnchorNodes(node) {\n        var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';\n        var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)\n              ? [node]\n              : node.querySelectorAll(SELECTOR);\n        var anchors = [];\n        forEach(items, function(node) {\n          var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);\n          if (attr && attr.length) {\n            anchors.push(node);\n          }\n        });\n        return anchors;\n      }\n\n      function groupAnimations(animations) {\n        var preparedAnimations = [];\n        var refLookup = {};\n        forEach(animations, function(animation, index) {\n          var element = animation.element;\n          var node = getDomNode(element);\n          var event = animation.event;\n          var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;\n          var anchorNodes = animation.structural ? getAnchorNodes(node) : [];\n\n          if (anchorNodes.length) {\n            var direction = enterOrMove ? 'to' : 'from';\n\n            forEach(anchorNodes, function(anchor) {\n              var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);\n              refLookup[key] = refLookup[key] || {};\n              refLookup[key][direction] = {\n                animationID: index,\n                element: jqLite(anchor)\n              };\n            });\n          } else {\n            preparedAnimations.push(animation);\n          }\n        });\n\n        var usedIndicesLookup = {};\n        var anchorGroups = {};\n        forEach(refLookup, function(operations, key) {\n          var from = operations.from;\n          var to = operations.to;\n\n          if (!from || !to) {\n            // only one of these is set therefore we can't have an\n            // anchor animation since all three pieces are required\n            var index = from ? from.animationID : to.animationID;\n            var indexKey = index.toString();\n            if (!usedIndicesLookup[indexKey]) {\n              usedIndicesLookup[indexKey] = true;\n              preparedAnimations.push(animations[index]);\n            }\n            return;\n          }\n\n          var fromAnimation = animations[from.animationID];\n          var toAnimation = animations[to.animationID];\n          var lookupKey = from.animationID.toString();\n          if (!anchorGroups[lookupKey]) {\n            var group = anchorGroups[lookupKey] = {\n              structural: true,\n              beforeStart: function() {\n                fromAnimation.beforeStart();\n                toAnimation.beforeStart();\n              },\n              close: function() {\n                fromAnimation.close();\n                toAnimation.close();\n              },\n              classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),\n              from: fromAnimation,\n              to: toAnimation,\n              anchors: [] // TODO(matsko): change to reference nodes\n            };\n\n            // the anchor animations require that the from and to elements both have at least\n            // one shared CSS class which effictively marries the two elements together to use\n            // the same animation driver and to properly sequence the anchor animation.\n            if (group.classes.length) {\n              preparedAnimations.push(group);\n            } else {\n              preparedAnimations.push(fromAnimation);\n              preparedAnimations.push(toAnimation);\n            }\n          }\n\n          anchorGroups[lookupKey].anchors.push({\n            'out': from.element, 'in': to.element\n          });\n        });\n\n        return preparedAnimations;\n      }\n\n      function cssClassesIntersection(a,b) {\n        a = a.split(' ');\n        b = b.split(' ');\n        var matches = [];\n\n        for (var i = 0; i < a.length; i++) {\n          var aa = a[i];\n          if (aa.substring(0,3) === 'ng-') continue;\n\n          for (var j = 0; j < b.length; j++) {\n            if (aa === b[j]) {\n              matches.push(aa);\n              break;\n            }\n          }\n        }\n\n        return matches.join(' ');\n      }\n\n      function invokeFirstDriver(animationDetails) {\n        // we loop in reverse order since the more general drivers (like CSS and JS)\n        // may attempt more elements, but custom drivers are more particular\n        for (var i = drivers.length - 1; i >= 0; i--) {\n          var driverName = drivers[i];\n          if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check\n\n          var factory = $injector.get(driverName);\n          var driver = factory(animationDetails);\n          if (driver) {\n            return driver;\n          }\n        }\n      }\n\n      function beforeStart() {\n        element.addClass(NG_ANIMATE_CLASSNAME);\n        if (tempClasses) {\n          $$jqLite.addClass(element, tempClasses);\n        }\n      }\n\n      function updateAnimationRunners(animation, newRunner) {\n        if (animation.from && animation.to) {\n          update(animation.from.element);\n          update(animation.to.element);\n        } else {\n          update(animation.element);\n        }\n\n        function update(element) {\n          getRunner(element).setHost(newRunner);\n        }\n      }\n\n      function handleDestroyedElement() {\n        var runner = getRunner(element);\n        if (runner && (event !== 'leave' || !options.$$domOperationFired)) {\n          runner.end();\n        }\n      }\n\n      function close(rejected) { // jshint ignore:line\n        element.off('$destroy', handleDestroyedElement);\n        removeRunner(element);\n\n        applyAnimationClasses(element, options);\n        applyAnimationStyles(element, options);\n        options.domOperation();\n\n        if (tempClasses) {\n          $$jqLite.removeClass(element, tempClasses);\n        }\n\n        element.removeClass(NG_ANIMATE_CLASSNAME);\n        runner.complete(!rejected);\n      }\n    };\n  }];\n}];\n\n/* global angularAnimateModule: true,\n\n   $$AnimateAsyncRunFactory,\n   $$rAFSchedulerFactory,\n   $$AnimateChildrenDirective,\n   $$AnimateRunnerFactory,\n   $$AnimateQueueProvider,\n   $$AnimationProvider,\n   $AnimateCssProvider,\n   $$AnimateCssDriverProvider,\n   $$AnimateJsProvider,\n   $$AnimateJsDriverProvider,\n*/\n\n/**\n * @ngdoc module\n * @name ngAnimate\n * @description\n *\n * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via\n * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.\n *\n * <div doc-module-components=\"ngAnimate\"></div>\n *\n * # Usage\n * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based\n * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For\n * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within\n * the HTML element that the animation will be triggered on.\n *\n * ## Directive Support\n * The following directives are \"animation aware\":\n *\n * | Directive                                                                                                | Supported Animations                                                     |\n * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|\n * | {@link ng.directive:ngRepeat#animations ngRepeat}                                                        | enter, leave and move                                                    |\n * | {@link ngRoute.directive:ngView#animations ngView}                                                       | enter and leave                                                          |\n * | {@link ng.directive:ngInclude#animations ngInclude}                                                      | enter and leave                                                          |\n * | {@link ng.directive:ngSwitch#animations ngSwitch}                                                        | enter and leave                                                          |\n * | {@link ng.directive:ngIf#animations ngIf}                                                                | enter and leave                                                          |\n * | {@link ng.directive:ngClass#animations ngClass}                                                          | add and remove (the CSS class(es) present)                               |\n * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide}            | add and remove (the ng-hide class value)                                 |\n * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel}    | add and remove (dirty, pristine, valid, invalid & all other validations) |\n * | {@link module:ngMessages#animations ngMessages}                                                          | add and remove (ng-active & ng-inactive)                                 |\n * | {@link module:ngMessages#animations ngMessage}                                                           | enter and leave                                                          |\n *\n * (More information can be found by visiting each the documentation associated with each directive.)\n *\n * ## CSS-based Animations\n *\n * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML\n * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.\n *\n * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:\n *\n * ```html\n * <div ng-if=\"bool\" class=\"fade\">\n *    Fade me in out\n * </div>\n * <button ng-click=\"bool=true\">Fade In!</button>\n * <button ng-click=\"bool=false\">Fade Out!</button>\n * ```\n *\n * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:\n *\n * ```css\n * /&#42; The starting CSS styles for the enter animation &#42;/\n * .fade.ng-enter {\n *   transition:0.5s linear all;\n *   opacity:0;\n * }\n *\n * /&#42; The finishing CSS styles for the enter animation &#42;/\n * .fade.ng-enter.ng-enter-active {\n *   opacity:1;\n * }\n * ```\n *\n * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two\n * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition\n * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.\n *\n * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:\n *\n * ```css\n * /&#42; now the element will fade out before it is removed from the DOM &#42;/\n * .fade.ng-leave {\n *   transition:0.5s linear all;\n *   opacity:1;\n * }\n * .fade.ng-leave.ng-leave-active {\n *   opacity:0;\n * }\n * ```\n *\n * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:\n *\n * ```css\n * /&#42; there is no need to define anything inside of the destination\n * CSS class since the keyframe will take charge of the animation &#42;/\n * .fade.ng-leave {\n *   animation: my_fade_animation 0.5s linear;\n *   -webkit-animation: my_fade_animation 0.5s linear;\n * }\n *\n * @keyframes my_fade_animation {\n *   from { opacity:1; }\n *   to { opacity:0; }\n * }\n *\n * @-webkit-keyframes my_fade_animation {\n *   from { opacity:1; }\n *   to { opacity:0; }\n * }\n * ```\n *\n * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.\n *\n * ### CSS Class-based Animations\n *\n * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different\n * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added\n * and removed.\n *\n * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:\n *\n * ```html\n * <div ng-show=\"bool\" class=\"fade\">\n *   Show and hide me\n * </div>\n * <button ng-click=\"bool=true\">Toggle</button>\n *\n * <style>\n * .fade.ng-hide {\n *   transition:0.5s linear all;\n *   opacity:0;\n * }\n * </style>\n * ```\n *\n * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since\n * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.\n *\n * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation\n * with CSS styles.\n *\n * ```html\n * <div ng-class=\"{on:onOff}\" class=\"highlight\">\n *   Highlight this box\n * </div>\n * <button ng-click=\"onOff=!onOff\">Toggle</button>\n *\n * <style>\n * .highlight {\n *   transition:0.5s linear all;\n * }\n * .highlight.on-add {\n *   background:white;\n * }\n * .highlight.on {\n *   background:yellow;\n * }\n * .highlight.on-remove {\n *   background:black;\n * }\n * </style>\n * ```\n *\n * We can also make use of CSS keyframes by placing them within the CSS classes.\n *\n *\n * ### CSS Staggering Animations\n * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a\n * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be\n * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for\n * the animation. The style property expected within the stagger class can either be a **transition-delay** or an\n * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).\n *\n * ```css\n * .my-animation.ng-enter {\n *   /&#42; standard transition code &#42;/\n *   transition: 1s linear all;\n *   opacity:0;\n * }\n * .my-animation.ng-enter-stagger {\n *   /&#42; this will have a 100ms delay between each successive leave animation &#42;/\n *   transition-delay: 0.1s;\n *\n *   /&#42; As of 1.4.4, this must always be set: it signals ngAnimate\n *     to not accidentally inherit a delay property from another CSS class &#42;/\n *   transition-duration: 0s;\n * }\n * .my-animation.ng-enter.ng-enter-active {\n *   /&#42; standard transition styles &#42;/\n *   opacity:1;\n * }\n * ```\n *\n * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations\n * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this\n * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation\n * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.\n *\n * The following code will issue the **ng-leave-stagger** event on the element provided:\n *\n * ```js\n * var kids = parent.children();\n *\n * $animate.leave(kids[0]); //stagger index=0\n * $animate.leave(kids[1]); //stagger index=1\n * $animate.leave(kids[2]); //stagger index=2\n * $animate.leave(kids[3]); //stagger index=3\n * $animate.leave(kids[4]); //stagger index=4\n *\n * window.requestAnimationFrame(function() {\n *   //stagger has reset itself\n *   $animate.leave(kids[5]); //stagger index=0\n *   $animate.leave(kids[6]); //stagger index=1\n *\n *   $scope.$digest();\n * });\n * ```\n *\n * Stagger animations are currently only supported within CSS-defined animations.\n *\n * ### The `ng-animate` CSS class\n *\n * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.\n * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).\n *\n * Therefore, animations can be applied to an element using this temporary class directly via CSS.\n *\n * ```css\n * .zipper.ng-animate {\n *   transition:0.5s linear all;\n * }\n * .zipper.ng-enter {\n *   opacity:0;\n * }\n * .zipper.ng-enter.ng-enter-active {\n *   opacity:1;\n * }\n * .zipper.ng-leave {\n *   opacity:1;\n * }\n * .zipper.ng-leave.ng-leave-active {\n *   opacity:0;\n * }\n * ```\n *\n * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove\n * the CSS class once an animation has completed.)\n *\n *\n * ## JavaScript-based Animations\n *\n * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared\n * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the\n * `module.animation()` module function we can register the ainmation.\n *\n * Let's see an example of a enter/leave animation using `ngRepeat`:\n *\n * ```html\n * <div ng-repeat=\"item in items\" class=\"slide\">\n *   {{ item }}\n * </div>\n * ```\n *\n * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:\n *\n * ```js\n * myModule.animation('.slide', [function() {\n *   return {\n *     // make note that other events (like addClass/removeClass)\n *     // have different function input parameters\n *     enter: function(element, doneFn) {\n *       jQuery(element).fadeIn(1000, doneFn);\n *\n *       // remember to call doneFn so that angular\n *       // knows that the animation has concluded\n *     },\n *\n *     move: function(element, doneFn) {\n *       jQuery(element).fadeIn(1000, doneFn);\n *     },\n *\n *     leave: function(element, doneFn) {\n *       jQuery(element).fadeOut(1000, doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as\n * greensock.js and velocity.js.\n *\n * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define\n * our animations inside of the same registered animation, however, the function input arguments are a bit different:\n *\n * ```html\n * <div ng-class=\"color\" class=\"colorful\">\n *   this box is moody\n * </div>\n * <button ng-click=\"color='red'\">Change to red</button>\n * <button ng-click=\"color='blue'\">Change to blue</button>\n * <button ng-click=\"color='green'\">Change to green</button>\n * ```\n *\n * ```js\n * myModule.animation('.colorful', [function() {\n *   return {\n *     addClass: function(element, className, doneFn) {\n *       // do some cool animation and call the doneFn\n *     },\n *     removeClass: function(element, className, doneFn) {\n *       // do some cool animation and call the doneFn\n *     },\n *     setClass: function(element, addedClass, removedClass, doneFn) {\n *       // do some cool animation and call the doneFn\n *     }\n *   }\n * }]\n * ```\n *\n * ## CSS + JS Animations Together\n *\n * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,\n * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking\n * charge of the animation**:\n *\n * ```html\n * <div ng-if=\"bool\" class=\"slide\">\n *   Slide in and out\n * </div>\n * ```\n *\n * ```js\n * myModule.animation('.slide', [function() {\n *   return {\n *     enter: function(element, doneFn) {\n *       jQuery(element).slideIn(1000, doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * ```css\n * .slide.ng-enter {\n *   transition:0.5s linear all;\n *   transform:translateY(-100px);\n * }\n * .slide.ng-enter.ng-enter-active {\n *   transform:translateY(0);\n * }\n * ```\n *\n * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the\n * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from\n * our own JS-based animation code:\n *\n * ```js\n * myModule.animation('.slide', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n*        // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.\n *       var runner = $animateCss(element, {\n *         event: 'enter',\n *         structural: true\n *       }).start();\n*        runner.done(doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.\n *\n * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or\n * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that\n * data into `$animateCss` directly:\n *\n * ```js\n * myModule.animation('.slide', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n *       var runner = $animateCss(element, {\n *         event: 'enter',\n *         structural: true,\n *         addClass: 'maroon-setting',\n *         from: { height:0 },\n *         to: { height: 200 }\n *       }).start();\n *\n *       runner.done(doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * Now we can fill in the rest via our transition CSS code:\n *\n * ```css\n * /&#42; the transition tells ngAnimate to make the animation happen &#42;/\n * .slide.ng-enter { transition:0.5s linear all; }\n *\n * /&#42; this extra CSS class will be absorbed into the transition\n * since the $animateCss code is adding the class &#42;/\n * .maroon-setting { background:red; }\n * ```\n *\n * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.\n *\n * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.\n *\n * ## Animation Anchoring (via `ng-animate-ref`)\n *\n * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between\n * structural areas of an application (like views) by pairing up elements using an attribute\n * called `ng-animate-ref`.\n *\n * Let's say for example we have two views that are managed by `ng-view` and we want to show\n * that there is a relationship between two components situated in within these views. By using the\n * `ng-animate-ref` attribute we can identify that the two components are paired together and we\n * can then attach an animation, which is triggered when the view changes.\n *\n * Say for example we have the following template code:\n *\n * ```html\n * <!-- index.html -->\n * <div ng-view class=\"view-animation\">\n * </div>\n *\n * <!-- home.html -->\n * <a href=\"#/banner-page\">\n *   <img src=\"./banner.jpg\" class=\"banner\" ng-animate-ref=\"banner\">\n * </a>\n *\n * <!-- banner-page.html -->\n * <img src=\"./banner.jpg\" class=\"banner\" ng-animate-ref=\"banner\">\n * ```\n *\n * Now, when the view changes (once the link is clicked), ngAnimate will examine the\n * HTML contents to see if there is a match reference between any components in the view\n * that is leaving and the view that is entering. It will scan both the view which is being\n * removed (leave) and inserted (enter) to see if there are any paired DOM elements that\n * contain a matching ref value.\n *\n * The two images match since they share the same ref value. ngAnimate will now create a\n * transport element (which is a clone of the first image element) and it will then attempt\n * to animate to the position of the second image element in the next view. For the animation to\n * work a special CSS class called `ng-anchor` will be added to the transported element.\n *\n * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then\n * ngAnimate will handle the entire transition for us as well as the addition and removal of\n * any changes of CSS classes between the elements:\n *\n * ```css\n * .banner.ng-anchor {\n *   /&#42; this animation will last for 1 second since there are\n *          two phases to the animation (an `in` and an `out` phase) &#42;/\n *   transition:0.5s linear all;\n * }\n * ```\n *\n * We also **must** include animations for the views that are being entered and removed\n * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).\n *\n * ```css\n * .view-animation.ng-enter, .view-animation.ng-leave {\n *   transition:0.5s linear all;\n *   position:fixed;\n *   left:0;\n *   top:0;\n *   width:100%;\n * }\n * .view-animation.ng-enter {\n *   transform:translateX(100%);\n * }\n * .view-animation.ng-leave,\n * .view-animation.ng-enter.ng-enter-active {\n *   transform:translateX(0%);\n * }\n * .view-animation.ng-leave.ng-leave-active {\n *   transform:translateX(-100%);\n * }\n * ```\n *\n * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:\n * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away\n * from its origin. Once that animation is over then the `in` stage occurs which animates the\n * element to its destination. The reason why there are two animations is to give enough time\n * for the enter animation on the new element to be ready.\n *\n * The example above sets up a transition for both the in and out phases, but we can also target the out or\n * in phases directly via `ng-anchor-out` and `ng-anchor-in`.\n *\n * ```css\n * .banner.ng-anchor-out {\n *   transition: 0.5s linear all;\n *\n *   /&#42; the scale will be applied during the out animation,\n *          but will be animated away when the in animation runs &#42;/\n *   transform: scale(1.2);\n * }\n *\n * .banner.ng-anchor-in {\n *   transition: 1s linear all;\n * }\n * ```\n *\n *\n *\n *\n * ### Anchoring Demo\n *\n  <example module=\"anchoringExample\"\n           name=\"anchoringExample\"\n           id=\"anchoringExample\"\n           deps=\"angular-animate.js;angular-route.js\"\n           animations=\"true\">\n    <file name=\"index.html\">\n      <a href=\"#/\">Home</a>\n      <hr />\n      <div class=\"view-container\">\n        <div ng-view class=\"view\"></div>\n      </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])\n        .config(['$routeProvider', function($routeProvider) {\n          $routeProvider.when('/', {\n            templateUrl: 'home.html',\n            controller: 'HomeController as home'\n          });\n          $routeProvider.when('/profile/:id', {\n            templateUrl: 'profile.html',\n            controller: 'ProfileController as profile'\n          });\n        }])\n        .run(['$rootScope', function($rootScope) {\n          $rootScope.records = [\n            { id:1, title: \"Miss Beulah Roob\" },\n            { id:2, title: \"Trent Morissette\" },\n            { id:3, title: \"Miss Ava Pouros\" },\n            { id:4, title: \"Rod Pouros\" },\n            { id:5, title: \"Abdul Rice\" },\n            { id:6, title: \"Laurie Rutherford Sr.\" },\n            { id:7, title: \"Nakia McLaughlin\" },\n            { id:8, title: \"Jordon Blanda DVM\" },\n            { id:9, title: \"Rhoda Hand\" },\n            { id:10, title: \"Alexandrea Sauer\" }\n          ];\n        }])\n        .controller('HomeController', [function() {\n          //empty\n        }])\n        .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {\n          var index = parseInt($routeParams.id, 10);\n          var record = $rootScope.records[index - 1];\n\n          this.title = record.title;\n          this.id = record.id;\n        }]);\n    </file>\n    <file name=\"home.html\">\n      <h2>Welcome to the home page</h1>\n      <p>Please click on an element</p>\n      <a class=\"record\"\n         ng-href=\"#/profile/{{ record.id }}\"\n         ng-animate-ref=\"{{ record.id }}\"\n         ng-repeat=\"record in records\">\n        {{ record.title }}\n      </a>\n    </file>\n    <file name=\"profile.html\">\n      <div class=\"profile record\" ng-animate-ref=\"{{ profile.id }}\">\n        {{ profile.title }}\n      </div>\n    </file>\n    <file name=\"animations.css\">\n      .record {\n        display:block;\n        font-size:20px;\n      }\n      .profile {\n        background:black;\n        color:white;\n        font-size:100px;\n      }\n      .view-container {\n        position:relative;\n      }\n      .view-container > .view.ng-animate {\n        position:absolute;\n        top:0;\n        left:0;\n        width:100%;\n        min-height:500px;\n      }\n      .view.ng-enter, .view.ng-leave,\n      .record.ng-anchor {\n        transition:0.5s linear all;\n      }\n      .view.ng-enter {\n        transform:translateX(100%);\n      }\n      .view.ng-enter.ng-enter-active, .view.ng-leave {\n        transform:translateX(0%);\n      }\n      .view.ng-leave.ng-leave-active {\n        transform:translateX(-100%);\n      }\n      .record.ng-anchor-out {\n        background:red;\n      }\n    </file>\n  </example>\n *\n * ### How is the element transported?\n *\n * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting\n * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element\n * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The\n * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match\n * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied\n * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class\n * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element\n * will become visible since the shim class will be removed.\n *\n * ### How is the morphing handled?\n *\n * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out\n * what CSS classes differ between the starting element and the destination element. These different CSS classes\n * will be added/removed on the anchor element and a transition will be applied (the transition that is provided\n * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will\n * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that\n * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since\n * the cloned element is placed inside of root element which is likely close to the body element).\n *\n * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.\n *\n *\n * ## Using $animate in your directive code\n *\n * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?\n * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's\n * imagine we have a greeting box that shows and hides itself when the data changes\n *\n * ```html\n * <greeting-box active=\"onOrOff\">Hi there</greeting-box>\n * ```\n *\n * ```js\n * ngModule.directive('greetingBox', ['$animate', function($animate) {\n *   return function(scope, element, attrs) {\n *     attrs.$observe('active', function(value) {\n *       value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');\n *     });\n *   });\n * }]);\n * ```\n *\n * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element\n * in our HTML code then we can trigger a CSS or JS animation to happen.\n *\n * ```css\n * /&#42; normally we would create a CSS class to reference on the element &#42;/\n * greeting-box.on { transition:0.5s linear all; background:green; color:white; }\n * ```\n *\n * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's\n * possible be sure to visit the {@link ng.$animate $animate service API page}.\n *\n *\n * ### Preventing Collisions With Third Party Libraries\n *\n * Some third-party frameworks place animation duration defaults across many element or className\n * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which\n * is expecting actual animations on these elements and has to wait for their completion.\n *\n * You can prevent this unwanted behavior by using a prefix on all your animation classes:\n *\n * ```css\n * /&#42; prefixed with animate- &#42;/\n * .animate-fade-add.animate-fade-add-active {\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * You then configure `$animate` to enforce this prefix:\n *\n * ```js\n * $animateProvider.classNameFilter(/animate-/);\n * ```\n *\n * This also may provide your application with a speed boost since only specific elements containing CSS class prefix\n * will be evaluated for animation when any DOM changes occur in the application.\n *\n * ## Callbacks and Promises\n *\n * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger\n * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has\n * ended by chaining onto the returned promise that animation method returns.\n *\n * ```js\n * // somewhere within the depths of the directive\n * $animate.enter(element, parent).then(function() {\n *   //the animation has completed\n * });\n * ```\n *\n * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case\n * anymore.)\n *\n * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering\n * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view\n * routing controller to hook into that:\n *\n * ```js\n * ngModule.controller('HomePageController', ['$animate', function($animate) {\n *   $animate.on('enter', ngViewElement, function(element) {\n *     // the animation for this route has completed\n *   }]);\n * }])\n * ```\n *\n * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)\n */\n\n/**\n * @ngdoc service\n * @name $animate\n * @kind object\n *\n * @description\n * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.\n *\n * Click here {@link ng.$animate to learn more about animations with `$animate`}.\n */\nangular.module('ngAnimate', [])\n  .directive('ngAnimateChildren', $$AnimateChildrenDirective)\n  .factory('$$rAFScheduler', $$rAFSchedulerFactory)\n\n  .factory('$$AnimateRunner', $$AnimateRunnerFactory)\n  .factory('$$animateAsyncRun', $$AnimateAsyncRunFactory)\n\n  .provider('$$animateQueue', $$AnimateQueueProvider)\n  .provider('$$animation', $$AnimationProvider)\n\n  .provider('$animateCss', $AnimateCssProvider)\n  .provider('$$animateCssDriver', $$AnimateCssDriverProvider)\n\n  .provider('$$animateJs', $$AnimateJsProvider)\n  .provider('$$animateJsDriver', $$AnimateJsDriverProvider);\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/client/vendor/angular-messages.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* jshint ignore:start */\n// this code is in the core, but not in angular-messages.js\nvar isArray = angular.isArray;\nvar forEach = angular.forEach;\nvar isString = angular.isString;\nvar jqLite = angular.element;\n/* jshint ignore:end */\n\n/**\n * @ngdoc module\n * @name ngMessages\n * @description\n *\n * The `ngMessages` module provides enhanced support for displaying messages within templates\n * (typically within forms or when rendering message objects that return key/value data).\n * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to\n * show and hide error messages specific to the state of an input field, the `ngMessages` and\n * `ngMessage` directives are designed to handle the complexity, inheritance and priority\n * sequencing based on the order of how the messages are defined in the template.\n *\n * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude`\n * `ngMessage` and `ngMessageExp` directives.\n *\n * # Usage\n * The `ngMessages` directive listens on a key/value collection which is set on the ngMessages attribute.\n * Since the {@link ngModel ngModel} directive exposes an `$error` object, this error object can be\n * used with `ngMessages` to display control error messages in an easier way than with just regular angular\n * template directives.\n *\n * ```html\n * <form name=\"myForm\">\n *   <label>\n *     Enter text:\n *     <input type=\"text\" ng-model=\"field\" name=\"myField\" required minlength=\"5\" />\n *   </label>\n *   <div ng-messages=\"myForm.myField.$error\" role=\"alert\">\n *     <div ng-message=\"required\">You did not enter a field</div>\n *     <div ng-message=\"minlength, maxlength\">\n *       Your email must be between 5 and 100 characters long\n *     </div>\n *   </div>\n * </form>\n * ```\n *\n * Now whatever key/value entries are present within the provided object (in this case `$error`) then\n * the ngMessages directive will render the inner first ngMessage directive (depending if the key values\n * match the attribute value present on each ngMessage directive). In other words, if your errors\n * object contains the following data:\n *\n * ```javascript\n * <!-- keep in mind that ngModel automatically sets these error flags -->\n * myField.$error = { minlength : true, required : true };\n * ```\n *\n * Then the `required` message will be displayed first. When required is false then the `minlength` message\n * will be displayed right after (since these messages are ordered this way in the template HTML code).\n * The prioritization of each message is determined by what order they're present in the DOM.\n * Therefore, instead of having custom JavaScript code determine the priority of what errors are\n * present before others, the presentation of the errors are handled within the template.\n *\n * By default, ngMessages will only display one error at a time. However, if you wish to display all\n * messages then the `ng-messages-multiple` attribute flag can be used on the element containing the\n * ngMessages directive to make this happen.\n *\n * ```html\n * <!-- attribute-style usage -->\n * <div ng-messages=\"myForm.myField.$error\" ng-messages-multiple>...</div>\n *\n * <!-- element-style usage -->\n * <ng-messages for=\"myForm.myField.$error\" multiple>...</ng-messages>\n * ```\n *\n * ## Reusing and Overriding Messages\n * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline\n * template. This allows for generic collection of messages to be reused across multiple parts of an\n * application.\n *\n * ```html\n * <script type=\"text/ng-template\" id=\"error-messages\">\n *   <div ng-message=\"required\">This field is required</div>\n *   <div ng-message=\"minlength\">This field is too short</div>\n * </script>\n *\n * <div ng-messages=\"myForm.myField.$error\" role=\"alert\">\n *   <div ng-messages-include=\"error-messages\"></div>\n * </div>\n * ```\n *\n * However, including generic messages may not be useful enough to match all input fields, therefore,\n * `ngMessages` provides the ability to override messages defined in the remote template by redefining\n * them within the directive container.\n *\n * ```html\n * <!-- a generic template of error messages known as \"my-custom-messages\" -->\n * <script type=\"text/ng-template\" id=\"my-custom-messages\">\n *   <div ng-message=\"required\">This field is required</div>\n *   <div ng-message=\"minlength\">This field is too short</div>\n * </script>\n *\n * <form name=\"myForm\">\n *   <label>\n *     Email address\n *     <input type=\"email\"\n *            id=\"email\"\n *            name=\"myEmail\"\n *            ng-model=\"email\"\n *            minlength=\"5\"\n *            required />\n *   </label>\n *   <!-- any ng-message elements that appear BEFORE the ng-messages-include will\n *        override the messages present in the ng-messages-include template -->\n *   <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *     <!-- this required message has overridden the template message -->\n *     <div ng-message=\"required\">You did not enter your email address</div>\n *\n *     <!-- this is a brand new message and will appear last in the prioritization -->\n *     <div ng-message=\"email\">Your email address is invalid</div>\n *\n *     <!-- and here are the generic error messages -->\n *     <div ng-messages-include=\"my-custom-messages\"></div>\n *   </div>\n * </form>\n * ```\n *\n * In the example HTML code above the message that is set on required will override the corresponding\n * required message defined within the remote template. Therefore, with particular input fields (such\n * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied\n * while more generic messages can be used to handle other, more general input errors.\n *\n * ## Dynamic Messaging\n * ngMessages also supports using expressions to dynamically change key values. Using arrays and\n * repeaters to list messages is also supported. This means that the code below will be able to\n * fully adapt itself and display the appropriate message when any of the expression data changes:\n *\n * ```html\n * <form name=\"myForm\">\n *   <label>\n *     Email address\n *     <input type=\"email\"\n *            name=\"myEmail\"\n *            ng-model=\"email\"\n *            minlength=\"5\"\n *            required />\n *   </label>\n *   <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *     <div ng-message=\"required\">You did not enter your email address</div>\n *     <div ng-repeat=\"errorMessage in errorMessages\">\n *       <!-- use ng-message-exp for a message whose key is given by an expression -->\n *       <div ng-message-exp=\"errorMessage.type\">{{ errorMessage.text }}</div>\n *     </div>\n *   </div>\n * </form>\n * ```\n *\n * The `errorMessage.type` expression can be a string value or it can be an array so\n * that multiple errors can be associated with a single error message:\n *\n * ```html\n *   <label>\n *     Email address\n *     <input type=\"email\"\n *            ng-model=\"data.email\"\n *            name=\"myEmail\"\n *            ng-minlength=\"5\"\n *            ng-maxlength=\"100\"\n *            required />\n *   </label>\n *   <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *     <div ng-message-exp=\"'required'\">You did not enter your email address</div>\n *     <div ng-message-exp=\"['minlength', 'maxlength']\">\n *       Your email must be between 5 and 100 characters long\n *     </div>\n *   </div>\n * ```\n *\n * Feel free to use other structural directives such as ng-if and ng-switch to further control\n * what messages are active and when. Be careful, if you place ng-message on the same element\n * as these structural directives, Angular may not be able to determine if a message is active\n * or not. Therefore it is best to place the ng-message on a child element of the structural\n * directive.\n *\n * ```html\n * <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *   <div ng-if=\"showRequiredError\">\n *     <div ng-message=\"required\">Please enter something</div>\n *   </div>\n * </div>\n * ```\n *\n * ## Animations\n * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and\n * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from\n * the DOM by the `ngMessages` directive.\n *\n * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS\n * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no\n * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can\n * hook into the animations whenever these classes are added/removed.\n *\n * Let's say that our HTML code for our messages container looks like so:\n *\n * ```html\n * <div ng-messages=\"myMessages\" class=\"my-messages\" role=\"alert\">\n *   <div ng-message=\"alert\" class=\"some-message\">...</div>\n *   <div ng-message=\"fail\" class=\"some-message\">...</div>\n * </div>\n * ```\n *\n * Then the CSS animation code for the message container looks like so:\n *\n * ```css\n * .my-messages {\n *   transition:1s linear all;\n * }\n * .my-messages.ng-active {\n *   // messages are visible\n * }\n * .my-messages.ng-inactive {\n *   // messages are hidden\n * }\n * ```\n *\n * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter\n * and leave animation is triggered for each particular element bound to the `ngMessage` directive.\n *\n * Therefore, the CSS code for the inner messages looks like so:\n *\n * ```css\n * .some-message {\n *   transition:1s linear all;\n * }\n *\n * .some-message.ng-enter {}\n * .some-message.ng-enter.ng-enter-active {}\n *\n * .some-message.ng-leave {}\n * .some-message.ng-leave.ng-leave-active {}\n * ```\n *\n * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate.\n */\nangular.module('ngMessages', [])\n\n   /**\n    * @ngdoc directive\n    * @module ngMessages\n    * @name ngMessages\n    * @restrict AE\n    *\n    * @description\n    * `ngMessages` is a directive that is designed to show and hide messages based on the state\n    * of a key/value object that it listens on. The directive itself complements error message\n    * reporting with the `ngModel` $error object (which stores a key/value state of validation errors).\n    *\n    * `ngMessages` manages the state of internal messages within its container element. The internal\n    * messages use the `ngMessage` directive and will be inserted/removed from the page depending\n    * on if they're present within the key/value object. By default, only one message will be displayed\n    * at a time and this depends on the prioritization of the messages within the template. (This can\n    * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.)\n    *\n    * A remote template can also be used to promote message reusability and messages can also be\n    * overridden.\n    *\n    * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\" role=\"alert\">\n    *   <ANY ng-message=\"stringValue\">...</ANY>\n    *   <ANY ng-message=\"stringValue1, stringValue2, ...\">...</ANY>\n    *   <ANY ng-message-exp=\"expressionValue\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\" role=\"alert\">\n    *   <ng-message when=\"stringValue\">...</ng-message>\n    *   <ng-message when=\"stringValue1, stringValue2, ...\">...</ng-message>\n    *   <ng-message when-exp=\"expressionValue\">...</ng-message>\n    * </ng-messages>\n    * ```\n    *\n    * @param {string} ngMessages an angular expression evaluating to a key/value object\n    *                 (this is typically the $error object on an ngModel instance).\n    * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true\n    *\n    * @example\n    * <example name=\"ngMessages-directive\" module=\"ngMessagesExample\"\n    *          deps=\"angular-messages.js\"\n    *          animations=\"true\" fixBase=\"true\">\n    *   <file name=\"index.html\">\n    *     <form name=\"myForm\">\n    *       <label>\n    *         Enter your name:\n    *         <input type=\"text\"\n    *                name=\"myName\"\n    *                ng-model=\"name\"\n    *                ng-minlength=\"5\"\n    *                ng-maxlength=\"20\"\n    *                required />\n    *       </label>\n    *       <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>\n    *\n    *       <div ng-messages=\"myForm.myName.$error\" style=\"color:maroon\" role=\"alert\">\n    *         <div ng-message=\"required\">You did not enter a field</div>\n    *         <div ng-message=\"minlength\">Your field is too short</div>\n    *         <div ng-message=\"maxlength\">Your field is too long</div>\n    *       </div>\n    *     </form>\n    *   </file>\n    *   <file name=\"script.js\">\n    *     angular.module('ngMessagesExample', ['ngMessages']);\n    *   </file>\n    * </example>\n    */\n   .directive('ngMessages', ['$animate', function($animate) {\n     var ACTIVE_CLASS = 'ng-active';\n     var INACTIVE_CLASS = 'ng-inactive';\n\n     return {\n       require: 'ngMessages',\n       restrict: 'AE',\n       controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {\n         var ctrl = this;\n         var latestKey = 0;\n         var nextAttachId = 0;\n\n         this.getAttachId = function getAttachId() { return nextAttachId++; };\n\n         var messages = this.messages = {};\n         var renderLater, cachedCollection;\n\n         this.render = function(collection) {\n           collection = collection || {};\n\n           renderLater = false;\n           cachedCollection = collection;\n\n           // this is true if the attribute is empty or if the attribute value is truthy\n           var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) ||\n                          isAttrTruthy($scope, $attrs.multiple);\n\n           var unmatchedMessages = [];\n           var matchedKeys = {};\n           var messageItem = ctrl.head;\n           var messageFound = false;\n           var totalMessages = 0;\n\n           // we use != instead of !== to allow for both undefined and null values\n           while (messageItem != null) {\n             totalMessages++;\n             var messageCtrl = messageItem.message;\n\n             var messageUsed = false;\n             if (!messageFound) {\n               forEach(collection, function(value, key) {\n                 if (!messageUsed && truthy(value) && messageCtrl.test(key)) {\n                   // this is to prevent the same error name from showing up twice\n                   if (matchedKeys[key]) return;\n                   matchedKeys[key] = true;\n\n                   messageUsed = true;\n                   messageCtrl.attach();\n                 }\n               });\n             }\n\n             if (messageUsed) {\n               // unless we want to display multiple messages then we should\n               // set a flag here to avoid displaying the next message in the list\n               messageFound = !multiple;\n             } else {\n               unmatchedMessages.push(messageCtrl);\n             }\n\n             messageItem = messageItem.next;\n           }\n\n           forEach(unmatchedMessages, function(messageCtrl) {\n             messageCtrl.detach();\n           });\n\n           unmatchedMessages.length !== totalMessages\n              ? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS)\n              : $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS);\n         };\n\n         $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render);\n\n         this.reRender = function() {\n           if (!renderLater) {\n             renderLater = true;\n             $scope.$evalAsync(function() {\n               if (renderLater) {\n                 cachedCollection && ctrl.render(cachedCollection);\n               }\n             });\n           }\n         };\n\n         this.register = function(comment, messageCtrl) {\n           var nextKey = latestKey.toString();\n           messages[nextKey] = {\n             message: messageCtrl\n           };\n           insertMessageNode($element[0], comment, nextKey);\n           comment.$$ngMessageNode = nextKey;\n           latestKey++;\n\n           ctrl.reRender();\n         };\n\n         this.deregister = function(comment) {\n           var key = comment.$$ngMessageNode;\n           delete comment.$$ngMessageNode;\n           removeMessageNode($element[0], comment, key);\n           delete messages[key];\n           ctrl.reRender();\n         };\n\n         function findPreviousMessage(parent, comment) {\n           var prevNode = comment;\n           var parentLookup = [];\n           while (prevNode && prevNode !== parent) {\n             var prevKey = prevNode.$$ngMessageNode;\n             if (prevKey && prevKey.length) {\n               return messages[prevKey];\n             }\n\n             // dive deeper into the DOM and examine its children for any ngMessage\n             // comments that may be in an element that appears deeper in the list\n             if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) {\n               parentLookup.push(prevNode);\n               prevNode = prevNode.childNodes[prevNode.childNodes.length - 1];\n             } else {\n               prevNode = prevNode.previousSibling || prevNode.parentNode;\n             }\n           }\n         }\n\n         function insertMessageNode(parent, comment, key) {\n           var messageNode = messages[key];\n           if (!ctrl.head) {\n             ctrl.head = messageNode;\n           } else {\n             var match = findPreviousMessage(parent, comment);\n             if (match) {\n               messageNode.next = match.next;\n               match.next = messageNode;\n             } else {\n               messageNode.next = ctrl.head;\n               ctrl.head = messageNode;\n             }\n           }\n         }\n\n         function removeMessageNode(parent, comment, key) {\n           var messageNode = messages[key];\n\n           var match = findPreviousMessage(parent, comment);\n           if (match) {\n             match.next = messageNode.next;\n           } else {\n             ctrl.head = messageNode.next;\n           }\n         }\n       }]\n     };\n\n     function isAttrTruthy(scope, attr) {\n      return (isString(attr) && attr.length === 0) || //empty attribute\n             truthy(scope.$eval(attr));\n     }\n\n     function truthy(val) {\n       return isString(val) ? val.length : !!val;\n     }\n   }])\n\n   /**\n    * @ngdoc directive\n    * @name ngMessagesInclude\n    * @restrict AE\n    * @scope\n    *\n    * @description\n    * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template\n    * code from a remote template and place the downloaded template code into the exact spot\n    * that the ngMessagesInclude directive is placed within the ngMessages container. This allows\n    * for a series of pre-defined messages to be reused and also allows for the developer to\n    * determine what messages are overridden due to the placement of the ngMessagesInclude directive.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\" role=\"alert\">\n    *   <ANY ng-messages-include=\"remoteTplString\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\" role=\"alert\">\n    *   <ng-messages-include src=\"expressionValue1\">...</ng-messages-include>\n    * </ng-messages>\n    * ```\n    *\n    * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.\n    *\n    * @param {string} ngMessagesInclude|src a string value corresponding to the remote template.\n    */\n   .directive('ngMessagesInclude',\n     ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) {\n\n     return {\n       restrict: 'AE',\n       require: '^^ngMessages', // we only require this for validation sake\n       link: function($scope, element, attrs) {\n         var src = attrs.ngMessagesInclude || attrs.src;\n         $templateRequest(src).then(function(html) {\n           $compile(html)($scope, function(contents) {\n             element.after(contents);\n\n             // the anchor is placed for debugging purposes\n             var anchor = jqLite($document[0].createComment(' ngMessagesInclude: ' + src + ' '));\n             element.after(anchor);\n\n             // we don't want to pollute the DOM anymore by keeping an empty directive element\n             element.remove();\n           });\n         });\n       }\n     };\n   }])\n\n   /**\n    * @ngdoc directive\n    * @name ngMessage\n    * @restrict AE\n    * @scope\n    *\n    * @description\n    * `ngMessage` is a directive with the purpose to show and hide a particular message.\n    * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element\n    * must be situated since it determines which messages are visible based on the state\n    * of the provided key/value map that `ngMessages` listens on.\n    *\n    * More information about using `ngMessage` can be found in the\n    * {@link module:ngMessages `ngMessages` module documentation}.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\" role=\"alert\">\n    *   <ANY ng-message=\"stringValue\">...</ANY>\n    *   <ANY ng-message=\"stringValue1, stringValue2, ...\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\" role=\"alert\">\n    *   <ng-message when=\"stringValue\">...</ng-message>\n    *   <ng-message when=\"stringValue1, stringValue2, ...\">...</ng-message>\n    * </ng-messages>\n    * ```\n    *\n    * @param {expression} ngMessage|when a string value corresponding to the message key.\n    */\n  .directive('ngMessage', ngMessageDirectiveFactory('AE'))\n\n\n   /**\n    * @ngdoc directive\n    * @name ngMessageExp\n    * @restrict AE\n    * @scope\n    *\n    * @description\n    * `ngMessageExp` is a directive with the purpose to show and hide a particular message.\n    * For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element\n    * must be situated since it determines which messages are visible based on the state\n    * of the provided key/value map that `ngMessages` listens on.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\">\n    *   <ANY ng-message-exp=\"expressionValue\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\">\n    *   <ng-message when-exp=\"expressionValue\">...</ng-message>\n    * </ng-messages>\n    * ```\n    *\n    * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.\n    *\n    * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key.\n    */\n  .directive('ngMessageExp', ngMessageDirectiveFactory('A'));\n\nfunction ngMessageDirectiveFactory(restrict) {\n  return ['$animate', function($animate) {\n    return {\n      restrict: 'AE',\n      transclude: 'element',\n      terminal: true,\n      require: '^^ngMessages',\n      link: function(scope, element, attrs, ngMessagesCtrl, $transclude) {\n        var commentNode = element[0];\n\n        var records;\n        var staticExp = attrs.ngMessage || attrs.when;\n        var dynamicExp = attrs.ngMessageExp || attrs.whenExp;\n        var assignRecords = function(items) {\n          records = items\n              ? (isArray(items)\n                    ? items\n                    : items.split(/[\\s,]+/))\n              : null;\n          ngMessagesCtrl.reRender();\n        };\n\n        if (dynamicExp) {\n          assignRecords(scope.$eval(dynamicExp));\n          scope.$watchCollection(dynamicExp, assignRecords);\n        } else {\n          assignRecords(staticExp);\n        }\n\n        var currentElement, messageCtrl;\n        ngMessagesCtrl.register(commentNode, messageCtrl = {\n          test: function(name) {\n            return contains(records, name);\n          },\n          attach: function() {\n            if (!currentElement) {\n              $transclude(scope, function(elm) {\n                $animate.enter(elm, null, element);\n                currentElement = elm;\n\n                // Each time we attach this node to a message we get a new id that we can match\n                // when we are destroying the node later.\n                var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId();\n\n                // in the event that the parent element is destroyed\n                // by any other structural directive then it's time\n                // to deregister the message from the controller\n                currentElement.on('$destroy', function() {\n                  if (currentElement && currentElement.$$attachId === $$attachId) {\n                    ngMessagesCtrl.deregister(commentNode);\n                    messageCtrl.detach();\n                  }\n                });\n              });\n            }\n          },\n          detach: function() {\n            if (currentElement) {\n              var elm = currentElement;\n              currentElement = null;\n              $animate.leave(elm);\n            }\n          }\n        });\n      }\n    };\n  }];\n\n  function contains(collection, key) {\n    if (collection) {\n      return isArray(collection)\n          ? collection.indexOf(key) >= 0\n          : collection.hasOwnProperty(key);\n    }\n  }\n}\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/client/vendor/angular-mocks.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {\n\n'use strict';\n\n/**\n * @ngdoc object\n * @name angular.mock\n * @description\n *\n * Namespace from 'angular-mocks.js' which contains testing related code.\n */\nangular.mock = {};\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n *\n * @description\n * This service is a mock implementation of {@link ng.$browser}. It provides fake\n * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,\n * cookies, etc...\n *\n * The api of this service is the same as that of the real {@link ng.$browser $browser}, except\n * that there are several helper methods available which can be used in tests.\n */\nangular.mock.$BrowserProvider = function() {\n  this.$get = function() {\n    return new angular.mock.$Browser();\n  };\n};\n\nangular.mock.$Browser = function() {\n  var self = this;\n\n  this.isMock = true;\n  self.$$url = \"http://server/\";\n  self.$$lastUrl = self.$$url; // used by url polling fn\n  self.pollFns = [];\n\n  // TODO(vojta): remove this temporary api\n  self.$$completeOutstandingRequest = angular.noop;\n  self.$$incOutstandingRequestCount = angular.noop;\n\n\n  // register url polling fn\n\n  self.onUrlChange = function(listener) {\n    self.pollFns.push(\n      function() {\n        if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {\n          self.$$lastUrl = self.$$url;\n          self.$$lastState = self.$$state;\n          listener(self.$$url, self.$$state);\n        }\n      }\n    );\n\n    return listener;\n  };\n\n  self.$$applicationDestroyed = angular.noop;\n  self.$$checkUrlChange = angular.noop;\n\n  self.deferredFns = [];\n  self.deferredNextId = 0;\n\n  self.defer = function(fn, delay) {\n    delay = delay || 0;\n    self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});\n    self.deferredFns.sort(function(a, b) { return a.time - b.time;});\n    return self.deferredNextId++;\n  };\n\n\n  /**\n   * @name $browser#defer.now\n   *\n   * @description\n   * Current milliseconds mock time.\n   */\n  self.defer.now = 0;\n\n\n  self.defer.cancel = function(deferId) {\n    var fnIndex;\n\n    angular.forEach(self.deferredFns, function(fn, index) {\n      if (fn.id === deferId) fnIndex = index;\n    });\n\n    if (angular.isDefined(fnIndex)) {\n      self.deferredFns.splice(fnIndex, 1);\n      return true;\n    }\n\n    return false;\n  };\n\n\n  /**\n   * @name $browser#defer.flush\n   *\n   * @description\n   * Flushes all pending requests and executes the defer callbacks.\n   *\n   * @param {number=} number of milliseconds to flush. See {@link #defer.now}\n   */\n  self.defer.flush = function(delay) {\n    if (angular.isDefined(delay)) {\n      self.defer.now += delay;\n    } else {\n      if (self.deferredFns.length) {\n        self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;\n      } else {\n        throw new Error('No deferred tasks to be flushed');\n      }\n    }\n\n    while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {\n      self.deferredFns.shift().fn();\n    }\n  };\n\n  self.$$baseHref = '/';\n  self.baseHref = function() {\n    return this.$$baseHref;\n  };\n};\nangular.mock.$Browser.prototype = {\n\n/**\n  * @name $browser#poll\n  *\n  * @description\n  * run all fns in pollFns\n  */\n  poll: function poll() {\n    angular.forEach(this.pollFns, function(pollFn) {\n      pollFn();\n    });\n  },\n\n  url: function(url, replace, state) {\n    if (angular.isUndefined(state)) {\n      state = null;\n    }\n    if (url) {\n      this.$$url = url;\n      // Native pushState serializes & copies the object; simulate it.\n      this.$$state = angular.copy(state);\n      return this;\n    }\n\n    return this.$$url;\n  },\n\n  state: function() {\n    return this.$$state;\n  },\n\n  notifyWhenNoOutstandingRequests: function(fn) {\n    fn();\n  }\n};\n\n\n/**\n * @ngdoc provider\n * @name $exceptionHandlerProvider\n *\n * @description\n * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors\n * passed to the `$exceptionHandler`.\n */\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n *\n * @description\n * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed\n * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration\n * information.\n *\n *\n * ```js\n *   describe('$exceptionHandlerProvider', function() {\n *\n *     it('should capture log messages and exceptions', function() {\n *\n *       module(function($exceptionHandlerProvider) {\n *         $exceptionHandlerProvider.mode('log');\n *       });\n *\n *       inject(function($log, $exceptionHandler, $timeout) {\n *         $timeout(function() { $log.log(1); });\n *         $timeout(function() { $log.log(2); throw 'banana peel'; });\n *         $timeout(function() { $log.log(3); });\n *         expect($exceptionHandler.errors).toEqual([]);\n *         expect($log.assertEmpty());\n *         $timeout.flush();\n *         expect($exceptionHandler.errors).toEqual(['banana peel']);\n *         expect($log.log.logs).toEqual([[1], [2], [3]]);\n *       });\n *     });\n *   });\n * ```\n */\n\nangular.mock.$ExceptionHandlerProvider = function() {\n  var handler;\n\n  /**\n   * @ngdoc method\n   * @name $exceptionHandlerProvider#mode\n   *\n   * @description\n   * Sets the logging mode.\n   *\n   * @param {string} mode Mode of operation, defaults to `rethrow`.\n   *\n   *   - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`\n   *            mode stores an array of errors in `$exceptionHandler.errors`, to allow later\n   *            assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and\n   *            {@link ngMock.$log#reset reset()}\n   *   - `rethrow`: If any errors are passed to the handler in tests, it typically means that there\n   *                is a bug in the application or test, so this mock will make these tests fail.\n   *                For any implementations that expect exceptions to be thrown, the `rethrow` mode\n   *                will also maintain a log of thrown errors.\n   */\n  this.mode = function(mode) {\n\n    switch (mode) {\n      case 'log':\n      case 'rethrow':\n        var errors = [];\n        handler = function(e) {\n          if (arguments.length == 1) {\n            errors.push(e);\n          } else {\n            errors.push([].slice.call(arguments, 0));\n          }\n          if (mode === \"rethrow\") {\n            throw e;\n          }\n        };\n        handler.errors = errors;\n        break;\n      default:\n        throw new Error(\"Unknown mode '\" + mode + \"', only 'log'/'rethrow' modes are allowed!\");\n    }\n  };\n\n  this.$get = function() {\n    return handler;\n  };\n\n  this.mode('rethrow');\n};\n\n\n/**\n * @ngdoc service\n * @name $log\n *\n * @description\n * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays\n * (one array per logging level). These arrays are exposed as `logs` property of each of the\n * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.\n *\n */\nangular.mock.$LogProvider = function() {\n  var debug = true;\n\n  function concat(array1, array2, index) {\n    return array1.concat(Array.prototype.slice.call(array2, index));\n  }\n\n  this.debugEnabled = function(flag) {\n    if (angular.isDefined(flag)) {\n      debug = flag;\n      return this;\n    } else {\n      return debug;\n    }\n  };\n\n  this.$get = function() {\n    var $log = {\n      log: function() { $log.log.logs.push(concat([], arguments, 0)); },\n      warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },\n      info: function() { $log.info.logs.push(concat([], arguments, 0)); },\n      error: function() { $log.error.logs.push(concat([], arguments, 0)); },\n      debug: function() {\n        if (debug) {\n          $log.debug.logs.push(concat([], arguments, 0));\n        }\n      }\n    };\n\n    /**\n     * @ngdoc method\n     * @name $log#reset\n     *\n     * @description\n     * Reset all of the logging arrays to empty.\n     */\n    $log.reset = function() {\n      /**\n       * @ngdoc property\n       * @name $log#log.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#log `log()`}.\n       *\n       * @example\n       * ```js\n       * $log.log('Some Log');\n       * var first = $log.log.logs.unshift();\n       * ```\n       */\n      $log.log.logs = [];\n      /**\n       * @ngdoc property\n       * @name $log#info.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#info `info()`}.\n       *\n       * @example\n       * ```js\n       * $log.info('Some Info');\n       * var first = $log.info.logs.unshift();\n       * ```\n       */\n      $log.info.logs = [];\n      /**\n       * @ngdoc property\n       * @name $log#warn.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#warn `warn()`}.\n       *\n       * @example\n       * ```js\n       * $log.warn('Some Warning');\n       * var first = $log.warn.logs.unshift();\n       * ```\n       */\n      $log.warn.logs = [];\n      /**\n       * @ngdoc property\n       * @name $log#error.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#error `error()`}.\n       *\n       * @example\n       * ```js\n       * $log.error('Some Error');\n       * var first = $log.error.logs.unshift();\n       * ```\n       */\n      $log.error.logs = [];\n        /**\n       * @ngdoc property\n       * @name $log#debug.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#debug `debug()`}.\n       *\n       * @example\n       * ```js\n       * $log.debug('Some Error');\n       * var first = $log.debug.logs.unshift();\n       * ```\n       */\n      $log.debug.logs = [];\n    };\n\n    /**\n     * @ngdoc method\n     * @name $log#assertEmpty\n     *\n     * @description\n     * Assert that all of the logging methods have no logged messages. If any messages are present,\n     * an exception is thrown.\n     */\n    $log.assertEmpty = function() {\n      var errors = [];\n      angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {\n        angular.forEach($log[logLevel].logs, function(log) {\n          angular.forEach(log, function(logItem) {\n            errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\\n' +\n                        (logItem.stack || ''));\n          });\n        });\n      });\n      if (errors.length) {\n        errors.unshift(\"Expected $log to be empty! Either a message was logged unexpectedly, or \" +\n          \"an expected log message was not checked and removed:\");\n        errors.push('');\n        throw new Error(errors.join('\\n---------\\n'));\n      }\n    };\n\n    $log.reset();\n    return $log;\n  };\n};\n\n\n/**\n * @ngdoc service\n * @name $interval\n *\n * @description\n * Mock implementation of the $interval service.\n *\n * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n * time.\n *\n * @param {function()} fn A function that should be called repeatedly.\n * @param {number} delay Number of milliseconds between each function call.\n * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n *   indefinitely.\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n * @param {...*=} Pass additional parameters to the executed function.\n * @returns {promise} A promise which will be notified on each iteration.\n */\nangular.mock.$IntervalProvider = function() {\n  this.$get = ['$browser', '$rootScope', '$q', '$$q',\n       function($browser,   $rootScope,   $q,   $$q) {\n    var repeatFns = [],\n        nextRepeatId = 0,\n        now = 0;\n\n    var $interval = function(fn, delay, count, invokeApply) {\n      var hasParams = arguments.length > 4,\n          args = hasParams ? Array.prototype.slice.call(arguments, 4) : [],\n          iteration = 0,\n          skipApply = (angular.isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise;\n\n      count = (angular.isDefined(count)) ? count : 0;\n      promise.then(null, null, (!hasParams) ? fn : function() {\n        fn.apply(null, args);\n      });\n\n      promise.$$intervalId = nextRepeatId;\n\n      function tick() {\n        deferred.notify(iteration++);\n\n        if (count > 0 && iteration >= count) {\n          var fnIndex;\n          deferred.resolve(iteration);\n\n          angular.forEach(repeatFns, function(fn, index) {\n            if (fn.id === promise.$$intervalId) fnIndex = index;\n          });\n\n          if (angular.isDefined(fnIndex)) {\n            repeatFns.splice(fnIndex, 1);\n          }\n        }\n\n        if (skipApply) {\n          $browser.defer.flush();\n        } else {\n          $rootScope.$apply();\n        }\n      }\n\n      repeatFns.push({\n        nextTime:(now + delay),\n        delay: delay,\n        fn: tick,\n        id: nextRepeatId,\n        deferred: deferred\n      });\n      repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});\n\n      nextRepeatId++;\n      return promise;\n    };\n    /**\n     * @ngdoc method\n     * @name $interval#cancel\n     *\n     * @description\n     * Cancels a task associated with the `promise`.\n     *\n     * @param {promise} promise A promise from calling the `$interval` function.\n     * @returns {boolean} Returns `true` if the task was successfully cancelled.\n     */\n    $interval.cancel = function(promise) {\n      if (!promise) return false;\n      var fnIndex;\n\n      angular.forEach(repeatFns, function(fn, index) {\n        if (fn.id === promise.$$intervalId) fnIndex = index;\n      });\n\n      if (angular.isDefined(fnIndex)) {\n        repeatFns[fnIndex].deferred.reject('canceled');\n        repeatFns.splice(fnIndex, 1);\n        return true;\n      }\n\n      return false;\n    };\n\n    /**\n     * @ngdoc method\n     * @name $interval#flush\n     * @description\n     *\n     * Runs interval tasks scheduled to be run in the next `millis` milliseconds.\n     *\n     * @param {number=} millis maximum timeout amount to flush up until.\n     *\n     * @return {number} The amount of time moved forward.\n     */\n    $interval.flush = function(millis) {\n      now += millis;\n      while (repeatFns.length && repeatFns[0].nextTime <= now) {\n        var task = repeatFns[0];\n        task.fn();\n        task.nextTime += task.delay;\n        repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});\n      }\n      return millis;\n    };\n\n    return $interval;\n  }];\n};\n\n\n/* jshint -W101 */\n/* The R_ISO8061_STR regex is never going to fit into the 100 char limit!\n * This directive should go inside the anonymous function but a bug in JSHint means that it would\n * not be enacted early enough to prevent the warning.\n */\nvar R_ISO8061_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?:\\:?(\\d\\d)(?:\\:?(\\d\\d)(?:\\.(\\d{3}))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d)))?$/;\n\nfunction jsonStringToDate(string) {\n  var match;\n  if (match = string.match(R_ISO8061_STR)) {\n    var date = new Date(0),\n        tzHour = 0,\n        tzMin  = 0;\n    if (match[9]) {\n      tzHour = toInt(match[9] + match[10]);\n      tzMin = toInt(match[9] + match[11]);\n    }\n    date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));\n    date.setUTCHours(toInt(match[4] || 0) - tzHour,\n                     toInt(match[5] || 0) - tzMin,\n                     toInt(match[6] || 0),\n                     toInt(match[7] || 0));\n    return date;\n  }\n  return string;\n}\n\nfunction toInt(str) {\n  return parseInt(str, 10);\n}\n\nfunction padNumber(num, digits, trim) {\n  var neg = '';\n  if (num < 0) {\n    neg =  '-';\n    num = -num;\n  }\n  num = '' + num;\n  while (num.length < digits) num = '0' + num;\n  if (trim) {\n    num = num.substr(num.length - digits);\n  }\n  return neg + num;\n}\n\n\n/**\n * @ngdoc type\n * @name angular.mock.TzDate\n * @description\n *\n * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.\n *\n * Mock of the Date type which has its timezone specified via constructor arg.\n *\n * The main purpose is to create Date-like instances with timezone fixed to the specified timezone\n * offset, so that we can test code that depends on local timezone settings without dependency on\n * the time zone settings of the machine where the code is running.\n *\n * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)\n * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*\n *\n * @example\n * !!!! WARNING !!!!!\n * This is not a complete Date object so only methods that were implemented can be called safely.\n * To make matters worse, TzDate instances inherit stuff from Date via a prototype.\n *\n * We do our best to intercept calls to \"unimplemented\" methods, but since the list of methods is\n * incomplete we might be missing some non-standard methods. This can result in errors like:\n * \"Date.prototype.foo called on incompatible Object\".\n *\n * ```js\n * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');\n * newYearInBratislava.getTimezoneOffset() => -60;\n * newYearInBratislava.getFullYear() => 2010;\n * newYearInBratislava.getMonth() => 0;\n * newYearInBratislava.getDate() => 1;\n * newYearInBratislava.getHours() => 0;\n * newYearInBratislava.getMinutes() => 0;\n * newYearInBratislava.getSeconds() => 0;\n * ```\n *\n */\nangular.mock.TzDate = function(offset, timestamp) {\n  var self = new Date(0);\n  if (angular.isString(timestamp)) {\n    var tsStr = timestamp;\n\n    self.origDate = jsonStringToDate(timestamp);\n\n    timestamp = self.origDate.getTime();\n    if (isNaN(timestamp)) {\n      throw {\n        name: \"Illegal Argument\",\n        message: \"Arg '\" + tsStr + \"' passed into TzDate constructor is not a valid date string\"\n      };\n    }\n  } else {\n    self.origDate = new Date(timestamp);\n  }\n\n  var localOffset = new Date(timestamp).getTimezoneOffset();\n  self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60;\n  self.date = new Date(timestamp + self.offsetDiff);\n\n  self.getTime = function() {\n    return self.date.getTime() - self.offsetDiff;\n  };\n\n  self.toLocaleDateString = function() {\n    return self.date.toLocaleDateString();\n  };\n\n  self.getFullYear = function() {\n    return self.date.getFullYear();\n  };\n\n  self.getMonth = function() {\n    return self.date.getMonth();\n  };\n\n  self.getDate = function() {\n    return self.date.getDate();\n  };\n\n  self.getHours = function() {\n    return self.date.getHours();\n  };\n\n  self.getMinutes = function() {\n    return self.date.getMinutes();\n  };\n\n  self.getSeconds = function() {\n    return self.date.getSeconds();\n  };\n\n  self.getMilliseconds = function() {\n    return self.date.getMilliseconds();\n  };\n\n  self.getTimezoneOffset = function() {\n    return offset * 60;\n  };\n\n  self.getUTCFullYear = function() {\n    return self.origDate.getUTCFullYear();\n  };\n\n  self.getUTCMonth = function() {\n    return self.origDate.getUTCMonth();\n  };\n\n  self.getUTCDate = function() {\n    return self.origDate.getUTCDate();\n  };\n\n  self.getUTCHours = function() {\n    return self.origDate.getUTCHours();\n  };\n\n  self.getUTCMinutes = function() {\n    return self.origDate.getUTCMinutes();\n  };\n\n  self.getUTCSeconds = function() {\n    return self.origDate.getUTCSeconds();\n  };\n\n  self.getUTCMilliseconds = function() {\n    return self.origDate.getUTCMilliseconds();\n  };\n\n  self.getDay = function() {\n    return self.date.getDay();\n  };\n\n  // provide this method only on browsers that already have it\n  if (self.toISOString) {\n    self.toISOString = function() {\n      return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +\n            padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +\n            padNumber(self.origDate.getUTCDate(), 2) + 'T' +\n            padNumber(self.origDate.getUTCHours(), 2) + ':' +\n            padNumber(self.origDate.getUTCMinutes(), 2) + ':' +\n            padNumber(self.origDate.getUTCSeconds(), 2) + '.' +\n            padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';\n    };\n  }\n\n  //hide all methods not implemented in this mock that the Date prototype exposes\n  var unimplementedMethods = ['getUTCDay',\n      'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',\n      'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',\n      'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',\n      'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',\n      'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];\n\n  angular.forEach(unimplementedMethods, function(methodName) {\n    self[methodName] = function() {\n      throw new Error(\"Method '\" + methodName + \"' is not implemented in the TzDate mock\");\n    };\n  });\n\n  return self;\n};\n\n//make \"tzDateInstance instanceof Date\" return true\nangular.mock.TzDate.prototype = Date.prototype;\n/* jshint +W101 */\n\nangular.mock.animate = angular.module('ngAnimateMock', ['ng'])\n\n  .config(['$provide', function($provide) {\n\n    $provide.factory('$$forceReflow', function() {\n      function reflowFn() {\n        reflowFn.totalReflows++;\n      }\n      reflowFn.totalReflows = 0;\n      return reflowFn;\n    });\n\n    $provide.factory('$$animateAsyncRun', function() {\n      var queue = [];\n      var queueFn = function() {\n        return function(fn) {\n          queue.push(fn);\n        };\n      };\n      queueFn.flush = function() {\n        if (queue.length === 0) return false;\n\n        for (var i = 0; i < queue.length; i++) {\n          queue[i]();\n        }\n        queue = [];\n\n        return true;\n      };\n      return queueFn;\n    });\n\n    $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF',\n                                    '$$forceReflow', '$$animateAsyncRun', '$rootScope',\n                            function($delegate,   $timeout,   $browser,   $$rAF,\n                                     $$forceReflow,   $$animateAsyncRun,  $rootScope) {\n      var animate = {\n        queue: [],\n        cancel: $delegate.cancel,\n        on: $delegate.on,\n        off: $delegate.off,\n        pin: $delegate.pin,\n        get reflows() {\n          return $$forceReflow.totalReflows;\n        },\n        enabled: $delegate.enabled,\n        flush: function() {\n          $rootScope.$digest();\n\n          var doNextRun, somethingFlushed = false;\n          do {\n            doNextRun = false;\n\n            if ($$rAF.queue.length) {\n              $$rAF.flush();\n              doNextRun = somethingFlushed = true;\n            }\n\n            if ($$animateAsyncRun.flush()) {\n              doNextRun = somethingFlushed = true;\n            }\n          } while (doNextRun);\n\n          if (!somethingFlushed) {\n            throw new Error('No pending animations ready to be closed or flushed');\n          }\n\n          $rootScope.$digest();\n        }\n      };\n\n      angular.forEach(\n        ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) {\n        animate[method] = function() {\n          animate.queue.push({\n            event: method,\n            element: arguments[0],\n            options: arguments[arguments.length - 1],\n            args: arguments\n          });\n          return $delegate[method].apply($delegate, arguments);\n        };\n      });\n\n      return animate;\n    }]);\n\n  }]);\n\n\n/**\n * @ngdoc function\n * @name angular.mock.dump\n * @description\n *\n * *NOTE*: this is not an injectable instance, just a globally available function.\n *\n * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for\n * debugging.\n *\n * This method is also available on window, where it can be used to display objects on debug\n * console.\n *\n * @param {*} object - any object to turn into string.\n * @return {string} a serialized string of the argument\n */\nangular.mock.dump = function(object) {\n  return serialize(object);\n\n  function serialize(object) {\n    var out;\n\n    if (angular.isElement(object)) {\n      object = angular.element(object);\n      out = angular.element('<div></div>');\n      angular.forEach(object, function(element) {\n        out.append(angular.element(element).clone());\n      });\n      out = out.html();\n    } else if (angular.isArray(object)) {\n      out = [];\n      angular.forEach(object, function(o) {\n        out.push(serialize(o));\n      });\n      out = '[ ' + out.join(', ') + ' ]';\n    } else if (angular.isObject(object)) {\n      if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {\n        out = serializeScope(object);\n      } else if (object instanceof Error) {\n        out = object.stack || ('' + object.name + ': ' + object.message);\n      } else {\n        // TODO(i): this prevents methods being logged,\n        // we should have a better way to serialize objects\n        out = angular.toJson(object, true);\n      }\n    } else {\n      out = String(object);\n    }\n\n    return out;\n  }\n\n  function serializeScope(scope, offset) {\n    offset = offset ||  '  ';\n    var log = [offset + 'Scope(' + scope.$id + '): {'];\n    for (var key in scope) {\n      if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\\$|this)/)) {\n        log.push('  ' + key + ': ' + angular.toJson(scope[key]));\n      }\n    }\n    var child = scope.$$childHead;\n    while (child) {\n      log.push(serializeScope(child, offset + '  '));\n      child = child.$$nextSibling;\n    }\n    log.push('}');\n    return log.join('\\n' + offset);\n  }\n};\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @description\n * Fake HTTP backend implementation suitable for unit testing applications that use the\n * {@link ng.$http $http service}.\n *\n * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less\n * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.\n *\n * During unit testing, we want our unit tests to run quickly and have no external dependencies so\n * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or\n * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is\n * to verify whether a certain request has been sent or not, or alternatively just let the\n * application make requests, respond with pre-trained responses and assert that the end result is\n * what we expect it to be.\n *\n * This mock implementation can be used to respond with static or dynamic responses via the\n * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).\n *\n * When an Angular application needs some data from a server, it calls the $http service, which\n * sends the request to a real server using $httpBackend service. With dependency injection, it is\n * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify\n * the requests and respond with some testing data without sending a request to a real server.\n *\n * There are two ways to specify what test data should be returned as http responses by the mock\n * backend when the code under test makes http requests:\n *\n * - `$httpBackend.expect` - specifies a request expectation\n * - `$httpBackend.when` - specifies a backend definition\n *\n *\n * # Request Expectations vs Backend Definitions\n *\n * Request expectations provide a way to make assertions about requests made by the application and\n * to define responses for those requests. The test will fail if the expected requests are not made\n * or they are made in the wrong order.\n *\n * Backend definitions allow you to define a fake backend for your application which doesn't assert\n * if a particular request was made or not, it just returns a trained response if a request is made.\n * The test will pass whether or not the request gets made during testing.\n *\n *\n * <table class=\"table\">\n *   <tr><th width=\"220px\"></th><th>Request expectations</th><th>Backend definitions</th></tr>\n *   <tr>\n *     <th>Syntax</th>\n *     <td>.expect(...).respond(...)</td>\n *     <td>.when(...).respond(...)</td>\n *   </tr>\n *   <tr>\n *     <th>Typical usage</th>\n *     <td>strict unit tests</td>\n *     <td>loose (black-box) unit testing</td>\n *   </tr>\n *   <tr>\n *     <th>Fulfills multiple requests</th>\n *     <td>NO</td>\n *     <td>YES</td>\n *   </tr>\n *   <tr>\n *     <th>Order of requests matters</th>\n *     <td>YES</td>\n *     <td>NO</td>\n *   </tr>\n *   <tr>\n *     <th>Request required</th>\n *     <td>YES</td>\n *     <td>NO</td>\n *   </tr>\n *   <tr>\n *     <th>Response required</th>\n *     <td>optional (see below)</td>\n *     <td>YES</td>\n *   </tr>\n * </table>\n *\n * In cases where both backend definitions and request expectations are specified during unit\n * testing, the request expectations are evaluated first.\n *\n * If a request expectation has no response specified, the algorithm will search your backend\n * definitions for an appropriate response.\n *\n * If a request didn't match any expectation or if the expectation doesn't have the response\n * defined, the backend definitions are evaluated in sequential order to see if any of them match\n * the request. The response from the first matched definition is returned.\n *\n *\n * # Flushing HTTP requests\n *\n * The $httpBackend used in production always responds to requests asynchronously. If we preserved\n * this behavior in unit testing, we'd have to create async unit tests, which are hard to write,\n * to follow and to maintain. But neither can the testing mock respond synchronously; that would\n * change the execution of the code under test. For this reason, the mock $httpBackend has a\n * `flush()` method, which allows the test to explicitly flush pending requests. This preserves\n * the async api of the backend, while allowing the test to execute synchronously.\n *\n *\n * # Unit testing with mock $httpBackend\n * The following code shows how to setup and use the mock backend when unit testing a controller.\n * First we create the controller under test:\n *\n  ```js\n  // The module code\n  angular\n    .module('MyApp', [])\n    .controller('MyController', MyController);\n\n  // The controller code\n  function MyController($scope, $http) {\n    var authToken;\n\n    $http.get('/auth.py').success(function(data, status, headers) {\n      authToken = headers('A-Token');\n      $scope.user = data;\n    });\n\n    $scope.saveMessage = function(message) {\n      var headers = { 'Authorization': authToken };\n      $scope.status = 'Saving...';\n\n      $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {\n        $scope.status = '';\n      }).error(function() {\n        $scope.status = 'Failed...';\n      });\n    };\n  }\n  ```\n *\n * Now we setup the mock backend and create the test specs:\n *\n  ```js\n    // testing controller\n    describe('MyController', function() {\n       var $httpBackend, $rootScope, createController, authRequestHandler;\n\n       // Set up the module\n       beforeEach(module('MyApp'));\n\n       beforeEach(inject(function($injector) {\n         // Set up the mock http service responses\n         $httpBackend = $injector.get('$httpBackend');\n         // backend definition common for all tests\n         authRequestHandler = $httpBackend.when('GET', '/auth.py')\n                                .respond({userId: 'userX'}, {'A-Token': 'xxx'});\n\n         // Get hold of a scope (i.e. the root scope)\n         $rootScope = $injector.get('$rootScope');\n         // The $controller service is used to create instances of controllers\n         var $controller = $injector.get('$controller');\n\n         createController = function() {\n           return $controller('MyController', {'$scope' : $rootScope });\n         };\n       }));\n\n\n       afterEach(function() {\n         $httpBackend.verifyNoOutstandingExpectation();\n         $httpBackend.verifyNoOutstandingRequest();\n       });\n\n\n       it('should fetch authentication token', function() {\n         $httpBackend.expectGET('/auth.py');\n         var controller = createController();\n         $httpBackend.flush();\n       });\n\n\n       it('should fail authentication', function() {\n\n         // Notice how you can change the response even after it was set\n         authRequestHandler.respond(401, '');\n\n         $httpBackend.expectGET('/auth.py');\n         var controller = createController();\n         $httpBackend.flush();\n         expect($rootScope.status).toBe('Failed...');\n       });\n\n\n       it('should send msg to server', function() {\n         var controller = createController();\n         $httpBackend.flush();\n\n         // now you don’t care about the authentication, but\n         // the controller will still send the request and\n         // $httpBackend will respond without you having to\n         // specify the expectation and response for this request\n\n         $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');\n         $rootScope.saveMessage('message content');\n         expect($rootScope.status).toBe('Saving...');\n         $httpBackend.flush();\n         expect($rootScope.status).toBe('');\n       });\n\n\n       it('should send auth header', function() {\n         var controller = createController();\n         $httpBackend.flush();\n\n         $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {\n           // check if the header was sent, if it wasn't the expectation won't\n           // match the request and the test will fail\n           return headers['Authorization'] == 'xxx';\n         }).respond(201, '');\n\n         $rootScope.saveMessage('whatever');\n         $httpBackend.flush();\n       });\n    });\n   ```\n */\nangular.mock.$HttpBackendProvider = function() {\n  this.$get = ['$rootScope', '$timeout', createHttpBackendMock];\n};\n\n/**\n * General factory function for $httpBackend mock.\n * Returns instance for unit testing (when no arguments specified):\n *   - passing through is disabled\n *   - auto flushing is disabled\n *\n * Returns instance for e2e testing (when `$delegate` and `$browser` specified):\n *   - passing through (delegating request to real backend) is enabled\n *   - auto flushing is enabled\n *\n * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)\n * @param {Object=} $browser Auto-flushing enabled if specified\n * @return {Object} Instance of $httpBackend mock\n */\nfunction createHttpBackendMock($rootScope, $timeout, $delegate, $browser) {\n  var definitions = [],\n      expectations = [],\n      responses = [],\n      responsesPush = angular.bind(responses, responses.push),\n      copy = angular.copy;\n\n  function createResponse(status, data, headers, statusText) {\n    if (angular.isFunction(status)) return status;\n\n    return function() {\n      return angular.isNumber(status)\n          ? [status, data, headers, statusText]\n          : [200, status, data, headers];\n    };\n  }\n\n  // TODO(vojta): change params to: method, url, data, headers, callback\n  function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {\n    var xhr = new MockXhr(),\n        expectation = expectations[0],\n        wasExpected = false;\n\n    function prettyPrint(data) {\n      return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)\n          ? data\n          : angular.toJson(data);\n    }\n\n    function wrapResponse(wrapped) {\n      if (!$browser && timeout) {\n        timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout);\n      }\n\n      return handleResponse;\n\n      function handleResponse() {\n        var response = wrapped.response(method, url, data, headers);\n        xhr.$$respHeaders = response[2];\n        callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),\n                 copy(response[3] || ''));\n      }\n\n      function handleTimeout() {\n        for (var i = 0, ii = responses.length; i < ii; i++) {\n          if (responses[i] === handleResponse) {\n            responses.splice(i, 1);\n            callback(-1, undefined, '');\n            break;\n          }\n        }\n      }\n    }\n\n    if (expectation && expectation.match(method, url)) {\n      if (!expectation.matchData(data)) {\n        throw new Error('Expected ' + expectation + ' with different data\\n' +\n            'EXPECTED: ' + prettyPrint(expectation.data) + '\\nGOT:      ' + data);\n      }\n\n      if (!expectation.matchHeaders(headers)) {\n        throw new Error('Expected ' + expectation + ' with different headers\\n' +\n                        'EXPECTED: ' + prettyPrint(expectation.headers) + '\\nGOT:      ' +\n                        prettyPrint(headers));\n      }\n\n      expectations.shift();\n\n      if (expectation.response) {\n        responses.push(wrapResponse(expectation));\n        return;\n      }\n      wasExpected = true;\n    }\n\n    var i = -1, definition;\n    while ((definition = definitions[++i])) {\n      if (definition.match(method, url, data, headers || {})) {\n        if (definition.response) {\n          // if $browser specified, we do auto flush all requests\n          ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));\n        } else if (definition.passThrough) {\n          $delegate(method, url, data, callback, headers, timeout, withCredentials);\n        } else throw new Error('No response defined !');\n        return;\n      }\n    }\n    throw wasExpected ?\n        new Error('No response defined !') :\n        new Error('Unexpected request: ' + method + ' ' + url + '\\n' +\n                  (expectation ? 'Expected ' + expectation : 'No more request expected'));\n  }\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#when\n   * @description\n   * Creates a new backend definition.\n   *\n   * @param {string} method HTTP method.\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives\n   *   data string and returns true if the data is as expected.\n   * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header\n   *   object and returns true if the headers match the current definition.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   *\n   *  - respond –\n   *      `{function([status,] data[, headers, statusText])\n   *      | function(function(method, url, data, headers)}`\n   *    – The respond method takes a set of static data to be returned or a function that can\n   *    return an array containing response status (number), response data (string), response\n   *    headers (Object), and the text for the status (string). The respond method returns the\n   *    `requestHandler` object for possible overrides.\n   */\n  $httpBackend.when = function(method, url, data, headers) {\n    var definition = new MockHttpExpectation(method, url, data, headers),\n        chain = {\n          respond: function(status, data, headers, statusText) {\n            definition.passThrough = undefined;\n            definition.response = createResponse(status, data, headers, statusText);\n            return chain;\n          }\n        };\n\n    if ($browser) {\n      chain.passThrough = function() {\n        definition.response = undefined;\n        definition.passThrough = true;\n        return chain;\n      };\n    }\n\n    definitions.push(definition);\n    return chain;\n  };\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenGET\n   * @description\n   * Creates a new backend definition for GET requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenHEAD\n   * @description\n   * Creates a new backend definition for HEAD requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenDELETE\n   * @description\n   * Creates a new backend definition for DELETE requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenPOST\n   * @description\n   * Creates a new backend definition for POST requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives\n   *   data string and returns true if the data is as expected.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenPUT\n   * @description\n   * Creates a new backend definition for PUT requests.  For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives\n   *   data string and returns true if the data is as expected.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenJSONP\n   * @description\n   * Creates a new backend definition for JSONP requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n  createShortMethods('when');\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expect\n   * @description\n   * Creates a new request expectation.\n   *\n   * @param {string} method HTTP method.\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header\n   *   object and returns true if the headers match the current expectation.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *  request is handled. You can save this object for later use and invoke `respond` again in\n   *  order to change how a matched request is handled.\n   *\n   *  - respond –\n   *    `{function([status,] data[, headers, statusText])\n   *    | function(function(method, url, data, headers)}`\n   *    – The respond method takes a set of static data to be returned or a function that can\n   *    return an array containing response status (number), response data (string), response\n   *    headers (Object), and the text for the status (string). The respond method returns the\n   *    `requestHandler` object for possible overrides.\n   */\n  $httpBackend.expect = function(method, url, data, headers) {\n    var expectation = new MockHttpExpectation(method, url, data, headers),\n        chain = {\n          respond: function(status, data, headers, statusText) {\n            expectation.response = createResponse(status, data, headers, statusText);\n            return chain;\n          }\n        };\n\n    expectations.push(expectation);\n    return chain;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectGET\n   * @description\n   * Creates a new request expectation for GET requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled. See #expect for more info.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectHEAD\n   * @description\n   * Creates a new request expectation for HEAD requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectDELETE\n   * @description\n   * Creates a new request expectation for DELETE requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectPOST\n   * @description\n   * Creates a new request expectation for POST requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectPUT\n   * @description\n   * Creates a new request expectation for PUT requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectPATCH\n   * @description\n   * Creates a new request expectation for PATCH requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectJSONP\n   * @description\n   * Creates a new request expectation for JSONP requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives an url\n   *   and returns true if the url matches the current definition.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n  createShortMethods('expect');\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#flush\n   * @description\n   * Flushes all pending requests using the trained responses.\n   *\n   * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,\n   *   all pending requests will be flushed. If there are no pending requests when the flush method\n   *   is called an exception is thrown (as this typically a sign of programming error).\n   */\n  $httpBackend.flush = function(count, digest) {\n    if (digest !== false) $rootScope.$digest();\n    if (!responses.length) throw new Error('No pending request to flush !');\n\n    if (angular.isDefined(count) && count !== null) {\n      while (count--) {\n        if (!responses.length) throw new Error('No more pending request to flush !');\n        responses.shift()();\n      }\n    } else {\n      while (responses.length) {\n        responses.shift()();\n      }\n    }\n    $httpBackend.verifyNoOutstandingExpectation(digest);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#verifyNoOutstandingExpectation\n   * @description\n   * Verifies that all of the requests defined via the `expect` api were made. If any of the\n   * requests were not made, verifyNoOutstandingExpectation throws an exception.\n   *\n   * Typically, you would call this method following each test case that asserts requests using an\n   * \"afterEach\" clause.\n   *\n   * ```js\n   *   afterEach($httpBackend.verifyNoOutstandingExpectation);\n   * ```\n   */\n  $httpBackend.verifyNoOutstandingExpectation = function(digest) {\n    if (digest !== false) $rootScope.$digest();\n    if (expectations.length) {\n      throw new Error('Unsatisfied requests: ' + expectations.join(', '));\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#verifyNoOutstandingRequest\n   * @description\n   * Verifies that there are no outstanding requests that need to be flushed.\n   *\n   * Typically, you would call this method following each test case that asserts requests using an\n   * \"afterEach\" clause.\n   *\n   * ```js\n   *   afterEach($httpBackend.verifyNoOutstandingRequest);\n   * ```\n   */\n  $httpBackend.verifyNoOutstandingRequest = function() {\n    if (responses.length) {\n      throw new Error('Unflushed requests: ' + responses.length);\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#resetExpectations\n   * @description\n   * Resets all request expectations, but preserves all backend definitions. Typically, you would\n   * call resetExpectations during a multiple-phase test when you want to reuse the same instance of\n   * $httpBackend mock.\n   */\n  $httpBackend.resetExpectations = function() {\n    expectations.length = 0;\n    responses.length = 0;\n  };\n\n  return $httpBackend;\n\n\n  function createShortMethods(prefix) {\n    angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {\n     $httpBackend[prefix + method] = function(url, headers) {\n       return $httpBackend[prefix](method, url, undefined, headers);\n     };\n    });\n\n    angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {\n      $httpBackend[prefix + method] = function(url, data, headers) {\n        return $httpBackend[prefix](method, url, data, headers);\n      };\n    });\n  }\n}\n\nfunction MockHttpExpectation(method, url, data, headers) {\n\n  this.data = data;\n  this.headers = headers;\n\n  this.match = function(m, u, d, h) {\n    if (method != m) return false;\n    if (!this.matchUrl(u)) return false;\n    if (angular.isDefined(d) && !this.matchData(d)) return false;\n    if (angular.isDefined(h) && !this.matchHeaders(h)) return false;\n    return true;\n  };\n\n  this.matchUrl = function(u) {\n    if (!url) return true;\n    if (angular.isFunction(url.test)) return url.test(u);\n    if (angular.isFunction(url)) return url(u);\n    return url == u;\n  };\n\n  this.matchHeaders = function(h) {\n    if (angular.isUndefined(headers)) return true;\n    if (angular.isFunction(headers)) return headers(h);\n    return angular.equals(headers, h);\n  };\n\n  this.matchData = function(d) {\n    if (angular.isUndefined(data)) return true;\n    if (data && angular.isFunction(data.test)) return data.test(d);\n    if (data && angular.isFunction(data)) return data(d);\n    if (data && !angular.isString(data)) {\n      return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));\n    }\n    return data == d;\n  };\n\n  this.toString = function() {\n    return method + ' ' + url;\n  };\n}\n\nfunction createMockXhr() {\n  return new MockXhr();\n}\n\nfunction MockXhr() {\n\n  // hack for testing $http, $httpBackend\n  MockXhr.$$lastInstance = this;\n\n  this.open = function(method, url, async) {\n    this.$$method = method;\n    this.$$url = url;\n    this.$$async = async;\n    this.$$reqHeaders = {};\n    this.$$respHeaders = {};\n  };\n\n  this.send = function(data) {\n    this.$$data = data;\n  };\n\n  this.setRequestHeader = function(key, value) {\n    this.$$reqHeaders[key] = value;\n  };\n\n  this.getResponseHeader = function(name) {\n    // the lookup must be case insensitive,\n    // that's why we try two quick lookups first and full scan last\n    var header = this.$$respHeaders[name];\n    if (header) return header;\n\n    name = angular.lowercase(name);\n    header = this.$$respHeaders[name];\n    if (header) return header;\n\n    header = undefined;\n    angular.forEach(this.$$respHeaders, function(headerVal, headerName) {\n      if (!header && angular.lowercase(headerName) == name) header = headerVal;\n    });\n    return header;\n  };\n\n  this.getAllResponseHeaders = function() {\n    var lines = [];\n\n    angular.forEach(this.$$respHeaders, function(value, key) {\n      lines.push(key + ': ' + value);\n    });\n    return lines.join('\\n');\n  };\n\n  this.abort = angular.noop;\n}\n\n\n/**\n * @ngdoc service\n * @name $timeout\n * @description\n *\n * This service is just a simple decorator for {@link ng.$timeout $timeout} service\n * that adds a \"flush\" and \"verifyNoPendingTasks\" methods.\n */\n\nangular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) {\n\n  /**\n   * @ngdoc method\n   * @name $timeout#flush\n   * @description\n   *\n   * Flushes the queue of pending tasks.\n   *\n   * @param {number=} delay maximum timeout amount to flush up until\n   */\n  $delegate.flush = function(delay) {\n    $browser.defer.flush(delay);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $timeout#verifyNoPendingTasks\n   * @description\n   *\n   * Verifies that there are no pending tasks that need to be flushed.\n   */\n  $delegate.verifyNoPendingTasks = function() {\n    if ($browser.deferredFns.length) {\n      throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +\n          formatPendingTasksAsString($browser.deferredFns));\n    }\n  };\n\n  function formatPendingTasksAsString(tasks) {\n    var result = [];\n    angular.forEach(tasks, function(task) {\n      result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');\n    });\n\n    return result.join(', ');\n  }\n\n  return $delegate;\n}];\n\nangular.mock.$RAFDecorator = ['$delegate', function($delegate) {\n  var rafFn = function(fn) {\n    var index = rafFn.queue.length;\n    rafFn.queue.push(fn);\n    return function() {\n      rafFn.queue.splice(index, 1);\n    };\n  };\n\n  rafFn.queue = [];\n  rafFn.supported = $delegate.supported;\n\n  rafFn.flush = function() {\n    if (rafFn.queue.length === 0) {\n      throw new Error('No rAF callbacks present');\n    }\n\n    var length = rafFn.queue.length;\n    for (var i = 0; i < length; i++) {\n      rafFn.queue[i]();\n    }\n\n    rafFn.queue = rafFn.queue.slice(i);\n  };\n\n  return rafFn;\n}];\n\n/**\n *\n */\nangular.mock.$RootElementProvider = function() {\n  this.$get = function() {\n    return angular.element('<div ng-app></div>');\n  };\n};\n\n/**\n * @ngdoc service\n * @name $controller\n * @description\n * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing\n * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}.\n *\n *\n * ## Example\n *\n * ```js\n *\n * // Directive definition ...\n *\n * myMod.directive('myDirective', {\n *   controller: 'MyDirectiveController',\n *   bindToController: {\n *     name: '@'\n *   }\n * });\n *\n *\n * // Controller definition ...\n *\n * myMod.controller('MyDirectiveController', ['log', function($log) {\n *   $log.info(this.name);\n * })];\n *\n *\n * // In a test ...\n *\n * describe('myDirectiveController', function() {\n *   it('should write the bound name to the log', inject(function($controller, $log) {\n *     var ctrl = $controller('MyDirectiveController', { /* no locals &#42;/ }, { name: 'Clark Kent' });\n *     expect(ctrl.name).toEqual('Clark Kent');\n *     expect($log.info.logs).toEqual(['Clark Kent']);\n *   });\n * });\n *\n * ```\n *\n * @param {Function|string} constructor If called with a function then it's considered to be the\n *    controller constructor function. Otherwise it's considered to be a string which is used\n *    to retrieve the controller constructor using the following steps:\n *\n *    * check if a controller with given name is registered via `$controllerProvider`\n *    * check if evaluating the string on the current scope returns a constructor\n *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\n *      `window` object (not recommended)\n *\n *    The string can use the `controller as property` syntax, where the controller instance is published\n *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n *    to work correctly.\n *\n * @param {Object} locals Injection locals for Controller.\n * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used\n *                           to simulate the `bindToController` feature and simplify certain kinds of tests.\n * @return {Object} Instance of given controller.\n */\nangular.mock.$ControllerDecorator = ['$delegate', function($delegate) {\n  return function(expression, locals, later, ident) {\n    if (later && typeof later === 'object') {\n      var create = $delegate(expression, locals, true, ident);\n      angular.extend(create.instance, later);\n      return create();\n    }\n    return $delegate(expression, locals, later, ident);\n  };\n}];\n\n\n/**\n * @ngdoc module\n * @name ngMock\n * @packageName angular-mocks\n * @description\n *\n * # ngMock\n *\n * The `ngMock` module provides support to inject and mock Angular services into unit tests.\n * In addition, ngMock also extends various core ng services such that they can be\n * inspected and controlled in a synchronous manner within test code.\n *\n *\n * <div doc-module-components=\"ngMock\"></div>\n *\n */\nangular.module('ngMock', ['ng']).provider({\n  $browser: angular.mock.$BrowserProvider,\n  $exceptionHandler: angular.mock.$ExceptionHandlerProvider,\n  $log: angular.mock.$LogProvider,\n  $interval: angular.mock.$IntervalProvider,\n  $httpBackend: angular.mock.$HttpBackendProvider,\n  $rootElement: angular.mock.$RootElementProvider\n}).config(['$provide', function($provide) {\n  $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);\n  $provide.decorator('$$rAF', angular.mock.$RAFDecorator);\n  $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);\n  $provide.decorator('$controller', angular.mock.$ControllerDecorator);\n}]);\n\n/**\n * @ngdoc module\n * @name ngMockE2E\n * @module ngMockE2E\n * @packageName angular-mocks\n * @description\n *\n * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.\n * Currently there is only one mock present in this module -\n * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.\n */\nangular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {\n  $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);\n}]);\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @module ngMockE2E\n * @description\n * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of\n * applications that use the {@link ng.$http $http service}.\n *\n * *Note*: For fake http backend implementation suitable for unit testing please see\n * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.\n *\n * This implementation can be used to respond with static or dynamic responses via the `when` api\n * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the\n * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch\n * templates from a webserver).\n *\n * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application\n * is being developed with the real backend api replaced with a mock, it is often desirable for\n * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch\n * templates or static files from the webserver). To configure the backend with this behavior\n * use the `passThrough` request handler of `when` instead of `respond`.\n *\n * Additionally, we don't want to manually have to flush mocked out requests like we do during unit\n * testing. For this reason the e2e $httpBackend flushes mocked out requests\n * automatically, closely simulating the behavior of the XMLHttpRequest object.\n *\n * To setup the application to run with this http backend, you have to create a module that depends\n * on the `ngMockE2E` and your application modules and defines the fake backend:\n *\n * ```js\n *   myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);\n *   myAppDev.run(function($httpBackend) {\n *     phones = [{name: 'phone1'}, {name: 'phone2'}];\n *\n *     // returns the current list of phones\n *     $httpBackend.whenGET('/phones').respond(phones);\n *\n *     // adds a new phone to the phones array\n *     $httpBackend.whenPOST('/phones').respond(function(method, url, data) {\n *       var phone = angular.fromJson(data);\n *       phones.push(phone);\n *       return [200, phone, {}];\n *     });\n *     $httpBackend.whenGET(/^\\/templates\\//).passThrough();\n *     //...\n *   });\n * ```\n *\n * Afterwards, bootstrap your app with this new module.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#when\n * @module ngMockE2E\n * @description\n * Creates a new backend definition.\n *\n * @param {string} method HTTP method.\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header\n *   object and returns true if the headers match the current definition.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n *\n *  - respond –\n *    `{function([status,] data[, headers, statusText])\n *    | function(function(method, url, data, headers)}`\n *    – The respond method takes a set of static data to be returned or a function that can return\n *    an array containing response status (number), response data (string), response headers\n *    (Object), and the text for the status (string).\n *  - passThrough – `{function()}` – Any request matching a backend definition with\n *    `passThrough` handler will be passed through to the real backend (an XHR request will be made\n *    to the server.)\n *  - Both methods return the `requestHandler` object for possible overrides.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenGET\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for GET requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenHEAD\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for HEAD requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenDELETE\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for DELETE requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenPOST\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for POST requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenPUT\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for PUT requests.  For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenPATCH\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for PATCH requests.  For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenJSONP\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for JSONP requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\nangular.mock.e2e = {};\nangular.mock.e2e.$httpBackendDecorator =\n  ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock];\n\n\n/**\n * @ngdoc type\n * @name $rootScope.Scope\n * @module ngMock\n * @description\n * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These\n * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when\n * `ngMock` module is loaded.\n *\n * In addition to all the regular `Scope` methods, the following helper methods are available:\n */\nangular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {\n\n  var $rootScopePrototype = Object.getPrototypeOf($delegate);\n\n  $rootScopePrototype.$countChildScopes = countChildScopes;\n  $rootScopePrototype.$countWatchers = countWatchers;\n\n  return $delegate;\n\n  // ------------------------------------------------------------------------------------------ //\n\n  /**\n   * @ngdoc method\n   * @name $rootScope.Scope#$countChildScopes\n   * @module ngMock\n   * @description\n   * Counts all the direct and indirect child scopes of the current scope.\n   *\n   * The current scope is excluded from the count. The count includes all isolate child scopes.\n   *\n   * @returns {number} Total number of child scopes.\n   */\n  function countChildScopes() {\n    // jshint validthis: true\n    var count = 0; // exclude the current scope\n    var pendingChildHeads = [this.$$childHead];\n    var currentScope;\n\n    while (pendingChildHeads.length) {\n      currentScope = pendingChildHeads.shift();\n\n      while (currentScope) {\n        count += 1;\n        pendingChildHeads.push(currentScope.$$childHead);\n        currentScope = currentScope.$$nextSibling;\n      }\n    }\n\n    return count;\n  }\n\n\n  /**\n   * @ngdoc method\n   * @name $rootScope.Scope#$countWatchers\n   * @module ngMock\n   * @description\n   * Counts all the watchers of direct and indirect child scopes of the current scope.\n   *\n   * The watchers of the current scope are included in the count and so are all the watchers of\n   * isolate child scopes.\n   *\n   * @returns {number} Total number of watchers.\n   */\n  function countWatchers() {\n    // jshint validthis: true\n    var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope\n    var pendingChildHeads = [this.$$childHead];\n    var currentScope;\n\n    while (pendingChildHeads.length) {\n      currentScope = pendingChildHeads.shift();\n\n      while (currentScope) {\n        count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;\n        pendingChildHeads.push(currentScope.$$childHead);\n        currentScope = currentScope.$$nextSibling;\n      }\n    }\n\n    return count;\n  }\n}];\n\n\nif (window.jasmine || window.mocha) {\n\n  var currentSpec = null,\n      annotatedFunctions = [],\n      isSpecRunning = function() {\n        return !!currentSpec;\n      };\n\n  angular.mock.$$annotate = angular.injector.$$annotate;\n  angular.injector.$$annotate = function(fn) {\n    if (typeof fn === 'function' && !fn.$inject) {\n      annotatedFunctions.push(fn);\n    }\n    return angular.mock.$$annotate.apply(this, arguments);\n  };\n\n\n  (window.beforeEach || window.setup)(function() {\n    annotatedFunctions = [];\n    currentSpec = this;\n  });\n\n  (window.afterEach || window.teardown)(function() {\n    var injector = currentSpec.$injector;\n\n    annotatedFunctions.forEach(function(fn) {\n      delete fn.$inject;\n    });\n\n    angular.forEach(currentSpec.$modules, function(module) {\n      if (module && module.$$hashKey) {\n        module.$$hashKey = undefined;\n      }\n    });\n\n    currentSpec.$injector = null;\n    currentSpec.$modules = null;\n    currentSpec = null;\n\n    if (injector) {\n      injector.get('$rootElement').off();\n    }\n\n    // clean up jquery's fragment cache\n    angular.forEach(angular.element.fragments, function(val, key) {\n      delete angular.element.fragments[key];\n    });\n\n    MockXhr.$$lastInstance = null;\n\n    angular.forEach(angular.callbacks, function(val, key) {\n      delete angular.callbacks[key];\n    });\n    angular.callbacks.counter = 0;\n  });\n\n  /**\n   * @ngdoc function\n   * @name angular.mock.module\n   * @description\n   *\n   * *NOTE*: This function is also published on window for easy access.<br>\n   * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha\n   *\n   * This function registers a module configuration code. It collects the configuration information\n   * which will be used when the injector is created by {@link angular.mock.inject inject}.\n   *\n   * See {@link angular.mock.inject inject} for usage example\n   *\n   * @param {...(string|Function|Object)} fns any number of modules which are represented as string\n   *        aliases or as anonymous module initialization functions. The modules are used to\n   *        configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an\n   *        object literal is passed they will be registered as values in the module, the key being\n   *        the module name and the value being what is returned.\n   */\n  window.module = angular.mock.module = function() {\n    var moduleFns = Array.prototype.slice.call(arguments, 0);\n    return isSpecRunning() ? workFn() : workFn;\n    /////////////////////\n    function workFn() {\n      if (currentSpec.$injector) {\n        throw new Error('Injector already created, can not register a module!');\n      } else {\n        var modules = currentSpec.$modules || (currentSpec.$modules = []);\n        angular.forEach(moduleFns, function(module) {\n          if (angular.isObject(module) && !angular.isArray(module)) {\n            modules.push(function($provide) {\n              angular.forEach(module, function(value, key) {\n                $provide.value(key, value);\n              });\n            });\n          } else {\n            modules.push(module);\n          }\n        });\n      }\n    }\n  };\n\n  /**\n   * @ngdoc function\n   * @name angular.mock.inject\n   * @description\n   *\n   * *NOTE*: This function is also published on window for easy access.<br>\n   * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha\n   *\n   * The inject function wraps a function into an injectable function. The inject() creates new\n   * instance of {@link auto.$injector $injector} per test, which is then used for\n   * resolving references.\n   *\n   *\n   * ## Resolving References (Underscore Wrapping)\n   * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this\n   * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable\n   * that is declared in the scope of the `describe()` block. Since we would, most likely, want\n   * the variable to have the same name of the reference we have a problem, since the parameter\n   * to the `inject()` function would hide the outer variable.\n   *\n   * To help with this, the injected parameters can, optionally, be enclosed with underscores.\n   * These are ignored by the injector when the reference name is resolved.\n   *\n   * For example, the parameter `_myService_` would be resolved as the reference `myService`.\n   * Since it is available in the function body as _myService_, we can then assign it to a variable\n   * defined in an outer scope.\n   *\n   * ```\n   * // Defined out reference variable outside\n   * var myService;\n   *\n   * // Wrap the parameter in underscores\n   * beforeEach( inject( function(_myService_){\n   *   myService = _myService_;\n   * }));\n   *\n   * // Use myService in a series of tests.\n   * it('makes use of myService', function() {\n   *   myService.doStuff();\n   * });\n   *\n   * ```\n   *\n   * See also {@link angular.mock.module angular.mock.module}\n   *\n   * ## Example\n   * Example of what a typical jasmine tests looks like with the inject method.\n   * ```js\n   *\n   *   angular.module('myApplicationModule', [])\n   *       .value('mode', 'app')\n   *       .value('version', 'v1.0.1');\n   *\n   *\n   *   describe('MyApp', function() {\n   *\n   *     // You need to load modules that you want to test,\n   *     // it loads only the \"ng\" module by default.\n   *     beforeEach(module('myApplicationModule'));\n   *\n   *\n   *     // inject() is used to inject arguments of all given functions\n   *     it('should provide a version', inject(function(mode, version) {\n   *       expect(version).toEqual('v1.0.1');\n   *       expect(mode).toEqual('app');\n   *     }));\n   *\n   *\n   *     // The inject and module method can also be used inside of the it or beforeEach\n   *     it('should override a version and test the new version is injected', function() {\n   *       // module() takes functions or strings (module aliases)\n   *       module(function($provide) {\n   *         $provide.value('version', 'overridden'); // override version here\n   *       });\n   *\n   *       inject(function(version) {\n   *         expect(version).toEqual('overridden');\n   *       });\n   *     });\n   *   });\n   *\n   * ```\n   *\n   * @param {...Function} fns any number of functions which will be injected using the injector.\n   */\n\n\n\n  var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {\n    this.message = e.message;\n    this.name = e.name;\n    if (e.line) this.line = e.line;\n    if (e.sourceId) this.sourceId = e.sourceId;\n    if (e.stack && errorForStack)\n      this.stack = e.stack + '\\n' + errorForStack.stack;\n    if (e.stackArray) this.stackArray = e.stackArray;\n  };\n  ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;\n\n  window.inject = angular.mock.inject = function() {\n    var blockFns = Array.prototype.slice.call(arguments, 0);\n    var errorForStack = new Error('Declaration Location');\n    return isSpecRunning() ? workFn.call(currentSpec) : workFn;\n    /////////////////////\n    function workFn() {\n      var modules = currentSpec.$modules || [];\n      var strictDi = !!currentSpec.$injectorStrict;\n      modules.unshift('ngMock');\n      modules.unshift('ng');\n      var injector = currentSpec.$injector;\n      if (!injector) {\n        if (strictDi) {\n          // If strictDi is enabled, annotate the providerInjector blocks\n          angular.forEach(modules, function(moduleFn) {\n            if (typeof moduleFn === \"function\") {\n              angular.injector.$$annotate(moduleFn);\n            }\n          });\n        }\n        injector = currentSpec.$injector = angular.injector(modules, strictDi);\n        currentSpec.$injectorStrict = strictDi;\n      }\n      for (var i = 0, ii = blockFns.length; i < ii; i++) {\n        if (currentSpec.$injectorStrict) {\n          // If the injector is strict / strictDi, and the spec wants to inject using automatic\n          // annotation, then annotate the function here.\n          injector.annotate(blockFns[i]);\n        }\n        try {\n          /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */\n          injector.invoke(blockFns[i] || angular.noop, this);\n          /* jshint +W040 */\n        } catch (e) {\n          if (e.stack && errorForStack) {\n            throw new ErrorAddingDeclarationLocationStack(e, errorForStack);\n          }\n          throw e;\n        } finally {\n          errorForStack = null;\n        }\n      }\n    }\n  };\n\n\n  angular.mock.inject.strictDi = function(value) {\n    value = arguments.length ? !!value : true;\n    return isSpecRunning() ? workFn() : workFn;\n\n    function workFn() {\n      if (value !== currentSpec.$injectorStrict) {\n        if (currentSpec.$injector) {\n          throw new Error('Injector already created, can not modify strict annotations');\n        } else {\n          currentSpec.$injectorStrict = value;\n        }\n      }\n    }\n  };\n}\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/client/vendor/angular-resource.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\nvar $resourceMinErr = angular.$$minErr('$resource');\n\n// Helper functions and regex to lookup a dotted path on an object\n// stopping at undefined/null.  The path must be composed of ASCII\n// identifiers (just like $parse)\nvar MEMBER_NAME_REGEX = /^(\\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;\n\nfunction isValidDottedPath(path) {\n  return (path != null && path !== '' && path !== 'hasOwnProperty' &&\n      MEMBER_NAME_REGEX.test('.' + path));\n}\n\nfunction lookupDottedPath(obj, path) {\n  if (!isValidDottedPath(path)) {\n    throw $resourceMinErr('badmember', 'Dotted member path \"@{0}\" is invalid.', path);\n  }\n  var keys = path.split('.');\n  for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {\n    var key = keys[i];\n    obj = (obj !== null) ? obj[key] : undefined;\n  }\n  return obj;\n}\n\n/**\n * Create a shallow copy of an object and clear other fields from the destination\n */\nfunction shallowClearAndCopy(src, dst) {\n  dst = dst || {};\n\n  angular.forEach(dst, function(value, key) {\n    delete dst[key];\n  });\n\n  for (var key in src) {\n    if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n      dst[key] = src[key];\n    }\n  }\n\n  return dst;\n}\n\n/**\n * @ngdoc module\n * @name ngResource\n * @description\n *\n * # ngResource\n *\n * The `ngResource` module provides interaction support with RESTful services\n * via the $resource service.\n *\n *\n * <div doc-module-components=\"ngResource\"></div>\n *\n * See {@link ngResource.$resource `$resource`} for usage.\n */\n\n/**\n * @ngdoc service\n * @name $resource\n * @requires $http\n *\n * @description\n * A factory which creates a resource object that lets you interact with\n * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.\n *\n * The returned resource object has action methods which provide high-level behaviors without\n * the need to interact with the low level {@link ng.$http $http} service.\n *\n * Requires the {@link ngResource `ngResource`} module to be installed.\n *\n * By default, trailing slashes will be stripped from the calculated URLs,\n * which can pose problems with server backends that do not expect that\n * behavior.  This can be disabled by configuring the `$resourceProvider` like\n * this:\n *\n * ```js\n     app.config(['$resourceProvider', function($resourceProvider) {\n       // Don't strip trailing slashes from calculated URLs\n       $resourceProvider.defaults.stripTrailingSlashes = false;\n     }]);\n * ```\n *\n * @param {string} url A parameterized URL template with parameters prefixed by `:` as in\n *   `/user/:username`. If you are using a URL with a port number (e.g.\n *   `http://example.com:8080/api`), it will be respected.\n *\n *   If you are using a url with a suffix, just add the suffix, like this:\n *   `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`\n *   or even `$resource('http://example.com/resource/:resource_id.:format')`\n *   If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be\n *   collapsed down to a single `.`.  If you need this sequence to appear and not collapse then you\n *   can escape it with `/\\.`.\n *\n * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in\n *   `actions` methods. If any of the parameter value is a function, it will be executed every time\n *   when a param value needs to be obtained for a request (unless the param was overridden).\n *\n *   Each key value in the parameter object is first bound to url template if present and then any\n *   excess keys are appended to the url search query after the `?`.\n *\n *   Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in\n *   URL `/path/greet?salutation=Hello`.\n *\n *   If the parameter value is prefixed with `@` then the value for that parameter will be extracted\n *   from the corresponding property on the `data` object (provided when calling an action method).  For\n *   example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam`\n *   will be `data.someProp`.\n *\n * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend\n *   the default set of resource actions. The declaration should be created in the format of {@link\n *   ng.$http#usage $http.config}:\n *\n *       {action1: {method:?, params:?, isArray:?, headers:?, ...},\n *        action2: {method:?, params:?, isArray:?, headers:?, ...},\n *        ...}\n *\n *   Where:\n *\n *   - **`action`** – {string} – The name of action. This name becomes the name of the method on\n *     your resource object.\n *   - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,\n *     `DELETE`, `JSONP`, etc).\n *   - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of\n *     the parameter value is a function, it will be executed every time when a param value needs to\n *     be obtained for a request (unless the param was overridden).\n *   - **`url`** – {string} – action specific `url` override. The url templating is supported just\n *     like for the resource-level urls.\n *   - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,\n *     see `returns` section.\n *   - **`transformRequest`** –\n *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n *     transform function or an array of such functions. The transform function takes the http\n *     request body and headers and returns its transformed (typically serialized) version.\n *     By default, transformRequest will contain one function that checks if the request data is\n *     an object and serializes to using `angular.toJson`. To prevent this behavior, set\n *     `transformRequest` to an empty array: `transformRequest: []`\n *   - **`transformResponse`** –\n *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n *     transform function or an array of such functions. The transform function takes the http\n *     response body and headers and returns its transformed (typically deserialized) version.\n *     By default, transformResponse will contain one function that checks if the response looks like\n *     a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, set\n *     `transformResponse` to an empty array: `transformResponse: []`\n *   - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\n *     GET request, otherwise if a cache instance built with\n *     {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\n *     caching.\n *   - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that\n *     should abort the request when resolved.\n *   - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the\n *     XHR object. See\n *     [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)\n *     for more information.\n *   - **`responseType`** - `{string}` - see\n *     [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).\n *   - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -\n *     `response` and `responseError`. Both `response` and `responseError` interceptors get called\n *     with `http response` object. See {@link ng.$http $http interceptors}.\n *\n * @param {Object} options Hash with custom settings that should extend the\n *   default `$resourceProvider` behavior.  The only supported option is\n *\n *   Where:\n *\n *   - **`stripTrailingSlashes`** – {boolean} – If true then the trailing\n *   slashes from any calculated URL will be stripped. (Defaults to true.)\n *\n * @returns {Object} A resource \"class\" object with methods for the default set of resource actions\n *   optionally extended with custom `actions`. The default set contains these actions:\n *   ```js\n *   { 'get':    {method:'GET'},\n *     'save':   {method:'POST'},\n *     'query':  {method:'GET', isArray:true},\n *     'remove': {method:'DELETE'},\n *     'delete': {method:'DELETE'} };\n *   ```\n *\n *   Calling these methods invoke an {@link ng.$http} with the specified http method,\n *   destination and parameters. When the data is returned from the server then the object is an\n *   instance of the resource class. The actions `save`, `remove` and `delete` are available on it\n *   as  methods with the `$` prefix. This allows you to easily perform CRUD operations (create,\n *   read, update, delete) on server-side data like this:\n *   ```js\n *   var User = $resource('/user/:userId', {userId:'@id'});\n *   var user = User.get({userId:123}, function() {\n *     user.abc = true;\n *     user.$save();\n *   });\n *   ```\n *\n *   It is important to realize that invoking a $resource object method immediately returns an\n *   empty reference (object or array depending on `isArray`). Once the data is returned from the\n *   server the existing reference is populated with the actual data. This is a useful trick since\n *   usually the resource is assigned to a model which is then rendered by the view. Having an empty\n *   object results in no rendering, once the data arrives from the server then the object is\n *   populated with the data and the view automatically re-renders itself showing the new data. This\n *   means that in most cases one never has to write a callback function for the action methods.\n *\n *   The action methods on the class object or instance object can be invoked with the following\n *   parameters:\n *\n *   - HTTP GET \"class\" actions: `Resource.action([parameters], [success], [error])`\n *   - non-GET \"class\" actions: `Resource.action([parameters], postData, [success], [error])`\n *   - non-GET instance actions:  `instance.$action([parameters], [success], [error])`\n *\n *\n *   Success callback is called with (value, responseHeaders) arguments, where the value is\n *   the populated resource instance or collection object. The error callback is called\n *   with (httpResponse) argument.\n *\n *   Class actions return empty instance (with additional properties below).\n *   Instance actions return promise of the action.\n *\n *   The Resource instances and collection have these additional properties:\n *\n *   - `$promise`: the {@link ng.$q promise} of the original server interaction that created this\n *     instance or collection.\n *\n *     On success, the promise is resolved with the same resource instance or collection object,\n *     updated with data from server. This makes it easy to use in\n *     {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view\n *     rendering until the resource(s) are loaded.\n *\n *     On failure, the promise is resolved with the {@link ng.$http http response} object, without\n *     the `resource` property.\n *\n *     If an interceptor object was provided, the promise will instead be resolved with the value\n *     returned by the interceptor.\n *\n *   - `$resolved`: `true` after first server interaction is completed (either with success or\n *      rejection), `false` before that. Knowing if the Resource has been resolved is useful in\n *      data-binding.\n *\n * @example\n *\n * # Credit card resource\n *\n * ```js\n     // Define CreditCard class\n     var CreditCard = $resource('/user/:userId/card/:cardId',\n      {userId:123, cardId:'@id'}, {\n       charge: {method:'POST', params:{charge:true}}\n      });\n\n     // We can retrieve a collection from the server\n     var cards = CreditCard.query(function() {\n       // GET: /user/123/card\n       // server returns: [ {id:456, number:'1234', name:'Smith'} ];\n\n       var card = cards[0];\n       // each item is an instance of CreditCard\n       expect(card instanceof CreditCard).toEqual(true);\n       card.name = \"J. Smith\";\n       // non GET methods are mapped onto the instances\n       card.$save();\n       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}\n       // server returns: {id:456, number:'1234', name: 'J. Smith'};\n\n       // our custom method is mapped as well.\n       card.$charge({amount:9.99});\n       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}\n     });\n\n     // we can create an instance as well\n     var newCard = new CreditCard({number:'0123'});\n     newCard.name = \"Mike Smith\";\n     newCard.$save();\n     // POST: /user/123/card {number:'0123', name:'Mike Smith'}\n     // server returns: {id:789, number:'0123', name: 'Mike Smith'};\n     expect(newCard.id).toEqual(789);\n * ```\n *\n * The object returned from this function execution is a resource \"class\" which has \"static\" method\n * for each action in the definition.\n *\n * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and\n * `headers`.\n * When the data is returned from the server then the object is an instance of the resource type and\n * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD\n * operations (create, read, update, delete) on server-side data.\n\n   ```js\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123}, function(user) {\n       user.abc = true;\n       user.$save();\n     });\n   ```\n *\n * It's worth noting that the success callback for `get`, `query` and other methods gets passed\n * in the response that came from the server as well as $http header getter function, so one\n * could rewrite the above example and get access to http headers as:\n *\n   ```js\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123}, function(u, getResponseHeaders){\n       u.abc = true;\n       u.$save(function(u, putResponseHeaders) {\n         //u => saved user object\n         //putResponseHeaders => $http header getter\n       });\n     });\n   ```\n *\n * You can also access the raw `$http` promise via the `$promise` property on the object returned\n *\n   ```\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123})\n         .$promise.then(function(user) {\n           $scope.user = user;\n         });\n   ```\n\n * # Creating a custom 'PUT' request\n * In this example we create a custom method on our resource to make a PUT request\n * ```js\n *    var app = angular.module('app', ['ngResource', 'ngRoute']);\n *\n *    // Some APIs expect a PUT request in the format URL/object/ID\n *    // Here we are creating an 'update' method\n *    app.factory('Notes', ['$resource', function($resource) {\n *    return $resource('/notes/:id', null,\n *        {\n *            'update': { method:'PUT' }\n *        });\n *    }]);\n *\n *    // In our controller we get the ID from the URL using ngRoute and $routeParams\n *    // We pass in $routeParams and our Notes factory along with $scope\n *    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',\n                                      function($scope, $routeParams, Notes) {\n *    // First get a note object from the factory\n *    var note = Notes.get({ id:$routeParams.id });\n *    $id = note.id;\n *\n *    // Now call update passing in the ID first then the object you are updating\n *    Notes.update({ id:$id }, note);\n *\n *    // This will PUT /notes/ID with the note object in the request payload\n *    }]);\n * ```\n */\nangular.module('ngResource', ['ng']).\n  provider('$resource', function() {\n    var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\\/\\/[^\\/]*/;\n    var provider = this;\n\n    this.defaults = {\n      // Strip slashes by default\n      stripTrailingSlashes: true,\n\n      // Default actions configuration\n      actions: {\n        'get': {method: 'GET'},\n        'save': {method: 'POST'},\n        'query': {method: 'GET', isArray: true},\n        'remove': {method: 'DELETE'},\n        'delete': {method: 'DELETE'}\n      }\n    };\n\n    this.$get = ['$http', '$q', function($http, $q) {\n\n      var noop = angular.noop,\n        forEach = angular.forEach,\n        extend = angular.extend,\n        copy = angular.copy,\n        isFunction = angular.isFunction;\n\n      /**\n       * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n       * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set\n       * (pchar) allowed in path segments:\n       *    segment       = *pchar\n       *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n       *    pct-encoded   = \"%\" HEXDIG HEXDIG\n       *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n       *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n       *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n       */\n      function encodeUriSegment(val) {\n        return encodeUriQuery(val, true).\n          replace(/%26/gi, '&').\n          replace(/%3D/gi, '=').\n          replace(/%2B/gi, '+');\n      }\n\n\n      /**\n       * This method is intended for encoding *key* or *value* parts of query component. We need a\n       * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't\n       * have to be encoded per http://tools.ietf.org/html/rfc3986:\n       *    query       = *( pchar / \"/\" / \"?\" )\n       *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n       *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n       *    pct-encoded   = \"%\" HEXDIG HEXDIG\n       *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n       *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n       */\n      function encodeUriQuery(val, pctEncodeSpaces) {\n        return encodeURIComponent(val).\n          replace(/%40/gi, '@').\n          replace(/%3A/gi, ':').\n          replace(/%24/g, '$').\n          replace(/%2C/gi, ',').\n          replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n      }\n\n      function Route(template, defaults) {\n        this.template = template;\n        this.defaults = extend({}, provider.defaults, defaults);\n        this.urlParams = {};\n      }\n\n      Route.prototype = {\n        setUrlParams: function(config, params, actionUrl) {\n          var self = this,\n            url = actionUrl || self.template,\n            val,\n            encodedVal,\n            protocolAndDomain = '';\n\n          var urlParams = self.urlParams = {};\n          forEach(url.split(/\\W/), function(param) {\n            if (param === 'hasOwnProperty') {\n              throw $resourceMinErr('badname', \"hasOwnProperty is not a valid parameter name.\");\n            }\n            if (!(new RegExp(\"^\\\\d+$\").test(param)) && param &&\n              (new RegExp(\"(^|[^\\\\\\\\]):\" + param + \"(\\\\W|$)\").test(url))) {\n              urlParams[param] = true;\n            }\n          });\n          url = url.replace(/\\\\:/g, ':');\n          url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {\n            protocolAndDomain = match;\n            return '';\n          });\n\n          params = params || {};\n          forEach(self.urlParams, function(_, urlParam) {\n            val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];\n            if (angular.isDefined(val) && val !== null) {\n              encodedVal = encodeUriSegment(val);\n              url = url.replace(new RegExp(\":\" + urlParam + \"(\\\\W|$)\", \"g\"), function(match, p1) {\n                return encodedVal + p1;\n              });\n            } else {\n              url = url.replace(new RegExp(\"(\\/?):\" + urlParam + \"(\\\\W|$)\", \"g\"), function(match,\n                  leadingSlashes, tail) {\n                if (tail.charAt(0) == '/') {\n                  return tail;\n                } else {\n                  return leadingSlashes + tail;\n                }\n              });\n            }\n          });\n\n          // strip trailing slashes and set the url (unless this behavior is specifically disabled)\n          if (self.defaults.stripTrailingSlashes) {\n            url = url.replace(/\\/+$/, '') || '/';\n          }\n\n          // then replace collapse `/.` if found in the last URL path segment before the query\n          // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`\n          url = url.replace(/\\/\\.(?=\\w+($|\\?))/, '.');\n          // replace escaped `/\\.` with `/.`\n          config.url = protocolAndDomain + url.replace(/\\/\\\\\\./, '/.');\n\n\n          // set params - delegate param encoding to $http\n          forEach(params, function(value, key) {\n            if (!self.urlParams[key]) {\n              config.params = config.params || {};\n              config.params[key] = value;\n            }\n          });\n        }\n      };\n\n\n      function resourceFactory(url, paramDefaults, actions, options) {\n        var route = new Route(url, options);\n\n        actions = extend({}, provider.defaults.actions, actions);\n\n        function extractParams(data, actionParams) {\n          var ids = {};\n          actionParams = extend({}, paramDefaults, actionParams);\n          forEach(actionParams, function(value, key) {\n            if (isFunction(value)) { value = value(); }\n            ids[key] = value && value.charAt && value.charAt(0) == '@' ?\n              lookupDottedPath(data, value.substr(1)) : value;\n          });\n          return ids;\n        }\n\n        function defaultResponseInterceptor(response) {\n          return response.resource;\n        }\n\n        function Resource(value) {\n          shallowClearAndCopy(value || {}, this);\n        }\n\n        Resource.prototype.toJSON = function() {\n          var data = extend({}, this);\n          delete data.$promise;\n          delete data.$resolved;\n          return data;\n        };\n\n        forEach(actions, function(action, name) {\n          var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);\n\n          Resource[name] = function(a1, a2, a3, a4) {\n            var params = {}, data, success, error;\n\n            /* jshint -W086 */ /* (purposefully fall through case statements) */\n            switch (arguments.length) {\n              case 4:\n                error = a4;\n                success = a3;\n              //fallthrough\n              case 3:\n              case 2:\n                if (isFunction(a2)) {\n                  if (isFunction(a1)) {\n                    success = a1;\n                    error = a2;\n                    break;\n                  }\n\n                  success = a2;\n                  error = a3;\n                  //fallthrough\n                } else {\n                  params = a1;\n                  data = a2;\n                  success = a3;\n                  break;\n                }\n              case 1:\n                if (isFunction(a1)) success = a1;\n                else if (hasBody) data = a1;\n                else params = a1;\n                break;\n              case 0: break;\n              default:\n                throw $resourceMinErr('badargs',\n                  \"Expected up to 4 arguments [params, data, success, error], got {0} arguments\",\n                  arguments.length);\n            }\n            /* jshint +W086 */ /* (purposefully fall through case statements) */\n\n            var isInstanceCall = this instanceof Resource;\n            var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));\n            var httpConfig = {};\n            var responseInterceptor = action.interceptor && action.interceptor.response ||\n              defaultResponseInterceptor;\n            var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||\n              undefined;\n\n            forEach(action, function(value, key) {\n              if (key != 'params' && key != 'isArray' && key != 'interceptor') {\n                httpConfig[key] = copy(value);\n              }\n            });\n\n            if (hasBody) httpConfig.data = data;\n            route.setUrlParams(httpConfig,\n              extend({}, extractParams(data, action.params || {}), params),\n              action.url);\n\n            var promise = $http(httpConfig).then(function(response) {\n              var data = response.data,\n                promise = value.$promise;\n\n              if (data) {\n                // Need to convert action.isArray to boolean in case it is undefined\n                // jshint -W018\n                if (angular.isArray(data) !== (!!action.isArray)) {\n                  throw $resourceMinErr('badcfg',\n                      'Error in resource configuration for action `{0}`. Expected response to ' +\n                      'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',\n                    angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);\n                }\n                // jshint +W018\n                if (action.isArray) {\n                  value.length = 0;\n                  forEach(data, function(item) {\n                    if (typeof item === \"object\") {\n                      value.push(new Resource(item));\n                    } else {\n                      // Valid JSON values may be string literals, and these should not be converted\n                      // into objects. These items will not have access to the Resource prototype\n                      // methods, but unfortunately there\n                      value.push(item);\n                    }\n                  });\n                } else {\n                  shallowClearAndCopy(data, value);\n                  value.$promise = promise;\n                }\n              }\n\n              value.$resolved = true;\n\n              response.resource = value;\n\n              return response;\n            }, function(response) {\n              value.$resolved = true;\n\n              (error || noop)(response);\n\n              return $q.reject(response);\n            });\n\n            promise = promise.then(\n              function(response) {\n                var value = responseInterceptor(response);\n                (success || noop)(value, response.headers);\n                return value;\n              },\n              responseErrorInterceptor);\n\n            if (!isInstanceCall) {\n              // we are creating instance / collection\n              // - set the initial promise\n              // - return the instance / collection\n              value.$promise = promise;\n              value.$resolved = false;\n\n              return value;\n            }\n\n            // instance call\n            return promise;\n          };\n\n\n          Resource.prototype['$' + name] = function(params, success, error) {\n            if (isFunction(params)) {\n              error = success; success = params; params = {};\n            }\n            var result = Resource[name].call(this, params, this, success, error);\n            return result.$promise || result;\n          };\n        });\n\n        Resource.bind = function(additionalParamDefaults) {\n          return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);\n        };\n\n        return Resource;\n      }\n\n      return resourceFactory;\n    }];\n  });\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/client/vendor/angular-sanitize.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $sanitizeMinErr = angular.$$minErr('$sanitize');\n\n/**\n * @ngdoc module\n * @name ngSanitize\n * @description\n *\n * # ngSanitize\n *\n * The `ngSanitize` module provides functionality to sanitize HTML.\n *\n *\n * <div doc-module-components=\"ngSanitize\"></div>\n *\n * See {@link ngSanitize.$sanitize `$sanitize`} for usage.\n */\n\n/*\n * HTML Parser By Misko Hevery (misko@hevery.com)\n * based on:  HTML Parser By John Resig (ejohn.org)\n * Original code by Erik Arvidsson, Mozilla Public License\n * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js\n *\n * // Use like so:\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n */\n\n\n/**\n * @ngdoc service\n * @name $sanitize\n * @kind function\n *\n * @description\n *   The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are\n *   then serialized back to properly escaped html string. This means that no unsafe input can make\n *   it into the returned string, however, since our parser is more strict than a typical browser\n *   parser, it's possible that some obscure input, which would be recognized as valid HTML by a\n *   browser, won't make it through the sanitizer. The input may also contain SVG markup.\n *   The whitelist is configured using the functions `aHrefSanitizationWhitelist` and\n *   `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.\n *\n * @param {string} html HTML input.\n * @returns {string} Sanitized HTML.\n *\n * @example\n   <example module=\"sanitizeExample\" deps=\"angular-sanitize.js\">\n   <file name=\"index.html\">\n     <script>\n         angular.module('sanitizeExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {\n             $scope.snippet =\n               '<p style=\"color:blue\">an html\\n' +\n               '<em onmouseover=\"this.textContent=\\'PWN3D!\\'\">click here</em>\\n' +\n               'snippet</p>';\n             $scope.deliberatelyTrustDangerousSnippet = function() {\n               return $sce.trustAsHtml($scope.snippet);\n             };\n           }]);\n     </script>\n     <div ng-controller=\"ExampleController\">\n        Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Directive</td>\n           <td>How</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"bind-html-with-sanitize\">\n           <td>ng-bind-html</td>\n           <td>Automatically uses $sanitize</td>\n           <td><pre>&lt;div ng-bind-html=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind-html=\"snippet\"></div></td>\n         </tr>\n         <tr id=\"bind-html-with-trust\">\n           <td>ng-bind-html</td>\n           <td>Bypass $sanitize by explicitly trusting the dangerous value</td>\n           <td>\n           <pre>&lt;div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"&gt;\n&lt;/div&gt;</pre>\n           </td>\n           <td><div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"></div></td>\n         </tr>\n         <tr id=\"bind-default\">\n           <td>ng-bind</td>\n           <td>Automatically escapes</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n       </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should sanitize the html snippet by default', function() {\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('<p>an html\\n<em>click here</em>\\nsnippet</p>');\n     });\n\n     it('should inline raw snippet if bound to a trusted value', function() {\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).\n         toBe(\"<p style=\\\"color:blue\\\">an html\\n\" +\n              \"<em onmouseover=\\\"this.textContent='PWN3D!'\\\">click here</em>\\n\" +\n              \"snippet</p>\");\n     });\n\n     it('should escape snippet without any filter', function() {\n       expect(element(by.css('#bind-default div')).getInnerHtml()).\n         toBe(\"&lt;p style=\\\"color:blue\\\"&gt;an html\\n\" +\n              \"&lt;em onmouseover=\\\"this.textContent='PWN3D!'\\\"&gt;click here&lt;/em&gt;\\n\" +\n              \"snippet&lt;/p&gt;\");\n     });\n\n     it('should update', function() {\n       element(by.model('snippet')).clear();\n       element(by.model('snippet')).sendKeys('new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('new <b>text</b>');\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(\n         'new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(\n         \"new &lt;b onclick=\\\"alert(1)\\\"&gt;text&lt;/b&gt;\");\n     });\n   </file>\n   </example>\n */\nfunction $SanitizeProvider() {\n  this.$get = ['$$sanitizeUri', function($$sanitizeUri) {\n    return function(html) {\n      var buf = [];\n      htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {\n        return !/^unsafe/.test($$sanitizeUri(uri, isImage));\n      }));\n      return buf.join('');\n    };\n  }];\n}\n\nfunction sanitizeText(chars) {\n  var buf = [];\n  var writer = htmlSanitizeWriter(buf, angular.noop);\n  writer.chars(chars);\n  return buf.join('');\n}\n\n\n// Regular Expressions for parsing tags and attributes\nvar START_TAG_REGEXP =\n       /^<((?:[a-zA-Z])[\\w:-]*)((?:\\s+[\\w:-]+(?:\\s*=\\s*(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?)*)\\s*(\\/?)\\s*(>?)/,\n  END_TAG_REGEXP = /^<\\/\\s*([\\w:-]+)[^>]*>/,\n  ATTR_REGEXP = /([\\w:-]+)(?:\\s*=\\s*(?:(?:\"((?:[^\"])*)\")|(?:'((?:[^'])*)')|([^>\\s]+)))?/g,\n  BEGIN_TAG_REGEXP = /^</,\n  BEGING_END_TAGE_REGEXP = /^<\\//,\n  COMMENT_REGEXP = /<!--(.*?)-->/g,\n  DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,\n  CDATA_REGEXP = /<!\\[CDATA\\[(.*?)]]>/g,\n  SURROGATE_PAIR_REGEXP = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g,\n  // Match everything outside of normal chars and \" (quote character)\n  NON_ALPHANUMERIC_REGEXP = /([^\\#-~| |!])/g;\n\n\n// Good source of info about elements and attributes\n// http://dev.w3.org/html5/spec/Overview.html#semantics\n// http://simon.html5.org/html-elements\n\n// Safe Void Elements - HTML5\n// http://dev.w3.org/html5/spec/Overview.html#void-elements\nvar voidElements = makeMap(\"area,br,col,hr,img,wbr\");\n\n// Elements that you can, intentionally, leave open (and which close themselves)\n// http://dev.w3.org/html5/spec/Overview.html#optional-tags\nvar optionalEndTagBlockElements = makeMap(\"colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr\"),\n    optionalEndTagInlineElements = makeMap(\"rp,rt\"),\n    optionalEndTagElements = angular.extend({},\n                                            optionalEndTagInlineElements,\n                                            optionalEndTagBlockElements);\n\n// Safe Block Elements - HTML5\nvar blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap(\"address,article,\" +\n        \"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,\" +\n        \"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul\"));\n\n// Inline Elements - HTML5\nvar inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap(\"a,abbr,acronym,b,\" +\n        \"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,\" +\n        \"samp,small,span,strike,strong,sub,sup,time,tt,u,var\"));\n\n// SVG Elements\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements\n// Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.\n// They can potentially allow for arbitrary javascript to be executed. See #11290\nvar svgElements = makeMap(\"circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,\" +\n        \"hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,\" +\n        \"radialGradient,rect,stop,svg,switch,text,title,tspan,use\");\n\n// Special Elements (can contain anything)\nvar specialElements = makeMap(\"script,style\");\n\nvar validElements = angular.extend({},\n                                   voidElements,\n                                   blockElements,\n                                   inlineElements,\n                                   optionalEndTagElements,\n                                   svgElements);\n\n//Attributes that have href and hence need to be sanitized\nvar uriAttrs = makeMap(\"background,cite,href,longdesc,src,usemap,xlink:href\");\n\nvar htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +\n    'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +\n    'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +\n    'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +\n    'valign,value,vspace,width');\n\n// SVG attributes (without \"id\" and \"name\" attributes)\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes\nvar svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +\n    'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +\n    'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +\n    'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +\n    'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +\n    'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +\n    'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +\n    'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +\n    'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +\n    'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +\n    'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +\n    'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +\n    'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +\n    'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +\n    'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);\n\nvar validAttrs = angular.extend({},\n                                uriAttrs,\n                                svgAttrs,\n                                htmlAttrs);\n\nfunction makeMap(str, lowercaseKeys) {\n  var obj = {}, items = str.split(','), i;\n  for (i = 0; i < items.length; i++) {\n    obj[lowercaseKeys ? angular.lowercase(items[i]) : items[i]] = true;\n  }\n  return obj;\n}\n\n\n/**\n * @example\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n * @param {string} html string\n * @param {object} handler\n */\nfunction htmlParser(html, handler) {\n  if (typeof html !== 'string') {\n    if (html === null || typeof html === 'undefined') {\n      html = '';\n    } else {\n      html = '' + html;\n    }\n  }\n  var index, chars, match, stack = [], last = html, text;\n  stack.last = function() { return stack[stack.length - 1]; };\n\n  while (html) {\n    text = '';\n    chars = true;\n\n    // Make sure we're not in a script or style element\n    if (!stack.last() || !specialElements[stack.last()]) {\n\n      // Comment\n      if (html.indexOf(\"<!--\") === 0) {\n        // comments containing -- are not allowed unless they terminate the comment\n        index = html.indexOf(\"--\", 4);\n\n        if (index >= 0 && html.lastIndexOf(\"-->\", index) === index) {\n          if (handler.comment) handler.comment(html.substring(4, index));\n          html = html.substring(index + 3);\n          chars = false;\n        }\n      // DOCTYPE\n      } else if (DOCTYPE_REGEXP.test(html)) {\n        match = html.match(DOCTYPE_REGEXP);\n\n        if (match) {\n          html = html.replace(match[0], '');\n          chars = false;\n        }\n      // end tag\n      } else if (BEGING_END_TAGE_REGEXP.test(html)) {\n        match = html.match(END_TAG_REGEXP);\n\n        if (match) {\n          html = html.substring(match[0].length);\n          match[0].replace(END_TAG_REGEXP, parseEndTag);\n          chars = false;\n        }\n\n      // start tag\n      } else if (BEGIN_TAG_REGEXP.test(html)) {\n        match = html.match(START_TAG_REGEXP);\n\n        if (match) {\n          // We only have a valid start-tag if there is a '>'.\n          if (match[4]) {\n            html = html.substring(match[0].length);\n            match[0].replace(START_TAG_REGEXP, parseStartTag);\n          }\n          chars = false;\n        } else {\n          // no ending tag found --- this piece should be encoded as an entity.\n          text += '<';\n          html = html.substring(1);\n        }\n      }\n\n      if (chars) {\n        index = html.indexOf(\"<\");\n\n        text += index < 0 ? html : html.substring(0, index);\n        html = index < 0 ? \"\" : html.substring(index);\n\n        if (handler.chars) handler.chars(decodeEntities(text));\n      }\n\n    } else {\n      // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\\W\\w].\n      html = html.replace(new RegExp(\"([\\\\W\\\\w]*)<\\\\s*\\\\/\\\\s*\" + stack.last() + \"[^>]*>\", 'i'),\n        function(all, text) {\n          text = text.replace(COMMENT_REGEXP, \"$1\").replace(CDATA_REGEXP, \"$1\");\n\n          if (handler.chars) handler.chars(decodeEntities(text));\n\n          return \"\";\n      });\n\n      parseEndTag(\"\", stack.last());\n    }\n\n    if (html == last) {\n      throw $sanitizeMinErr('badparse', \"The sanitizer was unable to parse the following block \" +\n                                        \"of html: {0}\", html);\n    }\n    last = html;\n  }\n\n  // Clean up any remaining tags\n  parseEndTag();\n\n  function parseStartTag(tag, tagName, rest, unary) {\n    tagName = angular.lowercase(tagName);\n    if (blockElements[tagName]) {\n      while (stack.last() && inlineElements[stack.last()]) {\n        parseEndTag(\"\", stack.last());\n      }\n    }\n\n    if (optionalEndTagElements[tagName] && stack.last() == tagName) {\n      parseEndTag(\"\", tagName);\n    }\n\n    unary = voidElements[tagName] || !!unary;\n\n    if (!unary) {\n      stack.push(tagName);\n    }\n\n    var attrs = {};\n\n    rest.replace(ATTR_REGEXP,\n      function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {\n        var value = doubleQuotedValue\n          || singleQuotedValue\n          || unquotedValue\n          || '';\n\n        attrs[name] = decodeEntities(value);\n    });\n    if (handler.start) handler.start(tagName, attrs, unary);\n  }\n\n  function parseEndTag(tag, tagName) {\n    var pos = 0, i;\n    tagName = angular.lowercase(tagName);\n    if (tagName) {\n      // Find the closest opened tag of the same type\n      for (pos = stack.length - 1; pos >= 0; pos--) {\n        if (stack[pos] == tagName) break;\n      }\n    }\n\n    if (pos >= 0) {\n      // Close all the open elements, up the stack\n      for (i = stack.length - 1; i >= pos; i--)\n        if (handler.end) handler.end(stack[i]);\n\n      // Remove the open elements from the stack\n      stack.length = pos;\n    }\n  }\n}\n\nvar hiddenPre=document.createElement(\"pre\");\n/**\n * decodes all entities into regular string\n * @param value\n * @returns {string} A string with decoded entities.\n */\nfunction decodeEntities(value) {\n  if (!value) { return ''; }\n\n  hiddenPre.innerHTML = value.replace(/</g,\"&lt;\");\n  // innerText depends on styling as it doesn't display hidden elements.\n  // Therefore, it's better to use textContent not to cause unnecessary reflows.\n  return hiddenPre.textContent;\n}\n\n/**\n * Escapes all potentially dangerous characters, so that the\n * resulting string can be safely inserted into attribute or\n * element text.\n * @param value\n * @returns {string} escaped text\n */\nfunction encodeEntities(value) {\n  return value.\n    replace(/&/g, '&amp;').\n    replace(SURROGATE_PAIR_REGEXP, function(value) {\n      var hi = value.charCodeAt(0);\n      var low = value.charCodeAt(1);\n      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';\n    }).\n    replace(NON_ALPHANUMERIC_REGEXP, function(value) {\n      return '&#' + value.charCodeAt(0) + ';';\n    }).\n    replace(/</g, '&lt;').\n    replace(/>/g, '&gt;');\n}\n\n/**\n * create an HTML/XML writer which writes to buffer\n * @param {Array} buf use buf.jain('') to get out sanitized html string\n * @returns {object} in the form of {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * }\n */\nfunction htmlSanitizeWriter(buf, uriValidator) {\n  var ignore = false;\n  var out = angular.bind(buf, buf.push);\n  return {\n    start: function(tag, attrs, unary) {\n      tag = angular.lowercase(tag);\n      if (!ignore && specialElements[tag]) {\n        ignore = tag;\n      }\n      if (!ignore && validElements[tag] === true) {\n        out('<');\n        out(tag);\n        angular.forEach(attrs, function(value, key) {\n          var lkey=angular.lowercase(key);\n          var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');\n          if (validAttrs[lkey] === true &&\n            (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {\n            out(' ');\n            out(key);\n            out('=\"');\n            out(encodeEntities(value));\n            out('\"');\n          }\n        });\n        out(unary ? '/>' : '>');\n      }\n    },\n    end: function(tag) {\n        tag = angular.lowercase(tag);\n        if (!ignore && validElements[tag] === true) {\n          out('</');\n          out(tag);\n          out('>');\n        }\n        if (tag == ignore) {\n          ignore = false;\n        }\n      },\n    chars: function(chars) {\n        if (!ignore) {\n          out(encodeEntities(chars));\n        }\n      }\n  };\n}\n\n\n// define ngSanitize module and register $sanitize service\nangular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);\n\n/* global sanitizeText: false */\n\n/**\n * @ngdoc filter\n * @name linky\n * @kind function\n *\n * @description\n * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and\n * plain email address links.\n *\n * Requires the {@link ngSanitize `ngSanitize`} module to be installed.\n *\n * @param {string} text Input text.\n * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.\n * @returns {string} Html-linkified text.\n *\n * @usage\n   <span ng-bind-html=\"linky_expression | linky\"></span>\n *\n * @example\n   <example module=\"linkyExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('linkyExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.snippet =\n               'Pretty text with some links:\\n'+\n               'http://angularjs.org/,\\n'+\n               'mailto:us@somewhere.org,\\n'+\n               'another@somewhere.org,\\n'+\n               'and one more: ftp://127.0.0.1/.';\n             $scope.snippetWithTarget = 'http://angularjs.org/';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n       Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Filter</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"linky-filter\">\n           <td>linky filter</td>\n           <td>\n             <pre>&lt;div ng-bind-html=\"snippet | linky\"&gt;<br>&lt;/div&gt;</pre>\n           </td>\n           <td>\n             <div ng-bind-html=\"snippet | linky\"></div>\n           </td>\n         </tr>\n         <tr id=\"linky-target\">\n          <td>linky target</td>\n          <td>\n            <pre>&lt;div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"&gt;<br>&lt;/div&gt;</pre>\n          </td>\n          <td>\n            <div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"></div>\n          </td>\n         </tr>\n         <tr id=\"escaped-html\">\n           <td>no filter</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should linkify the snippet with urls', function() {\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);\n       });\n\n       it('should not linkify snippet without the linky filter', function() {\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);\n       });\n\n       it('should update', function() {\n         element(by.model('snippet')).clear();\n         element(by.model('snippet')).sendKeys('new http://link.');\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('new http://link.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())\n             .toBe('new http://link.');\n       });\n\n       it('should work with the target property', function() {\n        expect(element(by.id('linky-target')).\n            element(by.binding(\"snippetWithTarget | linky:'_blank'\")).getText()).\n            toBe('http://angularjs.org/');\n        expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');\n       });\n     </file>\n   </example>\n */\nangular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {\n  var LINKY_URL_REGEXP =\n        /((ftp|https?):\\/\\/|(www\\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\\S*[^\\s.;,(){}<>\"\\u201d\\u2019]/i,\n      MAILTO_REGEXP = /^mailto:/i;\n\n  return function(text, target) {\n    if (!text) return text;\n    var match;\n    var raw = text;\n    var html = [];\n    var url;\n    var i;\n    while ((match = raw.match(LINKY_URL_REGEXP))) {\n      // We can not end in these as they are sometimes found at the end of the sentence\n      url = match[0];\n      // if we did not match ftp/http/www/mailto then assume mailto\n      if (!match[2] && !match[4]) {\n        url = (match[3] ? 'http://' : 'mailto:') + url;\n      }\n      i = match.index;\n      addText(raw.substr(0, i));\n      addLink(url, match[0].replace(MAILTO_REGEXP, ''));\n      raw = raw.substring(i + match[0].length);\n    }\n    addText(raw);\n    return $sanitize(html.join(''));\n\n    function addText(text) {\n      if (!text) {\n        return;\n      }\n      html.push(sanitizeText(text));\n    }\n\n    function addLink(url, text) {\n      html.push('<a ');\n      if (angular.isDefined(target)) {\n        html.push('target=\"',\n                  target,\n                  '\" ');\n      }\n      html.push('href=\"',\n                url.replace(/\"/g, '&quot;'),\n                '\">');\n      addText(text);\n      html.push('</a>');\n    }\n  };\n}]);\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/client/vendor/angular-toastr.js",
    "content": "(function() {\n  'use strict';\n\n  angular.module('toastr', [])\n    .factory('toastr', toastr);\n\n  toastr.$inject = ['$animate', '$injector', '$document', '$rootScope', '$sce', 'toastrConfig', '$q'];\n\n  function toastr($animate, $injector, $document, $rootScope, $sce, toastrConfig, $q) {\n    var container;\n    var index = 0;\n    var toasts = [];\n\n    var previousToastMessage = '';\n    var openToasts = {};\n\n    var containerDefer = $q.defer();\n\n    var toast = {\n      clear: clear,\n      error: error,\n      info: info,\n      remove: remove,\n      success: success,\n      warning: warning\n    };\n\n    return toast;\n\n    /* Public API */\n    function clear(toast) {\n      if (toast) {\n        remove(toast.toastId);\n      } else {\n        for (var i = 0; i < toasts.length; i++) {\n          remove(toasts[i].toastId);\n        }\n      }\n    }\n\n    function error(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.error;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function info(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.info;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function success(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.success;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function warning(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.warning;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function remove(toastId, wasClicked) {\n      var toast = findToast(toastId);\n\n      if (toast && ! toast.deleting) { // Avoid clicking when fading out\n        toast.deleting = true;\n        toast.isOpened = false;\n        $animate.leave(toast.el).then(function() {\n          if (toast.scope.options.onHidden) {\n            toast.scope.options.onHidden(wasClicked);\n          }\n          toast.scope.$destroy();\n          var index = toasts.indexOf(toast);\n          delete openToasts[toast.scope.message];\n          toasts.splice(index, 1);\n          var maxOpened = toastrConfig.maxOpened;\n          if (maxOpened && toasts.length >= maxOpened) {\n            toasts[maxOpened - 1].open.resolve();\n          }\n          if (lastToast()) {\n            container.remove();\n            container = null;\n            containerDefer = $q.defer();\n          }\n        });\n      }\n\n      function findToast(toastId) {\n        for (var i = 0; i < toasts.length; i++) {\n          if (toasts[i].toastId === toastId) {\n            return toasts[i];\n          }\n        }\n      }\n\n      function lastToast() {\n        return !toasts.length;\n      }\n    }\n\n    /* Internal functions */\n    function _buildNotification(type, message, title, optionsOverride)\n    {\n      if (angular.isObject(title)) {\n        optionsOverride = title;\n        title = null;\n      }\n\n      return _notify({\n        iconClass: type,\n        message: message,\n        optionsOverride: optionsOverride,\n        title: title\n      });\n    }\n\n    function _getOptions() {\n      return angular.extend({}, toastrConfig);\n    }\n\n    function _createOrGetContainer(options) {\n      if(container) { return containerDefer.promise; }\n\n      container = angular.element('<div></div>');\n      container.attr('id', options.containerId);\n      container.addClass(options.positionClass);\n      container.css({'pointer-events': 'auto'});\n\n      var target = angular.element(document.querySelector(options.target));\n\n      if ( ! target || ! target.length) {\n        throw 'Target for toasts doesn\\'t exist';\n      }\n\n      $animate.enter(container, target).then(function() {\n        containerDefer.resolve();\n      });\n\n      return containerDefer.promise;\n    }\n\n    function _notify(map) {\n      var options = _getOptions();\n\n      if (shouldExit()) { return; }\n\n      var newToast = createToast();\n\n      toasts.push(newToast);\n\n      if (options.autoDismiss && options.maxOpened > 0) {\n        var oldToasts = toasts.slice(0, (toasts.length - options.maxOpened));\n        for (var i = 0, len = oldToasts.length; i < len; i++) {\n          remove(oldToasts[i].toastId);\n        }\n      }\n\n      if (maxOpenedNotReached()) {\n        newToast.open.resolve();\n      }\n\n      newToast.open.promise.then(function() {\n        _createOrGetContainer(options).then(function() {\n          newToast.isOpened = true;\n          if (options.newestOnTop) {\n            $animate.enter(newToast.el, container).then(function() {\n              newToast.scope.init();\n            });\n          } else {\n            var sibling = container[0].lastChild ? angular.element(container[0].lastChild) : null;\n            $animate.enter(newToast.el, container, sibling).then(function() {\n              newToast.scope.init();\n            });\n          }\n        });\n      });\n\n      return newToast;\n\n      function createScope(toast, map, options) {\n        if (options.allowHtml) {\n          toast.scope.allowHtml = true;\n          toast.scope.title = $sce.trustAsHtml(map.title);\n          toast.scope.message = $sce.trustAsHtml(map.message);\n        } else {\n          toast.scope.title = map.title;\n          toast.scope.message = map.message;\n        }\n\n        toast.scope.toastType = toast.iconClass;\n        toast.scope.toastId = toast.toastId;\n\n        toast.scope.options = {\n          extendedTimeOut: options.extendedTimeOut,\n          messageClass: options.messageClass,\n          onHidden: options.onHidden,\n          onShown: options.onShown,\n          progressBar: options.progressBar,\n          tapToDismiss: options.tapToDismiss,\n          timeOut: options.timeOut,\n          titleClass: options.titleClass,\n          toastClass: options.toastClass\n        };\n\n        if (options.closeButton) {\n          toast.scope.options.closeHtml = options.closeHtml;\n        }\n      }\n\n      function createToast() {\n        var newToast = {\n          toastId: index++,\n          isOpened: false,\n          scope: $rootScope.$new(),\n          open: $q.defer()\n        };\n        newToast.iconClass = map.iconClass;\n        if (map.optionsOverride) {\n          options = angular.extend(options, cleanOptionsOverride(map.optionsOverride));\n          newToast.iconClass = map.optionsOverride.iconClass || newToast.iconClass;\n        }\n\n        createScope(newToast, map, options);\n\n        newToast.el = createToastEl(newToast.scope);\n\n        return newToast;\n\n        function cleanOptionsOverride(options) {\n          var badOptions = ['containerId', 'iconClasses', 'maxOpened', 'newestOnTop',\n                            'positionClass', 'preventDuplicates', 'preventOpenDuplicates', 'templates'];\n          for (var i = 0, l = badOptions.length; i < l; i++) {\n            delete options[badOptions[i]];\n          }\n\n          return options;\n        }\n      }\n\n      function createToastEl(scope) {\n        var angularDomEl = angular.element('<div toast></div>'),\n          $compile = $injector.get('$compile');\n        return $compile(angularDomEl)(scope);\n      }\n\n      function maxOpenedNotReached() {\n        return options.maxOpened && toasts.length <= options.maxOpened || !options.maxOpened;\n      }\n\n      function shouldExit() {\n        var isDuplicateOfLast = options.preventDuplicates && map.message === previousToastMessage;\n        var isDuplicateOpen = options.preventOpenDuplicates && openToasts[map.message];\n\n        if (isDuplicateOfLast || isDuplicateOpen) {\n          return true;\n        }\n\n        previousToastMessage = map.message;\n        openToasts[map.message] = true;\n\n        return false;\n      }\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .constant('toastrConfig', {\n      allowHtml: false,\n      autoDismiss: false,\n      closeButton: false,\n      closeHtml: '<button>&times;</button>',\n      containerId: 'toast-container',\n      extendedTimeOut: 1000,\n      iconClasses: {\n        error: 'toast-error',\n        info: 'toast-info',\n        success: 'toast-success',\n        warning: 'toast-warning'\n      },\n      maxOpened: 0,\n      messageClass: 'toast-message',\n      newestOnTop: true,\n      onHidden: null,\n      onShown: null,\n      positionClass: 'toast-top-right',\n      preventDuplicates: false,\n      preventOpenDuplicates: false,\n      progressBar: false,\n      tapToDismiss: true,\n      target: 'body',\n      templates: {\n        toast: 'directives/toast/toast.html',\n        progressbar: 'directives/progressbar/progressbar.html'\n      },\n      timeOut: 5000,\n      titleClass: 'toast-title',\n      toastClass: 'toast'\n    });\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('progressBar', progressBar);\n\n  progressBar.$inject = ['toastrConfig'];\n\n  function progressBar(toastrConfig) {\n    return {\n      replace: true,\n      require: '^toast',\n      templateUrl: function() {\n        return toastrConfig.templates.progressbar;\n      },\n      link: linkFunction\n    };\n\n    function linkFunction(scope, element, attrs, toastCtrl) {\n      var intervalId, currentTimeOut, hideTime;\n\n      toastCtrl.progressBar = scope;\n\n      scope.start = function(duration) {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n\n        currentTimeOut = parseFloat(duration);\n        hideTime = new Date().getTime() + currentTimeOut;\n        intervalId = setInterval(updateProgress, 10);\n      };\n\n      scope.stop = function() {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n      };\n\n      function updateProgress() {\n        var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100;\n        element.css('width', percentage + '%');\n      }\n\n      scope.$on('$destroy', function() {\n        // Failsafe stop\n        clearInterval(intervalId);\n      });\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .controller('ToastController', ToastController);\n\n  function ToastController() {\n    this.progressBar = null;\n\n    this.startProgressBar = function(duration) {\n      if (this.progressBar) {\n        this.progressBar.start(duration);\n      }\n    };\n\n    this.stopProgressBar = function() {\n      if (this.progressBar) {\n        this.progressBar.stop();\n      }\n    };\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('toast', toast);\n\n  toast.$inject = ['$injector', '$interval', 'toastrConfig', 'toastr'];\n\n  function toast($injector, $interval, toastrConfig, toastr) {\n    return {\n      replace: true,\n      templateUrl: function() {\n        return toastrConfig.templates.toast;\n      },\n      controller: 'ToastController',\n      link: toastLinkFunction\n    };\n\n    function toastLinkFunction(scope, element, attrs, toastCtrl) {\n      var timeout;\n\n      scope.toastClass = scope.options.toastClass;\n      scope.titleClass = scope.options.titleClass;\n      scope.messageClass = scope.options.messageClass;\n      scope.progressBar = scope.options.progressBar;\n\n      if (wantsCloseButton()) {\n        var button = angular.element(scope.options.closeHtml),\n          $compile = $injector.get('$compile');\n        button.addClass('toast-close-button');\n        button.attr('ng-click', 'close()');\n        $compile(button)(scope);\n        element.prepend(button);\n      }\n\n      scope.init = function() {\n        if (scope.options.timeOut) {\n          timeout = createTimeout(scope.options.timeOut);\n        }\n        if (scope.options.onShown) {\n          scope.options.onShown();\n        }\n      };\n\n      element.on('mouseenter', function() {\n        hideAndStopProgressBar();\n        if (timeout) {\n          $interval.cancel(timeout);\n        }\n      });\n\n      scope.tapToast = function () {\n        if (scope.options.tapToDismiss) {\n          scope.close(true);\n        }\n      };\n\n      scope.close = function (wasClicked) {\n        toastr.remove(scope.toastId, wasClicked);\n      };\n\n      element.on('mouseleave', function() {\n        if (scope.options.timeOut === 0 && scope.options.extendedTimeOut === 0) { return; }\n        scope.$apply(function() {\n          scope.progressBar = scope.options.progressBar;\n        });\n        timeout = createTimeout(scope.options.extendedTimeOut);\n      });\n\n      function createTimeout(time) {\n        toastCtrl.startProgressBar(time);\n        return $interval(function() {\n          toastCtrl.stopProgressBar();\n          toastr.remove(scope.toastId);\n        }, time, 1);\n      }\n\n      function hideAndStopProgressBar() {\n        scope.progressBar = false;\n        toastCtrl.stopProgressBar();\n      }\n\n      function wantsCloseButton() {\n        return scope.options.closeHtml;\n      }\n    }\n  }\n}());\n"
  },
  {
    "path": "examples/client/vendor/angular-toastr.tpls.js",
    "content": "(function() {\n  'use strict';\n\n  angular.module('toastr', [])\n    .factory('toastr', toastr);\n\n  toastr.$inject = ['$animate', '$injector', '$document', '$rootScope', '$sce', 'toastrConfig', '$q'];\n\n  function toastr($animate, $injector, $document, $rootScope, $sce, toastrConfig, $q) {\n    var container;\n    var index = 0;\n    var toasts = [];\n\n    var previousToastMessage = '';\n    var openToasts = {};\n\n    var containerDefer = $q.defer();\n\n    var toast = {\n      clear: clear,\n      error: error,\n      info: info,\n      remove: remove,\n      success: success,\n      warning: warning\n    };\n\n    return toast;\n\n    /* Public API */\n    function clear(toast) {\n      if (toast) {\n        remove(toast.toastId);\n      } else {\n        for (var i = 0; i < toasts.length; i++) {\n          remove(toasts[i].toastId);\n        }\n      }\n    }\n\n    function error(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.error;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function info(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.info;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function success(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.success;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function warning(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.warning;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function remove(toastId, wasClicked) {\n      var toast = findToast(toastId);\n\n      if (toast && ! toast.deleting) { // Avoid clicking when fading out\n        toast.deleting = true;\n        toast.isOpened = false;\n        $animate.leave(toast.el).then(function() {\n          if (toast.scope.options.onHidden) {\n            toast.scope.options.onHidden(wasClicked);\n          }\n          toast.scope.$destroy();\n          var index = toasts.indexOf(toast);\n          delete openToasts[toast.scope.message];\n          toasts.splice(index, 1);\n          var maxOpened = toastrConfig.maxOpened;\n          if (maxOpened && toasts.length >= maxOpened) {\n            toasts[maxOpened - 1].open.resolve();\n          }\n          if (lastToast()) {\n            container.remove();\n            container = null;\n            containerDefer = $q.defer();\n          }\n        });\n      }\n\n      function findToast(toastId) {\n        for (var i = 0; i < toasts.length; i++) {\n          if (toasts[i].toastId === toastId) {\n            return toasts[i];\n          }\n        }\n      }\n\n      function lastToast() {\n        return !toasts.length;\n      }\n    }\n\n    /* Internal functions */\n    function _buildNotification(type, message, title, optionsOverride)\n    {\n      if (angular.isObject(title)) {\n        optionsOverride = title;\n        title = null;\n      }\n\n      return _notify({\n        iconClass: type,\n        message: message,\n        optionsOverride: optionsOverride,\n        title: title\n      });\n    }\n\n    function _getOptions() {\n      return angular.extend({}, toastrConfig);\n    }\n\n    function _createOrGetContainer(options) {\n      if(container) { return containerDefer.promise; }\n\n      container = angular.element('<div></div>');\n      container.attr('id', options.containerId);\n      container.addClass(options.positionClass);\n      container.css({'pointer-events': 'auto'});\n\n      var target = angular.element(document.querySelector(options.target));\n\n      if ( ! target || ! target.length) {\n        throw 'Target for toasts doesn\\'t exist';\n      }\n\n      $animate.enter(container, target).then(function() {\n        containerDefer.resolve();\n      });\n\n      return containerDefer.promise;\n    }\n\n    function _notify(map) {\n      var options = _getOptions();\n\n      if (shouldExit()) { return; }\n\n      var newToast = createToast();\n\n      toasts.push(newToast);\n\n      if (options.autoDismiss && options.maxOpened > 0) {\n        var oldToasts = toasts.slice(0, (toasts.length - options.maxOpened));\n        for (var i = 0, len = oldToasts.length; i < len; i++) {\n          remove(oldToasts[i].toastId);\n        }\n      }\n\n      if (maxOpenedNotReached()) {\n        newToast.open.resolve();\n      }\n\n      newToast.open.promise.then(function() {\n        _createOrGetContainer(options).then(function() {\n          newToast.isOpened = true;\n          if (options.newestOnTop) {\n            $animate.enter(newToast.el, container).then(function() {\n              newToast.scope.init();\n            });\n          } else {\n            var sibling = container[0].lastChild ? angular.element(container[0].lastChild) : null;\n            $animate.enter(newToast.el, container, sibling).then(function() {\n              newToast.scope.init();\n            });\n          }\n        });\n      });\n\n      return newToast;\n\n      function createScope(toast, map, options) {\n        if (options.allowHtml) {\n          toast.scope.allowHtml = true;\n          toast.scope.title = $sce.trustAsHtml(map.title);\n          toast.scope.message = $sce.trustAsHtml(map.message);\n        } else {\n          toast.scope.title = map.title;\n          toast.scope.message = map.message;\n        }\n\n        toast.scope.toastType = toast.iconClass;\n        toast.scope.toastId = toast.toastId;\n\n        toast.scope.options = {\n          extendedTimeOut: options.extendedTimeOut,\n          messageClass: options.messageClass,\n          onHidden: options.onHidden,\n          onShown: options.onShown,\n          progressBar: options.progressBar,\n          tapToDismiss: options.tapToDismiss,\n          timeOut: options.timeOut,\n          titleClass: options.titleClass,\n          toastClass: options.toastClass\n        };\n\n        if (options.closeButton) {\n          toast.scope.options.closeHtml = options.closeHtml;\n        }\n      }\n\n      function createToast() {\n        var newToast = {\n          toastId: index++,\n          isOpened: false,\n          scope: $rootScope.$new(),\n          open: $q.defer()\n        };\n        newToast.iconClass = map.iconClass;\n        if (map.optionsOverride) {\n          options = angular.extend(options, cleanOptionsOverride(map.optionsOverride));\n          newToast.iconClass = map.optionsOverride.iconClass || newToast.iconClass;\n        }\n\n        createScope(newToast, map, options);\n\n        newToast.el = createToastEl(newToast.scope);\n\n        return newToast;\n\n        function cleanOptionsOverride(options) {\n          var badOptions = ['containerId', 'iconClasses', 'maxOpened', 'newestOnTop',\n                            'positionClass', 'preventDuplicates', 'preventOpenDuplicates', 'templates'];\n          for (var i = 0, l = badOptions.length; i < l; i++) {\n            delete options[badOptions[i]];\n          }\n\n          return options;\n        }\n      }\n\n      function createToastEl(scope) {\n        var angularDomEl = angular.element('<div toast></div>'),\n          $compile = $injector.get('$compile');\n        return $compile(angularDomEl)(scope);\n      }\n\n      function maxOpenedNotReached() {\n        return options.maxOpened && toasts.length <= options.maxOpened || !options.maxOpened;\n      }\n\n      function shouldExit() {\n        var isDuplicateOfLast = options.preventDuplicates && map.message === previousToastMessage;\n        var isDuplicateOpen = options.preventOpenDuplicates && openToasts[map.message];\n\n        if (isDuplicateOfLast || isDuplicateOpen) {\n          return true;\n        }\n\n        previousToastMessage = map.message;\n        openToasts[map.message] = true;\n\n        return false;\n      }\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .constant('toastrConfig', {\n      allowHtml: false,\n      autoDismiss: false,\n      closeButton: false,\n      closeHtml: '<button>&times;</button>',\n      containerId: 'toast-container',\n      extendedTimeOut: 1000,\n      iconClasses: {\n        error: 'toast-error',\n        info: 'toast-info',\n        success: 'toast-success',\n        warning: 'toast-warning'\n      },\n      maxOpened: 0,\n      messageClass: 'toast-message',\n      newestOnTop: true,\n      onHidden: null,\n      onShown: null,\n      positionClass: 'toast-top-right',\n      preventDuplicates: false,\n      preventOpenDuplicates: false,\n      progressBar: false,\n      tapToDismiss: true,\n      target: 'body',\n      templates: {\n        toast: 'directives/toast/toast.html',\n        progressbar: 'directives/progressbar/progressbar.html'\n      },\n      timeOut: 5000,\n      titleClass: 'toast-title',\n      toastClass: 'toast'\n    });\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('progressBar', progressBar);\n\n  progressBar.$inject = ['toastrConfig'];\n\n  function progressBar(toastrConfig) {\n    return {\n      replace: true,\n      require: '^toast',\n      templateUrl: function() {\n        return toastrConfig.templates.progressbar;\n      },\n      link: linkFunction\n    };\n\n    function linkFunction(scope, element, attrs, toastCtrl) {\n      var intervalId, currentTimeOut, hideTime;\n\n      toastCtrl.progressBar = scope;\n\n      scope.start = function(duration) {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n\n        currentTimeOut = parseFloat(duration);\n        hideTime = new Date().getTime() + currentTimeOut;\n        intervalId = setInterval(updateProgress, 10);\n      };\n\n      scope.stop = function() {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n      };\n\n      function updateProgress() {\n        var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100;\n        element.css('width', percentage + '%');\n      }\n\n      scope.$on('$destroy', function() {\n        // Failsafe stop\n        clearInterval(intervalId);\n      });\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .controller('ToastController', ToastController);\n\n  function ToastController() {\n    this.progressBar = null;\n\n    this.startProgressBar = function(duration) {\n      if (this.progressBar) {\n        this.progressBar.start(duration);\n      }\n    };\n\n    this.stopProgressBar = function() {\n      if (this.progressBar) {\n        this.progressBar.stop();\n      }\n    };\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('toast', toast);\n\n  toast.$inject = ['$injector', '$interval', 'toastrConfig', 'toastr'];\n\n  function toast($injector, $interval, toastrConfig, toastr) {\n    return {\n      replace: true,\n      templateUrl: function() {\n        return toastrConfig.templates.toast;\n      },\n      controller: 'ToastController',\n      link: toastLinkFunction\n    };\n\n    function toastLinkFunction(scope, element, attrs, toastCtrl) {\n      var timeout;\n\n      scope.toastClass = scope.options.toastClass;\n      scope.titleClass = scope.options.titleClass;\n      scope.messageClass = scope.options.messageClass;\n      scope.progressBar = scope.options.progressBar;\n\n      if (wantsCloseButton()) {\n        var button = angular.element(scope.options.closeHtml),\n          $compile = $injector.get('$compile');\n        button.addClass('toast-close-button');\n        button.attr('ng-click', 'close()');\n        $compile(button)(scope);\n        element.prepend(button);\n      }\n\n      scope.init = function() {\n        if (scope.options.timeOut) {\n          timeout = createTimeout(scope.options.timeOut);\n        }\n        if (scope.options.onShown) {\n          scope.options.onShown();\n        }\n      };\n\n      element.on('mouseenter', function() {\n        hideAndStopProgressBar();\n        if (timeout) {\n          $interval.cancel(timeout);\n        }\n      });\n\n      scope.tapToast = function () {\n        if (scope.options.tapToDismiss) {\n          scope.close(true);\n        }\n      };\n\n      scope.close = function (wasClicked) {\n        toastr.remove(scope.toastId, wasClicked);\n      };\n\n      element.on('mouseleave', function() {\n        if (scope.options.timeOut === 0 && scope.options.extendedTimeOut === 0) { return; }\n        scope.$apply(function() {\n          scope.progressBar = scope.options.progressBar;\n        });\n        timeout = createTimeout(scope.options.extendedTimeOut);\n      });\n\n      function createTimeout(time) {\n        toastCtrl.startProgressBar(time);\n        return $interval(function() {\n          toastCtrl.stopProgressBar();\n          toastr.remove(scope.toastId);\n        }, time, 1);\n      }\n\n      function hideAndStopProgressBar() {\n        scope.progressBar = false;\n        toastCtrl.stopProgressBar();\n      }\n\n      function wantsCloseButton() {\n        return scope.options.closeHtml;\n      }\n    }\n  }\n}());\n\nangular.module(\"toastr\").run([\"$templateCache\", function($templateCache) {$templateCache.put(\"directives/progressbar/progressbar.html\",\"<div class=\\\"toast-progress\\\"></div>\\n\");\n$templateCache.put(\"directives/toast/toast.html\",\"<div class=\\\"{{toastClass}} {{toastType}}\\\" ng-click=\\\"tapToast()\\\">\\n  <div ng-switch on=\\\"allowHtml\\\">\\n    <div ng-switch-default ng-if=\\\"title\\\" class=\\\"{{titleClass}}\\\">{{title}}</div>\\n    <div ng-switch-default class=\\\"{{messageClass}}\\\">{{message}}</div>\\n    <div ng-switch-when=\\\"true\\\" ng-if=\\\"title\\\" class=\\\"{{titleClass}}\\\" ng-bind-html=\\\"title\\\"></div>\\n    <div ng-switch-when=\\\"true\\\" class=\\\"{{messageClass}}\\\" ng-bind-html=\\\"message\\\"></div>\\n  </div>\\n  <progress-bar ng-if=\\\"progressBar\\\"></progress-bar>\\n</div>\\n\");}]);"
  },
  {
    "path": "examples/client/vendor/angular-ui-router.js",
    "content": "/**\n * State-based routing for AngularJS\n * @version v0.2.15\n * @link http://angular-ui.github.com/\n * @license MIT License, http://www.opensource.org/licenses/MIT\n */\n\n/* commonjs package manager support (eg componentjs) */\nif (typeof module !== \"undefined\" && typeof exports !== \"undefined\" && module.exports === exports){\n  module.exports = 'ui.router';\n}\n\n(function (window, angular, undefined) {\n/*jshint globalstrict:true*/\n/*global angular:false*/\n'use strict';\n\nvar isDefined = angular.isDefined,\n    isFunction = angular.isFunction,\n    isString = angular.isString,\n    isObject = angular.isObject,\n    isArray = angular.isArray,\n    forEach = angular.forEach,\n    extend = angular.extend,\n    copy = angular.copy;\n\nfunction inherit(parent, extra) {\n  return extend(new (extend(function() {}, { prototype: parent }))(), extra);\n}\n\nfunction merge(dst) {\n  forEach(arguments, function(obj) {\n    if (obj !== dst) {\n      forEach(obj, function(value, key) {\n        if (!dst.hasOwnProperty(key)) dst[key] = value;\n      });\n    }\n  });\n  return dst;\n}\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nfunction ancestors(first, second) {\n  var path = [];\n\n  for (var n in first.path) {\n    if (first.path[n] !== second.path[n]) break;\n    path.push(first.path[n]);\n  }\n  return path;\n}\n\n/**\n * IE8-safe wrapper for `Object.keys()`.\n *\n * @param {Object} object A JavaScript object.\n * @return {Array} Returns the keys of the object as an array.\n */\nfunction objectKeys(object) {\n  if (Object.keys) {\n    return Object.keys(object);\n  }\n  var result = [];\n\n  forEach(object, function(val, key) {\n    result.push(key);\n  });\n  return result;\n}\n\n/**\n * IE8-safe wrapper for `Array.prototype.indexOf()`.\n *\n * @param {Array} array A JavaScript array.\n * @param {*} value A value to search the array for.\n * @return {Number} Returns the array index value of `value`, or `-1` if not present.\n */\nfunction indexOf(array, value) {\n  if (Array.prototype.indexOf) {\n    return array.indexOf(value, Number(arguments[2]) || 0);\n  }\n  var len = array.length >>> 0, from = Number(arguments[2]) || 0;\n  from = (from < 0) ? Math.ceil(from) : Math.floor(from);\n\n  if (from < 0) from += len;\n\n  for (; from < len; from++) {\n    if (from in array && array[from] === value) return from;\n  }\n  return -1;\n}\n\n/**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} currentParams The value of the current state parameters ($stateParams).\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\nfunction inheritParams(currentParams, newParams, $current, $to) {\n  var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];\n\n  for (var i in parents) {\n    if (!parents[i].params) continue;\n    parentParams = objectKeys(parents[i].params);\n    if (!parentParams.length) continue;\n\n    for (var j in parentParams) {\n      if (indexOf(inheritList, parentParams[j]) >= 0) continue;\n      inheritList.push(parentParams[j]);\n      inherited[parentParams[j]] = currentParams[parentParams[j]];\n    }\n  }\n  return extend({}, inherited, newParams);\n}\n\n/**\n * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.\n *\n * @param {Object} a The first object.\n * @param {Object} b The second object.\n * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,\n *                     it defaults to the list of keys in `a`.\n * @return {Boolean} Returns `true` if the keys match, otherwise `false`.\n */\nfunction equalForKeys(a, b, keys) {\n  if (!keys) {\n    keys = [];\n    for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility\n  }\n\n  for (var i=0; i<keys.length; i++) {\n    var k = keys[i];\n    if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized\n  }\n  return true;\n}\n\n/**\n * Returns the subset of an object, based on a list of keys.\n *\n * @param {Array} keys\n * @param {Object} values\n * @return {Boolean} Returns a subset of `values`.\n */\nfunction filterByKeys(keys, values) {\n  var filtered = {};\n\n  forEach(keys, function (name) {\n    filtered[name] = values[name];\n  });\n  return filtered;\n}\n\n// like _.indexBy\n// when you know that your index values will be unique, or you want last-one-in to win\nfunction indexBy(array, propName) {\n  var result = {};\n  forEach(array, function(item) {\n    result[item[propName]] = item;\n  });\n  return result;\n}\n\n// extracted from underscore.js\n// Return a copy of the object only containing the whitelisted properties.\nfunction pick(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  forEach(keys, function(key) {\n    if (key in obj) copy[key] = obj[key];\n  });\n  return copy;\n}\n\n// extracted from underscore.js\n// Return a copy of the object omitting the blacklisted properties.\nfunction omit(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  for (var key in obj) {\n    if (indexOf(keys, key) == -1) copy[key] = obj[key];\n  }\n  return copy;\n}\n\nfunction pluck(collection, key) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = isFunction(key) ? key(val) : val[key];\n  });\n  return result;\n}\n\nfunction filter(collection, callback) {\n  var array = isArray(collection);\n  var result = array ? [] : {};\n  forEach(collection, function(val, i) {\n    if (callback(val, i)) {\n      result[array ? result.length : i] = val;\n    }\n  });\n  return result;\n}\n\nfunction map(collection, callback) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = callback(val, i);\n  });\n  return result;\n}\n\n/**\n * @ngdoc overview\n * @name ui.router.util\n *\n * @description\n * # ui.router.util sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n *\n */\nangular.module('ui.router.util', ['ng']);\n\n/**\n * @ngdoc overview\n * @name ui.router.router\n * \n * @requires ui.router.util\n *\n * @description\n * # ui.router.router sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n */\nangular.module('ui.router.router', ['ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router.state\n * \n * @requires ui.router.router\n * @requires ui.router.util\n *\n * @description\n * # ui.router.state sub-module\n *\n * This module is a dependency of the main ui.router module. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n * \n */\nangular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router\n *\n * @requires ui.router.state\n *\n * @description\n * # ui.router\n * \n * ## The main module for ui.router \n * There are several sub-modules included with the ui.router module, however only this module is needed\n * as a dependency within your angular app. The other modules are for organization purposes. \n *\n * The modules are:\n * * ui.router - the main \"umbrella\" module\n * * ui.router.router - \n * \n * *You'll need to include **only** this module as the dependency within your angular app.*\n * \n * <pre>\n * <!doctype html>\n * <html ng-app=\"myApp\">\n * <head>\n *   <script src=\"js/angular.js\"></script>\n *   <!-- Include the ui-router script -->\n *   <script src=\"js/angular-ui-router.min.js\"></script>\n *   <script>\n *     // ...and add 'ui.router' as a dependency\n *     var myApp = angular.module('myApp', ['ui.router']);\n *   </script>\n * </head>\n * <body>\n * </body>\n * </html>\n * </pre>\n */\nangular.module('ui.router', ['ui.router.state']);\n\nangular.module('ui.router.compat', ['ui.router']);\n\n/**\n * @ngdoc object\n * @name ui.router.util.$resolve\n *\n * @requires $q\n * @requires $injector\n *\n * @description\n * Manages resolution of (acyclic) graphs of promises.\n */\n$Resolve.$inject = ['$q', '$injector'];\nfunction $Resolve(  $q,    $injector) {\n  \n  var VISIT_IN_PROGRESS = 1,\n      VISIT_DONE = 2,\n      NOTHING = {},\n      NO_DEPENDENCIES = [],\n      NO_LOCALS = NOTHING,\n      NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });\n  \n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#study\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Studies a set of invocables that are likely to be used multiple times.\n   * <pre>\n   * $resolve.study(invocables)(locals, parent, self)\n   * </pre>\n   * is equivalent to\n   * <pre>\n   * $resolve.resolve(invocables, locals, parent, self)\n   * </pre>\n   * but the former is more efficient (in fact `resolve` just calls `study` \n   * internally).\n   *\n   * @param {object} invocables Invocable objects\n   * @return {function} a function to pass in locals, parent and self\n   */\n  this.study = function (invocables) {\n    if (!isObject(invocables)) throw new Error(\"'invocables' must be an object\");\n    var invocableKeys = objectKeys(invocables || {});\n    \n    // Perform a topological sort of invocables to build an ordered plan\n    var plan = [], cycle = [], visited = {};\n    function visit(value, key) {\n      if (visited[key] === VISIT_DONE) return;\n      \n      cycle.push(key);\n      if (visited[key] === VISIT_IN_PROGRESS) {\n        cycle.splice(0, indexOf(cycle, key));\n        throw new Error(\"Cyclic dependency: \" + cycle.join(\" -> \"));\n      }\n      visited[key] = VISIT_IN_PROGRESS;\n      \n      if (isString(value)) {\n        plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);\n      } else {\n        var params = $injector.annotate(value);\n        forEach(params, function (param) {\n          if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);\n        });\n        plan.push(key, value, params);\n      }\n      \n      cycle.pop();\n      visited[key] = VISIT_DONE;\n    }\n    forEach(invocables, visit);\n    invocables = cycle = visited = null; // plan is all that's required\n    \n    function isResolve(value) {\n      return isObject(value) && value.then && value.$$promises;\n    }\n    \n    return function (locals, parent, self) {\n      if (isResolve(locals) && self === undefined) {\n        self = parent; parent = locals; locals = null;\n      }\n      if (!locals) locals = NO_LOCALS;\n      else if (!isObject(locals)) {\n        throw new Error(\"'locals' must be an object\");\n      }       \n      if (!parent) parent = NO_PARENT;\n      else if (!isResolve(parent)) {\n        throw new Error(\"'parent' must be a promise returned by $resolve.resolve()\");\n      }\n      \n      // To complete the overall resolution, we have to wait for the parent\n      // promise and for the promise for each invokable in our plan.\n      var resolution = $q.defer(),\n          result = resolution.promise,\n          promises = result.$$promises = {},\n          values = extend({}, locals),\n          wait = 1 + plan.length/3,\n          merged = false;\n          \n      function done() {\n        // Merge parent values we haven't got yet and publish our own $$values\n        if (!--wait) {\n          if (!merged) merge(values, parent.$$values); \n          result.$$values = values;\n          result.$$promises = result.$$promises || true; // keep for isResolve()\n          delete result.$$inheritedValues;\n          resolution.resolve(values);\n        }\n      }\n      \n      function fail(reason) {\n        result.$$failure = reason;\n        resolution.reject(reason);\n      }\n\n      // Short-circuit if parent has already failed\n      if (isDefined(parent.$$failure)) {\n        fail(parent.$$failure);\n        return result;\n      }\n      \n      if (parent.$$inheritedValues) {\n        merge(values, omit(parent.$$inheritedValues, invocableKeys));\n      }\n\n      // Merge parent values if the parent has already resolved, or merge\n      // parent promises and wait if the parent resolve is still in progress.\n      extend(promises, parent.$$promises);\n      if (parent.$$values) {\n        merged = merge(values, omit(parent.$$values, invocableKeys));\n        result.$$inheritedValues = omit(parent.$$values, invocableKeys);\n        done();\n      } else {\n        if (parent.$$inheritedValues) {\n          result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);\n        }        \n        parent.then(done, fail);\n      }\n      \n      // Process each invocable in the plan, but ignore any where a local of the same name exists.\n      for (var i=0, ii=plan.length; i<ii; i+=3) {\n        if (locals.hasOwnProperty(plan[i])) done();\n        else invoke(plan[i], plan[i+1], plan[i+2]);\n      }\n      \n      function invoke(key, invocable, params) {\n        // Create a deferred for this invocation. Failures will propagate to the resolution as well.\n        var invocation = $q.defer(), waitParams = 0;\n        function onfailure(reason) {\n          invocation.reject(reason);\n          fail(reason);\n        }\n        // Wait for any parameter that we have a promise for (either from parent or from this\n        // resolve; in that case study() will have made sure it's ordered before us in the plan).\n        forEach(params, function (dep) {\n          if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {\n            waitParams++;\n            promises[dep].then(function (result) {\n              values[dep] = result;\n              if (!(--waitParams)) proceed();\n            }, onfailure);\n          }\n        });\n        if (!waitParams) proceed();\n        function proceed() {\n          if (isDefined(result.$$failure)) return;\n          try {\n            invocation.resolve($injector.invoke(invocable, self, values));\n            invocation.promise.then(function (result) {\n              values[key] = result;\n              done();\n            }, onfailure);\n          } catch (e) {\n            onfailure(e);\n          }\n        }\n        // Publish promise synchronously; invocations further down in the plan may depend on it.\n        promises[key] = invocation.promise;\n      }\n      \n      return result;\n    };\n  };\n  \n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#resolve\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Resolves a set of invocables. An invocable is a function to be invoked via \n   * `$injector.invoke()`, and can have an arbitrary number of dependencies. \n   * An invocable can either return a value directly,\n   * or a `$q` promise. If a promise is returned it will be resolved and the \n   * resulting value will be used instead. Dependencies of invocables are resolved \n   * (in this order of precedence)\n   *\n   * - from the specified `locals`\n   * - from another invocable that is part of this `$resolve` call\n   * - from an invocable that is inherited from a `parent` call to `$resolve` \n   *   (or recursively\n   * - from any ancestor `$resolve` of that parent).\n   *\n   * The return value of `$resolve` is a promise for an object that contains \n   * (in this order of precedence)\n   *\n   * - any `locals` (if specified)\n   * - the resolved return values of all injectables\n   * - any values inherited from a `parent` call to `$resolve` (if specified)\n   *\n   * The promise will resolve after the `parent` promise (if any) and all promises \n   * returned by injectables have been resolved. If any invocable \n   * (or `$injector.invoke`) throws an exception, or if a promise returned by an \n   * invocable is rejected, the `$resolve` promise is immediately rejected with the \n   * same error. A rejection of a `parent` promise (if specified) will likewise be \n   * propagated immediately. Once the `$resolve` promise has been rejected, no \n   * further invocables will be called.\n   * \n   * Cyclic dependencies between invocables are not permitted and will caues `$resolve`\n   * to throw an error. As a special case, an injectable can depend on a parameter \n   * with the same name as the injectable, which will be fulfilled from the `parent` \n   * injectable of the same name. This allows inherited values to be decorated. \n   * Note that in this case any other injectable in the same `$resolve` with the same\n   * dependency would see the decorated value, not the inherited value.\n   *\n   * Note that missing dependencies -- unlike cyclic dependencies -- will cause an \n   * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous) \n   * exception.\n   *\n   * Invocables are invoked eagerly as soon as all dependencies are available. \n   * This is true even for dependencies inherited from a `parent` call to `$resolve`.\n   *\n   * As a special case, an invocable can be a string, in which case it is taken to \n   * be a service name to be passed to `$injector.get()`. This is supported primarily \n   * for backwards-compatibility with the `resolve` property of `$routeProvider` \n   * routes.\n   *\n   * @param {object} invocables functions to invoke or \n   * `$injector` services to fetch.\n   * @param {object} locals  values to make available to the injectables\n   * @param {object} parent  a promise returned by another call to `$resolve`.\n   * @param {object} self  the `this` for the invoked methods\n   * @return {object} Promise for an object that contains the resolved return value\n   * of all invocables, as well as any inherited and local values.\n   */\n  this.resolve = function (invocables, locals, parent, self) {\n    return this.study(invocables)(locals, parent, self);\n  };\n}\n\nangular.module('ui.router.util').service('$resolve', $Resolve);\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$templateFactory\n *\n * @requires $http\n * @requires $templateCache\n * @requires $injector\n *\n * @description\n * Service. Manages loading of templates.\n */\n$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];\nfunction $TemplateFactory(  $http,   $templateCache,   $injector) {\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromConfig\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a configuration object. \n   *\n   * @param {object} config Configuration object for which to load a template. \n   * The following properties are search in the specified order, and the first one \n   * that is defined is used to create the template:\n   *\n   * @param {string|object} config.template html string template or function to \n   * load via {@link ui.router.util.$templateFactory#fromString fromString}.\n   * @param {string|object} config.templateUrl url to load or a function returning \n   * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.\n   * @param {Function} config.templateProvider function to invoke via \n   * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.\n   * @param {object} params  Parameters to pass to the template function.\n   * @param {object} locals Locals to pass to `invoke` if the template is loaded \n   * via a `templateProvider`. Defaults to `{ params: params }`.\n   *\n   * @return {string|object}  The template html as a string, or a promise for \n   * that string,or `null` if no template is configured.\n   */\n  this.fromConfig = function (config, params, locals) {\n    return (\n      isDefined(config.template) ? this.fromString(config.template, params) :\n      isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :\n      isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :\n      null\n    );\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromString\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a string or a function returning a string.\n   *\n   * @param {string|object} template html template as a string or function that \n   * returns an html template as a string.\n   * @param {object} params Parameters to pass to the template function.\n   *\n   * @return {string|object} The template html as a string, or a promise for that \n   * string.\n   */\n  this.fromString = function (template, params) {\n    return isFunction(template) ? template(params) : template;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromUrl\n   * @methodOf ui.router.util.$templateFactory\n   * \n   * @description\n   * Loads a template from the a URL via `$http` and `$templateCache`.\n   *\n   * @param {string|Function} url url of the template to load, or a function \n   * that returns a url.\n   * @param {Object} params Parameters to pass to the url function.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromUrl = function (url, params) {\n    if (isFunction(url)) url = url(params);\n    if (url == null) return null;\n    else return $http\n        .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})\n        .then(function(response) { return response.data; });\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromProvider\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template by invoking an injectable provider function.\n   *\n   * @param {Function} provider Function to invoke via `$injector.invoke`\n   * @param {Object} params Parameters for the template.\n   * @param {Object} locals Locals to pass to `invoke`. Defaults to \n   * `{ params: params }`.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromProvider = function (provider, params, locals) {\n    return $injector.invoke(provider, null, locals || { params: params });\n  };\n}\n\nangular.module('ui.router.util').service('$templateFactory', $TemplateFactory);\n\nvar $$UMFP; // reference to $UrlMatcherFactoryProvider\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:UrlMatcher\n *\n * @description\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list\n * of search parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.\n *\n * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace\n * syntax, which optionally allows a regular expression for the parameter to be specified:\n *\n * * `':'` name - colon placeholder\n * * `'*'` name - catch-all placeholder\n * * `'{' name '}'` - curly placeholder\n * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the\n *   regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters). For colon\n * placeholders or curly placeholders without an explicit regexp, a path parameter matches any\n * number of characters other than '/'. For catch-all placeholders the path parameter matches\n * any number of characters.\n *\n * Examples:\n *\n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n *   trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n *   '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n *   parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n *   path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n *   in the built-in  `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n * @param {string} pattern  The pattern to compile into a matcher.\n * @param {Object} config  A configuration object hash:\n * @param {Object=} parentMatcher Used to concatenate the pattern/config onto\n *   an existing UrlMatcher\n *\n * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n *\n * @property {string} prefix  A static prefix of this pattern. The matcher guarantees that any\n *   URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns\n *   non-null) will start with this prefix.\n *\n * @property {string} source  The pattern that was passed into the constructor\n *\n * @property {string} sourcePath  The path portion of the source property\n *\n * @property {string} sourceSearch  The search portion of the source property\n *\n * @property {string} regex  The constructed regex that will be used to match against the url when\n *   it is time to determine which url will match.\n *\n * @returns {Object}  New `UrlMatcher` object\n */\nfunction UrlMatcher(pattern, config, parentMatcher) {\n  config = extend({ params: {} }, isObject(config) ? config : {});\n\n  // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n  //   '*' name\n  //   ':' name\n  //   '{' name '}'\n  //   '{' name ':' regexp '}'\n  // The regular expression is somewhat complicated due to the need to allow curly braces\n  // inside the regular expression. The placeholder regexp breaks down as follows:\n  //    ([:*])([\\w\\[\\]]+)              - classic placeholder ($1 / $2) (search version has - for snake-case)\n  //    \\{([\\w\\[\\]]+)(?:\\:( ... ))?\\}  - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n  //    (?: ... | ... | ... )+         - the regexp consists of any number of atoms, an atom being either\n  //    [^{}\\\\]+                       - anything other than curly braces or backslash\n  //    \\\\.                            - a backslash escape\n  //    \\{(?:[^{}\\\\]+|\\\\.)*\\}          - a matched set of curly braces containing other atoms\n  var placeholder       = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      searchPlaceholder = /([:]?)([\\w\\[\\]-]+)|\\{([\\w\\[\\]-]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      compiled = '^', last = 0, m,\n      segments = this.segments = [],\n      parentParams = parentMatcher ? parentMatcher.params : {},\n      params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),\n      paramNames = [];\n\n  function addParameter(id, type, config, location) {\n    paramNames.push(id);\n    if (parentParams[id]) return parentParams[id];\n    if (!/^\\w+(-+\\w+)*(?:\\[\\])?$/.test(id)) throw new Error(\"Invalid parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    if (params[id]) throw new Error(\"Duplicate parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    params[id] = new $$UMFP.Param(id, type, config, location);\n    return params[id];\n  }\n\n  function quoteRegExp(string, pattern, squash, optional) {\n    var surroundPattern = ['',''], result = string.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, \"\\\\$&\");\n    if (!pattern) return result;\n    switch(squash) {\n      case false: surroundPattern = ['(', ')' + (optional ? \"?\" : \"\")]; break;\n      case true:  surroundPattern = ['?(', ')?']; break;\n      default:    surroundPattern = ['(' + squash + \"|\", ')?']; break;\n    }\n    return result + surroundPattern[0] + pattern + surroundPattern[1];\n  }\n\n  this.source = pattern;\n\n  // Split into static segments separated by path parameter placeholders.\n  // The number of segments is always 1 more than the number of parameters.\n  function matchDetails(m, isSearch) {\n    var id, regexp, segment, type, cfg, arrayMode;\n    id          = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null\n    cfg         = config.params[id];\n    segment     = pattern.substring(last, m.index);\n    regexp      = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);\n    type        = $$UMFP.type(regexp || \"string\") || inherit($$UMFP.type(\"string\"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });\n    return {\n      id: id, regexp: regexp, segment: segment, type: type, cfg: cfg\n    };\n  }\n\n  var p, param, segment;\n  while ((m = placeholder.exec(pattern))) {\n    p = matchDetails(m, false);\n    if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n    param = addParameter(p.id, p.type, p.cfg, \"path\");\n    compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);\n    segments.push(p.segment);\n    last = placeholder.lastIndex;\n  }\n  segment = pattern.substring(last);\n\n  // Find any search parameter names and remove them from the last segment\n  var i = segment.indexOf('?');\n\n  if (i >= 0) {\n    var search = this.sourceSearch = segment.substring(i);\n    segment = segment.substring(0, i);\n    this.sourcePath = pattern.substring(0, last + i);\n\n    if (search.length > 0) {\n      last = 0;\n      while ((m = searchPlaceholder.exec(search))) {\n        p = matchDetails(m, true);\n        param = addParameter(p.id, p.type, p.cfg, \"search\");\n        last = placeholder.lastIndex;\n        // check if ?&\n      }\n    }\n  } else {\n    this.sourcePath = pattern;\n    this.sourceSearch = '';\n  }\n\n  compiled += quoteRegExp(segment) + (config.strict === false ? '\\/?' : '') + '$';\n  segments.push(segment);\n\n  this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);\n  this.prefix = segments[0];\n  this.$$paramNames = paramNames;\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#concat\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns a new matcher for a pattern constructed by appending the path part and adding the\n * search parameters of the specified pattern to this pattern. The current pattern is not\n * modified. This can be understood as creating a pattern for URLs that are relative to (or\n * suffixes of) the current pattern.\n *\n * @example\n * The following two matchers are equivalent:\n * <pre>\n * new UrlMatcher('/user/{id}?q').concat('/details?date');\n * new UrlMatcher('/user/{id}/details?q&date');\n * </pre>\n *\n * @param {string} pattern  The pattern to append.\n * @param {Object} config  An object hash of the configuration for the matcher.\n * @returns {UrlMatcher}  A matcher for the concatenated pattern.\n */\nUrlMatcher.prototype.concat = function (pattern, config) {\n  // Because order of search parameters is irrelevant, we can add our own search\n  // parameters to the end of the new pattern. Parse the new pattern by itself\n  // and then join the bits together, but it's much easier to do this on a string level.\n  var defaultConfig = {\n    caseInsensitive: $$UMFP.caseInsensitive(),\n    strict: $$UMFP.strictMode(),\n    squash: $$UMFP.defaultSquashPolicy()\n  };\n  return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);\n};\n\nUrlMatcher.prototype.toString = function () {\n  return this.source;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#exec\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Tests the specified path against this matcher, and returns an object containing the captured\n * parameter values, or null if the path does not match. The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `searchParams`. This means that search parameters are always treated\n * as optional.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n *   x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * </pre>\n *\n * @param {string} path  The URL path to match, e.g. `$location.path()`.\n * @param {Object} searchParams  URL search parameters, e.g. `$location.search()`.\n * @returns {Object}  The captured parameter values.\n */\nUrlMatcher.prototype.exec = function (path, searchParams) {\n  var m = this.regexp.exec(path);\n  if (!m) return null;\n  searchParams = searchParams || {};\n\n  var paramNames = this.parameters(), nTotal = paramNames.length,\n    nPath = this.segments.length - 1,\n    values = {}, i, j, cfg, paramName;\n\n  if (nPath !== m.length - 1) throw new Error(\"Unbalanced capture group in route '\" + this.source + \"'\");\n\n  function decodePathArray(string) {\n    function reverseString(str) { return str.split(\"\").reverse().join(\"\"); }\n    function unquoteDashes(str) { return str.replace(/\\\\-/g, \"-\"); }\n\n    var split = reverseString(string).split(/-(?!\\\\)/);\n    var allReversed = map(split, reverseString);\n    return map(allReversed, unquoteDashes).reverse();\n  }\n\n  for (i = 0; i < nPath; i++) {\n    paramName = paramNames[i];\n    var param = this.params[paramName];\n    var paramVal = m[i+1];\n    // if the param value matches a pre-replace pair, replace the value before decoding.\n    for (j = 0; j < param.replace; j++) {\n      if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;\n    }\n    if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);\n    values[paramName] = param.value(paramVal);\n  }\n  for (/**/; i < nTotal; i++) {\n    paramName = paramNames[i];\n    values[paramName] = this.params[paramName].value(searchParams[paramName]);\n  }\n\n  return values;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#parameters\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns the names of all path and search parameters of this pattern in an unspecified order.\n *\n * @returns {Array.<string>}  An array of parameter names. Must be treated as read-only. If the\n *    pattern has no parameters, an empty array is returned.\n */\nUrlMatcher.prototype.parameters = function (param) {\n  if (!isDefined(param)) return this.$$paramNames;\n  return this.params[param] || null;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#validate\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param {Object} params The object hash of parameters to validate.\n * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.\n */\nUrlMatcher.prototype.validates = function (params) {\n  return this.params.$$validates(params);\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#format\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters. Null values for path parameters are\n * treated as empty strings.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * </pre>\n *\n * @param {Object} values  the values to substitute for the parameters in this pattern.\n * @returns {string}  the formatted URL (path and optionally search part).\n */\nUrlMatcher.prototype.format = function (values) {\n  values = values || {};\n  var segments = this.segments, params = this.parameters(), paramset = this.params;\n  if (!this.validates(values)) return null;\n\n  var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];\n\n  function encodeDashes(str) { // Replace dashes with encoded \"\\-\"\n    return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });\n  }\n\n  for (i = 0; i < nTotal; i++) {\n    var isPathParam = i < nPath;\n    var name = params[i], param = paramset[name], value = param.value(values[name]);\n    var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);\n    var squash = isDefaultValue ? param.squash : false;\n    var encoded = param.type.encode(value);\n\n    if (isPathParam) {\n      var nextSegment = segments[i + 1];\n      if (squash === false) {\n        if (encoded != null) {\n          if (isArray(encoded)) {\n            result += map(encoded, encodeDashes).join(\"-\");\n          } else {\n            result += encodeURIComponent(encoded);\n          }\n        }\n        result += nextSegment;\n      } else if (squash === true) {\n        var capture = result.match(/\\/$/) ? /\\/?(.*)/ : /(.*)/;\n        result += nextSegment.match(capture)[1];\n      } else if (isString(squash)) {\n        result += squash + nextSegment;\n      }\n    } else {\n      if (encoded == null || (isDefaultValue && squash !== false)) continue;\n      if (!isArray(encoded)) encoded = [ encoded ];\n      encoded = map(encoded, encodeURIComponent).join('&' + name + '=');\n      result += (search ? '&' : '?') + (name + '=' + encoded);\n      search = true;\n    }\n  }\n\n  return result;\n};\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:Type\n *\n * @description\n * Implements an interface to define custom parameter types that can be decoded from and encoded to\n * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}\n * objects when matching or formatting URLs, or comparing or validating parameter values.\n *\n * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more\n * information on registering custom types.\n *\n * @param {Object} config  A configuration object which contains the custom type definition.  The object's\n *        properties will override the default methods and/or pattern in `Type`'s public interface.\n * @example\n * <pre>\n * {\n *   decode: function(val) { return parseInt(val, 10); },\n *   encode: function(val) { return val && val.toString(); },\n *   equals: function(a, b) { return this.is(a) && a === b; },\n *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },\n *   pattern: /\\d+/\n * }\n * </pre>\n *\n * @property {RegExp} pattern The regular expression pattern used to match values of this type when\n *           coming from a substring of a URL.\n *\n * @returns {Object}  Returns a new `Type` object.\n */\nfunction Type(config) {\n  extend(this, config);\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#is\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Detects whether a value is of a particular type. Accepts a native (decoded) value\n * and determines whether it matches the current `Type` object.\n *\n * @param {*} val  The value to check.\n * @param {string} key  Optional. If the type check is happening in the context of a specific\n *        {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the\n *        parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.\n * @returns {Boolean}  Returns `true` if the value matches the type, otherwise `false`.\n */\nType.prototype.is = function(val, key) {\n  return true;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#encode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the\n * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it\n * only needs to be a representation of `val` that has been coerced to a string.\n *\n * @param {*} val  The value to encode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {string}  Returns a string representation of `val` that can be encoded in a URL.\n */\nType.prototype.encode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#decode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Converts a parameter value (from URL string or transition param) to a custom/native value.\n *\n * @param {string} val  The URL parameter value to decode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {*}  Returns a custom representation of the URL parameter value.\n */\nType.prototype.decode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#equals\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Determines whether two decoded values are equivalent.\n *\n * @param {*} a  A value to compare against.\n * @param {*} b  A value to compare against.\n * @returns {Boolean}  Returns `true` if the values are equivalent/equal, otherwise `false`.\n */\nType.prototype.equals = function(a, b) {\n  return a == b;\n};\n\nType.prototype.$subPattern = function() {\n  var sub = this.pattern.toString();\n  return sub.substr(1, sub.length - 2);\n};\n\nType.prototype.pattern = /.*/;\n\nType.prototype.toString = function() { return \"{Type:\" + this.name + \"}\"; };\n\n/** Given an encoded string, or a decoded object, returns a decoded object */\nType.prototype.$normalize = function(val) {\n  return this.is(val) ? val : this.decode(val);\n};\n\n/*\n * Wraps an existing custom Type as an array of Type, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\nType.prototype.$asArray = function(mode, isSearch) {\n  if (!mode) return this;\n  if (mode === \"auto\" && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n\n  function ArrayType(type, mode) {\n    function bindTo(type, callbackName) {\n      return function() {\n        return type[callbackName].apply(type, arguments);\n      };\n    }\n\n    // Wrap non-array value as array\n    function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }\n    // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n    function arrayUnwrap(val) {\n      switch(val.length) {\n        case 0: return undefined;\n        case 1: return mode === \"auto\" ? val[0] : val;\n        default: return val;\n      }\n    }\n    function falsey(val) { return !val; }\n\n    // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n    function arrayHandler(callback, allTruthyMode) {\n      return function handleArray(val) {\n        val = arrayWrap(val);\n        var result = map(val, callback);\n        if (allTruthyMode === true)\n          return filter(result, falsey).length === 0;\n        return arrayUnwrap(result);\n      };\n    }\n\n    // Wraps type (.equals) functions to operate on each value of an array\n    function arrayEqualsHandler(callback) {\n      return function handleArray(val1, val2) {\n        var left = arrayWrap(val1), right = arrayWrap(val2);\n        if (left.length !== right.length) return false;\n        for (var i = 0; i < left.length; i++) {\n          if (!callback(left[i], right[i])) return false;\n        }\n        return true;\n      };\n    }\n\n    this.encode = arrayHandler(bindTo(type, 'encode'));\n    this.decode = arrayHandler(bindTo(type, 'decode'));\n    this.is     = arrayHandler(bindTo(type, 'is'), true);\n    this.equals = arrayEqualsHandler(bindTo(type, 'equals'));\n    this.pattern = type.pattern;\n    this.$normalize = arrayHandler(bindTo(type, '$normalize'));\n    this.name = type.name;\n    this.$arrayMode = mode;\n  }\n\n  return new ArrayType(this, mode);\n};\n\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$urlMatcherFactory\n *\n * @description\n * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory\n * is also available to providers under the name `$urlMatcherFactoryProvider`.\n */\nfunction $UrlMatcherFactory() {\n  $$UMFP = this;\n\n  var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;\n\n  function valToString(val) { return val != null ? val.toString().replace(/\\//g, \"%2F\") : val; }\n  function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, \"/\") : val; }\n\n  var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {\n    string: {\n      encode: valToString,\n      decode: valFromString,\n      // TODO: in 1.0, make string .is() return false if value is undefined/null by default.\n      // In 0.2.x, string params are optional by default for backwards compat\n      is: function(val) { return val == null || !isDefined(val) || typeof val === \"string\"; },\n      pattern: /[^/]*/\n    },\n    int: {\n      encode: valToString,\n      decode: function(val) { return parseInt(val, 10); },\n      is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },\n      pattern: /\\d+/\n    },\n    bool: {\n      encode: function(val) { return val ? 1 : 0; },\n      decode: function(val) { return parseInt(val, 10) !== 0; },\n      is: function(val) { return val === true || val === false; },\n      pattern: /0|1/\n    },\n    date: {\n      encode: function (val) {\n        if (!this.is(val))\n          return undefined;\n        return [ val.getFullYear(),\n          ('0' + (val.getMonth() + 1)).slice(-2),\n          ('0' + val.getDate()).slice(-2)\n        ].join(\"-\");\n      },\n      decode: function (val) {\n        if (this.is(val)) return val;\n        var match = this.capture.exec(val);\n        return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n      },\n      is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },\n      equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },\n      pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n      capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/\n    },\n    json: {\n      encode: angular.toJson,\n      decode: angular.fromJson,\n      is: angular.isObject,\n      equals: angular.equals,\n      pattern: /[^/]*/\n    },\n    any: { // does not encode/decode\n      encode: angular.identity,\n      decode: angular.identity,\n      equals: angular.equals,\n      pattern: /.*/\n    }\n  };\n\n  function getDefaultConfig() {\n    return {\n      strict: isStrictMode,\n      caseInsensitive: isCaseInsensitive\n    };\n  }\n\n  function isInjectable(value) {\n    return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));\n  }\n\n  /**\n   * [Internal] Get the default value of a parameter, which may be an injectable function.\n   */\n  $UrlMatcherFactory.$$getDefaultValue = function(config) {\n    if (!isInjectable(config.value)) return config.value;\n    if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n    return injector.invoke(config.value);\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#caseInsensitive\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URL matching should be case sensitive (the default behavior), or not.\n   *\n   * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;\n   * @returns {boolean} the current value of caseInsensitive\n   */\n  this.caseInsensitive = function(value) {\n    if (isDefined(value))\n      isCaseInsensitive = value;\n    return isCaseInsensitive;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#strictMode\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URLs should match trailing slashes, or not (the default behavior).\n   *\n   * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.\n   * @returns {boolean} the current value of strictMode\n   */\n  this.strictMode = function(value) {\n    if (isDefined(value))\n      isStrictMode = value;\n    return isStrictMode;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Sets the default behavior when generating or matching URLs with default parameter values.\n   *\n   * @param {string} value A string that defines the default parameter URL squashing behavior.\n   *    `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL\n   *    `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the\n   *             parameter is surrounded by slashes, squash (remove) one slash from the URL\n   *    any other string, e.g. \"~\": When generating an href with a default parameter value, squash (remove)\n   *             the parameter value from the URL and replace it with this string.\n   */\n  this.defaultSquashPolicy = function(value) {\n    if (!isDefined(value)) return defaultSquashPolicy;\n    if (value !== true && value !== false && !isString(value))\n      throw new Error(\"Invalid squash policy: \" + value + \". Valid policies: false, true, arbitrary-string\");\n    defaultSquashPolicy = value;\n    return value;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#compile\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.\n   *\n   * @param {string} pattern  The URL pattern.\n   * @param {Object} config  The config object hash.\n   * @returns {UrlMatcher}  The UrlMatcher.\n   */\n  this.compile = function (pattern, config) {\n    return new UrlMatcher(pattern, extend(getDefaultConfig(), config));\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#isMatcher\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Returns true if the specified object is a `UrlMatcher`, or false otherwise.\n   *\n   * @param {Object} object  The object to perform the type check against.\n   * @returns {Boolean}  Returns `true` if the object matches the `UrlMatcher` interface, by\n   *          implementing all the same methods.\n   */\n  this.isMatcher = function (o) {\n    if (!isObject(o)) return false;\n    var result = true;\n\n    forEach(UrlMatcher.prototype, function(val, name) {\n      if (isFunction(val)) {\n        result = result && (isDefined(o[name]) && isFunction(o[name]));\n      }\n    });\n    return result;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#type\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to\n   * generate URLs with typed parameters.\n   *\n   * @param {string} name  The type name.\n   * @param {Object|Function} definition   The type definition. See\n   *        {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   * @param {Object|Function} definitionFn (optional) A function that is injected before the app\n   *        runtime starts.  The result of this function is merged into the existing `definition`.\n   *        See {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   *\n   * @returns {Object}  Returns `$urlMatcherFactoryProvider`.\n   *\n   * @example\n   * This is a simple example of a custom type that encodes and decodes items from an\n   * array, using the array index as the URL-encoded value:\n   *\n   * <pre>\n   * var list = ['John', 'Paul', 'George', 'Ringo'];\n   *\n   * $urlMatcherFactoryProvider.type('listItem', {\n   *   encode: function(item) {\n   *     // Represent the list item in the URL using its corresponding index\n   *     return list.indexOf(item);\n   *   },\n   *   decode: function(item) {\n   *     // Look up the list item by index\n   *     return list[parseInt(item, 10)];\n   *   },\n   *   is: function(item) {\n   *     // Ensure the item is valid by checking to see that it appears\n   *     // in the list\n   *     return list.indexOf(item) > -1;\n   *   }\n   * });\n   *\n   * $stateProvider.state('list', {\n   *   url: \"/list/{item:listItem}\",\n   *   controller: function($scope, $stateParams) {\n   *     console.log($stateParams.item);\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * // Changes URL to '/list/3', logs \"Ringo\" to the console\n   * $state.go('list', { item: \"Ringo\" });\n   * </pre>\n   *\n   * This is a more complex example of a type that relies on dependency injection to\n   * interact with services, and uses the parameter name from the URL to infer how to\n   * handle encoding and decoding parameter values:\n   *\n   * <pre>\n   * // Defines a custom type that gets a value from a service,\n   * // where each service gets different types of values from\n   * // a backend API:\n   * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {\n   *\n   *   // Matches up services to URL parameter names\n   *   var services = {\n   *     user: Users,\n   *     post: Posts\n   *   };\n   *\n   *   return {\n   *     encode: function(object) {\n   *       // Represent the object in the URL using its unique ID\n   *       return object.id;\n   *     },\n   *     decode: function(value, key) {\n   *       // Look up the object by ID, using the parameter\n   *       // name (key) to call the correct service\n   *       return services[key].findById(value);\n   *     },\n   *     is: function(object, key) {\n   *       // Check that object is a valid dbObject\n   *       return angular.isObject(object) && object.id && services[key];\n   *     }\n   *     equals: function(a, b) {\n   *       // Check the equality of decoded objects by comparing\n   *       // their unique IDs\n   *       return a.id === b.id;\n   *     }\n   *   };\n   * });\n   *\n   * // In a config() block, you can then attach URLs with\n   * // type-annotated parameters:\n   * $stateProvider.state('users', {\n   *   url: \"/users\",\n   *   // ...\n   * }).state('users.item', {\n   *   url: \"/{user:dbObject}\",\n   *   controller: function($scope, $stateParams) {\n   *     // $stateParams.user will now be an object returned from\n   *     // the Users service\n   *   },\n   *   // ...\n   * });\n   * </pre>\n   */\n  this.type = function (name, definition, definitionFn) {\n    if (!isDefined(definition)) return $types[name];\n    if ($types.hasOwnProperty(name)) throw new Error(\"A type named '\" + name + \"' has already been defined.\");\n\n    $types[name] = new Type(extend({ name: name }, definition));\n    if (definitionFn) {\n      typeQueue.push({ name: name, def: definitionFn });\n      if (!enqueue) flushTypeQueue();\n    }\n    return this;\n  };\n\n  // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s\n  function flushTypeQueue() {\n    while(typeQueue.length) {\n      var type = typeQueue.shift();\n      if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n      angular.extend($types[type.name], injector.invoke(type.def));\n    }\n  }\n\n  // Register default types. Store them in the prototype of $types.\n  forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });\n  $types = inherit($types, {});\n\n  /* No need to document $get, since it returns this */\n  this.$get = ['$injector', function ($injector) {\n    injector = $injector;\n    enqueue = false;\n    flushTypeQueue();\n\n    forEach(defaultTypes, function(type, name) {\n      if (!$types[name]) $types[name] = new Type(type);\n    });\n    return this;\n  }];\n\n  this.Param = function Param(id, type, config, location) {\n    var self = this;\n    config = unwrapShorthand(config);\n    type = getType(config, type, location);\n    var arrayMode = getArrayMode();\n    type = arrayMode ? type.$asArray(arrayMode, location === \"search\") : type;\n    if (type.name === \"string\" && !arrayMode && location === \"path\" && config.value === undefined)\n      config.value = \"\"; // for 0.2.x; in 0.3.0+ do not automatically default to \"\"\n    var isOptional = config.value !== undefined;\n    var squash = getSquashPolicy(config, isOptional);\n    var replace = getReplace(config, arrayMode, isOptional, squash);\n\n    function unwrapShorthand(config) {\n      var keys = isObject(config) ? objectKeys(config) : [];\n      var isShorthand = indexOf(keys, \"value\") === -1 && indexOf(keys, \"type\") === -1 &&\n                        indexOf(keys, \"squash\") === -1 && indexOf(keys, \"array\") === -1;\n      if (isShorthand) config = { value: config };\n      config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };\n      return config;\n    }\n\n    function getType(config, urlType, location) {\n      if (config.type && urlType) throw new Error(\"Param '\"+id+\"' has two type configurations.\");\n      if (urlType) return urlType;\n      if (!config.type) return (location === \"config\" ? $types.any : $types.string);\n      return config.type instanceof Type ? config.type : new Type(config.type);\n    }\n\n    // array config: param name (param[]) overrides default settings.  explicit config overrides param name.\n    function getArrayMode() {\n      var arrayDefaults = { array: (location === \"search\" ? \"auto\" : false) };\n      var arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n      return extend(arrayDefaults, arrayParamNomenclature, config).array;\n    }\n\n    /**\n     * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n     */\n    function getSquashPolicy(config, isOptional) {\n      var squash = config.squash;\n      if (!isOptional || squash === false) return false;\n      if (!isDefined(squash) || squash == null) return defaultSquashPolicy;\n      if (squash === true || isString(squash)) return squash;\n      throw new Error(\"Invalid squash policy: '\" + squash + \"'. Valid policies: false, true, or arbitrary string\");\n    }\n\n    function getReplace(config, arrayMode, isOptional, squash) {\n      var replace, configuredKeys, defaultPolicy = [\n        { from: \"\",   to: (isOptional || arrayMode ? undefined : \"\") },\n        { from: null, to: (isOptional || arrayMode ? undefined : \"\") }\n      ];\n      replace = isArray(config.replace) ? config.replace : [];\n      if (isString(squash))\n        replace.push({ from: squash, to: undefined });\n      configuredKeys = map(replace, function(item) { return item.from; } );\n      return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);\n    }\n\n    /**\n     * [Internal] Get the default value of a parameter, which may be an injectable function.\n     */\n    function $$getDefaultValue() {\n      if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n      var defaultValue = injector.invoke(config.$$fn);\n      if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))\n        throw new Error(\"Default value (\" + defaultValue + \") for parameter '\" + self.id + \"' is not an instance of Type (\" + self.type.name + \")\");\n      return defaultValue;\n    }\n\n    /**\n     * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n     * default value, which may be the result of an injectable function.\n     */\n    function $value(value) {\n      function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }\n      function $replace(value) {\n        var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });\n        return replacement.length ? replacement[0] : value;\n      }\n      value = $replace(value);\n      return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);\n    }\n\n    function toString() { return \"{Param:\" + id + \" \" + type + \" squash: '\" + squash + \"' optional: \" + isOptional + \"}\"; }\n\n    extend(this, {\n      id: id,\n      type: type,\n      location: location,\n      array: arrayMode,\n      squash: squash,\n      replace: replace,\n      isOptional: isOptional,\n      value: $value,\n      dynamic: undefined,\n      config: config,\n      toString: toString\n    });\n  };\n\n  function ParamSet(params) {\n    extend(this, params || {});\n  }\n\n  ParamSet.prototype = {\n    $$new: function() {\n      return inherit(this, extend(new ParamSet(), { $$parent: this}));\n    },\n    $$keys: function () {\n      var keys = [], chain = [], parent = this,\n        ignore = objectKeys(ParamSet.prototype);\n      while (parent) { chain.push(parent); parent = parent.$$parent; }\n      chain.reverse();\n      forEach(chain, function(paramset) {\n        forEach(objectKeys(paramset), function(key) {\n            if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);\n        });\n      });\n      return keys;\n    },\n    $$values: function(paramValues) {\n      var values = {}, self = this;\n      forEach(self.$$keys(), function(key) {\n        values[key] = self[key].value(paramValues && paramValues[key]);\n      });\n      return values;\n    },\n    $$equals: function(paramValues1, paramValues2) {\n      var equal = true, self = this;\n      forEach(self.$$keys(), function(key) {\n        var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];\n        if (!self[key].type.equals(left, right)) equal = false;\n      });\n      return equal;\n    },\n    $$validates: function $$validate(paramValues) {\n      var keys = this.$$keys(), i, param, rawVal, normalized, encoded;\n      for (i = 0; i < keys.length; i++) {\n        param = this[keys[i]];\n        rawVal = paramValues[keys[i]];\n        if ((rawVal === undefined || rawVal === null) && param.isOptional)\n          break; // There was no parameter value, but the param is optional\n        normalized = param.type.$normalize(rawVal);\n        if (!param.type.is(normalized))\n          return false; // The value was not of the correct Type, and could not be decoded to the correct Type\n        encoded = param.type.encode(normalized);\n        if (angular.isString(encoded) && !param.type.pattern.exec(encoded))\n          return false; // The value was of the correct type, but when encoded, did not match the Type's regexp\n      }\n      return true;\n    },\n    $$parent: undefined\n  };\n\n  this.ParamSet = ParamSet;\n}\n\n// Register as a provider so it's available to other providers\nangular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);\nangular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);\n\n/**\n * @ngdoc object\n * @name ui.router.router.$urlRouterProvider\n *\n * @requires ui.router.util.$urlMatcherFactoryProvider\n * @requires $locationProvider\n *\n * @description\n * `$urlRouterProvider` has the responsibility of watching `$location`. \n * When `$location` changes it runs through a list of rules one by one until a \n * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify \n * a url in a state configuration. All urls are compiled into a UrlMatcher object.\n *\n * There are several methods on `$urlRouterProvider` that make it useful to use directly\n * in your module config.\n */\n$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];\nfunction $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {\n  var rules = [], otherwise = null, interceptDeferred = false, listener;\n\n  // Returns a string that is a prefix of all strings matching the RegExp\n  function regExpPrefix(re) {\n    var prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\n    return (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\n  }\n\n  // Interpolates matched values into a String.replace()-style pattern\n  function interpolate(pattern, match) {\n    return pattern.replace(/\\$(\\$|\\d{1,2})/, function (m, what) {\n      return match[what === '$' ? 0 : Number(what)];\n    });\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#rule\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines rules that are used by `$urlRouterProvider` to find matches for\n   * specific URLs.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // Here's an example of how you might allow case insensitive urls\n   *   $urlRouterProvider.rule(function ($injector, $location) {\n   *     var path = $location.path(),\n   *         normalized = path.toLowerCase();\n   *\n   *     if (path !== normalized) {\n   *       return normalized;\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {object} rule Handler function that takes `$injector` and `$location`\n   * services as arguments. You can use them to return a valid path as a string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.rule = function (rule) {\n    if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    rules.push(rule);\n    return this;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouterProvider#otherwise\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines a path that is used when an invalid route is requested.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // if the path doesn't match any of the urls you configured\n   *   // otherwise will take care of routing the user to the\n   *   // specified url\n   *   $urlRouterProvider.otherwise('/index');\n   *\n   *   // Example of using function rule as param\n   *   $urlRouterProvider.otherwise(function ($injector, $location) {\n   *     return '/a/valid/url';\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} rule The url path you want to redirect to or a function \n   * rule that returns the url path. The function version is passed two params: \n   * `$injector` and `$location` services, and must return a url string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.otherwise = function (rule) {\n    if (isString(rule)) {\n      var redirect = rule;\n      rule = function () { return redirect; };\n    }\n    else if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    otherwise = rule;\n    return this;\n  };\n\n\n  function handleIfMatch($injector, handler, match) {\n    if (!match) return false;\n    var result = $injector.invoke(handler, handler, { $match: match });\n    return isDefined(result) ? result : true;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#when\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Registers a handler for a given url matching. if handle is a string, it is\n   * treated as a redirect, and is interpolated according to the syntax of match\n   * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n   *\n   * If the handler is a function, it is injectable. It gets invoked if `$location`\n   * matches. You have the option of inject the match object as `$match`.\n   *\n   * The handler can return\n   *\n   * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n   *   will continue trying to find another one that matches.\n   * - **string** which is treated as a redirect and passed to `$location.url()`\n   * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n   *     if ($state.$current.navigable !== state ||\n   *         !equalForKeys($match, $stateParams) {\n   *      $state.transitionTo(state, $match, false);\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} what The incoming path that you want to redirect.\n   * @param {string|object} handler The path you want to redirect your user to.\n   */\n  this.when = function (what, handler) {\n    var redirect, handlerIsString = isString(handler);\n    if (isString(what)) what = $urlMatcherFactory.compile(what);\n\n    if (!handlerIsString && !isFunction(handler) && !isArray(handler))\n      throw new Error(\"invalid 'handler' in when()\");\n\n    var strategies = {\n      matcher: function (what, handler) {\n        if (handlerIsString) {\n          redirect = $urlMatcherFactory.compile(handler);\n          handler = ['$match', function ($match) { return redirect.format($match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));\n        }, {\n          prefix: isString(what.prefix) ? what.prefix : ''\n        });\n      },\n      regex: function (what, handler) {\n        if (what.global || what.sticky) throw new Error(\"when() RegExp must not be global or sticky\");\n\n        if (handlerIsString) {\n          redirect = handler;\n          handler = ['$match', function ($match) { return interpolate(redirect, $match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path()));\n        }, {\n          prefix: regExpPrefix(what)\n        });\n      }\n    };\n\n    var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };\n\n    for (var n in check) {\n      if (check[n]) return this.rule(strategies[n](what, handler));\n    }\n\n    throw new Error(\"invalid 'what' in when()\");\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#deferIntercept\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Disables (or enables) deferring location change interception.\n   *\n   * If you wish to customize the behavior of syncing the URL (for example, if you wish to\n   * defer a transition but maintain the current URL), call this method at configuration time.\n   * Then, at run time, call `$urlRouter.listen()` after you have configured your own\n   * `$locationChangeSuccess` event handler.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *\n   *   // Prevent $urlRouter from automatically intercepting URL changes;\n   *   // this allows you to configure custom behavior in between\n   *   // location changes and route synchronization:\n   *   $urlRouterProvider.deferIntercept();\n   *\n   * }).run(function ($rootScope, $urlRouter, UserService) {\n   *\n   *   $rootScope.$on('$locationChangeSuccess', function(e) {\n   *     // UserService is an example service for managing user state\n   *     if (UserService.isLoggedIn()) return;\n   *\n   *     // Prevent $urlRouter's default handler from firing\n   *     e.preventDefault();\n   *\n   *     UserService.handleLogin().then(function() {\n   *       // Once the user has logged in, sync the current URL\n   *       // to the router:\n   *       $urlRouter.sync();\n   *     });\n   *   });\n   *\n   *   // Configures $urlRouter's listener *after* your custom listener\n   *   $urlRouter.listen();\n   * });\n   * </pre>\n   *\n   * @param {boolean} defer Indicates whether to defer location change interception. Passing\n            no parameter is equivalent to `true`.\n   */\n  this.deferIntercept = function (defer) {\n    if (defer === undefined) defer = true;\n    interceptDeferred = defer;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouter\n   *\n   * @requires $location\n   * @requires $rootScope\n   * @requires $injector\n   * @requires $browser\n   *\n   * @description\n   *\n   */\n  this.$get = $get;\n  $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];\n  function $get(   $location,   $rootScope,   $injector,   $browser) {\n\n    var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;\n\n    function appendBasePath(url, isHtml5, absolute) {\n      if (baseHref === '/') return url;\n      if (isHtml5) return baseHref.slice(0, -1) + url;\n      if (absolute) return baseHref.slice(1) + url;\n      return url;\n    }\n\n    // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree\n    function update(evt) {\n      if (evt && evt.defaultPrevented) return;\n      var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;\n      lastPushedUrl = undefined;\n      // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573\n      //if (ignoreUpdate) return true;\n\n      function check(rule) {\n        var handled = rule($injector, $location);\n\n        if (!handled) return false;\n        if (isString(handled)) $location.replace().url(handled);\n        return true;\n      }\n      var n = rules.length, i;\n\n      for (i = 0; i < n; i++) {\n        if (check(rules[i])) return;\n      }\n      // always check otherwise last to allow dynamic updates to the set of rules\n      if (otherwise) check(otherwise);\n    }\n\n    function listen() {\n      listener = listener || $rootScope.$on('$locationChangeSuccess', update);\n      return listener;\n    }\n\n    if (!interceptDeferred) listen();\n\n    return {\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#sync\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.\n       * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,\n       * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed\n       * with the transition by calling `$urlRouter.sync()`.\n       *\n       * @example\n       * <pre>\n       * angular.module('app', ['ui.router'])\n       *   .run(function($rootScope, $urlRouter) {\n       *     $rootScope.$on('$locationChangeSuccess', function(evt) {\n       *       // Halt state change from even starting\n       *       evt.preventDefault();\n       *       // Perform custom logic\n       *       var meetsRequirement = ...\n       *       // Continue with the update and state transition if logic allows\n       *       if (meetsRequirement) $urlRouter.sync();\n       *     });\n       * });\n       * </pre>\n       */\n      sync: function() {\n        update();\n      },\n\n      listen: function() {\n        return listen();\n      },\n\n      update: function(read) {\n        if (read) {\n          location = $location.url();\n          return;\n        }\n        if ($location.url() === location) return;\n\n        $location.url(location);\n        $location.replace();\n      },\n\n      push: function(urlMatcher, params, options) {\n         var url = urlMatcher.format(params || {});\n\n        // Handle the special hash param, if needed\n        if (url !== null && params && params['#']) {\n            url += '#' + params['#'];\n        }\n\n        $location.url(url);\n        lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;\n        if (options && options.replace) $location.replace();\n      },\n\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#href\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * A URL generation method that returns the compiled URL for a given\n       * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.\n       *\n       * @example\n       * <pre>\n       * $bob = $urlRouter.href(new UrlMatcher(\"/about/:person\"), {\n       *   person: \"bob\"\n       * });\n       * // $bob == \"/about/bob\";\n       * </pre>\n       *\n       * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.\n       * @param {object=} params An object of parameter values to fill the matcher's required parameters.\n       * @param {object=} options Options object. The options are:\n       *\n       * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n       *\n       * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n       */\n      href: function(urlMatcher, params, options) {\n        if (!urlMatcher.validates(params)) return null;\n\n        var isHtml5 = $locationProvider.html5Mode();\n        if (angular.isObject(isHtml5)) {\n          isHtml5 = isHtml5.enabled;\n        }\n        \n        var url = urlMatcher.format(params);\n        options = options || {};\n\n        if (!isHtml5 && url !== null) {\n          url = \"#\" + $locationProvider.hashPrefix() + url;\n        }\n\n        // Handle special hash param, if needed\n        if (url !== null && params && params['#']) {\n          url += '#' + params['#'];\n        }\n\n        url = appendBasePath(url, isHtml5, options.absolute);\n\n        if (!options.absolute || !url) {\n          return url;\n        }\n\n        var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();\n        port = (port === 80 || port === 443 ? '' : ':' + port);\n\n        return [$location.protocol(), '://', $location.host(), port, slash, url].join('');\n      }\n    };\n  }\n}\n\nangular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$stateProvider\n *\n * @requires ui.router.router.$urlRouterProvider\n * @requires ui.router.util.$urlMatcherFactoryProvider\n *\n * @description\n * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\n$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];\nfunction $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {\n\n  var root, states = {}, $state, queue = {}, abstractKey = 'abstract';\n\n  // Builds state properties from definition passed to registerState()\n  var stateBuilder = {\n\n    // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.\n    // state.children = [];\n    // if (parent) parent.children.push(state);\n    parent: function(state) {\n      if (isDefined(state.parent) && state.parent) return findState(state.parent);\n      // regex matches any valid composite state name\n      // would match \"contact.list\" but not \"contacts\"\n      var compositeName = /^(.+)\\.[^.]+$/.exec(state.name);\n      return compositeName ? findState(compositeName[1]) : root;\n    },\n\n    // inherit 'data' from parent and override by own values (if any)\n    data: function(state) {\n      if (state.parent && state.parent.data) {\n        state.data = state.self.data = extend({}, state.parent.data, state.data);\n      }\n      return state.data;\n    },\n\n    // Build a URLMatcher if necessary, either via a relative or absolute URL\n    url: function(state) {\n      var url = state.url, config = { params: state.params || {} };\n\n      if (isString(url)) {\n        if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);\n        return (state.parent.navigable || root).url.concat(url, config);\n      }\n\n      if (!url || $urlMatcherFactory.isMatcher(url)) return url;\n      throw new Error(\"Invalid url '\" + url + \"' in state '\" + state + \"'\");\n    },\n\n    // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n    navigable: function(state) {\n      return state.url ? state : (state.parent ? state.parent.navigable : null);\n    },\n\n    // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params\n    ownParams: function(state) {\n      var params = state.url && state.url.params || new $$UMFP.ParamSet();\n      forEach(state.params || {}, function(config, id) {\n        if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, \"config\");\n      });\n      return params;\n    },\n\n    // Derive parameters for this state and ensure they're a super-set of parent's parameters\n    params: function(state) {\n      return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();\n    },\n\n    // If there is no explicit multi-view configuration, make one up so we don't have\n    // to handle both cases in the view directive later. Note that having an explicit\n    // 'views' property will mean the default unnamed view properties are ignored. This\n    // is also a good time to resolve view names to absolute names, so everything is a\n    // straight lookup at link time.\n    views: function(state) {\n      var views = {};\n\n      forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {\n        if (name.indexOf('@') < 0) name += '@' + state.parent.name;\n        views[name] = view;\n      });\n      return views;\n    },\n\n    // Keep a full path from the root down to this state as this is needed for state activation.\n    path: function(state) {\n      return state.parent ? state.parent.path.concat(state) : []; // exclude root from path\n    },\n\n    // Speed up $state.contains() as it's used a lot\n    includes: function(state) {\n      var includes = state.parent ? extend({}, state.parent.includes) : {};\n      includes[state.name] = true;\n      return includes;\n    },\n\n    $delegates: {}\n  };\n\n  function isRelative(stateName) {\n    return stateName.indexOf(\".\") === 0 || stateName.indexOf(\"^\") === 0;\n  }\n\n  function findState(stateOrName, base) {\n    if (!stateOrName) return undefined;\n\n    var isStr = isString(stateOrName),\n        name  = isStr ? stateOrName : stateOrName.name,\n        path  = isRelative(name);\n\n    if (path) {\n      if (!base) throw new Error(\"No reference point given for path '\"  + name + \"'\");\n      base = findState(base);\n      \n      var rel = name.split(\".\"), i = 0, pathLength = rel.length, current = base;\n\n      for (; i < pathLength; i++) {\n        if (rel[i] === \"\" && i === 0) {\n          current = base;\n          continue;\n        }\n        if (rel[i] === \"^\") {\n          if (!current.parent) throw new Error(\"Path '\" + name + \"' not valid for state '\" + base.name + \"'\");\n          current = current.parent;\n          continue;\n        }\n        break;\n      }\n      rel = rel.slice(i).join(\".\");\n      name = current.name + (current.name && rel ? \".\" : \"\") + rel;\n    }\n    var state = states[name];\n\n    if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n      return state;\n    }\n    return undefined;\n  }\n\n  function queueState(parentName, state) {\n    if (!queue[parentName]) {\n      queue[parentName] = [];\n    }\n    queue[parentName].push(state);\n  }\n\n  function flushQueuedChildren(parentName) {\n    var queued = queue[parentName] || [];\n    while(queued.length) {\n      registerState(queued.shift());\n    }\n  }\n\n  function registerState(state) {\n    // Wrap a new object around the state so we can store our private details easily.\n    state = inherit(state, {\n      self: state,\n      resolve: state.resolve || {},\n      toString: function() { return this.name; }\n    });\n\n    var name = state.name;\n    if (!isString(name) || name.indexOf('@') >= 0) throw new Error(\"State must have a valid name\");\n    if (states.hasOwnProperty(name)) throw new Error(\"State '\" + name + \"'' is already defined\");\n\n    // Get parent name\n    var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))\n        : (isString(state.parent)) ? state.parent\n        : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name\n        : '';\n\n    // If parent is not registered yet, add state to queue and register later\n    if (parentName && !states[parentName]) {\n      return queueState(parentName, state.self);\n    }\n\n    for (var key in stateBuilder) {\n      if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);\n    }\n    states[name] = state;\n\n    // Register the state in the global state list and with $urlRouter if necessary.\n    if (!state[abstractKey] && state.url) {\n      $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {\n        if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {\n          $state.transitionTo(state, $match, { inherit: true, location: false });\n        }\n      }]);\n    }\n\n    // Register any queued children\n    flushQueuedChildren(name);\n\n    return state;\n  }\n\n  // Checks text to see if it looks like a glob.\n  function isGlob (text) {\n    return text.indexOf('*') > -1;\n  }\n\n  // Returns true if glob matches current $state name.\n  function doesStateMatchGlob (glob) {\n    var globSegments = glob.split('.'),\n        segments = $state.$current.name.split('.');\n\n    //match single stars\n    for (var i = 0, l = globSegments.length; i < l; i++) {\n      if (globSegments[i] === '*') {\n        segments[i] = '*';\n      }\n    }\n\n    //match greedy starts\n    if (globSegments[0] === '**') {\n       segments = segments.slice(indexOf(segments, globSegments[1]));\n       segments.unshift('**');\n    }\n    //match greedy ends\n    if (globSegments[globSegments.length - 1] === '**') {\n       segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);\n       segments.push('**');\n    }\n\n    if (globSegments.length != segments.length) {\n      return false;\n    }\n\n    return segments.join('') === globSegments.join('');\n  }\n\n\n  // Implicit root state that is always active\n  root = registerState({\n    name: '',\n    url: '^',\n    views: null,\n    'abstract': true\n  });\n  root.navigable = null;\n\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#decorator\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Allows you to extend (carefully) or override (at your own peril) the \n   * `stateBuilder` object used internally by `$stateProvider`. This can be used \n   * to add custom functionality to ui-router, for example inferring templateUrl \n   * based on the state name.\n   *\n   * When passing only a name, it returns the current (original or decorated) builder\n   * function that matches `name`.\n   *\n   * The builder functions that can be decorated are listed below. Though not all\n   * necessarily have a good use case for decoration, that is up to you to decide.\n   *\n   * In addition, users can attach custom decorators, which will generate new \n   * properties within the state's internal definition. There is currently no clear \n   * use-case for this beyond accessing internal states (i.e. $state.$current), \n   * however, expect this to become increasingly relevant as we introduce additional \n   * meta-programming features.\n   *\n   * **Warning**: Decorators should not be interdependent because the order of \n   * execution of the builder functions in non-deterministic. Builder functions \n   * should only be dependent on the state definition object and super function.\n   *\n   *\n   * Existing builder functions and current return values:\n   *\n   * - **parent** `{object}` - returns the parent state object.\n   * - **data** `{object}` - returns state data, including any inherited data that is not\n   *   overridden by own values (if any).\n   * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n   *   or `null`.\n   * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is \n   *   navigable).\n   * - **params** `{object}` - returns an array of state params that are ensured to \n   *   be a super-set of parent's params.\n   * - **views** `{object}` - returns a views object where each key is an absolute view \n   *   name (i.e. \"viewName@stateName\") and each value is the config object \n   *   (template, controller) for the view. Even when you don't use the views object \n   *   explicitly on a state config, one is still created for you internally.\n   *   So by decorating this builder function you have access to decorating template \n   *   and controller properties.\n   * - **ownParams** `{object}` - returns an array of params that belong to the state, \n   *   not including any params defined by ancestor states.\n   * - **path** `{string}` - returns the full path from the root down to this state. \n   *   Needed for state activation.\n   * - **includes** `{object}` - returns an object that includes every state that \n   *   would pass a `$state.includes()` test.\n   *\n   * @example\n   * <pre>\n   * // Override the internal 'views' builder with a function that takes the state\n   * // definition, and a reference to the internal function being overridden:\n   * $stateProvider.decorator('views', function (state, parent) {\n   *   var result = {},\n   *       views = parent(state);\n   *\n   *   angular.forEach(views, function (config, name) {\n   *     var autoName = (state.name + '.' + name).replace('.', '/');\n   *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n   *     result[name] = config;\n   *   });\n   *   return result;\n   * });\n   *\n   * $stateProvider.state('home', {\n   *   views: {\n   *     'contact.list': { controller: 'ListController' },\n   *     'contact.item': { controller: 'ItemController' }\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * $state.go('home');\n   * // Auto-populates list and item views with /partials/home/contact/list.html,\n   * // and /partials/home/contact/item.html, respectively.\n   * </pre>\n   *\n   * @param {string} name The name of the builder function to decorate. \n   * @param {object} func A function that is responsible for decorating the original \n   * builder function. The function receives two parameters:\n   *\n   *   - `{object}` - state - The state config object.\n   *   - `{object}` - super - The original builder function.\n   *\n   * @return {object} $stateProvider - $stateProvider instance\n   */\n  this.decorator = decorator;\n  function decorator(name, func) {\n    /*jshint validthis: true */\n    if (isString(name) && !isDefined(func)) {\n      return stateBuilder[name];\n    }\n    if (!isFunction(func) || !isString(name)) {\n      return this;\n    }\n    if (stateBuilder[name] && !stateBuilder.$delegates[name]) {\n      stateBuilder.$delegates[name] = stateBuilder[name];\n    }\n    stateBuilder[name] = func;\n    return this;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#state\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Registers a state configuration under a given state name. The stateConfig object\n   * has the following acceptable properties.\n   *\n   * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n   * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n   * @param {object} stateConfig State configuration object.\n   * @param {string|function=} stateConfig.template\n   * <a id='template'></a>\n   *   html template as a string or a function that returns\n   *   an html template as a string which should be used by the uiView directives. This property \n   *   takes precedence over templateUrl.\n   *   \n   *   If `template` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by\n   *     applying the current state\n   *\n   * <pre>template:\n   *   \"<h1>inline template definition</h1>\" +\n   *   \"<div ui-view></div>\"</pre>\n   * <pre>template: function(params) {\n   *       return \"<h1>generated template</h1>\"; }</pre>\n   * </div>\n   *\n   * @param {string|function=} stateConfig.templateUrl\n   * <a id='templateUrl'></a>\n   *\n   *   path or function that returns a path to an html\n   *   template that should be used by uiView.\n   *   \n   *   If `templateUrl` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by \n   *     applying the current state\n   *\n   * <pre>templateUrl: \"home.html\"</pre>\n   * <pre>templateUrl: function(params) {\n   *     return myTemplates[params.pageId]; }</pre>\n   *\n   * @param {function=} stateConfig.templateProvider\n   * <a id='templateProvider'></a>\n   *    Provider function that returns HTML content string.\n   * <pre> templateProvider:\n   *       function(MyTemplateService, params) {\n   *         return MyTemplateService.getTemplate(params.pageId);\n   *       }</pre>\n   *\n   * @param {string|function=} stateConfig.controller\n   * <a id='controller'></a>\n   *\n   *  Controller fn that should be associated with newly\n   *   related scope or the name of a registered controller if passed as a string.\n   *   Optionally, the ControllerAs may be declared here.\n   * <pre>controller: \"MyRegisteredController\"</pre>\n   * <pre>controller:\n   *     \"MyRegisteredController as fooCtrl\"}</pre>\n   * <pre>controller: function($scope, MyService) {\n   *     $scope.data = MyService.getData(); }</pre>\n   *\n   * @param {function=} stateConfig.controllerProvider\n   * <a id='controllerProvider'></a>\n   *\n   * Injectable provider function that returns the actual controller or string.\n   * <pre>controllerProvider:\n   *   function(MyResolveData) {\n   *     if (MyResolveData.foo)\n   *       return \"FooCtrl\"\n   *     else if (MyResolveData.bar)\n   *       return \"BarCtrl\";\n   *     else return function($scope) {\n   *       $scope.baz = \"Qux\";\n   *     }\n   *   }</pre>\n   *\n   * @param {string=} stateConfig.controllerAs\n   * <a id='controllerAs'></a>\n   * \n   * A controller alias name. If present the controller will be\n   *   published to scope under the controllerAs name.\n   * <pre>controllerAs: \"myCtrl\"</pre>\n   *\n   * @param {string|object=} stateConfig.parent\n   * <a id='parent'></a>\n   * Optionally specifies the parent state of this state.\n   *\n   * <pre>parent: 'parentState'</pre>\n   * <pre>parent: parentState // JS variable</pre>\n   *\n   * @param {object=} stateConfig.resolve\n   * <a id='resolve'></a>\n   *\n   * An optional map&lt;string, function&gt; of dependencies which\n   *   should be injected into the controller. If any of these dependencies are promises, \n   *   the router will wait for them all to be resolved before the controller is instantiated.\n   *   If all the promises are resolved successfully, the $stateChangeSuccess event is fired\n   *   and the values of the resolved promises are injected into any controllers that reference them.\n   *   If any  of the promises are rejected the $stateChangeError event is fired.\n   *\n   *   The map object is:\n   *   \n   *   - key - {string}: name of dependency to be injected into controller\n   *   - factory - {string|function}: If string then it is alias for service. Otherwise if function, \n   *     it is injected and return value it treated as dependency. If result is a promise, it is \n   *     resolved before its value is injected into controller.\n   *\n   * <pre>resolve: {\n   *     myResolve1:\n   *       function($http, $stateParams) {\n   *         return $http.get(\"/api/foos/\"+stateParams.fooID);\n   *       }\n   *     }</pre>\n   *\n   * @param {string=} stateConfig.url\n   * <a id='url'></a>\n   *\n   *   A url fragment with optional parameters. When a state is navigated or\n   *   transitioned to, the `$stateParams` service will be populated with any \n   *   parameters that were passed.\n   *\n   *   (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for\n   *   more details on acceptable patterns )\n   *\n   * examples:\n   * <pre>url: \"/home\"\n   * url: \"/users/:userid\"\n   * url: \"/books/{bookid:[a-zA-Z_-]}\"\n   * url: \"/books/{categoryid:int}\"\n   * url: \"/books/{publishername:string}/{categoryid:int}\"\n   * url: \"/messages?before&after\"\n   * url: \"/messages?{before:date}&{after:date}\"\n   * url: \"/messages/:mailboxid?{before:date}&{after:date}\"\n   * </pre>\n   *\n   * @param {object=} stateConfig.views\n   * <a id='views'></a>\n   * an optional map&lt;string, object&gt; which defined multiple views, or targets views\n   * manually/explicitly.\n   *\n   * Examples:\n   *\n   * Targets three named `ui-view`s in the parent state's template\n   * <pre>views: {\n   *     header: {\n   *       controller: \"headerCtrl\",\n   *       templateUrl: \"header.html\"\n   *     }, body: {\n   *       controller: \"bodyCtrl\",\n   *       templateUrl: \"body.html\"\n   *     }, footer: {\n   *       controller: \"footCtrl\",\n   *       templateUrl: \"footer.html\"\n   *     }\n   *   }</pre>\n   *\n   * Targets named `ui-view=\"header\"` from grandparent state 'top''s template, and named `ui-view=\"body\" from parent state's template.\n   * <pre>views: {\n   *     'header@top': {\n   *       controller: \"msgHeaderCtrl\",\n   *       templateUrl: \"msgHeader.html\"\n   *     }, 'body': {\n   *       controller: \"messagesCtrl\",\n   *       templateUrl: \"messages.html\"\n   *     }\n   *   }</pre>\n   *\n   * @param {boolean=} [stateConfig.abstract=false]\n   * <a id='abstract'></a>\n   * An abstract state will never be directly activated,\n   *   but can provide inherited properties to its common children states.\n   * <pre>abstract: true</pre>\n   *\n   * @param {function=} stateConfig.onEnter\n   * <a id='onEnter'></a>\n   *\n   * Callback function for when a state is entered. Good way\n   *   to trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onEnter: function(MyService, $stateParams) {\n   *     MyService.foo($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {function=} stateConfig.onExit\n   * <a id='onExit'></a>\n   *\n   * Callback function for when a state is exited. Good way to\n   *   trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onExit: function(MyService, $stateParams) {\n   *     MyService.cleanup($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {boolean=} [stateConfig.reloadOnSearch=true]\n   * <a id='reloadOnSearch'></a>\n   *\n   * If `false`, will not retrigger the same state\n   *   just because a search/query parameter has changed (via $location.search() or $location.hash()). \n   *   Useful for when you'd like to modify $location.search() without triggering a reload.\n   * <pre>reloadOnSearch: false</pre>\n   *\n   * @param {object=} stateConfig.data\n   * <a id='data'></a>\n   *\n   * Arbitrary data object, useful for custom configuration.  The parent state's `data` is\n   *   prototypally inherited.  In other words, adding a data property to a state adds it to\n   *   the entire subtree via prototypal inheritance.\n   *\n   * <pre>data: {\n   *     requiredRole: 'foo'\n   * } </pre>\n   *\n   * @param {object=} stateConfig.params\n   * <a id='params'></a>\n   *\n   * A map which optionally configures parameters declared in the `url`, or\n   *   defines additional non-url parameters.  For each parameter being\n   *   configured, add a configuration object keyed to the name of the parameter.\n   *\n   *   Each parameter configuration object may contain the following properties:\n   *\n   *   - ** value ** - {object|function=}: specifies the default value for this\n   *     parameter.  This implicitly sets this parameter as optional.\n   *\n   *     When UI-Router routes to a state and no value is\n   *     specified for this parameter in the URL or transition, the\n   *     default value will be used instead.  If `value` is a function,\n   *     it will be injected and invoked, and the return value used.\n   *\n   *     *Note*: `undefined` is treated as \"no default value\" while `null`\n   *     is treated as \"the default value is `null`\".\n   *\n   *     *Shorthand*: If you only need to configure the default value of the\n   *     parameter, you may use a shorthand syntax.   In the **`params`**\n   *     map, instead mapping the param name to a full parameter configuration\n   *     object, simply set map it to the default parameter value, e.g.:\n   *\n   * <pre>// define a parameter's default value\n   * params: {\n   *     param1: { value: \"defaultValue\" }\n   * }\n   * // shorthand default values\n   * params: {\n   *     param1: \"defaultValue\",\n   *     param2: \"param2Default\"\n   * }</pre>\n   *\n   *   - ** array ** - {boolean=}: *(default: false)* If true, the param value will be\n   *     treated as an array of values.  If you specified a Type, the value will be\n   *     treated as an array of the specified Type.  Note: query parameter values\n   *     default to a special `\"auto\"` mode.\n   *\n   *     For query parameters in `\"auto\"` mode, if multiple  values for a single parameter\n   *     are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values\n   *     are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`).  However, if\n   *     only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single\n   *     value (e.g.: `{ foo: '1' }`).\n   *\n   * <pre>params: {\n   *     param1: { array: true }\n   * }</pre>\n   *\n   *   - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when\n   *     the current parameter value is the same as the default value. If `squash` is not set, it uses the\n   *     configured default squash policy.\n   *     (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})\n   *\n   *   There are three squash settings:\n   *\n   *     - false: The parameter's default value is not squashed.  It is encoded and included in the URL\n   *     - true: The parameter's default value is omitted from the URL.  If the parameter is preceeded and followed\n   *       by slashes in the state's `url` declaration, then one of those slashes are omitted.\n   *       This can allow for cleaner looking URLs.\n   *     - `\"<arbitrary string>\"`: The parameter's default value is replaced with an arbitrary placeholder of  your choice.\n   *\n   * <pre>params: {\n   *     param1: {\n   *       value: \"defaultId\",\n   *       squash: true\n   * } }\n   * // squash \"defaultValue\" to \"~\"\n   * params: {\n   *     param1: {\n   *       value: \"defaultValue\",\n   *       squash: \"~\"\n   * } }\n   * </pre>\n   *\n   *\n   * @example\n   * <pre>\n   * // Some state name examples\n   *\n   * // stateName can be a single top-level name (must be unique).\n   * $stateProvider.state(\"home\", {});\n   *\n   * // Or it can be a nested state name. This state is a child of the\n   * // above \"home\" state.\n   * $stateProvider.state(\"home.newest\", {});\n   *\n   * // Nest states as deeply as needed.\n   * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n   *\n   * // state() returns $stateProvider, so you can chain state declarations.\n   * $stateProvider\n   *   .state(\"home\", {})\n   *   .state(\"about\", {})\n   *   .state(\"contacts\", {});\n   * </pre>\n   *\n   */\n  this.state = state;\n  function state(name, definition) {\n    /*jshint validthis: true */\n    if (isObject(name)) definition = name;\n    else definition.name = name;\n    registerState(definition);\n    return this;\n  }\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$state\n   *\n   * @requires $rootScope\n   * @requires $q\n   * @requires ui.router.state.$view\n   * @requires $injector\n   * @requires ui.router.util.$resolve\n   * @requires ui.router.state.$stateParams\n   * @requires ui.router.router.$urlRouter\n   *\n   * @property {object} params A param object, e.g. {sectionId: section.id)}, that \n   * you'd like to test against the current active state.\n   * @property {object} current A reference to the state's config object. However \n   * you passed it in. Useful for accessing custom data.\n   * @property {object} transition Currently pending transition. A promise that'll \n   * resolve or reject.\n   *\n   * @description\n   * `$state` service is responsible for representing states as well as transitioning\n   * between them. It also provides interfaces to ask for current state or even states\n   * you're coming from.\n   */\n  this.$get = $get;\n  $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];\n  function $get(   $rootScope,   $q,   $view,   $injector,   $resolve,   $stateParams,   $urlRouter,   $location,   $urlMatcherFactory) {\n\n    var TransitionSuperseded = $q.reject(new Error('transition superseded'));\n    var TransitionPrevented = $q.reject(new Error('transition prevented'));\n    var TransitionAborted = $q.reject(new Error('transition aborted'));\n    var TransitionFailed = $q.reject(new Error('transition failed'));\n\n    // Handles the case where a state which is the target of a transition is not found, and the user\n    // can optionally retry or defer the transition\n    function handleRedirect(redirect, state, params, options) {\n      /**\n       * @ngdoc event\n       * @name ui.router.state.$state#$stateNotFound\n       * @eventOf ui.router.state.$state\n       * @eventType broadcast on root scope\n       * @description\n       * Fired when a requested state **cannot be found** using the provided state name during transition.\n       * The event is broadcast allowing any handlers a single chance to deal with the error (usually by\n       * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,\n       * you can see its three properties in the example. You can use `event.preventDefault()` to abort the\n       * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.\n       *\n       * @param {Object} event Event object.\n       * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.\n       * @param {State} fromState Current state object.\n       * @param {Object} fromParams Current state params.\n       *\n       * @example\n       *\n       * <pre>\n       * // somewhere, assume lazy.state has not been defined\n       * $state.go(\"lazy.state\", {a:1, b:2}, {inherit:false});\n       *\n       * // somewhere else\n       * $scope.$on('$stateNotFound',\n       * function(event, unfoundState, fromState, fromParams){\n       *     console.log(unfoundState.to); // \"lazy.state\"\n       *     console.log(unfoundState.toParams); // {a:1, b:2}\n       *     console.log(unfoundState.options); // {inherit:false} + default options\n       * })\n       * </pre>\n       */\n      var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);\n\n      if (evt.defaultPrevented) {\n        $urlRouter.update();\n        return TransitionAborted;\n      }\n\n      if (!evt.retry) {\n        return null;\n      }\n\n      // Allow the handler to return a promise to defer state lookup retry\n      if (options.$retry) {\n        $urlRouter.update();\n        return TransitionFailed;\n      }\n      var retryTransition = $state.transition = $q.when(evt.retry);\n\n      retryTransition.then(function() {\n        if (retryTransition !== $state.transition) return TransitionSuperseded;\n        redirect.options.$retry = true;\n        return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);\n      }, function() {\n        return TransitionAborted;\n      });\n      $urlRouter.update();\n\n      return retryTransition;\n    }\n\n    root.locals = { resolve: null, globals: { $stateParams: {} } };\n\n    $state = {\n      params: {},\n      current: root.self,\n      $current: root,\n      transition: null\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#reload\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method that force reloads the current state. All resolves are re-resolved,\n     * controllers reinstantiated, and events re-fired.\n     *\n     * @example\n     * <pre>\n     * var app angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.reload = function(){\n     *     $state.reload();\n     *   }\n     * });\n     * </pre>\n     *\n     * `reload()` is just an alias for:\n     * <pre>\n     * $state.transitionTo($state.current, $stateParams, { \n     *   reload: true, inherit: false, notify: true\n     * });\n     * </pre>\n     *\n     * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.\n     * @example\n     * <pre>\n     * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item' \n     * //and current state is 'contacts.detail.item'\n     * var app angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.reload = function(){\n     *     //will reload 'contact.detail' and 'contact.detail.item' states\n     *     $state.reload('contact.detail');\n     *   }\n     * });\n     * </pre>\n     *\n     * `reload()` is just an alias for:\n     * <pre>\n     * $state.transitionTo($state.current, $stateParams, { \n     *   reload: true, inherit: false, notify: true\n     * });\n     * </pre>\n\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.reload = function reload(state) {\n      return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#go\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Convenience method for transitioning to a new state. `$state.go` calls \n     * `$state.transitionTo` internally but automatically sets options to \n     * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. \n     * This allows you to easily use an absolute or relative to path and specify \n     * only the parameters you'd like to update (while letting unspecified parameters \n     * inherit from the currently active ancestor states).\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.go('contact.detail');\n     *   };\n     * });\n     * </pre>\n     * <img src='../ngdoc_assets/StateGoExamples.png'/>\n     *\n     * @param {string} to Absolute state name or relative state path. Some examples:\n     *\n     * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n     * - `$state.go('^')` - will go to a parent state\n     * - `$state.go('^.sibling')` - will go to a sibling state\n     * - `$state.go('.child.grandchild')` - will go to grandchild state\n     *\n     * @param {object=} params A map of the parameters that will be sent to the state, \n     * will populate $stateParams. Any parameters that are not specified will be inherited from currently \n     * defined parameters. This allows, for example, going to a sibling state that shares parameters\n     * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.\n     * transitioning to a sibling will get you the parameters for all parents, transitioning to a child\n     * will get you all current parameters, etc.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *\n     * @returns {promise} A promise representing the state of the new transition.\n     *\n     * Possible success values:\n     *\n     * - $state.current\n     *\n     * <br/>Possible rejection values:\n     *\n     * - 'transition superseded' - when a newer transition has been started after this one\n     * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener\n     * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or\n     *   when a `$stateNotFound` `event.retry` promise errors.\n     * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.\n     * - *resolve error* - when an error has occurred with a `resolve`\n     *\n     */\n    $state.go = function go(to, params, options) {\n      return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#transitionTo\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}\n     * uses `transitionTo` internally. `$state.go` is recommended in most situations.\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.transitionTo('contact.detail');\n     *   };\n     * });\n     * </pre>\n     *\n     * @param {string} to State name.\n     * @param {object=} toParams A map of the parameters that will be sent to the state,\n     * will populate $stateParams.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *    if String, then will reload the state with the name given in reload, and any children.\n     *    if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.\n     *\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.transitionTo = function transitionTo(to, toParams, options) {\n      toParams = toParams || {};\n      options = extend({\n        location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false\n      }, options || {});\n\n      var from = $state.$current, fromParams = $state.params, fromPath = from.path;\n      var evt, toState = findState(to, options.relative);\n\n      // Store the hash param for later (since it will be stripped out by various methods)\n      var hash = toParams['#'];\n\n      if (!isDefined(toState)) {\n        var redirect = { to: to, toParams: toParams, options: options };\n        var redirectResult = handleRedirect(redirect, from.self, fromParams, options);\n\n        if (redirectResult) {\n          return redirectResult;\n        }\n\n        // Always retry once if the $stateNotFound was not prevented\n        // (handles either redirect changed or state lazy-definition)\n        to = redirect.to;\n        toParams = redirect.toParams;\n        options = redirect.options;\n        toState = findState(to, options.relative);\n\n        if (!isDefined(toState)) {\n          if (!options.relative) throw new Error(\"No such state '\" + to + \"'\");\n          throw new Error(\"Could not resolve '\" + to + \"' from state '\" + options.relative + \"'\");\n        }\n      }\n      if (toState[abstractKey]) throw new Error(\"Cannot transition to abstract state '\" + to + \"'\");\n      if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);\n      if (!toState.params.$$validates(toParams)) return TransitionFailed;\n\n      toParams = toState.params.$$values(toParams);\n      to = toState;\n\n      var toPath = to.path;\n\n      // Starting from the root of the path, keep all levels that haven't changed\n      var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];\n\n      if (!options.reload) {\n        while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {\n          locals = toLocals[keep] = state.locals;\n          keep++;\n          state = toPath[keep];\n        }\n      } else if (isString(options.reload) || isObject(options.reload)) {\n        if (isObject(options.reload) && !options.reload.name) {\n          throw new Error('Invalid reload state object');\n        }\n        \n        var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);\n        if (options.reload && !reloadState) {\n          throw new Error(\"No such reload state '\" + (isString(options.reload) ? options.reload : options.reload.name) + \"'\");\n        }\n\n        while (state && state === fromPath[keep] && state !== reloadState) {\n          locals = toLocals[keep] = state.locals;\n          keep++;\n          state = toPath[keep];\n        }\n      }\n\n      // If we're going to the same state and all locals are kept, we've got nothing to do.\n      // But clear 'transition', as we still want to cancel any other pending transitions.\n      // TODO: We may not want to bump 'transition' if we're called from a location change\n      // that we've initiated ourselves, because we might accidentally abort a legitimate\n      // transition initiated from code?\n      if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {\n        if (hash) toParams['#'] = hash;\n        $state.params = toParams;\n        copy($state.params, $stateParams);\n        if (options.location && to.navigable && to.navigable.url) {\n          $urlRouter.push(to.navigable.url, toParams, {\n            $$avoidResync: true, replace: options.location === 'replace'\n          });\n          $urlRouter.update(true);\n        }\n        $state.transition = null;\n        return $q.when($state.current);\n      }\n\n      // Filter parameters before we pass them to event handlers etc.\n      toParams = filterByKeys(to.params.$$keys(), toParams || {});\n\n      // Broadcast start event and cancel the transition if requested\n      if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeStart\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when the state transition **begins**. You can use `event.preventDefault()`\n         * to prevent the transition from happening and then the transition promise will be\n         * rejected with a `'transition prevented'` value.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         *\n         * @example\n         *\n         * <pre>\n         * $rootScope.$on('$stateChangeStart',\n         * function(event, toState, toParams, fromState, fromParams){\n         *     event.preventDefault();\n         *     // transitionTo() promise will be rejected with\n         *     // a 'transition prevented' error\n         * })\n         * </pre>\n         */\n        if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {\n          $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);\n          $urlRouter.update();\n          return TransitionPrevented;\n        }\n      }\n\n      // Resolve locals for the remaining states, but don't update any global state just\n      // yet -- if anything fails to resolve the current state needs to remain untouched.\n      // We also set up an inheritance chain for the locals here. This allows the view directive\n      // to quickly look up the correct definition for each view in the current state. Even\n      // though we create the locals object itself outside resolveState(), it is initially\n      // empty and gets filled asynchronously. We need to keep track of the promise for the\n      // (fully resolved) current locals, and pass this down the chain.\n      var resolved = $q.when(locals);\n\n      for (var l = keep; l < toPath.length; l++, state = toPath[l]) {\n        locals = toLocals[l] = inherit(locals);\n        resolved = resolveState(state, toParams, state === to, resolved, locals, options);\n      }\n\n      // Once everything is resolved, we are ready to perform the actual transition\n      // and return a promise for the new state. We also keep track of what the\n      // current promise is, so that we can detect overlapping transitions and\n      // keep only the outcome of the last transition.\n      var transition = $state.transition = resolved.then(function () {\n        var l, entering, exiting;\n\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Exit 'from' states not kept\n        for (l = fromPath.length - 1; l >= keep; l--) {\n          exiting = fromPath[l];\n          if (exiting.self.onExit) {\n            $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);\n          }\n          exiting.locals = null;\n        }\n\n        // Enter 'to' states not kept\n        for (l = keep; l < toPath.length; l++) {\n          entering = toPath[l];\n          entering.locals = toLocals[l];\n          if (entering.self.onEnter) {\n            $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);\n          }\n        }\n\n        // Re-add the saved hash before we start returning things\n        if (hash) toParams['#'] = hash;\n\n        // Run it again, to catch any transitions in callbacks\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Update globals in $state\n        $state.$current = to;\n        $state.current = to.self;\n        $state.params = toParams;\n        copy($state.params, $stateParams);\n        $state.transition = null;\n\n        if (options.location && to.navigable) {\n          $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {\n            $$avoidResync: true, replace: options.location === 'replace'\n          });\n        }\n\n        if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeSuccess\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired once the state transition is **complete**.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         */\n          $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);\n        }\n        $urlRouter.update(true);\n\n        return $state.current;\n      }, function (error) {\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        $state.transition = null;\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeError\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when an **error occurs** during transition. It's important to note that if you\n         * have any errors in your resolve functions (javascript errors, non-existent services, etc)\n         * they will not throw traditionally. You must listen for this $stateChangeError event to\n         * catch **ALL** errors.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         * @param {Error} error The resolve error object.\n         */\n        evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);\n\n        if (!evt.defaultPrevented) {\n            $urlRouter.update();\n        }\n\n        return $q.reject(error);\n      });\n\n      return transition;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#is\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Similar to {@link ui.router.state.$state#methods_includes $state.includes},\n     * but only checks for the full state name. If params is supplied then it will be\n     * tested for strict equality against the current active params object, so all params\n     * must match with none missing and no extras.\n     *\n     * @example\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // absolute name\n     * $state.is('contact.details.item'); // returns true\n     * $state.is(contactDetailItemStateObject); // returns true\n     *\n     * // relative name (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.is('.item')}\">Item</div>\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like\n     * to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object} -  If `stateOrName` is a relative state name and `options.relative` is set, .is will\n     * test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it is the state.\n     */\n    $state.is = function is(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) { return undefined; }\n      if ($state.$current !== state) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#includes\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method to determine if the current active state is equal to or is the child of the\n     * state stateName. If any params are passed then they will be tested for a match as well.\n     * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n     *\n     * @example\n     * Partial and relative names\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // Using partial names\n     * $state.includes(\"contacts\"); // returns true\n     * $state.includes(\"contacts.details\"); // returns true\n     * $state.includes(\"contacts.details.item\"); // returns true\n     * $state.includes(\"contacts.list\"); // returns false\n     * $state.includes(\"about\"); // returns false\n     *\n     * // Using relative names (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.includes('.item')}\">Item</div>\n     * </pre>\n     *\n     * Basic globbing patterns\n     * <pre>\n     * $state.$current.name = 'contacts.details.item.url';\n     *\n     * $state.includes(\"*.details.*.*\"); // returns true\n     * $state.includes(\"*.details.**\"); // returns true\n     * $state.includes(\"**.item.**\"); // returns true\n     * $state.includes(\"*.details.item.url\"); // returns true\n     * $state.includes(\"*.details.*.url\"); // returns true\n     * $state.includes(\"*.details.*\"); // returns false\n     * $state.includes(\"item.**\"); // returns false\n     * </pre>\n     *\n     * @param {string} stateOrName A partial name, relative name, or glob pattern\n     * to be searched for within the current state name.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`,\n     * that you'd like to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object=} -  If `stateOrName` is a relative state reference and `options.relative` is set,\n     * .includes will test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it does include the state\n     */\n    $state.includes = function includes(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      if (isString(stateOrName) && isGlob(stateOrName)) {\n        if (!doesStateMatchGlob(stateOrName)) {\n          return false;\n        }\n        stateOrName = $state.$current.name;\n      }\n\n      var state = findState(stateOrName, options.relative);\n      if (!isDefined(state)) { return undefined; }\n      if (!isDefined($state.$current.includes[state.name])) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;\n    };\n\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#href\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A url generation method that returns the compiled url for the given state populated with the given params.\n     *\n     * @example\n     * <pre>\n     * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.\n     * @param {object=} params An object of parameter values to fill the state's required parameters.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`lossy`** - {boolean=true} -  If true, and if there is no url associated with the state provided in the\n     *    first parameter, then the constructed href url will be built from the first navigable ancestor (aka\n     *    ancestor with a valid url).\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n     * \n     * @returns {string} compiled state url\n     */\n    $state.href = function href(stateOrName, params, options) {\n      options = extend({\n        lossy:    true,\n        inherit:  true,\n        absolute: false,\n        relative: $state.$current\n      }, options || {});\n\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) return null;\n      if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);\n      \n      var nav = (state && options.lossy) ? state.navigable : state;\n\n      if (!nav || nav.url === undefined || nav.url === null) {\n        return null;\n      }\n      return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {\n        absolute: options.absolute\n      });\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#get\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Returns the state configuration object for any specific state or all states.\n     *\n     * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for\n     * the requested state. If not provided, returns an array of ALL state configs.\n     * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.\n     * @returns {Object|Array} State configuration object or array of all objects.\n     */\n    $state.get = function (stateOrName, context) {\n      if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });\n      var state = findState(stateOrName, context || $state.$current);\n      return (state && state.self) ? state.self : null;\n    };\n\n    function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {\n      // Make a restricted $stateParams with only the parameters that apply to this state if\n      // necessary. In addition to being available to the controller and onEnter/onExit callbacks,\n      // we also need $stateParams to be available for any $injector calls we make during the\n      // dependency resolution process.\n      var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);\n      var locals = { $stateParams: $stateParams };\n\n      // Resolve 'global' dependencies for the state, i.e. those not specific to a view.\n      // We're also including $stateParams in this; that way the parameters are restricted\n      // to the set that should be visible to the state, and are independent of when we update\n      // the global $state and $stateParams values.\n      dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);\n      var promises = [dst.resolve.then(function (globals) {\n        dst.globals = globals;\n      })];\n      if (inherited) promises.push(inherited);\n\n      function resolveViews() {\n        var viewsPromises = [];\n\n        // Resolve template and dependencies for all views.\n        forEach(state.views, function (view, name) {\n          var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});\n          injectables.$template = [ function () {\n            return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';\n          }];\n\n          viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {\n            // References to the controller (only instantiated at link time)\n            if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {\n              var injectLocals = angular.extend({}, injectables, dst.globals);\n              result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);\n            } else {\n              result.$$controller = view.controller;\n            }\n            // Provide access to the state itself for internal use\n            result.$$state = state;\n            result.$$controllerAs = view.controllerAs;\n            dst[name] = result;\n          }));\n        });\n\n        return $q.all(viewsPromises).then(function(){\n          return dst.globals;\n        });\n      }\n\n      // Wait for all the promises and then return the activation object\n      return $q.all(promises).then(resolveViews).then(function (values) {\n        return dst;\n      });\n    }\n\n    return $state;\n  }\n\n  function shouldSkipReload(to, toParams, from, fromParams, locals, options) {\n    // Return true if there are no differences in non-search (path/object) params, false if there are differences\n    function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {\n      // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.\n      function notSearchParam(key) {\n        return fromAndToState.params[key].location != \"search\";\n      }\n      var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);\n      var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));\n      var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);\n      return nonQueryParamSet.$$equals(fromParams, toParams);\n    }\n\n    // If reload was not explicitly requested\n    // and we're transitioning to the same state we're already in\n    // and    the locals didn't change\n    //     or they changed in a way that doesn't merit reloading\n    //        (reloadOnParams:false, or reloadOnSearch.false and only search params changed)\n    // Then return true.\n    if (!options.reload && to === from &&\n      (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {\n      return true;\n    }\n  }\n}\n\nangular.module('ui.router.state')\n  .value('$stateParams', {})\n  .provider('$state', $StateProvider);\n\n\n$ViewProvider.$inject = [];\nfunction $ViewProvider() {\n\n  this.$get = $get;\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$view\n   *\n   * @requires ui.router.util.$templateFactory\n   * @requires $rootScope\n   *\n   * @description\n   *\n   */\n  $get.$inject = ['$rootScope', '$templateFactory'];\n  function $get(   $rootScope,   $templateFactory) {\n    return {\n      // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })\n      /**\n       * @ngdoc function\n       * @name ui.router.state.$view#load\n       * @methodOf ui.router.state.$view\n       *\n       * @description\n       *\n       * @param {string} name name\n       * @param {object} options option object.\n       */\n      load: function load(name, options) {\n        var result, defaults = {\n          template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}\n        };\n        options = extend(defaults, options);\n\n        if (options.view) {\n          result = $templateFactory.fromConfig(options.view, options.params, options.locals);\n        }\n        if (result && options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$viewContentLoading\n         * @eventOf ui.router.state.$view\n         * @eventType broadcast on root scope\n         * @description\n         *\n         * Fired once the view **begins loading**, *before* the DOM is rendered.\n         *\n         * @param {Object} event Event object.\n         * @param {Object} viewConfig The view config properties (template, controller, etc).\n         *\n         * @example\n         *\n         * <pre>\n         * $scope.$on('$viewContentLoading',\n         * function(event, viewConfig){\n         *     // Access to all the view config properties.\n         *     // and one special property 'targetView'\n         *     // viewConfig.targetView\n         * });\n         * </pre>\n         */\n          $rootScope.$broadcast('$viewContentLoading', options);\n        }\n        return result;\n      }\n    };\n  }\n}\n\nangular.module('ui.router.state').provider('$view', $ViewProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$uiViewScrollProvider\n *\n * @description\n * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.\n */\nfunction $ViewScrollProvider() {\n\n  var useAnchorScroll = false;\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll\n   * @methodOf ui.router.state.$uiViewScrollProvider\n   *\n   * @description\n   * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for\n   * scrolling based on the url anchor.\n   */\n  this.useAnchorScroll = function () {\n    useAnchorScroll = true;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$uiViewScroll\n   *\n   * @requires $anchorScroll\n   * @requires $timeout\n   *\n   * @description\n   * When called with a jqLite element, it scrolls the element into view (after a\n   * `$timeout` so the DOM has time to refresh).\n   *\n   * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,\n   * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.\n   */\n  this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {\n    if (useAnchorScroll) {\n      return $anchorScroll;\n    }\n\n    return function ($element) {\n      return $timeout(function () {\n        $element[0].scrollIntoView();\n      }, 0, false);\n    };\n  }];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-view\n *\n * @requires ui.router.state.$state\n * @requires $compile\n * @requires $controller\n * @requires $injector\n * @requires ui.router.state.$uiViewScroll\n * @requires $document\n *\n * @restrict ECA\n *\n * @description\n * The ui-view directive tells $state where to place your templates.\n *\n * @param {string=} name A view name. The name should be unique amongst the other views in the\n * same state. You can have views of the same name that live in different states.\n *\n * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window\n * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll\n * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you\n * scroll ui-view elements into view when they are populated during a state activation.\n *\n * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*\n *\n * @param {string=} onload Expression to evaluate whenever the view updates.\n * \n * @example\n * A view can be unnamed or named. \n * <pre>\n * <!-- Unnamed -->\n * <div ui-view></div> \n * \n * <!-- Named -->\n * <div ui-view=\"viewName\"></div>\n * </pre>\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a \n * single view and it is unnamed then you can populate it like so:\n * <pre>\n * <div ui-view></div> \n * $stateProvider.state(\"home\", {\n *   template: \"<h1>HELLO!</h1>\"\n * })\n * </pre>\n * \n * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}\n * config property, by name, in this case an empty name:\n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * But typically you'll only use the views property if you name your view or have more than one view \n * in the same template. There's not really a compelling reason to name a view if its the only one, \n * but you could if you wanted, like so:\n * <pre>\n * <div ui-view=\"main\"></div>\n * </pre> \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"main\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * Really though, you'll use views to set up multiple views:\n * <pre>\n * <div ui-view></div>\n * <div ui-view=\"chart\"></div> \n * <div ui-view=\"data\"></div> \n * </pre>\n * \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     },\n *     \"chart\": {\n *       template: \"<chart_thing/>\"\n *     },\n *     \"data\": {\n *       template: \"<data_thing/>\"\n *     }\n *   }    \n * })\n * </pre>\n *\n * Examples for `autoscroll`:\n *\n * <pre>\n * <!-- If autoscroll present with no expression,\n *      then scroll ui-view into view -->\n * <ui-view autoscroll/>\n *\n * <!-- If autoscroll present with valid expression,\n *      then scroll ui-view into view if expression evaluates to true -->\n * <ui-view autoscroll='true'/>\n * <ui-view autoscroll='false'/>\n * <ui-view autoscroll='scopeVariable'/>\n * </pre>\n */\n$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];\nfunction $ViewDirective(   $state,   $injector,   $uiViewScroll,   $interpolate) {\n\n  function getService() {\n    return ($injector.has) ? function(service) {\n      return $injector.has(service) ? $injector.get(service) : null;\n    } : function(service) {\n      try {\n        return $injector.get(service);\n      } catch (e) {\n        return null;\n      }\n    };\n  }\n\n  var service = getService(),\n      $animator = service('$animator'),\n      $animate = service('$animate');\n\n  // Returns a set of DOM manipulation functions based on which Angular version\n  // it should use\n  function getRenderer(attrs, scope) {\n    var statics = function() {\n      return {\n        enter: function (element, target, cb) { target.after(element); cb(); },\n        leave: function (element, cb) { element.remove(); cb(); }\n      };\n    };\n\n    if ($animate) {\n      return {\n        enter: function(element, target, cb) {\n          var promise = $animate.enter(element, null, target, cb);\n          if (promise && promise.then) promise.then(cb);\n        },\n        leave: function(element, cb) {\n          var promise = $animate.leave(element, cb);\n          if (promise && promise.then) promise.then(cb);\n        }\n      };\n    }\n\n    if ($animator) {\n      var animate = $animator && $animator(scope, attrs);\n\n      return {\n        enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },\n        leave: function(element, cb) { animate.leave(element); cb(); }\n      };\n    }\n\n    return statics();\n  }\n\n  var directive = {\n    restrict: 'ECA',\n    terminal: true,\n    priority: 400,\n    transclude: 'element',\n    compile: function (tElement, tAttrs, $transclude) {\n      return function (scope, $element, attrs) {\n        var previousEl, currentEl, currentScope, latestLocals,\n            onloadExp     = attrs.onload || '',\n            autoScrollExp = attrs.autoscroll,\n            renderer      = getRenderer(attrs, scope);\n\n        scope.$on('$stateChangeSuccess', function() {\n          updateView(false);\n        });\n        scope.$on('$viewContentLoading', function() {\n          updateView(false);\n        });\n\n        updateView(true);\n\n        function cleanupLastView() {\n          if (previousEl) {\n            previousEl.remove();\n            previousEl = null;\n          }\n\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n\n          if (currentEl) {\n            renderer.leave(currentEl, function() {\n              previousEl = null;\n            });\n\n            previousEl = currentEl;\n            currentEl = null;\n          }\n        }\n\n        function updateView(firstTime) {\n          var newScope,\n              name            = getUiViewName(scope, attrs, $element, $interpolate),\n              previousLocals  = name && $state.$current && $state.$current.locals[name];\n\n          if (!firstTime && previousLocals === latestLocals) return; // nothing to do\n          newScope = scope.$new();\n          latestLocals = $state.$current.locals[name];\n\n          var clone = $transclude(newScope, function(clone) {\n            renderer.enter(clone, $element, function onUiViewEnter() {\n              if(currentScope) {\n                currentScope.$emit('$viewContentAnimationEnded');\n              }\n\n              if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {\n                $uiViewScroll(clone);\n              }\n            });\n            cleanupLastView();\n          });\n\n          currentEl = clone;\n          currentScope = newScope;\n          /**\n           * @ngdoc event\n           * @name ui.router.state.directive:ui-view#$viewContentLoaded\n           * @eventOf ui.router.state.directive:ui-view\n           * @eventType emits on ui-view directive scope\n           * @description           *\n           * Fired once the view is **loaded**, *after* the DOM is rendered.\n           *\n           * @param {Object} event Event object.\n           */\n          currentScope.$emit('$viewContentLoaded');\n          currentScope.$eval(onloadExp);\n        }\n      };\n    }\n  };\n\n  return directive;\n}\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];\nfunction $ViewDirectiveFill (  $compile,   $controller,   $state,   $interpolate) {\n  return {\n    restrict: 'ECA',\n    priority: -400,\n    compile: function (tElement) {\n      var initial = tElement.html();\n      return function (scope, $element, attrs) {\n        var current = $state.$current,\n            name = getUiViewName(scope, attrs, $element, $interpolate),\n            locals  = current && current.locals[name];\n\n        if (! locals) {\n          return;\n        }\n\n        $element.data('$uiView', { name: name, state: locals.$$state });\n        $element.html(locals.$template ? locals.$template : initial);\n\n        var link = $compile($element.contents());\n\n        if (locals.$$controller) {\n          locals.$scope = scope;\n          locals.$element = $element;\n          var controller = $controller(locals.$$controller, locals);\n          if (locals.$$controllerAs) {\n            scope[locals.$$controllerAs] = controller;\n          }\n          $element.data('$ngControllerController', controller);\n          $element.children().data('$ngControllerController', controller);\n        }\n\n        link(scope);\n      };\n    }\n  };\n}\n\n/**\n * Shared ui-view code for both directives:\n * Given scope, element, and its attributes, return the view's name\n */\nfunction getUiViewName(scope, attrs, element, $interpolate) {\n  var name = $interpolate(attrs.uiView || attrs.name || '')(scope);\n  var inherited = element.inheritedData('$uiView');\n  return name.indexOf('@') >= 0 ?  name :  (name + '@' + (inherited ? inherited.state.name : ''));\n}\n\nangular.module('ui.router.state').directive('uiView', $ViewDirective);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n\nfunction parseStateRef(ref, current) {\n  var preparsed = ref.match(/^\\s*({[^}]*})\\s*$/), parsed;\n  if (preparsed) ref = current + '(' + preparsed[1] + ')';\n  parsed = ref.replace(/\\n/g, \" \").match(/^([^(]+?)\\s*(\\((.*)\\))?$/);\n  if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n  return { state: parsed[1], paramExpr: parsed[3] || null };\n}\n\nfunction stateContext(el) {\n  var stateData = el.parent().inheritedData('$uiView');\n\n  if (stateData && stateData.state && stateData.state.name) {\n    return stateData.state;\n  }\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref\n *\n * @requires ui.router.state.$state\n * @requires $timeout\n *\n * @restrict A\n *\n * @description\n * A directive that binds a link (`<a>` tag) to a state. If the state has an associated \n * URL, the directive will automatically generate & update the `href` attribute via \n * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking \n * the link will trigger a state transition with optional parameters. \n *\n * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be \n * handled natively by the browser.\n *\n * You can also use relative state paths within ui-sref, just like the relative \n * paths passed to `$state.go()`. You just need to be aware that the path is relative\n * to the state that the link lives in, in other words the state that loaded the \n * template containing the link.\n *\n * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}\n * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,\n * and `reload`.\n *\n * @example\n * Here's an example of how you'd use ui-sref and how it would compile. If you have the \n * following template:\n * <pre>\n * <a ui-sref=\"home\">Home</a> | <a ui-sref=\"about\">About</a> | <a ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a ui-sref=\"contacts.detail({ id: contact.id })\">{{ contact.name }}</a>\n *     </li>\n * </ul>\n * </pre>\n * \n * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):\n * <pre>\n * <a href=\"#/home\" ui-sref=\"home\">Home</a> | <a href=\"#/about\" ui-sref=\"about\">About</a> | <a href=\"#/contacts?page=2\" ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/1\" ui-sref=\"contacts.detail({ id: contact.id })\">Joe</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/2\" ui-sref=\"contacts.detail({ id: contact.id })\">Alice</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/3\" ui-sref=\"contacts.detail({ id: contact.id })\">Bob</a>\n *     </li>\n * </ul>\n *\n * <a ui-sref=\"home\" ui-sref-opts=\"{reload: true}\">Home</a>\n * </pre>\n *\n * @param {string} ui-sref 'stateName' can be any valid absolute or relative state\n * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}\n */\n$StateRefDirective.$inject = ['$state', '$timeout'];\nfunction $StateRefDirective($state, $timeout) {\n  var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];\n\n  return {\n    restrict: 'A',\n    require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n    link: function(scope, element, attrs, uiSrefActive) {\n      var ref = parseStateRef(attrs.uiSref, $state.current.name);\n      var params = null, url = null, base = stateContext(element) || $state.$current;\n      // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n      var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n                 'xlink:href' : 'href';\n      var newHref = null, isAnchor = element.prop(\"tagName\").toUpperCase() === \"A\";\n      var isForm = element[0].nodeName === \"FORM\";\n      var attr = isForm ? \"action\" : hrefKind, nav = true;\n\n      var options = { relative: base, inherit: true };\n      var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};\n\n      angular.forEach(allowedOptions, function(option) {\n        if (option in optionsOverride) {\n          options[option] = optionsOverride[option];\n        }\n      });\n\n      var update = function(newVal) {\n        if (newVal) params = angular.copy(newVal);\n        if (!nav) return;\n\n        newHref = $state.href(ref.state, params, options);\n\n        var activeDirective = uiSrefActive[1] || uiSrefActive[0];\n        if (activeDirective) {\n          activeDirective.$$addStateInfo(ref.state, params);\n        }\n        if (newHref === null) {\n          nav = false;\n          return false;\n        }\n        attrs.$set(attr, newHref);\n      };\n\n      if (ref.paramExpr) {\n        scope.$watch(ref.paramExpr, function(newVal, oldVal) {\n          if (newVal !== params) update(newVal);\n        }, true);\n        params = angular.copy(scope.$eval(ref.paramExpr));\n      }\n      update();\n\n      if (isForm) return;\n\n      element.bind(\"click\", function(e) {\n        var button = e.which || e.button;\n        if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {\n          // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n          var transition = $timeout(function() {\n            $state.go(ref.state, params, options);\n          });\n          e.preventDefault();\n\n          // if the state has no URL, ignore one preventDefault from the <a> directive.\n          var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;\n          e.preventDefault = function() {\n            if (ignorePreventDefaultCount-- <= 0)\n              $timeout.cancel(transition);\n          };\n        }\n      });\n    }\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * A directive working alongside ui-sref to add classes to an element when the\n * related ui-sref directive's state is active, and removing them when it is inactive.\n * The primary use-case is to simplify the special appearance of navigation menus\n * relying on `ui-sref`, by having the \"active\" state's menu button appear different,\n * distinguishing it from the inactive menu items.\n *\n * ui-sref-active can live on the same element as ui-sref or on a parent element. The first\n * ui-sref-active found at the same level or above the ui-sref will be used.\n *\n * Will activate when the ui-sref's target state or any child state is active. If you\n * need to activate only when the ui-sref target state is active and *not* any of\n * it's children, then you will use\n * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}\n *\n * @example\n * Given the following template:\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item\">\n *     <a href ui-sref=\"app.user({user: 'bilbobaggins'})\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n *\n * When the app state is \"app.user\" (or any children states), and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item active\">\n *     <a ui-sref=\"app.user({user: 'bilbobaggins'})\" href=\"/users/bilbobaggins\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n * The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * Multiple classes may be specified in a space-separated format:\n * <pre>\n * <ul>\n *   <li ui-sref-active='class1 class2 class3'>\n *     <a ui-sref=\"app.user\">link</a>\n *   </li>\n * </ul>\n * </pre>\n */\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active-eq\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate\n * when the exact target state used in the `ui-sref` is active; no child states.\n *\n */\n$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];\nfunction $StateRefActiveDirective($state, $stateParams, $interpolate) {\n  return  {\n    restrict: \"A\",\n    controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {\n      var states = [], activeClass;\n\n      // There probably isn't much point in $observing this\n      // uiSrefActive and uiSrefActiveEq share the same directive object with some\n      // slight difference in logic routing\n      activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);\n\n      // Allow uiSref to communicate with uiSrefActive[Equals]\n      this.$$addStateInfo = function (newState, newParams) {\n        var state = $state.get(newState, stateContext($element));\n\n        states.push({\n          state: state || { name: newState },\n          params: newParams\n        });\n\n        update();\n      };\n\n      $scope.$on('$stateChangeSuccess', update);\n\n      // Update route state\n      function update() {\n        if (anyMatch()) {\n          $element.addClass(activeClass);\n        } else {\n          $element.removeClass(activeClass);\n        }\n      }\n\n      function anyMatch() {\n        for (var i = 0; i < states.length; i++) {\n          if (isMatch(states[i].state, states[i].params)) {\n            return true;\n          }\n        }\n        return false;\n      }\n\n      function isMatch(state, params) {\n        if (typeof $attrs.uiSrefActiveEq !== 'undefined') {\n          return $state.is(state.name, params);\n        } else {\n          return $state.includes(state.name, params);\n        }\n      }\n    }]\n  };\n}\n\nangular.module('ui.router.state')\n  .directive('uiSref', $StateRefDirective)\n  .directive('uiSrefActive', $StateRefActiveDirective)\n  .directive('uiSrefActiveEq', $StateRefActiveDirective);\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:isState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_is $state.is(\"stateName\")}.\n */\n$IsStateFilter.$inject = ['$state'];\nfunction $IsStateFilter($state) {\n  var isFilter = function (state) {\n    return $state.is(state);\n  };\n  isFilter.$stateful = true;\n  return isFilter;\n}\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:includedByState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.\n */\n$IncludedByStateFilter.$inject = ['$state'];\nfunction $IncludedByStateFilter($state) {\n  var includesFilter = function (state) {\n    return $state.includes(state);\n  };\n  includesFilter.$stateful = true;\n  return  includesFilter;\n}\n\nangular.module('ui.router.state')\n  .filter('isState', $IsStateFilter)\n  .filter('includedByState', $IncludedByStateFilter);\n})(window, window.angular);"
  },
  {
    "path": "examples/client/vendor/angular.js",
    "content": "/**\n * @license AngularJS v1.4.4\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, document, undefined) {'use strict';\n\n/**\n * @description\n *\n * This object provides a utility for producing rich Error messages within\n * Angular. It can be called as follows:\n *\n * var exampleMinErr = minErr('example');\n * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);\n *\n * The above creates an instance of minErr in the example namespace. The\n * resulting error will have a namespaced error code of example.one.  The\n * resulting error will replace {0} with the value of foo, and {1} with the\n * value of bar. The object is not restricted in the number of arguments it can\n * take.\n *\n * If fewer arguments are specified than necessary for interpolation, the extra\n * interpolation markers will be preserved in the final string.\n *\n * Since data will be parsed statically during a build step, some restrictions\n * are applied with respect to how minErr instances are created and called.\n * Instances should have names of the form namespaceMinErr for a minErr created\n * using minErr('namespace') . Error codes, namespaces and template strings\n * should all be static strings, not variables or general expressions.\n *\n * @param {string} module The namespace to use for the new minErr instance.\n * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning\n *   error from returned function, for cases when a particular type of error is useful.\n * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance\n */\n\nfunction minErr(module, ErrorConstructor) {\n  ErrorConstructor = ErrorConstructor || Error;\n  return function() {\n    var SKIP_INDEXES = 2;\n\n    var templateArgs = arguments,\n      code = templateArgs[0],\n      message = '[' + (module ? module + ':' : '') + code + '] ',\n      template = templateArgs[1],\n      paramPrefix, i;\n\n    message += template.replace(/\\{\\d+\\}/g, function(match) {\n      var index = +match.slice(1, -1),\n        shiftedIndex = index + SKIP_INDEXES;\n\n      if (shiftedIndex < templateArgs.length) {\n        return toDebugString(templateArgs[shiftedIndex]);\n      }\n\n      return match;\n    });\n\n    message += '\\nhttp://errors.angularjs.org/1.4.4/' +\n      (module ? module + '/' : '') + code;\n\n    for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {\n      message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +\n        encodeURIComponent(toDebugString(templateArgs[i]));\n    }\n\n    return new ErrorConstructor(message);\n  };\n}\n\n/* We need to tell jshint what variables are being exported */\n/* global angular: true,\n  msie: true,\n  jqLite: true,\n  jQuery: true,\n  slice: true,\n  splice: true,\n  push: true,\n  toString: true,\n  ngMinErr: true,\n  angularModule: true,\n  uid: true,\n  REGEX_STRING_REGEXP: true,\n  VALIDITY_STATE_PROPERTY: true,\n\n  lowercase: true,\n  uppercase: true,\n  manualLowercase: true,\n  manualUppercase: true,\n  nodeName_: true,\n  isArrayLike: true,\n  forEach: true,\n  forEachSorted: true,\n  reverseParams: true,\n  nextUid: true,\n  setHashKey: true,\n  extend: true,\n  toInt: true,\n  inherit: true,\n  merge: true,\n  noop: true,\n  identity: true,\n  valueFn: true,\n  isUndefined: true,\n  isDefined: true,\n  isObject: true,\n  isBlankObject: true,\n  isString: true,\n  isNumber: true,\n  isDate: true,\n  isArray: true,\n  isFunction: true,\n  isRegExp: true,\n  isWindow: true,\n  isScope: true,\n  isFile: true,\n  isFormData: true,\n  isBlob: true,\n  isBoolean: true,\n  isPromiseLike: true,\n  trim: true,\n  escapeForRegexp: true,\n  isElement: true,\n  makeMap: true,\n  includes: true,\n  arrayRemove: true,\n  copy: true,\n  shallowCopy: true,\n  equals: true,\n  csp: true,\n  jq: true,\n  concat: true,\n  sliceArgs: true,\n  bind: true,\n  toJsonReplacer: true,\n  toJson: true,\n  fromJson: true,\n  convertTimezoneToLocal: true,\n  timezoneToOffset: true,\n  startingTag: true,\n  tryDecodeURIComponent: true,\n  parseKeyValue: true,\n  toKeyValue: true,\n  encodeUriSegment: true,\n  encodeUriQuery: true,\n  angularInit: true,\n  bootstrap: true,\n  getTestability: true,\n  snake_case: true,\n  bindJQuery: true,\n  assertArg: true,\n  assertArgFn: true,\n  assertNotHasOwnProperty: true,\n  getter: true,\n  getBlockNodes: true,\n  hasOwnProperty: true,\n  createMap: true,\n\n  NODE_TYPE_ELEMENT: true,\n  NODE_TYPE_ATTRIBUTE: true,\n  NODE_TYPE_TEXT: true,\n  NODE_TYPE_COMMENT: true,\n  NODE_TYPE_DOCUMENT: true,\n  NODE_TYPE_DOCUMENT_FRAGMENT: true,\n*/\n\n////////////////////////////////////\n\n/**\n * @ngdoc module\n * @name ng\n * @module ng\n * @description\n *\n * # ng (core module)\n * The ng module is loaded by default when an AngularJS application is started. The module itself\n * contains the essential components for an AngularJS application to function. The table below\n * lists a high level breakdown of each of the services/factories, filters, directives and testing\n * components available within this core module.\n *\n * <div doc-module-components=\"ng\"></div>\n */\n\nvar REGEX_STRING_REGEXP = /^\\/(.+)\\/([a-z]*)$/;\n\n// The name of a form control's ValidityState property.\n// This is used so that it's possible for internal tests to create mock ValidityStates.\nvar VALIDITY_STATE_PROPERTY = 'validity';\n\n/**\n * @ngdoc function\n * @name angular.lowercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to lowercase.\n * @param {string} string String to be converted to lowercase.\n * @returns {string} Lowercased string.\n */\nvar lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * @ngdoc function\n * @name angular.uppercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to uppercase.\n * @param {string} string String to be converted to uppercase.\n * @returns {string} Uppercased string.\n */\nvar uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};\n\n\nvar manualLowercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})\n      : s;\n};\nvar manualUppercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})\n      : s;\n};\n\n\n// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish\n// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods\n// with correct but slower alternatives.\nif ('i' !== 'I'.toLowerCase()) {\n  lowercase = manualLowercase;\n  uppercase = manualUppercase;\n}\n\n\nvar\n    msie,             // holds major version number for IE, or NaN if UA is not IE.\n    jqLite,           // delay binding since jQuery could be loaded after us.\n    jQuery,           // delay binding\n    slice             = [].slice,\n    splice            = [].splice,\n    push              = [].push,\n    toString          = Object.prototype.toString,\n    getPrototypeOf    = Object.getPrototypeOf,\n    ngMinErr          = minErr('ng'),\n\n    /** @name angular */\n    angular           = window.angular || (window.angular = {}),\n    angularModule,\n    uid               = 0;\n\n/**\n * documentMode is an IE-only property\n * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx\n */\nmsie = document.documentMode;\n\n\n/**\n * @private\n * @param {*} obj\n * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,\n *                   String ...)\n */\nfunction isArrayLike(obj) {\n  if (obj == null || isWindow(obj)) {\n    return false;\n  }\n\n  // Support: iOS 8.2 (not reproducible in simulator)\n  // \"length\" in obj used to prevent JIT error (gh-11508)\n  var length = \"length\" in Object(obj) && obj.length;\n\n  if (obj.nodeType === NODE_TYPE_ELEMENT && length) {\n    return true;\n  }\n\n  return isString(obj) || isArray(obj) || length === 0 ||\n         typeof length === 'number' && length > 0 && (length - 1) in obj;\n}\n\n/**\n * @ngdoc function\n * @name angular.forEach\n * @module ng\n * @kind function\n *\n * @description\n * Invokes the `iterator` function once for each item in `obj` collection, which can be either an\n * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`\n * is the value of an object property or an array element, `key` is the object property key or\n * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.\n *\n * It is worth noting that `.forEach` does not iterate over inherited properties because it filters\n * using the `hasOwnProperty` method.\n *\n * Unlike ES262's\n * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),\n * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just\n * return the value provided.\n *\n   ```js\n     var values = {name: 'misko', gender: 'male'};\n     var log = [];\n     angular.forEach(values, function(value, key) {\n       this.push(key + ': ' + value);\n     }, log);\n     expect(log).toEqual(['name: misko', 'gender: male']);\n   ```\n *\n * @param {Object|Array} obj Object to iterate over.\n * @param {Function} iterator Iterator function.\n * @param {Object=} context Object to become context (`this`) for the iterator function.\n * @returns {Object|Array} Reference to `obj`.\n */\n\nfunction forEach(obj, iterator, context) {\n  var key, length;\n  if (obj) {\n    if (isFunction(obj)) {\n      for (key in obj) {\n        // Need to check if hasOwnProperty exists,\n        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function\n        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (isArray(obj) || isArrayLike(obj)) {\n      var isPrimitive = typeof obj !== 'object';\n      for (key = 0, length = obj.length; key < length; key++) {\n        if (isPrimitive || key in obj) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (obj.forEach && obj.forEach !== forEach) {\n        obj.forEach(iterator, context, obj);\n    } else if (isBlankObject(obj)) {\n      // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty\n      for (key in obj) {\n        iterator.call(context, obj[key], key, obj);\n      }\n    } else if (typeof obj.hasOwnProperty === 'function') {\n      // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed\n      for (key in obj) {\n        if (obj.hasOwnProperty(key)) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else {\n      // Slow path for objects which do not have a method `hasOwnProperty`\n      for (key in obj) {\n        if (hasOwnProperty.call(obj, key)) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nfunction forEachSorted(obj, iterator, context) {\n  var keys = Object.keys(obj).sort();\n  for (var i = 0; i < keys.length; i++) {\n    iterator.call(context, obj[keys[i]], keys[i]);\n  }\n  return keys;\n}\n\n\n/**\n * when using forEach the params are value, key, but it is often useful to have key, value.\n * @param {function(string, *)} iteratorFn\n * @returns {function(*, string)}\n */\nfunction reverseParams(iteratorFn) {\n  return function(value, key) { iteratorFn(key, value); };\n}\n\n/**\n * A consistent way of creating unique IDs in angular.\n *\n * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before\n * we hit number precision issues in JavaScript.\n *\n * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M\n *\n * @returns {number} an unique alpha-numeric string\n */\nfunction nextUid() {\n  return ++uid;\n}\n\n\n/**\n * Set or clear the hashkey for an object.\n * @param obj object\n * @param h the hashkey (!truthy to delete the hashkey)\n */\nfunction setHashKey(obj, h) {\n  if (h) {\n    obj.$$hashKey = h;\n  } else {\n    delete obj.$$hashKey;\n  }\n}\n\n\nfunction baseExtend(dst, objs, deep) {\n  var h = dst.$$hashKey;\n\n  for (var i = 0, ii = objs.length; i < ii; ++i) {\n    var obj = objs[i];\n    if (!isObject(obj) && !isFunction(obj)) continue;\n    var keys = Object.keys(obj);\n    for (var j = 0, jj = keys.length; j < jj; j++) {\n      var key = keys[j];\n      var src = obj[key];\n\n      if (deep && isObject(src)) {\n        if (isDate(src)) {\n          dst[key] = new Date(src.valueOf());\n        } else if (isRegExp(src)) {\n          dst[key] = new RegExp(src);\n        } else {\n          if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};\n          baseExtend(dst[key], [src], true);\n        }\n      } else {\n        dst[key] = src;\n      }\n    }\n  }\n\n  setHashKey(dst, h);\n  return dst;\n}\n\n/**\n * @ngdoc function\n * @name angular.extend\n * @module ng\n * @kind function\n *\n * @description\n * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.\n *\n * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use\n * {@link angular.merge} for this.\n *\n * @param {Object} dst Destination object.\n * @param {...Object} src Source object(s).\n * @returns {Object} Reference to `dst`.\n */\nfunction extend(dst) {\n  return baseExtend(dst, slice.call(arguments, 1), false);\n}\n\n\n/**\n* @ngdoc function\n* @name angular.merge\n* @module ng\n* @kind function\n*\n* @description\n* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.\n*\n* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source\n* objects, performing a deep copy.\n*\n* @param {Object} dst Destination object.\n* @param {...Object} src Source object(s).\n* @returns {Object} Reference to `dst`.\n*/\nfunction merge(dst) {\n  return baseExtend(dst, slice.call(arguments, 1), true);\n}\n\n\n\nfunction toInt(str) {\n  return parseInt(str, 10);\n}\n\n\nfunction inherit(parent, extra) {\n  return extend(Object.create(parent), extra);\n}\n\n/**\n * @ngdoc function\n * @name angular.noop\n * @module ng\n * @kind function\n *\n * @description\n * A function that performs no operations. This function can be useful when writing code in the\n * functional style.\n   ```js\n     function foo(callback) {\n       var result = calculateResult();\n       (callback || angular.noop)(result);\n     }\n   ```\n */\nfunction noop() {}\nnoop.$inject = [];\n\n\n/**\n * @ngdoc function\n * @name angular.identity\n * @module ng\n * @kind function\n *\n * @description\n * A function that returns its first argument. This function is useful when writing code in the\n * functional style.\n *\n   ```js\n     function transformer(transformationFn, value) {\n       return (transformationFn || angular.identity)(value);\n     };\n   ```\n  * @param {*} value to be returned.\n  * @returns {*} the value passed in.\n */\nfunction identity($) {return $;}\nidentity.$inject = [];\n\n\nfunction valueFn(value) {return function() {return value;};}\n\nfunction hasCustomToString(obj) {\n  return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isUndefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is undefined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is undefined.\n */\nfunction isUndefined(value) {return typeof value === 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is defined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is defined.\n */\nfunction isDefined(value) {return typeof value !== 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isObject\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not\n * considered to be objects. Note that JavaScript arrays are objects.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Object` but not `null`.\n */\nfunction isObject(value) {\n  // http://jsperf.com/isobject4\n  return value !== null && typeof value === 'object';\n}\n\n\n/**\n * Determine if a value is an object with a null prototype\n *\n * @returns {boolean} True if `value` is an `Object` with a null prototype\n */\nfunction isBlankObject(value) {\n  return value !== null && typeof value === 'object' && !getPrototypeOf(value);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isString\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `String`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `String`.\n */\nfunction isString(value) {return typeof value === 'string';}\n\n\n/**\n * @ngdoc function\n * @name angular.isNumber\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Number`.\n *\n * This includes the \"special\" numbers `NaN`, `+Infinity` and `-Infinity`.\n *\n * If you wish to exclude these then you can use the native\n * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)\n * method.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Number`.\n */\nfunction isNumber(value) {return typeof value === 'number';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDate\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a value is a date.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Date`.\n */\nfunction isDate(value) {\n  return toString.call(value) === '[object Date]';\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isArray\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Array`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Array`.\n */\nvar isArray = Array.isArray;\n\n/**\n * @ngdoc function\n * @name angular.isFunction\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Function`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Function`.\n */\nfunction isFunction(value) {return typeof value === 'function';}\n\n\n/**\n * Determines if a value is a regular expression object.\n *\n * @private\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `RegExp`.\n */\nfunction isRegExp(value) {\n  return toString.call(value) === '[object RegExp]';\n}\n\n\n/**\n * Checks if `obj` is a window object.\n *\n * @private\n * @param {*} obj Object to check\n * @returns {boolean} True if `obj` is a window obj.\n */\nfunction isWindow(obj) {\n  return obj && obj.window === obj;\n}\n\n\nfunction isScope(obj) {\n  return obj && obj.$evalAsync && obj.$watch;\n}\n\n\nfunction isFile(obj) {\n  return toString.call(obj) === '[object File]';\n}\n\n\nfunction isFormData(obj) {\n  return toString.call(obj) === '[object FormData]';\n}\n\n\nfunction isBlob(obj) {\n  return toString.call(obj) === '[object Blob]';\n}\n\n\nfunction isBoolean(value) {\n  return typeof value === 'boolean';\n}\n\n\nfunction isPromiseLike(obj) {\n  return obj && isFunction(obj.then);\n}\n\n\nvar TYPED_ARRAY_REGEXP = /^\\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\\]$/;\nfunction isTypedArray(value) {\n  return TYPED_ARRAY_REGEXP.test(toString.call(value));\n}\n\n\nvar trim = function(value) {\n  return isString(value) ? value.trim() : value;\n};\n\n// Copied from:\n// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021\n// Prereq: s is a string.\nvar escapeForRegexp = function(s) {\n  return s.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1').\n           replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * @ngdoc function\n * @name angular.isElement\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a DOM element (or wrapped jQuery element).\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).\n */\nfunction isElement(node) {\n  return !!(node &&\n    (node.nodeName  // we are a direct element\n    || (node.prop && node.attr && node.find)));  // we have an on and find method part of jQuery API\n}\n\n/**\n * @param str 'key1,key2,...'\n * @returns {object} in the form of {key1:true, key2:true, ...}\n */\nfunction makeMap(str) {\n  var obj = {}, items = str.split(\",\"), i;\n  for (i = 0; i < items.length; i++) {\n    obj[items[i]] = true;\n  }\n  return obj;\n}\n\n\nfunction nodeName_(element) {\n  return lowercase(element.nodeName || (element[0] && element[0].nodeName));\n}\n\nfunction includes(array, obj) {\n  return Array.prototype.indexOf.call(array, obj) != -1;\n}\n\nfunction arrayRemove(array, value) {\n  var index = array.indexOf(value);\n  if (index >= 0) {\n    array.splice(index, 1);\n  }\n  return index;\n}\n\n/**\n * @ngdoc function\n * @name angular.copy\n * @module ng\n * @kind function\n *\n * @description\n * Creates a deep copy of `source`, which should be an object or an array.\n *\n * * If no destination is supplied, a copy of the object or array is created.\n * * If a destination is provided, all of its elements (for arrays) or properties (for objects)\n *   are deleted and then all elements/properties from the source are copied to it.\n * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.\n * * If `source` is identical to 'destination' an exception will be thrown.\n *\n * @param {*} source The source that will be used to make a copy.\n *                   Can be any type, including primitives, `null`, and `undefined`.\n * @param {(Object|Array)=} destination Destination into which the source is copied. If\n *     provided, must be of the same type as `source`.\n * @returns {*} The copy or updated `destination`, if `destination` was specified.\n *\n * @example\n <example module=\"copyExample\">\n <file name=\"index.html\">\n <div ng-controller=\"ExampleController\">\n <form novalidate class=\"simple-form\">\n Name: <input type=\"text\" ng-model=\"user.name\" /><br />\n E-mail: <input type=\"email\" ng-model=\"user.email\" /><br />\n Gender: <input type=\"radio\" ng-model=\"user.gender\" value=\"male\" />male\n <input type=\"radio\" ng-model=\"user.gender\" value=\"female\" />female<br />\n <button ng-click=\"reset()\">RESET</button>\n <button ng-click=\"update(user)\">SAVE</button>\n </form>\n <pre>form = {{user | json}}</pre>\n <pre>master = {{master | json}}</pre>\n </div>\n\n <script>\n  angular.module('copyExample', [])\n    .controller('ExampleController', ['$scope', function($scope) {\n      $scope.master= {};\n\n      $scope.update = function(user) {\n        // Example with 1 argument\n        $scope.master= angular.copy(user);\n      };\n\n      $scope.reset = function() {\n        // Example with 2 arguments\n        angular.copy($scope.master, $scope.user);\n      };\n\n      $scope.reset();\n    }]);\n </script>\n </file>\n </example>\n */\nfunction copy(source, destination, stackSource, stackDest) {\n  if (isWindow(source) || isScope(source)) {\n    throw ngMinErr('cpws',\n      \"Can't copy! Making copies of Window or Scope instances is not supported.\");\n  }\n  if (isTypedArray(destination)) {\n    throw ngMinErr('cpta',\n      \"Can't copy! TypedArray destination cannot be mutated.\");\n  }\n\n  if (!destination) {\n    destination = source;\n    if (isObject(source)) {\n      var index;\n      if (stackSource && (index = stackSource.indexOf(source)) !== -1) {\n        return stackDest[index];\n      }\n\n      // TypedArray, Date and RegExp have specific copy functionality and must be\n      // pushed onto the stack before returning.\n      // Array and other objects create the base object and recurse to copy child\n      // objects. The array/object will be pushed onto the stack when recursed.\n      if (isArray(source)) {\n        return copy(source, [], stackSource, stackDest);\n      } else if (isTypedArray(source)) {\n        destination = new source.constructor(source);\n      } else if (isDate(source)) {\n        destination = new Date(source.getTime());\n      } else if (isRegExp(source)) {\n        destination = new RegExp(source.source, source.toString().match(/[^\\/]*$/)[0]);\n        destination.lastIndex = source.lastIndex;\n      } else {\n        var emptyObject = Object.create(getPrototypeOf(source));\n        return copy(source, emptyObject, stackSource, stackDest);\n      }\n\n      if (stackDest) {\n        stackSource.push(source);\n        stackDest.push(destination);\n      }\n    }\n  } else {\n    if (source === destination) throw ngMinErr('cpi',\n      \"Can't copy! Source and destination are identical.\");\n\n    stackSource = stackSource || [];\n    stackDest = stackDest || [];\n\n    if (isObject(source)) {\n      stackSource.push(source);\n      stackDest.push(destination);\n    }\n\n    var result, key;\n    if (isArray(source)) {\n      destination.length = 0;\n      for (var i = 0; i < source.length; i++) {\n        destination.push(copy(source[i], null, stackSource, stackDest));\n      }\n    } else {\n      var h = destination.$$hashKey;\n      if (isArray(destination)) {\n        destination.length = 0;\n      } else {\n        forEach(destination, function(value, key) {\n          delete destination[key];\n        });\n      }\n      if (isBlankObject(source)) {\n        // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty\n        for (key in source) {\n          destination[key] = copy(source[key], null, stackSource, stackDest);\n        }\n      } else if (source && typeof source.hasOwnProperty === 'function') {\n        // Slow path, which must rely on hasOwnProperty\n        for (key in source) {\n          if (source.hasOwnProperty(key)) {\n            destination[key] = copy(source[key], null, stackSource, stackDest);\n          }\n        }\n      } else {\n        // Slowest path --- hasOwnProperty can't be called as a method\n        for (key in source) {\n          if (hasOwnProperty.call(source, key)) {\n            destination[key] = copy(source[key], null, stackSource, stackDest);\n          }\n        }\n      }\n      setHashKey(destination,h);\n    }\n  }\n  return destination;\n}\n\n/**\n * Creates a shallow copy of an object, an array or a primitive.\n *\n * Assumes that there are no proto properties for objects.\n */\nfunction shallowCopy(src, dst) {\n  if (isArray(src)) {\n    dst = dst || [];\n\n    for (var i = 0, ii = src.length; i < ii; i++) {\n      dst[i] = src[i];\n    }\n  } else if (isObject(src)) {\n    dst = dst || {};\n\n    for (var key in src) {\n      if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n        dst[key] = src[key];\n      }\n    }\n  }\n\n  return dst || src;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.equals\n * @module ng\n * @kind function\n *\n * @description\n * Determines if two objects or two values are equivalent. Supports value types, regular\n * expressions, arrays and objects.\n *\n * Two objects or values are considered equivalent if at least one of the following is true:\n *\n * * Both objects or values pass `===` comparison.\n * * Both objects or values are of the same type and all of their properties are equal by\n *   comparing them with `angular.equals`.\n * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)\n * * Both values represent the same regular expression (In JavaScript,\n *   /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual\n *   representation matches).\n *\n * During a property comparison, properties of `function` type and properties with names\n * that begin with `$` are ignored.\n *\n * Scope and DOMWindow objects are being compared only by identify (`===`).\n *\n * @param {*} o1 Object or value to compare.\n * @param {*} o2 Object or value to compare.\n * @returns {boolean} True if arguments are equal.\n */\nfunction equals(o1, o2) {\n  if (o1 === o2) return true;\n  if (o1 === null || o2 === null) return false;\n  if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n  var t1 = typeof o1, t2 = typeof o2, length, key, keySet;\n  if (t1 == t2) {\n    if (t1 == 'object') {\n      if (isArray(o1)) {\n        if (!isArray(o2)) return false;\n        if ((length = o1.length) == o2.length) {\n          for (key = 0; key < length; key++) {\n            if (!equals(o1[key], o2[key])) return false;\n          }\n          return true;\n        }\n      } else if (isDate(o1)) {\n        if (!isDate(o2)) return false;\n        return equals(o1.getTime(), o2.getTime());\n      } else if (isRegExp(o1)) {\n        return isRegExp(o2) ? o1.toString() == o2.toString() : false;\n      } else {\n        if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||\n          isArray(o2) || isDate(o2) || isRegExp(o2)) return false;\n        keySet = createMap();\n        for (key in o1) {\n          if (key.charAt(0) === '$' || isFunction(o1[key])) continue;\n          if (!equals(o1[key], o2[key])) return false;\n          keySet[key] = true;\n        }\n        for (key in o2) {\n          if (!(key in keySet) &&\n              key.charAt(0) !== '$' &&\n              o2[key] !== undefined &&\n              !isFunction(o2[key])) return false;\n        }\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nvar csp = function() {\n  if (!isDefined(csp.rules)) {\n\n\n    var ngCspElement = (document.querySelector('[ng-csp]') ||\n                    document.querySelector('[data-ng-csp]'));\n\n    if (ngCspElement) {\n      var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||\n                    ngCspElement.getAttribute('data-ng-csp');\n      csp.rules = {\n        noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),\n        noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)\n      };\n    } else {\n      csp.rules = {\n        noUnsafeEval: noUnsafeEval(),\n        noInlineStyle: false\n      };\n    }\n  }\n\n  return csp.rules;\n\n  function noUnsafeEval() {\n    try {\n      /* jshint -W031, -W054 */\n      new Function('');\n      /* jshint +W031, +W054 */\n      return false;\n    } catch (e) {\n      return true;\n    }\n  }\n};\n\n/**\n * @ngdoc directive\n * @module ng\n * @name ngJq\n *\n * @element ANY\n * @param {string=} ngJq the name of the library available under `window`\n * to be used for angular.element\n * @description\n * Use this directive to force the angular.element library.  This should be\n * used to force either jqLite by leaving ng-jq blank or setting the name of\n * the jquery variable under window (eg. jQuery).\n *\n * Since angular looks for this directive when it is loaded (doesn't wait for the\n * DOMContentLoaded event), it must be placed on an element that comes before the script\n * which loads angular. Also, only the first instance of `ng-jq` will be used and all\n * others ignored.\n *\n * @example\n * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.\n ```html\n <!doctype html>\n <html ng-app ng-jq>\n ...\n ...\n </html>\n ```\n * @example\n * This example shows how to use a jQuery based library of a different name.\n * The library name must be available at the top most 'window'.\n ```html\n <!doctype html>\n <html ng-app ng-jq=\"jQueryLib\">\n ...\n ...\n </html>\n ```\n */\nvar jq = function() {\n  if (isDefined(jq.name_)) return jq.name_;\n  var el;\n  var i, ii = ngAttrPrefixes.length, prefix, name;\n  for (i = 0; i < ii; ++i) {\n    prefix = ngAttrPrefixes[i];\n    if (el = document.querySelector('[' + prefix.replace(':', '\\\\:') + 'jq]')) {\n      name = el.getAttribute(prefix + 'jq');\n      break;\n    }\n  }\n\n  return (jq.name_ = name);\n};\n\nfunction concat(array1, array2, index) {\n  return array1.concat(slice.call(array2, index));\n}\n\nfunction sliceArgs(args, startIndex) {\n  return slice.call(args, startIndex || 0);\n}\n\n\n/* jshint -W101 */\n/**\n * @ngdoc function\n * @name angular.bind\n * @module ng\n * @kind function\n *\n * @description\n * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for\n * `fn`). You can supply optional `args` that are prebound to the function. This feature is also\n * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as\n * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).\n *\n * @param {Object} self Context which `fn` should be evaluated in.\n * @param {function()} fn Function to be bound.\n * @param {...*} args Optional arguments to be prebound to the `fn` function call.\n * @returns {function()} Function that wraps the `fn` with all the specified bindings.\n */\n/* jshint +W101 */\nfunction bind(self, fn) {\n  var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\n  if (isFunction(fn) && !(fn instanceof RegExp)) {\n    return curryArgs.length\n      ? function() {\n          return arguments.length\n            ? fn.apply(self, concat(curryArgs, arguments, 0))\n            : fn.apply(self, curryArgs);\n        }\n      : function() {\n          return arguments.length\n            ? fn.apply(self, arguments)\n            : fn.call(self);\n        };\n  } else {\n    // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)\n    return fn;\n  }\n}\n\n\nfunction toJsonReplacer(key, value) {\n  var val = value;\n\n  if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {\n    val = undefined;\n  } else if (isWindow(value)) {\n    val = '$WINDOW';\n  } else if (value &&  document === value) {\n    val = '$DOCUMENT';\n  } else if (isScope(value)) {\n    val = '$SCOPE';\n  }\n\n  return val;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.toJson\n * @module ng\n * @kind function\n *\n * @description\n * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be\n * stripped since angular uses this notation internally.\n *\n * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.\n * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.\n *    If set to an integer, the JSON output will contain that many spaces per indentation.\n * @returns {string|undefined} JSON-ified string representing `obj`.\n */\nfunction toJson(obj, pretty) {\n  if (typeof obj === 'undefined') return undefined;\n  if (!isNumber(pretty)) {\n    pretty = pretty ? 2 : null;\n  }\n  return JSON.stringify(obj, toJsonReplacer, pretty);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.fromJson\n * @module ng\n * @kind function\n *\n * @description\n * Deserializes a JSON string.\n *\n * @param {string} json JSON string to deserialize.\n * @returns {Object|Array|string|number} Deserialized JSON string.\n */\nfunction fromJson(json) {\n  return isString(json)\n      ? JSON.parse(json)\n      : json;\n}\n\n\nfunction timezoneToOffset(timezone, fallback) {\n  var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;\n  return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;\n}\n\n\nfunction addDateMinutes(date, minutes) {\n  date = new Date(date.getTime());\n  date.setMinutes(date.getMinutes() + minutes);\n  return date;\n}\n\n\nfunction convertTimezoneToLocal(date, timezone, reverse) {\n  reverse = reverse ? -1 : 1;\n  var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());\n  return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));\n}\n\n\n/**\n * @returns {string} Returns the string representation of the element.\n */\nfunction startingTag(element) {\n  element = jqLite(element).clone();\n  try {\n    // turns out IE does not let you set .html() on elements which\n    // are not allowed to have children. So we just ignore it.\n    element.empty();\n  } catch (e) {}\n  var elemHtml = jqLite('<div>').append(element).html();\n  try {\n    return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :\n        elemHtml.\n          match(/^(<[^>]+>)/)[1].\n          replace(/^<([\\w\\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });\n  } catch (e) {\n    return lowercase(elemHtml);\n  }\n\n}\n\n\n/////////////////////////////////////////////////\n\n/**\n * Tries to decode the URI component without throwing an exception.\n *\n * @private\n * @param str value potential URI component to check.\n * @returns {boolean} True if `value` can be decoded\n * with the decodeURIComponent function.\n */\nfunction tryDecodeURIComponent(value) {\n  try {\n    return decodeURIComponent(value);\n  } catch (e) {\n    // Ignore any invalid uri component\n  }\n}\n\n\n/**\n * Parses an escaped url query string into key-value pairs.\n * @returns {Object.<string,boolean|Array>}\n */\nfunction parseKeyValue(/**string*/keyValue) {\n  var obj = {};\n  forEach((keyValue || \"\").split('&'), function(keyValue) {\n    var splitPoint, key, val;\n    if (keyValue) {\n      key = keyValue = keyValue.replace(/\\+/g,'%20');\n      splitPoint = keyValue.indexOf('=');\n      if (splitPoint !== -1) {\n        key = keyValue.substring(0, splitPoint);\n        val = keyValue.substring(splitPoint + 1);\n      }\n      key = tryDecodeURIComponent(key);\n      if (isDefined(key)) {\n        val = isDefined(val) ? tryDecodeURIComponent(val) : true;\n        if (!hasOwnProperty.call(obj, key)) {\n          obj[key] = val;\n        } else if (isArray(obj[key])) {\n          obj[key].push(val);\n        } else {\n          obj[key] = [obj[key],val];\n        }\n      }\n    }\n  });\n  return obj;\n}\n\nfunction toKeyValue(obj) {\n  var parts = [];\n  forEach(obj, function(value, key) {\n    if (isArray(value)) {\n      forEach(value, function(arrayValue) {\n        parts.push(encodeUriQuery(key, true) +\n                   (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));\n      });\n    } else {\n    parts.push(encodeUriQuery(key, true) +\n               (value === true ? '' : '=' + encodeUriQuery(value, true)));\n    }\n  });\n  return parts.length ? parts.join('&') : '';\n}\n\n\n/**\n * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path\n * segments:\n *    segment       = *pchar\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriSegment(val) {\n  return encodeUriQuery(val, true).\n             replace(/%26/gi, '&').\n             replace(/%3D/gi, '=').\n             replace(/%2B/gi, '+');\n}\n\n\n/**\n * This method is intended for encoding *key* or *value* parts of query component. We need a custom\n * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be\n * encoded per http://tools.ietf.org/html/rfc3986:\n *    query       = *( pchar / \"/\" / \"?\" )\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriQuery(val, pctEncodeSpaces) {\n  return encodeURIComponent(val).\n             replace(/%40/gi, '@').\n             replace(/%3A/gi, ':').\n             replace(/%24/g, '$').\n             replace(/%2C/gi, ',').\n             replace(/%3B/gi, ';').\n             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n}\n\nvar ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];\n\nfunction getNgAttribute(element, ngAttr) {\n  var attr, i, ii = ngAttrPrefixes.length;\n  for (i = 0; i < ii; ++i) {\n    attr = ngAttrPrefixes[i] + ngAttr;\n    if (isString(attr = element.getAttribute(attr))) {\n      return attr;\n    }\n  }\n  return null;\n}\n\n/**\n * @ngdoc directive\n * @name ngApp\n * @module ng\n *\n * @element ANY\n * @param {angular.Module} ngApp an optional application\n *   {@link angular.module module} name to load.\n * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be\n *   created in \"strict-di\" mode. This means that the application will fail to invoke functions which\n *   do not use explicit function annotation (and are thus unsuitable for minification), as described\n *   in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in\n *   tracking down the root of these bugs.\n *\n * @description\n *\n * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive\n * designates the **root element** of the application and is typically placed near the root element\n * of the page - e.g. on the `<body>` or `<html>` tags.\n *\n * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`\n * found in the document will be used to define the root element to auto-bootstrap as an\n * application. To run multiple applications in an HTML document you must manually bootstrap them using\n * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.\n *\n * You can specify an **AngularJS module** to be used as the root module for the application.  This\n * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It\n * should contain the application code needed or have dependencies on other modules that will\n * contain the code. See {@link angular.module} for more information.\n *\n * In the example below if the `ngApp` directive were not placed on the `html` element then the\n * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`\n * would not be resolved to `3`.\n *\n * `ngApp` is the easiest, and most common way to bootstrap an application.\n *\n <example module=\"ngAppDemo\">\n   <file name=\"index.html\">\n   <div ng-controller=\"ngAppDemoController\">\n     I can add: {{a}} + {{b}} =  {{ a+b }}\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {\n     $scope.a = 1;\n     $scope.b = 2;\n   });\n   </file>\n </example>\n *\n * Using `ngStrictDi`, you would see something like this:\n *\n <example ng-app-included=\"true\">\n   <file name=\"index.html\">\n   <div ng-app=\"ngAppStrictDemo\" ng-strict-di>\n       <div ng-controller=\"GoodController1\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style (see\n              script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"GoodController2\">\n           Name: <input ng-model=\"name\"><br />\n           Hello, {{name}}!\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style\n              (see script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"BadController\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>The controller could not be instantiated, due to relying\n              on automatic function annotations (which are disabled in\n              strict mode). As such, the content of this section is not\n              interpolated, and there should be an error in your web console.\n           </p>\n       </div>\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppStrictDemo', [])\n     // BadController will fail to instantiate, due to relying on automatic function annotation,\n     // rather than an explicit annotation\n     .controller('BadController', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     })\n     // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,\n     // due to using explicit annotations using the array style and $inject property, respectively.\n     .controller('GoodController1', ['$scope', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     }])\n     .controller('GoodController2', GoodController2);\n     function GoodController2($scope) {\n       $scope.name = \"World\";\n     }\n     GoodController2.$inject = ['$scope'];\n   </file>\n   <file name=\"style.css\">\n   div[ng-controller] {\n       margin-bottom: 1em;\n       -webkit-border-radius: 4px;\n       border-radius: 4px;\n       border: 1px solid;\n       padding: .5em;\n   }\n   div[ng-controller^=Good] {\n       border-color: #d6e9c6;\n       background-color: #dff0d8;\n       color: #3c763d;\n   }\n   div[ng-controller^=Bad] {\n       border-color: #ebccd1;\n       background-color: #f2dede;\n       color: #a94442;\n       margin-bottom: 0;\n   }\n   </file>\n </example>\n */\nfunction angularInit(element, bootstrap) {\n  var appElement,\n      module,\n      config = {};\n\n  // The element `element` has priority over any other element\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n\n    if (!appElement && element.hasAttribute && element.hasAttribute(name)) {\n      appElement = element;\n      module = element.getAttribute(name);\n    }\n  });\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n    var candidate;\n\n    if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\\\:') + ']'))) {\n      appElement = candidate;\n      module = candidate.getAttribute(name);\n    }\n  });\n  if (appElement) {\n    config.strictDi = getNgAttribute(appElement, \"strict-di\") !== null;\n    bootstrap(appElement, module ? [module] : [], config);\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.bootstrap\n * @module ng\n * @description\n * Use this function to manually start up angular application.\n *\n * See: {@link guide/bootstrap Bootstrap}\n *\n * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.\n * They must use {@link ng.directive:ngApp ngApp}.\n *\n * Angular will detect if it has been loaded into the browser more than once and only allow the\n * first loaded script to be bootstrapped and will report a warning to the browser console for\n * each of the subsequent scripts. This prevents strange results in applications, where otherwise\n * multiple instances of Angular try to work on the DOM.\n *\n * ```html\n * <!doctype html>\n * <html>\n * <body>\n * <div ng-controller=\"WelcomeController\">\n *   {{greeting}}\n * </div>\n *\n * <script src=\"angular.js\"></script>\n * <script>\n *   var app = angular.module('demo', [])\n *   .controller('WelcomeController', function($scope) {\n *       $scope.greeting = 'Welcome!';\n *   });\n *   angular.bootstrap(document, ['demo']);\n * </script>\n * </body>\n * </html>\n * ```\n *\n * @param {DOMElement} element DOM element which is the root of angular application.\n * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.\n *     Each item in the array should be the name of a predefined module or a (DI annotated)\n *     function that will be invoked by the injector as a `config` block.\n *     See: {@link angular.module modules}\n * @param {Object=} config an object for defining configuration options for the application. The\n *     following keys are supported:\n *\n * * `strictDi` - disable automatic function annotation for the application. This is meant to\n *   assist in finding bugs which break minified code. Defaults to `false`.\n *\n * @returns {auto.$injector} Returns the newly created injector for this app.\n */\nfunction bootstrap(element, modules, config) {\n  if (!isObject(config)) config = {};\n  var defaultConfig = {\n    strictDi: false\n  };\n  config = extend(defaultConfig, config);\n  var doBootstrap = function() {\n    element = jqLite(element);\n\n    if (element.injector()) {\n      var tag = (element[0] === document) ? 'document' : startingTag(element);\n      //Encode angle brackets to prevent input from being sanitized to empty string #8683\n      throw ngMinErr(\n          'btstrpd',\n          \"App Already Bootstrapped with this Element '{0}'\",\n          tag.replace(/</,'&lt;').replace(/>/,'&gt;'));\n    }\n\n    modules = modules || [];\n    modules.unshift(['$provide', function($provide) {\n      $provide.value('$rootElement', element);\n    }]);\n\n    if (config.debugInfoEnabled) {\n      // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.\n      modules.push(['$compileProvider', function($compileProvider) {\n        $compileProvider.debugInfoEnabled(true);\n      }]);\n    }\n\n    modules.unshift('ng');\n    var injector = createInjector(modules, config.strictDi);\n    injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',\n       function bootstrapApply(scope, element, compile, injector) {\n        scope.$apply(function() {\n          element.data('$injector', injector);\n          compile(element)(scope);\n        });\n      }]\n    );\n    return injector;\n  };\n\n  var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;\n  var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;\n\n  if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {\n    config.debugInfoEnabled = true;\n    window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');\n  }\n\n  if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {\n    return doBootstrap();\n  }\n\n  window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');\n  angular.resumeBootstrap = function(extraModules) {\n    forEach(extraModules, function(module) {\n      modules.push(module);\n    });\n    return doBootstrap();\n  };\n\n  if (isFunction(angular.resumeDeferredBootstrap)) {\n    angular.resumeDeferredBootstrap();\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.reloadWithDebugInfo\n * @module ng\n * @description\n * Use this function to reload the current application with debug information turned on.\n * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.\n *\n * See {@link ng.$compileProvider#debugInfoEnabled} for more.\n */\nfunction reloadWithDebugInfo() {\n  window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\n  window.location.reload();\n}\n\n/**\n * @name angular.getTestability\n * @module ng\n * @description\n * Get the testability service for the instance of Angular on the given\n * element.\n * @param {DOMElement} element DOM element which is the root of angular application.\n */\nfunction getTestability(rootElement) {\n  var injector = angular.element(rootElement).injector();\n  if (!injector) {\n    throw ngMinErr('test',\n      'no injector found for element argument to getTestability');\n  }\n  return injector.get('$$testability');\n}\n\nvar SNAKE_CASE_REGEXP = /[A-Z]/g;\nfunction snake_case(name, separator) {\n  separator = separator || '_';\n  return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n    return (pos ? separator : '') + letter.toLowerCase();\n  });\n}\n\nvar bindJQueryFired = false;\nvar skipDestroyOnNextJQueryCleanData;\nfunction bindJQuery() {\n  var originalCleanData;\n\n  if (bindJQueryFired) {\n    return;\n  }\n\n  // bind to jQuery if present;\n  var jqName = jq();\n  jQuery = window.jQuery; // use default jQuery.\n  if (isDefined(jqName)) { // `ngJq` present\n    jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.\n  }\n\n  // Use jQuery if it exists with proper functionality, otherwise default to us.\n  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.\n  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older\n  // versions. It will not work for sure with jQuery <1.7, though.\n  if (jQuery && jQuery.fn.on) {\n    jqLite = jQuery;\n    extend(jQuery.fn, {\n      scope: JQLitePrototype.scope,\n      isolateScope: JQLitePrototype.isolateScope,\n      controller: JQLitePrototype.controller,\n      injector: JQLitePrototype.injector,\n      inheritedData: JQLitePrototype.inheritedData\n    });\n\n    // All nodes removed from the DOM via various jQuery APIs like .remove()\n    // are passed through jQuery.cleanData. Monkey-patch this method to fire\n    // the $destroy event on all removed nodes.\n    originalCleanData = jQuery.cleanData;\n    jQuery.cleanData = function(elems) {\n      var events;\n      if (!skipDestroyOnNextJQueryCleanData) {\n        for (var i = 0, elem; (elem = elems[i]) != null; i++) {\n          events = jQuery._data(elem, \"events\");\n          if (events && events.$destroy) {\n            jQuery(elem).triggerHandler('$destroy');\n          }\n        }\n      } else {\n        skipDestroyOnNextJQueryCleanData = false;\n      }\n      originalCleanData(elems);\n    };\n  } else {\n    jqLite = JQLite;\n  }\n\n  angular.element = jqLite;\n\n  // Prevent double-proxying.\n  bindJQueryFired = true;\n}\n\n/**\n * throw error if the argument is falsy.\n */\nfunction assertArg(arg, name, reason) {\n  if (!arg) {\n    throw ngMinErr('areq', \"Argument '{0}' is {1}\", (name || '?'), (reason || \"required\"));\n  }\n  return arg;\n}\n\nfunction assertArgFn(arg, name, acceptArrayAnnotation) {\n  if (acceptArrayAnnotation && isArray(arg)) {\n      arg = arg[arg.length - 1];\n  }\n\n  assertArg(isFunction(arg), name, 'not a function, got ' +\n      (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));\n  return arg;\n}\n\n/**\n * throw error if the name given is hasOwnProperty\n * @param  {String} name    the name to test\n * @param  {String} context the context in which the name is used, such as module or directive\n */\nfunction assertNotHasOwnProperty(name, context) {\n  if (name === 'hasOwnProperty') {\n    throw ngMinErr('badname', \"hasOwnProperty is not a valid {0} name\", context);\n  }\n}\n\n/**\n * Return the value accessible from the object by path. Any undefined traversals are ignored\n * @param {Object} obj starting object\n * @param {String} path path to traverse\n * @param {boolean} [bindFnToScope=true]\n * @returns {Object} value as accessible by path\n */\n//TODO(misko): this function needs to be removed\nfunction getter(obj, path, bindFnToScope) {\n  if (!path) return obj;\n  var keys = path.split('.');\n  var key;\n  var lastInstance = obj;\n  var len = keys.length;\n\n  for (var i = 0; i < len; i++) {\n    key = keys[i];\n    if (obj) {\n      obj = (lastInstance = obj)[key];\n    }\n  }\n  if (!bindFnToScope && isFunction(obj)) {\n    return bind(lastInstance, obj);\n  }\n  return obj;\n}\n\n/**\n * Return the DOM siblings between the first and last node in the given array.\n * @param {Array} array like object\n * @returns {jqLite} jqLite collection containing the nodes\n */\nfunction getBlockNodes(nodes) {\n  // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original\n  //             collection, otherwise update the original collection.\n  var node = nodes[0];\n  var endNode = nodes[nodes.length - 1];\n  var blockNodes = [node];\n\n  do {\n    node = node.nextSibling;\n    if (!node) break;\n    blockNodes.push(node);\n  } while (node !== endNode);\n\n  return jqLite(blockNodes);\n}\n\n\n/**\n * Creates a new object without a prototype. This object is useful for lookup without having to\n * guard against prototypically inherited properties via hasOwnProperty.\n *\n * Related micro-benchmarks:\n * - http://jsperf.com/object-create2\n * - http://jsperf.com/proto-map-lookup/2\n * - http://jsperf.com/for-in-vs-object-keys2\n *\n * @returns {Object}\n */\nfunction createMap() {\n  return Object.create(null);\n}\n\nvar NODE_TYPE_ELEMENT = 1;\nvar NODE_TYPE_ATTRIBUTE = 2;\nvar NODE_TYPE_TEXT = 3;\nvar NODE_TYPE_COMMENT = 8;\nvar NODE_TYPE_DOCUMENT = 9;\nvar NODE_TYPE_DOCUMENT_FRAGMENT = 11;\n\n/**\n * @ngdoc type\n * @name angular.Module\n * @module ng\n * @description\n *\n * Interface for configuring angular {@link angular.module modules}.\n */\n\nfunction setupModuleLoader(window) {\n\n  var $injectorMinErr = minErr('$injector');\n  var ngMinErr = minErr('ng');\n\n  function ensure(obj, name, factory) {\n    return obj[name] || (obj[name] = factory());\n  }\n\n  var angular = ensure(window, 'angular', Object);\n\n  // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap\n  angular.$$minErr = angular.$$minErr || minErr;\n\n  return ensure(angular, 'module', function() {\n    /** @type {Object.<string, angular.Module>} */\n    var modules = {};\n\n    /**\n     * @ngdoc function\n     * @name angular.module\n     * @module ng\n     * @description\n     *\n     * The `angular.module` is a global place for creating, registering and retrieving Angular\n     * modules.\n     * All modules (angular core or 3rd party) that should be available to an application must be\n     * registered using this mechanism.\n     *\n     * Passing one argument retrieves an existing {@link angular.Module},\n     * whereas passing more than one argument creates a new {@link angular.Module}\n     *\n     *\n     * # Module\n     *\n     * A module is a collection of services, directives, controllers, filters, and configuration information.\n     * `angular.module` is used to configure the {@link auto.$injector $injector}.\n     *\n     * ```js\n     * // Create a new module\n     * var myModule = angular.module('myModule', []);\n     *\n     * // register a new service\n     * myModule.value('appName', 'MyCoolApp');\n     *\n     * // configure existing services inside initialization blocks.\n     * myModule.config(['$locationProvider', function($locationProvider) {\n     *   // Configure existing providers\n     *   $locationProvider.hashPrefix('!');\n     * }]);\n     * ```\n     *\n     * Then you can create an injector and load your modules like this:\n     *\n     * ```js\n     * var injector = angular.injector(['ng', 'myModule'])\n     * ```\n     *\n     * However it's more likely that you'll just use\n     * {@link ng.directive:ngApp ngApp} or\n     * {@link angular.bootstrap} to simplify this process for you.\n     *\n     * @param {!string} name The name of the module to create or retrieve.\n     * @param {!Array.<string>=} requires If specified then new module is being created. If\n     *        unspecified then the module is being retrieved for further configuration.\n     * @param {Function=} configFn Optional configuration function for the module. Same as\n     *        {@link angular.Module#config Module#config()}.\n     * @returns {module} new module with the {@link angular.Module} api.\n     */\n    return function module(name, requires, configFn) {\n      var assertNotHasOwnProperty = function(name, context) {\n        if (name === 'hasOwnProperty') {\n          throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n        }\n      };\n\n      assertNotHasOwnProperty(name, 'module');\n      if (requires && modules.hasOwnProperty(name)) {\n        modules[name] = null;\n      }\n      return ensure(modules, name, function() {\n        if (!requires) {\n          throw $injectorMinErr('nomod', \"Module '{0}' is not available! You either misspelled \" +\n             \"the module name or forgot to load it. If registering a module ensure that you \" +\n             \"specify the dependencies as the second argument.\", name);\n        }\n\n        /** @type {!Array.<Array.<*>>} */\n        var invokeQueue = [];\n\n        /** @type {!Array.<Function>} */\n        var configBlocks = [];\n\n        /** @type {!Array.<Function>} */\n        var runBlocks = [];\n\n        var config = invokeLater('$injector', 'invoke', 'push', configBlocks);\n\n        /** @type {angular.Module} */\n        var moduleInstance = {\n          // Private state\n          _invokeQueue: invokeQueue,\n          _configBlocks: configBlocks,\n          _runBlocks: runBlocks,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#requires\n           * @module ng\n           *\n           * @description\n           * Holds the list of modules which the injector will load before the current module is\n           * loaded.\n           */\n          requires: requires,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#name\n           * @module ng\n           *\n           * @description\n           * Name of the module.\n           */\n          name: name,\n\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#provider\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerType Construction function for creating new instance of the\n           *                                service.\n           * @description\n           * See {@link auto.$provide#provider $provide.provider()}.\n           */\n          provider: invokeLaterAndSetModuleName('$provide', 'provider'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#factory\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerFunction Function for creating new instance of the service.\n           * @description\n           * See {@link auto.$provide#factory $provide.factory()}.\n           */\n          factory: invokeLaterAndSetModuleName('$provide', 'factory'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#service\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} constructor A constructor function that will be instantiated.\n           * @description\n           * See {@link auto.$provide#service $provide.service()}.\n           */\n          service: invokeLaterAndSetModuleName('$provide', 'service'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#value\n           * @module ng\n           * @param {string} name service name\n           * @param {*} object Service instance object.\n           * @description\n           * See {@link auto.$provide#value $provide.value()}.\n           */\n          value: invokeLater('$provide', 'value'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#constant\n           * @module ng\n           * @param {string} name constant name\n           * @param {*} object Constant value.\n           * @description\n           * Because the constant are fixed, they get applied before other provide methods.\n           * See {@link auto.$provide#constant $provide.constant()}.\n           */\n          constant: invokeLater('$provide', 'constant', 'unshift'),\n\n           /**\n           * @ngdoc method\n           * @name angular.Module#decorator\n           * @module ng\n           * @param {string} The name of the service to decorate.\n           * @param {Function} This function will be invoked when the service needs to be\n           *                                    instantiated and should return the decorated service instance.\n           * @description\n           * See {@link auto.$provide#decorator $provide.decorator()}.\n           */\n          decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#animation\n           * @module ng\n           * @param {string} name animation name\n           * @param {Function} animationFactory Factory function for creating new instance of an\n           *                                    animation.\n           * @description\n           *\n           * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.\n           *\n           *\n           * Defines an animation hook that can be later used with\n           * {@link $animate $animate} service and directives that use this service.\n           *\n           * ```js\n           * module.animation('.animation-name', function($inject1, $inject2) {\n           *   return {\n           *     eventName : function(element, done) {\n           *       //code to run the animation\n           *       //once complete, then run done()\n           *       return function cancellationFunction(element) {\n           *         //code to cancel the animation\n           *       }\n           *     }\n           *   }\n           * })\n           * ```\n           *\n           * See {@link ng.$animateProvider#register $animateProvider.register()} and\n           * {@link ngAnimate ngAnimate module} for more information.\n           */\n          animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#filter\n           * @module ng\n           * @param {string} name Filter name - this must be a valid angular expression identifier\n           * @param {Function} filterFactory Factory function for creating new instance of filter.\n           * @description\n           * See {@link ng.$filterProvider#register $filterProvider.register()}.\n           *\n           * <div class=\"alert alert-warning\">\n           * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n           * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n           * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n           * (`myapp_subsection_filterx`).\n           * </div>\n           */\n          filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#controller\n           * @module ng\n           * @param {string|Object} name Controller name, or an object map of controllers where the\n           *    keys are the names and the values are the constructors.\n           * @param {Function} constructor Controller constructor function.\n           * @description\n           * See {@link ng.$controllerProvider#register $controllerProvider.register()}.\n           */\n          controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#directive\n           * @module ng\n           * @param {string|Object} name Directive name, or an object map of directives where the\n           *    keys are the names and the values are the factories.\n           * @param {Function} directiveFactory Factory function for creating new instance of\n           * directives.\n           * @description\n           * See {@link ng.$compileProvider#directive $compileProvider.directive()}.\n           */\n          directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#config\n           * @module ng\n           * @param {Function} configFn Execute this function on module load. Useful for service\n           *    configuration.\n           * @description\n           * Use this method to register work which needs to be performed on module loading.\n           * For more about how to configure services, see\n           * {@link providers#provider-recipe Provider Recipe}.\n           */\n          config: config,\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#run\n           * @module ng\n           * @param {Function} initializationFn Execute this function after injector creation.\n           *    Useful for application initialization.\n           * @description\n           * Use this method to register work which should be performed when the injector is done\n           * loading all modules.\n           */\n          run: function(block) {\n            runBlocks.push(block);\n            return this;\n          }\n        };\n\n        if (configFn) {\n          config(configFn);\n        }\n\n        return moduleInstance;\n\n        /**\n         * @param {string} provider\n         * @param {string} method\n         * @param {String=} insertMethod\n         * @returns {angular.Module}\n         */\n        function invokeLater(provider, method, insertMethod, queue) {\n          if (!queue) queue = invokeQueue;\n          return function() {\n            queue[insertMethod || 'push']([provider, method, arguments]);\n            return moduleInstance;\n          };\n        }\n\n        /**\n         * @param {string} provider\n         * @param {string} method\n         * @returns {angular.Module}\n         */\n        function invokeLaterAndSetModuleName(provider, method) {\n          return function(recipeName, factoryFunction) {\n            if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;\n            invokeQueue.push([provider, method, arguments]);\n            return moduleInstance;\n          };\n        }\n      });\n    };\n  });\n\n}\n\n/* global: toDebugString: true */\n\nfunction serializeObject(obj) {\n  var seen = [];\n\n  return JSON.stringify(obj, function(key, val) {\n    val = toJsonReplacer(key, val);\n    if (isObject(val)) {\n\n      if (seen.indexOf(val) >= 0) return '<<already seen>>';\n\n      seen.push(val);\n    }\n    return val;\n  });\n}\n\nfunction toDebugString(obj) {\n  if (typeof obj === 'function') {\n    return obj.toString().replace(/ \\{[\\s\\S]*$/, '');\n  } else if (typeof obj === 'undefined') {\n    return 'undefined';\n  } else if (typeof obj !== 'string') {\n    return serializeObject(obj);\n  }\n  return obj;\n}\n\n/* global angularModule: true,\n  version: true,\n\n  $CompileProvider,\n\n  htmlAnchorDirective,\n  inputDirective,\n  inputDirective,\n  formDirective,\n  scriptDirective,\n  selectDirective,\n  styleDirective,\n  optionDirective,\n  ngBindDirective,\n  ngBindHtmlDirective,\n  ngBindTemplateDirective,\n  ngClassDirective,\n  ngClassEvenDirective,\n  ngClassOddDirective,\n  ngCloakDirective,\n  ngControllerDirective,\n  ngFormDirective,\n  ngHideDirective,\n  ngIfDirective,\n  ngIncludeDirective,\n  ngIncludeFillContentDirective,\n  ngInitDirective,\n  ngNonBindableDirective,\n  ngPluralizeDirective,\n  ngRepeatDirective,\n  ngShowDirective,\n  ngStyleDirective,\n  ngSwitchDirective,\n  ngSwitchWhenDirective,\n  ngSwitchDefaultDirective,\n  ngOptionsDirective,\n  ngTranscludeDirective,\n  ngModelDirective,\n  ngListDirective,\n  ngChangeDirective,\n  patternDirective,\n  patternDirective,\n  requiredDirective,\n  requiredDirective,\n  minlengthDirective,\n  minlengthDirective,\n  maxlengthDirective,\n  maxlengthDirective,\n  ngValueDirective,\n  ngModelOptionsDirective,\n  ngAttributeAliasDirectives,\n  ngEventDirectives,\n\n  $AnchorScrollProvider,\n  $AnimateProvider,\n  $CoreAnimateCssProvider,\n  $$CoreAnimateQueueProvider,\n  $$CoreAnimateRunnerProvider,\n  $BrowserProvider,\n  $CacheFactoryProvider,\n  $ControllerProvider,\n  $DocumentProvider,\n  $ExceptionHandlerProvider,\n  $FilterProvider,\n  $$ForceReflowProvider,\n  $InterpolateProvider,\n  $IntervalProvider,\n  $$HashMapProvider,\n  $HttpProvider,\n  $HttpParamSerializerProvider,\n  $HttpParamSerializerJQLikeProvider,\n  $HttpBackendProvider,\n  $LocationProvider,\n  $LogProvider,\n  $ParseProvider,\n  $RootScopeProvider,\n  $QProvider,\n  $$QProvider,\n  $$SanitizeUriProvider,\n  $SceProvider,\n  $SceDelegateProvider,\n  $SnifferProvider,\n  $TemplateCacheProvider,\n  $TemplateRequestProvider,\n  $$TestabilityProvider,\n  $TimeoutProvider,\n  $$RAFProvider,\n  $WindowProvider,\n  $$jqLiteProvider,\n  $$CookieReaderProvider\n*/\n\n\n/**\n * @ngdoc object\n * @name angular.version\n * @module ng\n * @description\n * An object that contains information about the current AngularJS version. This object has the\n * following properties:\n *\n * - `full` – `{string}` – Full version string, such as \"0.9.18\".\n * - `major` – `{number}` – Major version number, such as \"0\".\n * - `minor` – `{number}` – Minor version number, such as \"9\".\n * - `dot` – `{number}` – Dot version number, such as \"18\".\n * - `codeName` – `{string}` – Code name of the release, such as \"jiggling-armfat\".\n */\nvar version = {\n  full: '1.4.4',    // all of these placeholder strings will be replaced by grunt's\n  major: 1,    // package task\n  minor: 4,\n  dot: 4,\n  codeName: 'pylon-requirement'\n};\n\n\nfunction publishExternalAPI(angular) {\n  extend(angular, {\n    'bootstrap': bootstrap,\n    'copy': copy,\n    'extend': extend,\n    'merge': merge,\n    'equals': equals,\n    'element': jqLite,\n    'forEach': forEach,\n    'injector': createInjector,\n    'noop': noop,\n    'bind': bind,\n    'toJson': toJson,\n    'fromJson': fromJson,\n    'identity': identity,\n    'isUndefined': isUndefined,\n    'isDefined': isDefined,\n    'isString': isString,\n    'isFunction': isFunction,\n    'isObject': isObject,\n    'isNumber': isNumber,\n    'isElement': isElement,\n    'isArray': isArray,\n    'version': version,\n    'isDate': isDate,\n    'lowercase': lowercase,\n    'uppercase': uppercase,\n    'callbacks': {counter: 0},\n    'getTestability': getTestability,\n    '$$minErr': minErr,\n    '$$csp': csp,\n    'reloadWithDebugInfo': reloadWithDebugInfo\n  });\n\n  angularModule = setupModuleLoader(window);\n\n  angularModule('ng', ['ngLocale'], ['$provide',\n    function ngModule($provide) {\n      // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.\n      $provide.provider({\n        $$sanitizeUri: $$SanitizeUriProvider\n      });\n      $provide.provider('$compile', $CompileProvider).\n        directive({\n            a: htmlAnchorDirective,\n            input: inputDirective,\n            textarea: inputDirective,\n            form: formDirective,\n            script: scriptDirective,\n            select: selectDirective,\n            style: styleDirective,\n            option: optionDirective,\n            ngBind: ngBindDirective,\n            ngBindHtml: ngBindHtmlDirective,\n            ngBindTemplate: ngBindTemplateDirective,\n            ngClass: ngClassDirective,\n            ngClassEven: ngClassEvenDirective,\n            ngClassOdd: ngClassOddDirective,\n            ngCloak: ngCloakDirective,\n            ngController: ngControllerDirective,\n            ngForm: ngFormDirective,\n            ngHide: ngHideDirective,\n            ngIf: ngIfDirective,\n            ngInclude: ngIncludeDirective,\n            ngInit: ngInitDirective,\n            ngNonBindable: ngNonBindableDirective,\n            ngPluralize: ngPluralizeDirective,\n            ngRepeat: ngRepeatDirective,\n            ngShow: ngShowDirective,\n            ngStyle: ngStyleDirective,\n            ngSwitch: ngSwitchDirective,\n            ngSwitchWhen: ngSwitchWhenDirective,\n            ngSwitchDefault: ngSwitchDefaultDirective,\n            ngOptions: ngOptionsDirective,\n            ngTransclude: ngTranscludeDirective,\n            ngModel: ngModelDirective,\n            ngList: ngListDirective,\n            ngChange: ngChangeDirective,\n            pattern: patternDirective,\n            ngPattern: patternDirective,\n            required: requiredDirective,\n            ngRequired: requiredDirective,\n            minlength: minlengthDirective,\n            ngMinlength: minlengthDirective,\n            maxlength: maxlengthDirective,\n            ngMaxlength: maxlengthDirective,\n            ngValue: ngValueDirective,\n            ngModelOptions: ngModelOptionsDirective\n        }).\n        directive({\n          ngInclude: ngIncludeFillContentDirective\n        }).\n        directive(ngAttributeAliasDirectives).\n        directive(ngEventDirectives);\n      $provide.provider({\n        $anchorScroll: $AnchorScrollProvider,\n        $animate: $AnimateProvider,\n        $animateCss: $CoreAnimateCssProvider,\n        $$animateQueue: $$CoreAnimateQueueProvider,\n        $$AnimateRunner: $$CoreAnimateRunnerProvider,\n        $browser: $BrowserProvider,\n        $cacheFactory: $CacheFactoryProvider,\n        $controller: $ControllerProvider,\n        $document: $DocumentProvider,\n        $exceptionHandler: $ExceptionHandlerProvider,\n        $filter: $FilterProvider,\n        $$forceReflow: $$ForceReflowProvider,\n        $interpolate: $InterpolateProvider,\n        $interval: $IntervalProvider,\n        $http: $HttpProvider,\n        $httpParamSerializer: $HttpParamSerializerProvider,\n        $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,\n        $httpBackend: $HttpBackendProvider,\n        $location: $LocationProvider,\n        $log: $LogProvider,\n        $parse: $ParseProvider,\n        $rootScope: $RootScopeProvider,\n        $q: $QProvider,\n        $$q: $$QProvider,\n        $sce: $SceProvider,\n        $sceDelegate: $SceDelegateProvider,\n        $sniffer: $SnifferProvider,\n        $templateCache: $TemplateCacheProvider,\n        $templateRequest: $TemplateRequestProvider,\n        $$testability: $$TestabilityProvider,\n        $timeout: $TimeoutProvider,\n        $window: $WindowProvider,\n        $$rAF: $$RAFProvider,\n        $$jqLite: $$jqLiteProvider,\n        $$HashMap: $$HashMapProvider,\n        $$cookieReader: $$CookieReaderProvider\n      });\n    }\n  ]);\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* global JQLitePrototype: true,\n  addEventListenerFn: true,\n  removeEventListenerFn: true,\n  BOOLEAN_ATTR: true,\n  ALIASED_ATTR: true,\n*/\n\n//////////////////////////////////\n//JQLite\n//////////////////////////////////\n\n/**\n * @ngdoc function\n * @name angular.element\n * @module ng\n * @kind function\n *\n * @description\n * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.\n *\n * If jQuery is available, `angular.element` is an alias for the\n * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`\n * delegates to Angular's built-in subset of jQuery, called \"jQuery lite\" or \"jqLite.\"\n *\n * <div class=\"alert alert-success\">jqLite is a tiny, API-compatible subset of jQuery that allows\n * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most\n * commonly needed functionality with the goal of having a very small footprint.</div>\n *\n * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.\n *\n * <div class=\"alert\">**Note:** all element references in Angular are always wrapped with jQuery or\n * jqLite; they are never raw DOM references.</div>\n *\n * ## Angular's jqLite\n * jqLite provides only the following jQuery methods:\n *\n * - [`addClass()`](http://api.jquery.com/addClass/)\n * - [`after()`](http://api.jquery.com/after/)\n * - [`append()`](http://api.jquery.com/append/)\n * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters\n * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData\n * - [`children()`](http://api.jquery.com/children/) - Does not support selectors\n * - [`clone()`](http://api.jquery.com/clone/)\n * - [`contents()`](http://api.jquery.com/contents/)\n * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.\n * - [`data()`](http://api.jquery.com/data/)\n * - [`detach()`](http://api.jquery.com/detach/)\n * - [`empty()`](http://api.jquery.com/empty/)\n * - [`eq()`](http://api.jquery.com/eq/)\n * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name\n * - [`hasClass()`](http://api.jquery.com/hasClass/)\n * - [`html()`](http://api.jquery.com/html/)\n * - [`next()`](http://api.jquery.com/next/) - Does not support selectors\n * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData\n * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors\n * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors\n * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors\n * - [`prepend()`](http://api.jquery.com/prepend/)\n * - [`prop()`](http://api.jquery.com/prop/)\n * - [`ready()`](http://api.jquery.com/ready/)\n * - [`remove()`](http://api.jquery.com/remove/)\n * - [`removeAttr()`](http://api.jquery.com/removeAttr/)\n * - [`removeClass()`](http://api.jquery.com/removeClass/)\n * - [`removeData()`](http://api.jquery.com/removeData/)\n * - [`replaceWith()`](http://api.jquery.com/replaceWith/)\n * - [`text()`](http://api.jquery.com/text/)\n * - [`toggleClass()`](http://api.jquery.com/toggleClass/)\n * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.\n * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces\n * - [`val()`](http://api.jquery.com/val/)\n * - [`wrap()`](http://api.jquery.com/wrap/)\n *\n * ## jQuery/jqLite Extras\n * Angular also provides the following additional methods and events to both jQuery and jqLite:\n *\n * ### Events\n * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event\n *    on all DOM nodes being removed.  This can be used to clean up any 3rd party bindings to the DOM\n *    element before it is removed.\n *\n * ### Methods\n * - `controller(name)` - retrieves the controller of the current element or its parent. By default\n *   retrieves controller associated with the `ngController` directive. If `name` is provided as\n *   camelCase directive name, then the controller for this directive will be retrieved (e.g.\n *   `'ngModel'`).\n * - `injector()` - retrieves the injector of the current element or its parent.\n * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current\n *   element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to\n *   be enabled.\n * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the\n *   current element. This getter should be used only on elements that contain a directive which starts a new isolate\n *   scope. Calling `scope()` on this element always returns the original non-isolate scope.\n *   Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.\n * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top\n *   parent element is reached.\n *\n * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.\n * @returns {Object} jQuery object.\n */\n\nJQLite.expando = 'ng339';\n\nvar jqCache = JQLite.cache = {},\n    jqId = 1,\n    addEventListenerFn = function(element, type, fn) {\n      element.addEventListener(type, fn, false);\n    },\n    removeEventListenerFn = function(element, type, fn) {\n      element.removeEventListener(type, fn, false);\n    };\n\n/*\n * !!! This is an undocumented \"private\" function !!!\n */\nJQLite._data = function(node) {\n  //jQuery always returns an object on cache miss\n  return this.cache[node[this.expando]] || {};\n};\n\nfunction jqNextId() { return ++jqId; }\n\n\nvar SPECIAL_CHARS_REGEXP = /([\\:\\-\\_]+(.))/g;\nvar MOZ_HACK_REGEXP = /^moz([A-Z])/;\nvar MOUSE_EVENT_MAP= { mouseleave: \"mouseout\", mouseenter: \"mouseover\"};\nvar jqLiteMinErr = minErr('jqLite');\n\n/**\n * Converts snake_case to camelCase.\n * Also there is special case for Moz prefix starting with upper case letter.\n * @param name Name to normalize\n */\nfunction camelCase(name) {\n  return name.\n    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {\n      return offset ? letter.toUpperCase() : letter;\n    }).\n    replace(MOZ_HACK_REGEXP, 'Moz$1');\n}\n\nvar SINGLE_TAG_REGEXP = /^<(\\w+)\\s*\\/?>(?:<\\/\\1>|)$/;\nvar HTML_REGEXP = /<|&#?\\w+;/;\nvar TAG_NAME_REGEXP = /<([\\w:]+)/;\nvar XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:]+)[^>]*)\\/>/gi;\n\nvar wrapMap = {\n  'option': [1, '<select multiple=\"multiple\">', '</select>'],\n\n  'thead': [1, '<table>', '</table>'],\n  'col': [2, '<table><colgroup>', '</colgroup></table>'],\n  'tr': [2, '<table><tbody>', '</tbody></table>'],\n  'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],\n  '_default': [0, \"\", \"\"]\n};\n\nwrapMap.optgroup = wrapMap.option;\nwrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;\nwrapMap.th = wrapMap.td;\n\n\nfunction jqLiteIsTextNode(html) {\n  return !HTML_REGEXP.test(html);\n}\n\nfunction jqLiteAcceptsData(node) {\n  // The window object can accept data but has no nodeType\n  // Otherwise we are only interested in elements (1) and documents (9)\n  var nodeType = node.nodeType;\n  return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;\n}\n\nfunction jqLiteHasData(node) {\n  for (var key in jqCache[node.ng339]) {\n    return true;\n  }\n  return false;\n}\n\nfunction jqLiteBuildFragment(html, context) {\n  var tmp, tag, wrap,\n      fragment = context.createDocumentFragment(),\n      nodes = [], i;\n\n  if (jqLiteIsTextNode(html)) {\n    // Convert non-html into a text node\n    nodes.push(context.createTextNode(html));\n  } else {\n    // Convert html into DOM nodes\n    tmp = tmp || fragment.appendChild(context.createElement(\"div\"));\n    tag = (TAG_NAME_REGEXP.exec(html) || [\"\", \"\"])[1].toLowerCase();\n    wrap = wrapMap[tag] || wrapMap._default;\n    tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, \"<$1></$2>\") + wrap[2];\n\n    // Descend through wrappers to the right content\n    i = wrap[0];\n    while (i--) {\n      tmp = tmp.lastChild;\n    }\n\n    nodes = concat(nodes, tmp.childNodes);\n\n    tmp = fragment.firstChild;\n    tmp.textContent = \"\";\n  }\n\n  // Remove wrapper from fragment\n  fragment.textContent = \"\";\n  fragment.innerHTML = \"\"; // Clear inner HTML\n  forEach(nodes, function(node) {\n    fragment.appendChild(node);\n  });\n\n  return fragment;\n}\n\nfunction jqLiteParseHTML(html, context) {\n  context = context || document;\n  var parsed;\n\n  if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {\n    return [context.createElement(parsed[1])];\n  }\n\n  if ((parsed = jqLiteBuildFragment(html, context))) {\n    return parsed.childNodes;\n  }\n\n  return [];\n}\n\n/////////////////////////////////////////////\nfunction JQLite(element) {\n  if (element instanceof JQLite) {\n    return element;\n  }\n\n  var argIsString;\n\n  if (isString(element)) {\n    element = trim(element);\n    argIsString = true;\n  }\n  if (!(this instanceof JQLite)) {\n    if (argIsString && element.charAt(0) != '<') {\n      throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');\n    }\n    return new JQLite(element);\n  }\n\n  if (argIsString) {\n    jqLiteAddNodes(this, jqLiteParseHTML(element));\n  } else {\n    jqLiteAddNodes(this, element);\n  }\n}\n\nfunction jqLiteClone(element) {\n  return element.cloneNode(true);\n}\n\nfunction jqLiteDealoc(element, onlyDescendants) {\n  if (!onlyDescendants) jqLiteRemoveData(element);\n\n  if (element.querySelectorAll) {\n    var descendants = element.querySelectorAll('*');\n    for (var i = 0, l = descendants.length; i < l; i++) {\n      jqLiteRemoveData(descendants[i]);\n    }\n  }\n}\n\nfunction jqLiteOff(element, type, fn, unsupported) {\n  if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');\n\n  var expandoStore = jqLiteExpandoStore(element);\n  var events = expandoStore && expandoStore.events;\n  var handle = expandoStore && expandoStore.handle;\n\n  if (!handle) return; //no listeners registered\n\n  if (!type) {\n    for (type in events) {\n      if (type !== '$destroy') {\n        removeEventListenerFn(element, type, handle);\n      }\n      delete events[type];\n    }\n  } else {\n    forEach(type.split(' '), function(type) {\n      if (isDefined(fn)) {\n        var listenerFns = events[type];\n        arrayRemove(listenerFns || [], fn);\n        if (listenerFns && listenerFns.length > 0) {\n          return;\n        }\n      }\n\n      removeEventListenerFn(element, type, handle);\n      delete events[type];\n    });\n  }\n}\n\nfunction jqLiteRemoveData(element, name) {\n  var expandoId = element.ng339;\n  var expandoStore = expandoId && jqCache[expandoId];\n\n  if (expandoStore) {\n    if (name) {\n      delete expandoStore.data[name];\n      return;\n    }\n\n    if (expandoStore.handle) {\n      if (expandoStore.events.$destroy) {\n        expandoStore.handle({}, '$destroy');\n      }\n      jqLiteOff(element);\n    }\n    delete jqCache[expandoId];\n    element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it\n  }\n}\n\n\nfunction jqLiteExpandoStore(element, createIfNecessary) {\n  var expandoId = element.ng339,\n      expandoStore = expandoId && jqCache[expandoId];\n\n  if (createIfNecessary && !expandoStore) {\n    element.ng339 = expandoId = jqNextId();\n    expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};\n  }\n\n  return expandoStore;\n}\n\n\nfunction jqLiteData(element, key, value) {\n  if (jqLiteAcceptsData(element)) {\n\n    var isSimpleSetter = isDefined(value);\n    var isSimpleGetter = !isSimpleSetter && key && !isObject(key);\n    var massGetter = !key;\n    var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);\n    var data = expandoStore && expandoStore.data;\n\n    if (isSimpleSetter) { // data('key', value)\n      data[key] = value;\n    } else {\n      if (massGetter) {  // data()\n        return data;\n      } else {\n        if (isSimpleGetter) { // data('key')\n          // don't force creation of expandoStore if it doesn't exist yet\n          return data && data[key];\n        } else { // mass-setter: data({key1: val1, key2: val2})\n          extend(data, key);\n        }\n      }\n    }\n  }\n}\n\nfunction jqLiteHasClass(element, selector) {\n  if (!element.getAttribute) return false;\n  return ((\" \" + (element.getAttribute('class') || '') + \" \").replace(/[\\n\\t]/g, \" \").\n      indexOf(\" \" + selector + \" \") > -1);\n}\n\nfunction jqLiteRemoveClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    forEach(cssClasses.split(' '), function(cssClass) {\n      element.setAttribute('class', trim(\n          (\" \" + (element.getAttribute('class') || '') + \" \")\n          .replace(/[\\n\\t]/g, \" \")\n          .replace(\" \" + trim(cssClass) + \" \", \" \"))\n      );\n    });\n  }\n}\n\nfunction jqLiteAddClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\n                            .replace(/[\\n\\t]/g, \" \");\n\n    forEach(cssClasses.split(' '), function(cssClass) {\n      cssClass = trim(cssClass);\n      if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\n        existingClasses += cssClass + ' ';\n      }\n    });\n\n    element.setAttribute('class', trim(existingClasses));\n  }\n}\n\n\nfunction jqLiteAddNodes(root, elements) {\n  // THIS CODE IS VERY HOT. Don't make changes without benchmarking.\n\n  if (elements) {\n\n    // if a Node (the most common case)\n    if (elements.nodeType) {\n      root[root.length++] = elements;\n    } else {\n      var length = elements.length;\n\n      // if an Array or NodeList and not a Window\n      if (typeof length === 'number' && elements.window !== elements) {\n        if (length) {\n          for (var i = 0; i < length; i++) {\n            root[root.length++] = elements[i];\n          }\n        }\n      } else {\n        root[root.length++] = elements;\n      }\n    }\n  }\n}\n\n\nfunction jqLiteController(element, name) {\n  return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');\n}\n\nfunction jqLiteInheritedData(element, name, value) {\n  // if element is the document object work with the html element instead\n  // this makes $(document).scope() possible\n  if (element.nodeType == NODE_TYPE_DOCUMENT) {\n    element = element.documentElement;\n  }\n  var names = isArray(name) ? name : [name];\n\n  while (element) {\n    for (var i = 0, ii = names.length; i < ii; i++) {\n      if ((value = jqLite.data(element, names[i])) !== undefined) return value;\n    }\n\n    // If dealing with a document fragment node with a host element, and no parent, use the host\n    // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM\n    // to lookup parent controllers.\n    element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);\n  }\n}\n\nfunction jqLiteEmpty(element) {\n  jqLiteDealoc(element, true);\n  while (element.firstChild) {\n    element.removeChild(element.firstChild);\n  }\n}\n\nfunction jqLiteRemove(element, keepData) {\n  if (!keepData) jqLiteDealoc(element);\n  var parent = element.parentNode;\n  if (parent) parent.removeChild(element);\n}\n\n\nfunction jqLiteDocumentLoaded(action, win) {\n  win = win || window;\n  if (win.document.readyState === 'complete') {\n    // Force the action to be run async for consistent behaviour\n    // from the action's point of view\n    // i.e. it will definitely not be in a $apply\n    win.setTimeout(action);\n  } else {\n    // No need to unbind this handler as load is only ever called once\n    jqLite(win).on('load', action);\n  }\n}\n\n//////////////////////////////////////////\n// Functions which are declared directly.\n//////////////////////////////////////////\nvar JQLitePrototype = JQLite.prototype = {\n  ready: function(fn) {\n    var fired = false;\n\n    function trigger() {\n      if (fired) return;\n      fired = true;\n      fn();\n    }\n\n    // check if document is already loaded\n    if (document.readyState === 'complete') {\n      setTimeout(trigger);\n    } else {\n      this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9\n      // we can not use jqLite since we are not done loading and jQuery could be loaded later.\n      // jshint -W064\n      JQLite(window).on('load', trigger); // fallback to window.onload for others\n      // jshint +W064\n    }\n  },\n  toString: function() {\n    var value = [];\n    forEach(this, function(e) { value.push('' + e);});\n    return '[' + value.join(', ') + ']';\n  },\n\n  eq: function(index) {\n      return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);\n  },\n\n  length: 0,\n  push: push,\n  sort: [].sort,\n  splice: [].splice\n};\n\n//////////////////////////////////////////\n// Functions iterating getter/setters.\n// these functions return self on setter and\n// value on get.\n//////////////////////////////////////////\nvar BOOLEAN_ATTR = {};\nforEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {\n  BOOLEAN_ATTR[lowercase(value)] = value;\n});\nvar BOOLEAN_ELEMENTS = {};\nforEach('input,select,option,textarea,button,form,details'.split(','), function(value) {\n  BOOLEAN_ELEMENTS[value] = true;\n});\nvar ALIASED_ATTR = {\n  'ngMinlength': 'minlength',\n  'ngMaxlength': 'maxlength',\n  'ngMin': 'min',\n  'ngMax': 'max',\n  'ngPattern': 'pattern'\n};\n\nfunction getBooleanAttrName(element, name) {\n  // check dom last since we will most likely fail on name\n  var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];\n\n  // booleanAttr is here twice to minimize DOM access\n  return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;\n}\n\nfunction getAliasedAttrName(element, name) {\n  var nodeName = element.nodeName;\n  return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];\n}\n\nforEach({\n  data: jqLiteData,\n  removeData: jqLiteRemoveData,\n  hasData: jqLiteHasData\n}, function(fn, name) {\n  JQLite[name] = fn;\n});\n\nforEach({\n  data: jqLiteData,\n  inheritedData: jqLiteInheritedData,\n\n  scope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);\n  },\n\n  isolateScope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');\n  },\n\n  controller: jqLiteController,\n\n  injector: function(element) {\n    return jqLiteInheritedData(element, '$injector');\n  },\n\n  removeAttr: function(element, name) {\n    element.removeAttribute(name);\n  },\n\n  hasClass: jqLiteHasClass,\n\n  css: function(element, name, value) {\n    name = camelCase(name);\n\n    if (isDefined(value)) {\n      element.style[name] = value;\n    } else {\n      return element.style[name];\n    }\n  },\n\n  attr: function(element, name, value) {\n    var nodeType = element.nodeType;\n    if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {\n      return;\n    }\n    var lowercasedName = lowercase(name);\n    if (BOOLEAN_ATTR[lowercasedName]) {\n      if (isDefined(value)) {\n        if (!!value) {\n          element[name] = true;\n          element.setAttribute(name, lowercasedName);\n        } else {\n          element[name] = false;\n          element.removeAttribute(lowercasedName);\n        }\n      } else {\n        return (element[name] ||\n                 (element.attributes.getNamedItem(name) || noop).specified)\n               ? lowercasedName\n               : undefined;\n      }\n    } else if (isDefined(value)) {\n      element.setAttribute(name, value);\n    } else if (element.getAttribute) {\n      // the extra argument \"2\" is to get the right thing for a.href in IE, see jQuery code\n      // some elements (e.g. Document) don't have get attribute, so return undefined\n      var ret = element.getAttribute(name, 2);\n      // normalize non-existing attributes to undefined (as jQuery)\n      return ret === null ? undefined : ret;\n    }\n  },\n\n  prop: function(element, name, value) {\n    if (isDefined(value)) {\n      element[name] = value;\n    } else {\n      return element[name];\n    }\n  },\n\n  text: (function() {\n    getText.$dv = '';\n    return getText;\n\n    function getText(element, value) {\n      if (isUndefined(value)) {\n        var nodeType = element.nodeType;\n        return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';\n      }\n      element.textContent = value;\n    }\n  })(),\n\n  val: function(element, value) {\n    if (isUndefined(value)) {\n      if (element.multiple && nodeName_(element) === 'select') {\n        var result = [];\n        forEach(element.options, function(option) {\n          if (option.selected) {\n            result.push(option.value || option.text);\n          }\n        });\n        return result.length === 0 ? null : result;\n      }\n      return element.value;\n    }\n    element.value = value;\n  },\n\n  html: function(element, value) {\n    if (isUndefined(value)) {\n      return element.innerHTML;\n    }\n    jqLiteDealoc(element, true);\n    element.innerHTML = value;\n  },\n\n  empty: jqLiteEmpty\n}, function(fn, name) {\n  /**\n   * Properties: writes return selection, reads return first value\n   */\n  JQLite.prototype[name] = function(arg1, arg2) {\n    var i, key;\n    var nodeCount = this.length;\n\n    // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it\n    // in a way that survives minification.\n    // jqLiteEmpty takes no arguments but is a setter.\n    if (fn !== jqLiteEmpty &&\n        (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {\n      if (isObject(arg1)) {\n\n        // we are a write, but the object properties are the key/values\n        for (i = 0; i < nodeCount; i++) {\n          if (fn === jqLiteData) {\n            // data() takes the whole object in jQuery\n            fn(this[i], arg1);\n          } else {\n            for (key in arg1) {\n              fn(this[i], key, arg1[key]);\n            }\n          }\n        }\n        // return self for chaining\n        return this;\n      } else {\n        // we are a read, so read the first child.\n        // TODO: do we still need this?\n        var value = fn.$dv;\n        // Only if we have $dv do we iterate over all, otherwise it is just the first element.\n        var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;\n        for (var j = 0; j < jj; j++) {\n          var nodeValue = fn(this[j], arg1, arg2);\n          value = value ? value + nodeValue : nodeValue;\n        }\n        return value;\n      }\n    } else {\n      // we are a write, so apply to all children\n      for (i = 0; i < nodeCount; i++) {\n        fn(this[i], arg1, arg2);\n      }\n      // return self for chaining\n      return this;\n    }\n  };\n});\n\nfunction createEventHandler(element, events) {\n  var eventHandler = function(event, type) {\n    // jQuery specific api\n    event.isDefaultPrevented = function() {\n      return event.defaultPrevented;\n    };\n\n    var eventFns = events[type || event.type];\n    var eventFnsLength = eventFns ? eventFns.length : 0;\n\n    if (!eventFnsLength) return;\n\n    if (isUndefined(event.immediatePropagationStopped)) {\n      var originalStopImmediatePropagation = event.stopImmediatePropagation;\n      event.stopImmediatePropagation = function() {\n        event.immediatePropagationStopped = true;\n\n        if (event.stopPropagation) {\n          event.stopPropagation();\n        }\n\n        if (originalStopImmediatePropagation) {\n          originalStopImmediatePropagation.call(event);\n        }\n      };\n    }\n\n    event.isImmediatePropagationStopped = function() {\n      return event.immediatePropagationStopped === true;\n    };\n\n    // Copy event handlers in case event handlers array is modified during execution.\n    if ((eventFnsLength > 1)) {\n      eventFns = shallowCopy(eventFns);\n    }\n\n    for (var i = 0; i < eventFnsLength; i++) {\n      if (!event.isImmediatePropagationStopped()) {\n        eventFns[i].call(element, event);\n      }\n    }\n  };\n\n  // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all\n  //       events on `element`\n  eventHandler.elem = element;\n  return eventHandler;\n}\n\n//////////////////////////////////////////\n// Functions iterating traversal.\n// These functions chain results into a single\n// selector.\n//////////////////////////////////////////\nforEach({\n  removeData: jqLiteRemoveData,\n\n  on: function jqLiteOn(element, type, fn, unsupported) {\n    if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');\n\n    // Do not add event handlers to non-elements because they will not be cleaned up.\n    if (!jqLiteAcceptsData(element)) {\n      return;\n    }\n\n    var expandoStore = jqLiteExpandoStore(element, true);\n    var events = expandoStore.events;\n    var handle = expandoStore.handle;\n\n    if (!handle) {\n      handle = expandoStore.handle = createEventHandler(element, events);\n    }\n\n    // http://jsperf.com/string-indexof-vs-split\n    var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];\n    var i = types.length;\n\n    while (i--) {\n      type = types[i];\n      var eventFns = events[type];\n\n      if (!eventFns) {\n        events[type] = [];\n\n        if (type === 'mouseenter' || type === 'mouseleave') {\n          // Refer to jQuery's implementation of mouseenter & mouseleave\n          // Read about mouseenter and mouseleave:\n          // http://www.quirksmode.org/js/events_mouse.html#link8\n\n          jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {\n            var target = this, related = event.relatedTarget;\n            // For mousenter/leave call the handler if related is outside the target.\n            // NB: No relatedTarget if the mouse left/entered the browser window\n            if (!related || (related !== target && !target.contains(related))) {\n              handle(event, type);\n            }\n          });\n\n        } else {\n          if (type !== '$destroy') {\n            addEventListenerFn(element, type, handle);\n          }\n        }\n        eventFns = events[type];\n      }\n      eventFns.push(fn);\n    }\n  },\n\n  off: jqLiteOff,\n\n  one: function(element, type, fn) {\n    element = jqLite(element);\n\n    //add the listener twice so that when it is called\n    //you can remove the original function and still be\n    //able to call element.off(ev, fn) normally\n    element.on(type, function onFn() {\n      element.off(type, fn);\n      element.off(type, onFn);\n    });\n    element.on(type, fn);\n  },\n\n  replaceWith: function(element, replaceNode) {\n    var index, parent = element.parentNode;\n    jqLiteDealoc(element);\n    forEach(new JQLite(replaceNode), function(node) {\n      if (index) {\n        parent.insertBefore(node, index.nextSibling);\n      } else {\n        parent.replaceChild(node, element);\n      }\n      index = node;\n    });\n  },\n\n  children: function(element) {\n    var children = [];\n    forEach(element.childNodes, function(element) {\n      if (element.nodeType === NODE_TYPE_ELEMENT) {\n        children.push(element);\n      }\n    });\n    return children;\n  },\n\n  contents: function(element) {\n    return element.contentDocument || element.childNodes || [];\n  },\n\n  append: function(element, node) {\n    var nodeType = element.nodeType;\n    if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;\n\n    node = new JQLite(node);\n\n    for (var i = 0, ii = node.length; i < ii; i++) {\n      var child = node[i];\n      element.appendChild(child);\n    }\n  },\n\n  prepend: function(element, node) {\n    if (element.nodeType === NODE_TYPE_ELEMENT) {\n      var index = element.firstChild;\n      forEach(new JQLite(node), function(child) {\n        element.insertBefore(child, index);\n      });\n    }\n  },\n\n  wrap: function(element, wrapNode) {\n    wrapNode = jqLite(wrapNode).eq(0).clone()[0];\n    var parent = element.parentNode;\n    if (parent) {\n      parent.replaceChild(wrapNode, element);\n    }\n    wrapNode.appendChild(element);\n  },\n\n  remove: jqLiteRemove,\n\n  detach: function(element) {\n    jqLiteRemove(element, true);\n  },\n\n  after: function(element, newElement) {\n    var index = element, parent = element.parentNode;\n    newElement = new JQLite(newElement);\n\n    for (var i = 0, ii = newElement.length; i < ii; i++) {\n      var node = newElement[i];\n      parent.insertBefore(node, index.nextSibling);\n      index = node;\n    }\n  },\n\n  addClass: jqLiteAddClass,\n  removeClass: jqLiteRemoveClass,\n\n  toggleClass: function(element, selector, condition) {\n    if (selector) {\n      forEach(selector.split(' '), function(className) {\n        var classCondition = condition;\n        if (isUndefined(classCondition)) {\n          classCondition = !jqLiteHasClass(element, className);\n        }\n        (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);\n      });\n    }\n  },\n\n  parent: function(element) {\n    var parent = element.parentNode;\n    return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;\n  },\n\n  next: function(element) {\n    return element.nextElementSibling;\n  },\n\n  find: function(element, selector) {\n    if (element.getElementsByTagName) {\n      return element.getElementsByTagName(selector);\n    } else {\n      return [];\n    }\n  },\n\n  clone: jqLiteClone,\n\n  triggerHandler: function(element, event, extraParameters) {\n\n    var dummyEvent, eventFnsCopy, handlerArgs;\n    var eventName = event.type || event;\n    var expandoStore = jqLiteExpandoStore(element);\n    var events = expandoStore && expandoStore.events;\n    var eventFns = events && events[eventName];\n\n    if (eventFns) {\n      // Create a dummy event to pass to the handlers\n      dummyEvent = {\n        preventDefault: function() { this.defaultPrevented = true; },\n        isDefaultPrevented: function() { return this.defaultPrevented === true; },\n        stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },\n        isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },\n        stopPropagation: noop,\n        type: eventName,\n        target: element\n      };\n\n      // If a custom event was provided then extend our dummy event with it\n      if (event.type) {\n        dummyEvent = extend(dummyEvent, event);\n      }\n\n      // Copy event handlers in case event handlers array is modified during execution.\n      eventFnsCopy = shallowCopy(eventFns);\n      handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];\n\n      forEach(eventFnsCopy, function(fn) {\n        if (!dummyEvent.isImmediatePropagationStopped()) {\n          fn.apply(element, handlerArgs);\n        }\n      });\n    }\n  }\n}, function(fn, name) {\n  /**\n   * chaining functions\n   */\n  JQLite.prototype[name] = function(arg1, arg2, arg3) {\n    var value;\n\n    for (var i = 0, ii = this.length; i < ii; i++) {\n      if (isUndefined(value)) {\n        value = fn(this[i], arg1, arg2, arg3);\n        if (isDefined(value)) {\n          // any function which returns a value needs to be wrapped\n          value = jqLite(value);\n        }\n      } else {\n        jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));\n      }\n    }\n    return isDefined(value) ? value : this;\n  };\n\n  // bind legacy bind/unbind to on/off\n  JQLite.prototype.bind = JQLite.prototype.on;\n  JQLite.prototype.unbind = JQLite.prototype.off;\n});\n\n\n// Provider for private $$jqLite service\nfunction $$jqLiteProvider() {\n  this.$get = function $$jqLite() {\n    return extend(JQLite, {\n      hasClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteHasClass(node, classes);\n      },\n      addClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteAddClass(node, classes);\n      },\n      removeClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteRemoveClass(node, classes);\n      }\n    });\n  };\n}\n\n/**\n * Computes a hash of an 'obj'.\n * Hash of a:\n *  string is string\n *  number is number as string\n *  object is either result of calling $$hashKey function on the object or uniquely generated id,\n *         that is also assigned to the $$hashKey property of the object.\n *\n * @param obj\n * @returns {string} hash string such that the same input will have the same hash string.\n *         The resulting string key is in 'type:hashKey' format.\n */\nfunction hashKey(obj, nextUidFn) {\n  var key = obj && obj.$$hashKey;\n\n  if (key) {\n    if (typeof key === 'function') {\n      key = obj.$$hashKey();\n    }\n    return key;\n  }\n\n  var objType = typeof obj;\n  if (objType == 'function' || (objType == 'object' && obj !== null)) {\n    key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();\n  } else {\n    key = objType + ':' + obj;\n  }\n\n  return key;\n}\n\n/**\n * HashMap which can use objects as keys\n */\nfunction HashMap(array, isolatedUid) {\n  if (isolatedUid) {\n    var uid = 0;\n    this.nextUid = function() {\n      return ++uid;\n    };\n  }\n  forEach(array, this.put, this);\n}\nHashMap.prototype = {\n  /**\n   * Store key value pair\n   * @param key key to store can be any type\n   * @param value value to store can be any type\n   */\n  put: function(key, value) {\n    this[hashKey(key, this.nextUid)] = value;\n  },\n\n  /**\n   * @param key\n   * @returns {Object} the value for the key\n   */\n  get: function(key) {\n    return this[hashKey(key, this.nextUid)];\n  },\n\n  /**\n   * Remove the key/value pair\n   * @param key\n   */\n  remove: function(key) {\n    var value = this[key = hashKey(key, this.nextUid)];\n    delete this[key];\n    return value;\n  }\n};\n\nvar $$HashMapProvider = [function() {\n  this.$get = [function() {\n    return HashMap;\n  }];\n}];\n\n/**\n * @ngdoc function\n * @module ng\n * @name angular.injector\n * @kind function\n *\n * @description\n * Creates an injector object that can be used for retrieving services as well as for\n * dependency injection (see {@link guide/di dependency injection}).\n *\n * @param {Array.<string|Function>} modules A list of module functions or their aliases. See\n *     {@link angular.module}. The `ng` module must be explicitly added.\n * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which\n *     disallows argument name annotation inference.\n * @returns {injector} Injector object. See {@link auto.$injector $injector}.\n *\n * @example\n * Typical usage\n * ```js\n *   // create an injector\n *   var $injector = angular.injector(['ng']);\n *\n *   // use the injector to kick off your application\n *   // use the type inference to auto inject arguments, or use implicit injection\n *   $injector.invoke(function($rootScope, $compile, $document) {\n *     $compile($document)($rootScope);\n *     $rootScope.$digest();\n *   });\n * ```\n *\n * Sometimes you want to get access to the injector of a currently running Angular app\n * from outside Angular. Perhaps, you want to inject and compile some markup after the\n * application has been bootstrapped. You can do this using the extra `injector()` added\n * to JQuery/jqLite elements. See {@link angular.element}.\n *\n * *This is fairly rare but could be the case if a third party library is injecting the\n * markup.*\n *\n * In the following example a new block of HTML containing a `ng-controller`\n * directive is added to the end of the document body by JQuery. We then compile and link\n * it into the current AngularJS scope.\n *\n * ```js\n * var $div = $('<div ng-controller=\"MyCtrl\">{{content.label}}</div>');\n * $(document.body).append($div);\n *\n * angular.element(document).injector().invoke(function($compile) {\n *   var scope = angular.element($div).scope();\n *   $compile($div)(scope);\n * });\n * ```\n */\n\n\n/**\n * @ngdoc module\n * @name auto\n * @description\n *\n * Implicit module which gets automatically added to each {@link auto.$injector $injector}.\n */\n\nvar FN_ARGS = /^[^\\(]*\\(\\s*([^\\)]*)\\)/m;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nvar $injectorMinErr = minErr('$injector');\n\nfunction anonFn(fn) {\n  // For anonymous functions, showing at the very least the function signature can help in\n  // debugging.\n  var fnText = fn.toString().replace(STRIP_COMMENTS, ''),\n      args = fnText.match(FN_ARGS);\n  if (args) {\n    return 'function(' + (args[1] || '').replace(/[\\s\\r\\n]+/, ' ') + ')';\n  }\n  return 'fn';\n}\n\nfunction annotate(fn, strictDi, name) {\n  var $inject,\n      fnText,\n      argDecl,\n      last;\n\n  if (typeof fn === 'function') {\n    if (!($inject = fn.$inject)) {\n      $inject = [];\n      if (fn.length) {\n        if (strictDi) {\n          if (!isString(name) || !name) {\n            name = fn.name || anonFn(fn);\n          }\n          throw $injectorMinErr('strictdi',\n            '{0} is not using explicit annotation and cannot be invoked in strict mode', name);\n        }\n        fnText = fn.toString().replace(STRIP_COMMENTS, '');\n        argDecl = fnText.match(FN_ARGS);\n        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n          arg.replace(FN_ARG, function(all, underscore, name) {\n            $inject.push(name);\n          });\n        });\n      }\n      fn.$inject = $inject;\n    }\n  } else if (isArray(fn)) {\n    last = fn.length - 1;\n    assertArgFn(fn[last], 'fn');\n    $inject = fn.slice(0, last);\n  } else {\n    assertArgFn(fn, 'fn', true);\n  }\n  return $inject;\n}\n\n///////////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $injector\n *\n * @description\n *\n * `$injector` is used to retrieve object instances as defined by\n * {@link auto.$provide provider}, instantiate types, invoke methods,\n * and load modules.\n *\n * The following always holds true:\n *\n * ```js\n *   var $injector = angular.injector();\n *   expect($injector.get('$injector')).toBe($injector);\n *   expect($injector.invoke(function($injector) {\n *     return $injector;\n *   })).toBe($injector);\n * ```\n *\n * # Injection Function Annotation\n *\n * JavaScript does not have annotations, and annotations are needed for dependency injection. The\n * following are all valid ways of annotating function with injection arguments and are equivalent.\n *\n * ```js\n *   // inferred (only works if code not minified/obfuscated)\n *   $injector.invoke(function(serviceA){});\n *\n *   // annotated\n *   function explicit(serviceA) {};\n *   explicit.$inject = ['serviceA'];\n *   $injector.invoke(explicit);\n *\n *   // inline\n *   $injector.invoke(['serviceA', function(serviceA){}]);\n * ```\n *\n * ## Inference\n *\n * In JavaScript calling `toString()` on a function returns the function definition. The definition\n * can then be parsed and the function arguments can be extracted. This method of discovering\n * annotations is disallowed when the injector is in strict mode.\n * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the\n * argument names.\n *\n * ## `$inject` Annotation\n * By adding an `$inject` property onto a function the injection parameters can be specified.\n *\n * ## Inline\n * As an array of injection names, where the last item in the array is the function to call.\n */\n\n/**\n * @ngdoc method\n * @name $injector#get\n *\n * @description\n * Return an instance of the service.\n *\n * @param {string} name The name of the instance to retrieve.\n * @param {string=} caller An optional string to provide the origin of the function call for error messages.\n * @return {*} The instance.\n */\n\n/**\n * @ngdoc method\n * @name $injector#invoke\n *\n * @description\n * Invoke the method and supply the method arguments from the `$injector`.\n *\n * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are\n *   injected according to the {@link guide/di $inject Annotation} rules.\n * @param {Object=} self The `this` for the invoked method.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n *                         object first, before the `$injector` is consulted.\n * @returns {*} the value returned by the invoked `fn` function.\n */\n\n/**\n * @ngdoc method\n * @name $injector#has\n *\n * @description\n * Allows the user to query if the particular service exists.\n *\n * @param {string} name Name of the service to query.\n * @returns {boolean} `true` if injector has given service.\n */\n\n/**\n * @ngdoc method\n * @name $injector#instantiate\n * @description\n * Create a new instance of JS type. The method takes a constructor function, invokes the new\n * operator, and supplies all of the arguments to the constructor function as specified by the\n * constructor annotation.\n *\n * @param {Function} Type Annotated constructor function.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {Object} new instance of `Type`.\n */\n\n/**\n * @ngdoc method\n * @name $injector#annotate\n *\n * @description\n * Returns an array of service names which the function is requesting for injection. This API is\n * used by the injector to determine which services need to be injected into the function when the\n * function is invoked. There are three ways in which the function can be annotated with the needed\n * dependencies.\n *\n * # Argument names\n *\n * The simplest form is to extract the dependencies from the arguments of the function. This is done\n * by converting the function into a string using `toString()` method and extracting the argument\n * names.\n * ```js\n *   // Given\n *   function MyController($scope, $route) {\n *     // ...\n *   }\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * You can disallow this method by using strict injection mode.\n *\n * This method does not work with code minification / obfuscation. For this reason the following\n * annotation strategies are supported.\n *\n * # The `$inject` property\n *\n * If a function has an `$inject` property and its value is an array of strings, then the strings\n * represent names of services to be injected into the function.\n * ```js\n *   // Given\n *   var MyController = function(obfuscatedScope, obfuscatedRoute) {\n *     // ...\n *   }\n *   // Define function dependencies\n *   MyController['$inject'] = ['$scope', '$route'];\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * # The array notation\n *\n * It is often desirable to inline Injected functions and that's when setting the `$inject` property\n * is very inconvenient. In these situations using the array notation to specify the dependencies in\n * a way that survives minification is a better choice:\n *\n * ```js\n *   // We wish to write this (not minification / obfuscation safe)\n *   injector.invoke(function($compile, $rootScope) {\n *     // ...\n *   });\n *\n *   // We are forced to write break inlining\n *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {\n *     // ...\n *   };\n *   tmpFn.$inject = ['$compile', '$rootScope'];\n *   injector.invoke(tmpFn);\n *\n *   // To better support inline function the inline annotation is supported\n *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {\n *     // ...\n *   }]);\n *\n *   // Therefore\n *   expect(injector.annotate(\n *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])\n *    ).toEqual(['$compile', '$rootScope']);\n * ```\n *\n * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to\n * be retrieved as described above.\n *\n * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.\n *\n * @returns {Array.<string>} The names of the services which the function requires.\n */\n\n\n\n\n/**\n * @ngdoc service\n * @name $provide\n *\n * @description\n *\n * The {@link auto.$provide $provide} service has a number of methods for registering components\n * with the {@link auto.$injector $injector}. Many of these functions are also exposed on\n * {@link angular.Module}.\n *\n * An Angular **service** is a singleton object created by a **service factory**.  These **service\n * factories** are functions which, in turn, are created by a **service provider**.\n * The **service providers** are constructor functions. When instantiated they must contain a\n * property called `$get`, which holds the **service factory** function.\n *\n * When you request a service, the {@link auto.$injector $injector} is responsible for finding the\n * correct **service provider**, instantiating it and then calling its `$get` **service factory**\n * function to get the instance of the **service**.\n *\n * Often services have no configuration options and there is no need to add methods to the service\n * provider.  The provider will be no more than a constructor function with a `$get` property. For\n * these cases the {@link auto.$provide $provide} service has additional helper methods to register\n * services without specifying a provider.\n *\n * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the\n *     {@link auto.$injector $injector}\n * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by\n *     providers and services.\n * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by\n *     services, not providers.\n * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,\n *     that will be wrapped in a **service provider** object, whose `$get` property will contain the\n *     given factory function.\n * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`\n *     that will be wrapped in a **service provider** object, whose `$get` property will instantiate\n *      a new object using the given constructor function.\n *\n * See the individual methods for more information and examples.\n */\n\n/**\n * @ngdoc method\n * @name $provide#provider\n * @description\n *\n * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions\n * are constructor functions, whose instances are responsible for \"providing\" a factory for a\n * service.\n *\n * Service provider names start with the name of the service they provide followed by `Provider`.\n * For example, the {@link ng.$log $log} service has a provider called\n * {@link ng.$logProvider $logProvider}.\n *\n * Service provider objects can have additional methods which allow configuration of the provider\n * and its service. Importantly, you can configure what kind of service is created by the `$get`\n * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a\n * method {@link ng.$logProvider#debugEnabled debugEnabled}\n * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the\n * console or not.\n *\n * @param {string} name The name of the instance. NOTE: the provider will be available under `name +\n                        'Provider'` key.\n * @param {(Object|function())} provider If the provider is:\n *\n *   - `Object`: then it should have a `$get` method. The `$get` method will be invoked using\n *     {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.\n *   - `Constructor`: a new instance of the provider will be created using\n *     {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.\n *\n * @returns {Object} registered provider instance\n\n * @example\n *\n * The following example shows how to create a simple event tracking service and register it using\n * {@link auto.$provide#provider $provide.provider()}.\n *\n * ```js\n *  // Define the eventTracker provider\n *  function EventTrackerProvider() {\n *    var trackingUrl = '/track';\n *\n *    // A provider method for configuring where the tracked events should been saved\n *    this.setTrackingUrl = function(url) {\n *      trackingUrl = url;\n *    };\n *\n *    // The service factory function\n *    this.$get = ['$http', function($http) {\n *      var trackedEvents = {};\n *      return {\n *        // Call this to track an event\n *        event: function(event) {\n *          var count = trackedEvents[event] || 0;\n *          count += 1;\n *          trackedEvents[event] = count;\n *          return count;\n *        },\n *        // Call this to save the tracked events to the trackingUrl\n *        save: function() {\n *          $http.post(trackingUrl, trackedEvents);\n *        }\n *      };\n *    }];\n *  }\n *\n *  describe('eventTracker', function() {\n *    var postSpy;\n *\n *    beforeEach(module(function($provide) {\n *      // Register the eventTracker provider\n *      $provide.provider('eventTracker', EventTrackerProvider);\n *    }));\n *\n *    beforeEach(module(function(eventTrackerProvider) {\n *      // Configure eventTracker provider\n *      eventTrackerProvider.setTrackingUrl('/custom-track');\n *    }));\n *\n *    it('tracks events', inject(function(eventTracker) {\n *      expect(eventTracker.event('login')).toEqual(1);\n *      expect(eventTracker.event('login')).toEqual(2);\n *    }));\n *\n *    it('saves to the tracking url', inject(function(eventTracker, $http) {\n *      postSpy = spyOn($http, 'post');\n *      eventTracker.event('login');\n *      eventTracker.save();\n *      expect(postSpy).toHaveBeenCalled();\n *      expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');\n *      expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');\n *      expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });\n *    }));\n *  });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $provide#factory\n * @description\n *\n * Register a **service factory**, which will be called to return the service instance.\n * This is short for registering a service where its provider consists of only a `$get` property,\n * which is the given service factory function.\n * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to\n * configure your service in a provider.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.\n *                      Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service\n * ```js\n *   $provide.factory('ping', ['$http', function($http) {\n *     return function ping() {\n *       return $http.send('/ping');\n *     };\n *   }]);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#service\n * @description\n *\n * Register a **service constructor**, which will be invoked with `new` to create the service\n * instance.\n * This is short for registering a service where its provider's `$get` property is the service\n * constructor function that will be used to instantiate the service instance.\n *\n * You should use {@link auto.$provide#service $provide.service(class)} if you define your service\n * as a type/class.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)\n *     that will be instantiated.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service using\n * {@link auto.$provide#service $provide.service(class)}.\n * ```js\n *   var Ping = function($http) {\n *     this.$http = $http;\n *   };\n *\n *   Ping.$inject = ['$http'];\n *\n *   Ping.prototype.send = function() {\n *     return this.$http.get('/ping');\n *   };\n *   $provide.service('ping', Ping);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping.send();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#value\n * @description\n *\n * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a\n * number, an array, an object or a function.  This is short for registering a service where its\n * provider's `$get` property is a factory function that takes no arguments and returns the **value\n * service**.\n *\n * Value services are similar to constant services, except that they cannot be injected into a\n * module configuration function (see {@link angular.Module#config}) but they can be overridden by\n * an Angular\n * {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the instance.\n * @param {*} value The value.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here are some examples of creating value services.\n * ```js\n *   $provide.value('ADMIN_USER', 'admin');\n *\n *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });\n *\n *   $provide.value('halfOf', function(value) {\n *     return value / 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#constant\n * @description\n *\n * Register a **constant service**, such as a string, a number, an array, an object or a function,\n * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be\n * injected into a module configuration function (see {@link angular.Module#config}) and it cannot\n * be overridden by an Angular {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the constant.\n * @param {*} value The constant value.\n * @returns {Object} registered instance\n *\n * @example\n * Here a some examples of creating constants:\n * ```js\n *   $provide.constant('SHARD_HEIGHT', 306);\n *\n *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);\n *\n *   $provide.constant('double', function(value) {\n *     return value * 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#decorator\n * @description\n *\n * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator\n * intercepts the creation of a service, allowing it to override or modify the behaviour of the\n * service. The object returned by the decorator may be the original service, or a new service\n * object which replaces or wraps and delegates to the original service.\n *\n * @param {string} name The name of the service to decorate.\n * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be\n *    instantiated and should return the decorated service instance. The function is called using\n *    the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.\n *    Local injection arguments:\n *\n *    * `$delegate` - The original service instance, which can be monkey patched, configured,\n *      decorated or delegated to.\n *\n * @example\n * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting\n * calls to {@link ng.$log#error $log.warn()}.\n * ```js\n *   $provide.decorator('$log', ['$delegate', function($delegate) {\n *     $delegate.warn = $delegate.error;\n *     return $delegate;\n *   }]);\n * ```\n */\n\n\nfunction createInjector(modulesToLoad, strictDi) {\n  strictDi = (strictDi === true);\n  var INSTANTIATING = {},\n      providerSuffix = 'Provider',\n      path = [],\n      loadedModules = new HashMap([], true),\n      providerCache = {\n        $provide: {\n            provider: supportObject(provider),\n            factory: supportObject(factory),\n            service: supportObject(service),\n            value: supportObject(value),\n            constant: supportObject(constant),\n            decorator: decorator\n          }\n      },\n      providerInjector = (providerCache.$injector =\n          createInternalInjector(providerCache, function(serviceName, caller) {\n            if (angular.isString(caller)) {\n              path.push(caller);\n            }\n            throw $injectorMinErr('unpr', \"Unknown provider: {0}\", path.join(' <- '));\n          })),\n      instanceCache = {},\n      instanceInjector = (instanceCache.$injector =\n          createInternalInjector(instanceCache, function(serviceName, caller) {\n            var provider = providerInjector.get(serviceName + providerSuffix, caller);\n            return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);\n          }));\n\n\n  forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });\n\n  return instanceInjector;\n\n  ////////////////////////////////////\n  // $provider\n  ////////////////////////////////////\n\n  function supportObject(delegate) {\n    return function(key, value) {\n      if (isObject(key)) {\n        forEach(key, reverseParams(delegate));\n      } else {\n        return delegate(key, value);\n      }\n    };\n  }\n\n  function provider(name, provider_) {\n    assertNotHasOwnProperty(name, 'service');\n    if (isFunction(provider_) || isArray(provider_)) {\n      provider_ = providerInjector.instantiate(provider_);\n    }\n    if (!provider_.$get) {\n      throw $injectorMinErr('pget', \"Provider '{0}' must define $get factory method.\", name);\n    }\n    return providerCache[name + providerSuffix] = provider_;\n  }\n\n  function enforceReturnValue(name, factory) {\n    return function enforcedReturnValue() {\n      var result = instanceInjector.invoke(factory, this);\n      if (isUndefined(result)) {\n        throw $injectorMinErr('undef', \"Provider '{0}' must return a value from $get factory method.\", name);\n      }\n      return result;\n    };\n  }\n\n  function factory(name, factoryFn, enforce) {\n    return provider(name, {\n      $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn\n    });\n  }\n\n  function service(name, constructor) {\n    return factory(name, ['$injector', function($injector) {\n      return $injector.instantiate(constructor);\n    }]);\n  }\n\n  function value(name, val) { return factory(name, valueFn(val), false); }\n\n  function constant(name, value) {\n    assertNotHasOwnProperty(name, 'constant');\n    providerCache[name] = value;\n    instanceCache[name] = value;\n  }\n\n  function decorator(serviceName, decorFn) {\n    var origProvider = providerInjector.get(serviceName + providerSuffix),\n        orig$get = origProvider.$get;\n\n    origProvider.$get = function() {\n      var origInstance = instanceInjector.invoke(orig$get, origProvider);\n      return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});\n    };\n  }\n\n  ////////////////////////////////////\n  // Module Loading\n  ////////////////////////////////////\n  function loadModules(modulesToLoad) {\n    assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');\n    var runBlocks = [], moduleFn;\n    forEach(modulesToLoad, function(module) {\n      if (loadedModules.get(module)) return;\n      loadedModules.put(module, true);\n\n      function runInvokeQueue(queue) {\n        var i, ii;\n        for (i = 0, ii = queue.length; i < ii; i++) {\n          var invokeArgs = queue[i],\n              provider = providerInjector.get(invokeArgs[0]);\n\n          provider[invokeArgs[1]].apply(provider, invokeArgs[2]);\n        }\n      }\n\n      try {\n        if (isString(module)) {\n          moduleFn = angularModule(module);\n          runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);\n          runInvokeQueue(moduleFn._invokeQueue);\n          runInvokeQueue(moduleFn._configBlocks);\n        } else if (isFunction(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else if (isArray(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else {\n          assertArgFn(module, 'module');\n        }\n      } catch (e) {\n        if (isArray(module)) {\n          module = module[module.length - 1];\n        }\n        if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {\n          // Safari & FF's stack traces don't contain error.message content\n          // unlike those of Chrome and IE\n          // So if stack doesn't contain message, we create a new string that contains both.\n          // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.\n          /* jshint -W022 */\n          e = e.message + '\\n' + e.stack;\n        }\n        throw $injectorMinErr('modulerr', \"Failed to instantiate module {0} due to:\\n{1}\",\n                  module, e.stack || e.message || e);\n      }\n    });\n    return runBlocks;\n  }\n\n  ////////////////////////////////////\n  // internal Injector\n  ////////////////////////////////////\n\n  function createInternalInjector(cache, factory) {\n\n    function getService(serviceName, caller) {\n      if (cache.hasOwnProperty(serviceName)) {\n        if (cache[serviceName] === INSTANTIATING) {\n          throw $injectorMinErr('cdep', 'Circular dependency found: {0}',\n                    serviceName + ' <- ' + path.join(' <- '));\n        }\n        return cache[serviceName];\n      } else {\n        try {\n          path.unshift(serviceName);\n          cache[serviceName] = INSTANTIATING;\n          return cache[serviceName] = factory(serviceName, caller);\n        } catch (err) {\n          if (cache[serviceName] === INSTANTIATING) {\n            delete cache[serviceName];\n          }\n          throw err;\n        } finally {\n          path.shift();\n        }\n      }\n    }\n\n    function invoke(fn, self, locals, serviceName) {\n      if (typeof locals === 'string') {\n        serviceName = locals;\n        locals = null;\n      }\n\n      var args = [],\n          $inject = createInjector.$$annotate(fn, strictDi, serviceName),\n          length, i,\n          key;\n\n      for (i = 0, length = $inject.length; i < length; i++) {\n        key = $inject[i];\n        if (typeof key !== 'string') {\n          throw $injectorMinErr('itkn',\n                  'Incorrect injection token! Expected service name as string, got {0}', key);\n        }\n        args.push(\n          locals && locals.hasOwnProperty(key)\n          ? locals[key]\n          : getService(key, serviceName)\n        );\n      }\n      if (isArray(fn)) {\n        fn = fn[length];\n      }\n\n      // http://jsperf.com/angularjs-invoke-apply-vs-switch\n      // #5388\n      return fn.apply(self, args);\n    }\n\n    function instantiate(Type, locals, serviceName) {\n      // Check if Type is annotated and use just the given function at n-1 as parameter\n      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);\n      // Object creation: http://jsperf.com/create-constructor/2\n      var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);\n      var returnedValue = invoke(Type, instance, locals, serviceName);\n\n      return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;\n    }\n\n    return {\n      invoke: invoke,\n      instantiate: instantiate,\n      get: getService,\n      annotate: createInjector.$$annotate,\n      has: function(name) {\n        return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);\n      }\n    };\n  }\n}\n\ncreateInjector.$$annotate = annotate;\n\n/**\n * @ngdoc provider\n * @name $anchorScrollProvider\n *\n * @description\n * Use `$anchorScrollProvider` to disable automatic scrolling whenever\n * {@link ng.$location#hash $location.hash()} changes.\n */\nfunction $AnchorScrollProvider() {\n\n  var autoScrollingEnabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $anchorScrollProvider#disableAutoScrolling\n   *\n   * @description\n   * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to\n   * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />\n   * Use this method to disable automatic scrolling.\n   *\n   * If automatic scrolling is disabled, one must explicitly call\n   * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the\n   * current hash.\n   */\n  this.disableAutoScrolling = function() {\n    autoScrollingEnabled = false;\n  };\n\n  /**\n   * @ngdoc service\n   * @name $anchorScroll\n   * @kind function\n   * @requires $window\n   * @requires $location\n   * @requires $rootScope\n   *\n   * @description\n   * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the\n   * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified\n   * in the\n   * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).\n   *\n   * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to\n   * match any anchor whenever it changes. This can be disabled by calling\n   * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.\n   *\n   * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a\n   * vertical scroll-offset (either fixed or dynamic).\n   *\n   * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of\n   *                       {@link ng.$location#hash $location.hash()} will be used.\n   *\n   * @property {(number|function|jqLite)} yOffset\n   * If set, specifies a vertical scroll-offset. This is often useful when there are fixed\n   * positioned elements at the top of the page, such as navbars, headers etc.\n   *\n   * `yOffset` can be specified in various ways:\n   * - **number**: A fixed number of pixels to be used as offset.<br /><br />\n   * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return\n   *   a number representing the offset (in pixels).<br /><br />\n   * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from\n   *   the top of the page to the element's bottom will be used as offset.<br />\n   *   **Note**: The element will be taken into account only as long as its `position` is set to\n   *   `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust\n   *   their height and/or positioning according to the viewport's size.\n   *\n   * <br />\n   * <div class=\"alert alert-warning\">\n   * In order for `yOffset` to work properly, scrolling should take place on the document's root and\n   * not some child element.\n   * </div>\n   *\n   * @example\n     <example module=\"anchorScrollExample\">\n       <file name=\"index.html\">\n         <div id=\"scrollArea\" ng-controller=\"ScrollController\">\n           <a ng-click=\"gotoBottom()\">Go to bottom</a>\n           <a id=\"bottom\"></a> You're at the bottom!\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollExample', [])\n           .controller('ScrollController', ['$scope', '$location', '$anchorScroll',\n             function ($scope, $location, $anchorScroll) {\n               $scope.gotoBottom = function() {\n                 // set the location.hash to the id of\n                 // the element you wish to scroll to.\n                 $location.hash('bottom');\n\n                 // call $anchorScroll()\n                 $anchorScroll();\n               };\n             }]);\n       </file>\n       <file name=\"style.css\">\n         #scrollArea {\n           height: 280px;\n           overflow: auto;\n         }\n\n         #bottom {\n           display: block;\n           margin-top: 2000px;\n         }\n       </file>\n     </example>\n   *\n   * <hr />\n   * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).\n   * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.\n   *\n   * @example\n     <example module=\"anchorScrollOffsetExample\">\n       <file name=\"index.html\">\n         <div class=\"fixed-header\" ng-controller=\"headerCtrl\">\n           <a href=\"\" ng-click=\"gotoAnchor(x)\" ng-repeat=\"x in [1,2,3,4,5]\">\n             Go to anchor {{x}}\n           </a>\n         </div>\n         <div id=\"anchor{{x}}\" class=\"anchor\" ng-repeat=\"x in [1,2,3,4,5]\">\n           Anchor {{x}} of 5\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollOffsetExample', [])\n           .run(['$anchorScroll', function($anchorScroll) {\n             $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels\n           }])\n           .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',\n             function ($anchorScroll, $location, $scope) {\n               $scope.gotoAnchor = function(x) {\n                 var newHash = 'anchor' + x;\n                 if ($location.hash() !== newHash) {\n                   // set the $location.hash to `newHash` and\n                   // $anchorScroll will automatically scroll to it\n                   $location.hash('anchor' + x);\n                 } else {\n                   // call $anchorScroll() explicitly,\n                   // since $location.hash hasn't changed\n                   $anchorScroll();\n                 }\n               };\n             }\n           ]);\n       </file>\n       <file name=\"style.css\">\n         body {\n           padding-top: 50px;\n         }\n\n         .anchor {\n           border: 2px dashed DarkOrchid;\n           padding: 10px 10px 200px 10px;\n         }\n\n         .fixed-header {\n           background-color: rgba(0, 0, 0, 0.2);\n           height: 50px;\n           position: fixed;\n           top: 0; left: 0; right: 0;\n         }\n\n         .fixed-header > a {\n           display: inline-block;\n           margin: 5px 15px;\n         }\n       </file>\n     </example>\n   */\n  this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {\n    var document = $window.document;\n\n    // Helper function to get first anchor from a NodeList\n    // (using `Array#some()` instead of `angular#forEach()` since it's more performant\n    //  and working in all supported browsers.)\n    function getFirstAnchor(list) {\n      var result = null;\n      Array.prototype.some.call(list, function(element) {\n        if (nodeName_(element) === 'a') {\n          result = element;\n          return true;\n        }\n      });\n      return result;\n    }\n\n    function getYOffset() {\n\n      var offset = scroll.yOffset;\n\n      if (isFunction(offset)) {\n        offset = offset();\n      } else if (isElement(offset)) {\n        var elem = offset[0];\n        var style = $window.getComputedStyle(elem);\n        if (style.position !== 'fixed') {\n          offset = 0;\n        } else {\n          offset = elem.getBoundingClientRect().bottom;\n        }\n      } else if (!isNumber(offset)) {\n        offset = 0;\n      }\n\n      return offset;\n    }\n\n    function scrollTo(elem) {\n      if (elem) {\n        elem.scrollIntoView();\n\n        var offset = getYOffset();\n\n        if (offset) {\n          // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.\n          // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the\n          // top of the viewport.\n          //\n          // IF the number of pixels from the top of `elem` to the end of the page's content is less\n          // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some\n          // way down the page.\n          //\n          // This is often the case for elements near the bottom of the page.\n          //\n          // In such cases we do not need to scroll the whole `offset` up, just the difference between\n          // the top of the element and the offset, which is enough to align the top of `elem` at the\n          // desired position.\n          var elemTop = elem.getBoundingClientRect().top;\n          $window.scrollBy(0, elemTop - offset);\n        }\n      } else {\n        $window.scrollTo(0, 0);\n      }\n    }\n\n    function scroll(hash) {\n      hash = isString(hash) ? hash : $location.hash();\n      var elm;\n\n      // empty hash, scroll to the top of the page\n      if (!hash) scrollTo(null);\n\n      // element with given id\n      else if ((elm = document.getElementById(hash))) scrollTo(elm);\n\n      // first anchor with given name :-D\n      else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);\n\n      // no element and hash == 'top', scroll to the top of the page\n      else if (hash === 'top') scrollTo(null);\n    }\n\n    // does not scroll when user clicks on anchor link that is currently on\n    // (no url change, no $location.hash() change), browser native does scroll\n    if (autoScrollingEnabled) {\n      $rootScope.$watch(function autoScrollWatch() {return $location.hash();},\n        function autoScrollWatchAction(newVal, oldVal) {\n          // skip the initial scroll if $location.hash is empty\n          if (newVal === oldVal && newVal === '') return;\n\n          jqLiteDocumentLoaded(function() {\n            $rootScope.$evalAsync(scroll);\n          });\n        });\n    }\n\n    return scroll;\n  }];\n}\n\nvar $animateMinErr = minErr('$animate');\nvar ELEMENT_NODE = 1;\nvar NG_ANIMATE_CLASSNAME = 'ng-animate';\n\nfunction mergeClasses(a,b) {\n  if (!a && !b) return '';\n  if (!a) return b;\n  if (!b) return a;\n  if (isArray(a)) a = a.join(' ');\n  if (isArray(b)) b = b.join(' ');\n  return a + ' ' + b;\n}\n\nfunction extractElementNode(element) {\n  for (var i = 0; i < element.length; i++) {\n    var elm = element[i];\n    if (elm.nodeType === ELEMENT_NODE) {\n      return elm;\n    }\n  }\n}\n\nfunction splitClasses(classes) {\n  if (isString(classes)) {\n    classes = classes.split(' ');\n  }\n\n  // Use createMap() to prevent class assumptions involving property names in\n  // Object.prototype\n  var obj = createMap();\n  forEach(classes, function(klass) {\n    // sometimes the split leaves empty string values\n    // incase extra spaces were applied to the options\n    if (klass.length) {\n      obj[klass] = true;\n    }\n  });\n  return obj;\n}\n\n// if any other type of options value besides an Object value is\n// passed into the $animate.method() animation then this helper code\n// will be run which will ignore it. While this patch is not the\n// greatest solution to this, a lot of existing plugins depend on\n// $animate to either call the callback (< 1.2) or return a promise\n// that can be changed. This helper function ensures that the options\n// are wiped clean incase a callback function is provided.\nfunction prepareAnimateOptions(options) {\n  return isObject(options)\n      ? options\n      : {};\n}\n\nvar $$CoreAnimateRunnerProvider = function() {\n  this.$get = ['$q', '$$rAF', function($q, $$rAF) {\n    function AnimateRunner() {}\n    AnimateRunner.all = noop;\n    AnimateRunner.chain = noop;\n    AnimateRunner.prototype = {\n      end: noop,\n      cancel: noop,\n      resume: noop,\n      pause: noop,\n      complete: noop,\n      then: function(pass, fail) {\n        return $q(function(resolve) {\n          $$rAF(function() {\n            resolve();\n          });\n        }).then(pass, fail);\n      }\n    };\n    return AnimateRunner;\n  }];\n};\n\n// this is prefixed with Core since it conflicts with\n// the animateQueueProvider defined in ngAnimate/animateQueue.js\nvar $$CoreAnimateQueueProvider = function() {\n  var postDigestQueue = new HashMap();\n  var postDigestElements = [];\n\n  this.$get = ['$$AnimateRunner', '$rootScope',\n       function($$AnimateRunner,   $rootScope) {\n    return {\n      enabled: noop,\n      on: noop,\n      off: noop,\n      pin: noop,\n\n      push: function(element, event, options, domOperation) {\n        domOperation        && domOperation();\n\n        options = options || {};\n        options.from        && element.css(options.from);\n        options.to          && element.css(options.to);\n\n        if (options.addClass || options.removeClass) {\n          addRemoveClassesPostDigest(element, options.addClass, options.removeClass);\n        }\n\n        return new $$AnimateRunner(); // jshint ignore:line\n      }\n    };\n\n    function addRemoveClassesPostDigest(element, add, remove) {\n      var classVal, data = postDigestQueue.get(element);\n\n      if (!data) {\n        postDigestQueue.put(element, data = {});\n        postDigestElements.push(element);\n      }\n\n      var updateData = function(classes, value) {\n        var changed = false;\n        if (classes) {\n          classes = isString(classes) ? classes.split(' ') :\n                    isArray(classes) ? classes : [];\n          forEach(classes, function(className) {\n            if (className) {\n              changed = true;\n              data[className] = value;\n            }\n          });\n        }\n        return changed;\n      };\n\n      var classesAdded = updateData(add, true);\n      var classesRemoved = updateData(remove, false);\n      if ((!classesAdded && !classesRemoved) || postDigestElements.length > 1) return;\n\n      $rootScope.$$postDigest(function() {\n        forEach(postDigestElements, function(element) {\n          var data = postDigestQueue.get(element);\n          if (data) {\n            var existing = splitClasses(element.attr('class'));\n            var toAdd = '';\n            var toRemove = '';\n            forEach(data, function(status, className) {\n              var hasClass = !!existing[className];\n              if (status !== hasClass) {\n                if (status) {\n                  toAdd += (toAdd.length ? ' ' : '') + className;\n                } else {\n                  toRemove += (toRemove.length ? ' ' : '') + className;\n                }\n              }\n            });\n\n            forEach(element, function(elm) {\n              toAdd    && jqLiteAddClass(elm, toAdd);\n              toRemove && jqLiteRemoveClass(elm, toRemove);\n            });\n            postDigestQueue.remove(element);\n          }\n        });\n\n        postDigestElements.length = 0;\n      });\n    }\n  }];\n};\n\n/**\n * @ngdoc provider\n * @name $animateProvider\n *\n * @description\n * Default implementation of $animate that doesn't perform any animations, instead just\n * synchronously performs DOM updates and resolves the returned runner promise.\n *\n * In order to enable animations the `ngAnimate` module has to be loaded.\n *\n * To see the functional implementation check out `src/ngAnimate/animate.js`.\n */\nvar $AnimateProvider = ['$provide', function($provide) {\n  var provider = this;\n\n  this.$$registeredAnimations = Object.create(null);\n\n   /**\n   * @ngdoc method\n   * @name $animateProvider#register\n   *\n   * @description\n   * Registers a new injectable animation factory function. The factory function produces the\n   * animation object which contains callback functions for each event that is expected to be\n   * animated.\n   *\n   *   * `eventFn`: `function(element, ... , doneFunction, options)`\n   *   The element to animate, the `doneFunction` and the options fed into the animation. Depending\n   *   on the type of animation additional arguments will be injected into the animation function. The\n   *   list below explains the function signatures for the different animation methods:\n   *\n   *   - setClass: function(element, addedClasses, removedClasses, doneFunction, options)\n   *   - addClass: function(element, addedClasses, doneFunction, options)\n   *   - removeClass: function(element, removedClasses, doneFunction, options)\n   *   - enter, leave, move: function(element, doneFunction, options)\n   *   - animate: function(element, fromStyles, toStyles, doneFunction, options)\n   *\n   *   Make sure to trigger the `doneFunction` once the animation is fully complete.\n   *\n   * ```js\n   *   return {\n   *     //enter, leave, move signature\n   *     eventFn : function(element, done, options) {\n   *       //code to run the animation\n   *       //once complete, then run done()\n   *       return function endFunction(wasCancelled) {\n   *         //code to cancel the animation\n   *       }\n   *     }\n   *   }\n   * ```\n   *\n   * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).\n   * @param {Function} factory The factory function that will be executed to return the animation\n   *                           object.\n   */\n  this.register = function(name, factory) {\n    if (name && name.charAt(0) !== '.') {\n      throw $animateMinErr('notcsel', \"Expecting class selector starting with '.' got '{0}'.\", name);\n    }\n\n    var key = name + '-animation';\n    provider.$$registeredAnimations[name.substr(1)] = key;\n    $provide.factory(key, factory);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $animateProvider#classNameFilter\n   *\n   * @description\n   * Sets and/or returns the CSS class regular expression that is checked when performing\n   * an animation. Upon bootstrap the classNameFilter value is not set at all and will\n   * therefore enable $animate to attempt to perform an animation on any element that is triggered.\n   * When setting the `classNameFilter` value, animations will only be performed on elements\n   * that successfully match the filter expression. This in turn can boost performance\n   * for low-powered devices as well as applications containing a lot of structural operations.\n   * @param {RegExp=} expression The className expression which will be checked against all animations\n   * @return {RegExp} The current CSS className expression value. If null then there is no expression value\n   */\n  this.classNameFilter = function(expression) {\n    if (arguments.length === 1) {\n      this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;\n      if (this.$$classNameFilter) {\n        var reservedRegex = new RegExp(\"(\\\\s+|\\\\/)\" + NG_ANIMATE_CLASSNAME + \"(\\\\s+|\\\\/)\");\n        if (reservedRegex.test(this.$$classNameFilter.toString())) {\n          throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the \"{0}\" CSS class.', NG_ANIMATE_CLASSNAME);\n\n        }\n      }\n    }\n    return this.$$classNameFilter;\n  };\n\n  this.$get = ['$$animateQueue', function($$animateQueue) {\n    function domInsert(element, parentElement, afterElement) {\n      // if for some reason the previous element was removed\n      // from the dom sometime before this code runs then let's\n      // just stick to using the parent element as the anchor\n      if (afterElement) {\n        var afterNode = extractElementNode(afterElement);\n        if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {\n          afterElement = null;\n        }\n      }\n      afterElement ? afterElement.after(element) : parentElement.prepend(element);\n    }\n\n    /**\n     * @ngdoc service\n     * @name $animate\n     * @description The $animate service exposes a series of DOM utility methods that provide support\n     * for animation hooks. The default behavior is the application of DOM operations, however,\n     * when an animation is detected (and animations are enabled), $animate will do the heavy lifting\n     * to ensure that animation runs with the triggered DOM operation.\n     *\n     * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't\n     * included and only when it is active then the animation hooks that `$animate` triggers will be\n     * functional. Once active then all structural `ng-` directives will trigger animations as they perform\n     * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,\n     * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.\n     *\n     * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.\n     *\n     * To learn more about enabling animation support, click here to visit the\n     * {@link ngAnimate ngAnimate module page}.\n     */\n    return {\n      // we don't call it directly since non-existant arguments may\n      // be interpreted as null within the sub enabled function\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#on\n       * @kind function\n       * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)\n       *    has fired on the given element or among any of its children. Once the listener is fired, the provided callback\n       *    is fired with the following params:\n       *\n       * ```js\n       * $animate.on('enter', container,\n       *    function callback(element, phase) {\n       *      // cool we detected an enter animation within the container\n       *    }\n       * );\n       * ```\n       *\n       * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)\n       * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself\n       *     as well as among its children\n       * @param {Function} callback the callback function that will be fired when the listener is triggered\n       *\n       * The arguments present in the callback function are:\n       * * `element` - The captured DOM element that the animation was fired on.\n       * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).\n       */\n      on: $$animateQueue.on,\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#off\n       * @kind function\n       * @description Deregisters an event listener based on the event which has been associated with the provided element. This method\n       * can be used in three different ways depending on the arguments:\n       *\n       * ```js\n       * // remove all the animation event listeners listening for `enter`\n       * $animate.off('enter');\n       *\n       * // remove all the animation event listeners listening for `enter` on the given element and its children\n       * $animate.off('enter', container);\n       *\n       * // remove the event listener function provided by `listenerFn` that is set\n       * // to listen for `enter` on the given `element` as well as its children\n       * $animate.off('enter', container, callback);\n       * ```\n       *\n       * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)\n       * @param {DOMElement=} container the container element the event listener was placed on\n       * @param {Function=} callback the callback function that was registered as the listener\n       */\n      off: $$animateQueue.off,\n\n      /**\n       * @ngdoc method\n       * @name $animate#pin\n       * @kind function\n       * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists\n       *    outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the\n       *    element despite being outside the realm of the application or within another application. Say for example if the application\n       *    was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated\n       *    as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind\n       *    that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.\n       *\n       *    Note that this feature is only active when the `ngAnimate` module is used.\n       *\n       * @param {DOMElement} element the external element that will be pinned\n       * @param {DOMElement} parentElement the host parent element that will be associated with the external element\n       */\n      pin: $$animateQueue.pin,\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#enabled\n       * @kind function\n       * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This\n       * function can be called in four ways:\n       *\n       * ```js\n       * // returns true or false\n       * $animate.enabled();\n       *\n       * // changes the enabled state for all animations\n       * $animate.enabled(false);\n       * $animate.enabled(true);\n       *\n       * // returns true or false if animations are enabled for an element\n       * $animate.enabled(element);\n       *\n       * // changes the enabled state for an element and its children\n       * $animate.enabled(element, true);\n       * $animate.enabled(element, false);\n       * ```\n       *\n       * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state\n       * @param {boolean=} enabled whether or not the animations will be enabled for the element\n       *\n       * @return {boolean} whether or not animations are enabled\n       */\n      enabled: $$animateQueue.enabled,\n\n      /**\n       * @ngdoc method\n       * @name $animate#cancel\n       * @kind function\n       * @description Cancels the provided animation.\n       *\n       * @param {Promise} animationPromise The animation promise that is returned when an animation is started.\n       */\n      cancel: function(runner) {\n        runner.end && runner.end();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#enter\n       * @kind function\n       * @description Inserts the element into the DOM either after the `after` element (if provided) or\n       *   as the first child within the `parent` element and then triggers an animation.\n       *   A promise is returned that will be resolved during the next digest once the animation\n       *   has completed.\n       *\n       * @param {DOMElement} element the element which will be inserted into the DOM\n       * @param {DOMElement} parent the parent element which will append the element as\n       *   a child (so long as the after element is not present)\n       * @param {DOMElement=} after the sibling element after which the element will be appended\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      enter: function(element, parent, after, options) {\n        parent = parent && jqLite(parent);\n        after = after && jqLite(after);\n        parent = parent || after.parent();\n        domInsert(element, parent, after);\n        return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#move\n       * @kind function\n       * @description Inserts (moves) the element into its new position in the DOM either after\n       *   the `after` element (if provided) or as the first child within the `parent` element\n       *   and then triggers an animation. A promise is returned that will be resolved\n       *   during the next digest once the animation has completed.\n       *\n       * @param {DOMElement} element the element which will be moved into the new DOM position\n       * @param {DOMElement} parent the parent element which will append the element as\n       *   a child (so long as the after element is not present)\n       * @param {DOMElement=} after the sibling element after which the element will be appended\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      move: function(element, parent, after, options) {\n        parent = parent && jqLite(parent);\n        after = after && jqLite(after);\n        parent = parent || after.parent();\n        domInsert(element, parent, after);\n        return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#leave\n       * @kind function\n       * @description Triggers an animation and then removes the element from the DOM.\n       * When the function is called a promise is returned that will be resolved during the next\n       * digest once the animation has completed.\n       *\n       * @param {DOMElement} element the element which will be removed from the DOM\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      leave: function(element, options) {\n        return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {\n          element.remove();\n        });\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#addClass\n       * @kind function\n       *\n       * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon\n       *   execution, the addClass operation will only be handled after the next digest and it will not trigger an\n       *   animation if element already contains the CSS class or if the class is removed at a later step.\n       *   Note that class-based animations are treated differently compared to structural animations\n       *   (like enter, move and leave) since the CSS classes may be added/removed at different points\n       *   depending if CSS or JavaScript animations are used.\n       *\n       * @param {DOMElement} element the element which the CSS classes will be applied to\n       * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      addClass: function(element, className, options) {\n        options = prepareAnimateOptions(options);\n        options.addClass = mergeClasses(options.addclass, className);\n        return $$animateQueue.push(element, 'addClass', options);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#removeClass\n       * @kind function\n       *\n       * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon\n       *   execution, the removeClass operation will only be handled after the next digest and it will not trigger an\n       *   animation if element does not contain the CSS class or if the class is added at a later step.\n       *   Note that class-based animations are treated differently compared to structural animations\n       *   (like enter, move and leave) since the CSS classes may be added/removed at different points\n       *   depending if CSS or JavaScript animations are used.\n       *\n       * @param {DOMElement} element the element which the CSS classes will be applied to\n       * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      removeClass: function(element, className, options) {\n        options = prepareAnimateOptions(options);\n        options.removeClass = mergeClasses(options.removeClass, className);\n        return $$animateQueue.push(element, 'removeClass', options);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#setClass\n       * @kind function\n       *\n       * @description Performs both the addition and removal of a CSS classes on an element and (during the process)\n       *    triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and\n       *    `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has\n       *    passed. Note that class-based animations are treated differently compared to structural animations\n       *    (like enter, move and leave) since the CSS classes may be added/removed at different points\n       *    depending if CSS or JavaScript animations are used.\n       *\n       * @param {DOMElement} element the element which the CSS classes will be applied to\n       * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)\n       * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      setClass: function(element, add, remove, options) {\n        options = prepareAnimateOptions(options);\n        options.addClass = mergeClasses(options.addClass, add);\n        options.removeClass = mergeClasses(options.removeClass, remove);\n        return $$animateQueue.push(element, 'setClass', options);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#animate\n       * @kind function\n       *\n       * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.\n       * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take\n       * on the provided styles. For example, if a transition animation is set for the given className then the provided from and\n       * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles\n       * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).\n       *\n       * @param {DOMElement} element the element which the CSS styles will be applied to\n       * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.\n       * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.\n       * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If\n       *    this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.\n       *    (Note that if no animation is detected then this value will not be appplied to the element.)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      animate: function(element, from, to, className, options) {\n        options = prepareAnimateOptions(options);\n        options.from = options.from ? extend(options.from, from) : from;\n        options.to   = options.to   ? extend(options.to, to)     : to;\n\n        className = className || 'ng-inline-animate';\n        options.tempClasses = mergeClasses(options.tempClasses, className);\n        return $$animateQueue.push(element, 'animate', options);\n      }\n    };\n  }];\n}];\n\n/**\n * @ngdoc service\n * @name $animateCss\n * @kind object\n *\n * @description\n * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,\n * then the `$animateCss` service will actually perform animations.\n *\n * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.\n */\nvar $CoreAnimateCssProvider = function() {\n  this.$get = ['$$rAF', '$q', function($$rAF, $q) {\n\n    var RAFPromise = function() {};\n    RAFPromise.prototype = {\n      done: function(cancel) {\n        this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();\n      },\n      end: function() {\n        this.done();\n      },\n      cancel: function() {\n        this.done(true);\n      },\n      getPromise: function() {\n        if (!this.defer) {\n          this.defer = $q.defer();\n        }\n        return this.defer.promise;\n      },\n      then: function(f1,f2) {\n        return this.getPromise().then(f1,f2);\n      },\n      'catch': function(f1) {\n        return this.getPromise().catch(f1);\n      },\n      'finally': function(f1) {\n        return this.getPromise().finally(f1);\n      }\n    };\n\n    return function(element, options) {\n      if (options.from) {\n        element.css(options.from);\n        options.from = null;\n      }\n\n      var closed, runner = new RAFPromise();\n      return {\n        start: run,\n        end: run\n      };\n\n      function run() {\n        $$rAF(function() {\n          close();\n          if (!closed) {\n            runner.done();\n          }\n          closed = true;\n        });\n        return runner;\n      }\n\n      function close() {\n        if (options.addClass) {\n          element.addClass(options.addClass);\n          options.addClass = null;\n        }\n        if (options.removeClass) {\n          element.removeClass(options.removeClass);\n          options.removeClass = null;\n        }\n        if (options.to) {\n          element.css(options.to);\n          options.to = null;\n        }\n      }\n    };\n  }];\n};\n\n/* global stripHash: true */\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n * @requires $log\n * @description\n * This object has two goals:\n *\n * - hide all the global state in the browser caused by the window object\n * - abstract away all the browser specific features and inconsistencies\n *\n * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`\n * service, which can be used for convenient testing of the application without the interaction with\n * the real browser apis.\n */\n/**\n * @param {object} window The global window object.\n * @param {object} document jQuery wrapped document.\n * @param {object} $log window.console or an object with the same interface.\n * @param {object} $sniffer $sniffer service\n */\nfunction Browser(window, document, $log, $sniffer) {\n  var self = this,\n      rawDocument = document[0],\n      location = window.location,\n      history = window.history,\n      setTimeout = window.setTimeout,\n      clearTimeout = window.clearTimeout,\n      pendingDeferIds = {};\n\n  self.isMock = false;\n\n  var outstandingRequestCount = 0;\n  var outstandingRequestCallbacks = [];\n\n  // TODO(vojta): remove this temporary api\n  self.$$completeOutstandingRequest = completeOutstandingRequest;\n  self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };\n\n  /**\n   * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`\n   * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.\n   */\n  function completeOutstandingRequest(fn) {\n    try {\n      fn.apply(null, sliceArgs(arguments, 1));\n    } finally {\n      outstandingRequestCount--;\n      if (outstandingRequestCount === 0) {\n        while (outstandingRequestCallbacks.length) {\n          try {\n            outstandingRequestCallbacks.pop()();\n          } catch (e) {\n            $log.error(e);\n          }\n        }\n      }\n    }\n  }\n\n  function getHash(url) {\n    var index = url.indexOf('#');\n    return index === -1 ? '' : url.substr(index);\n  }\n\n  /**\n   * @private\n   * Note: this method is used only by scenario runner\n   * TODO(vojta): prefix this method with $$ ?\n   * @param {function()} callback Function that will be called when no outstanding request\n   */\n  self.notifyWhenNoOutstandingRequests = function(callback) {\n    if (outstandingRequestCount === 0) {\n      callback();\n    } else {\n      outstandingRequestCallbacks.push(callback);\n    }\n  };\n\n  //////////////////////////////////////////////////////////////\n  // URL API\n  //////////////////////////////////////////////////////////////\n\n  var cachedState, lastHistoryState,\n      lastBrowserUrl = location.href,\n      baseElement = document.find('base'),\n      reloadLocation = null;\n\n  cacheState();\n  lastHistoryState = cachedState;\n\n  /**\n   * @name $browser#url\n   *\n   * @description\n   * GETTER:\n   * Without any argument, this method just returns current value of location.href.\n   *\n   * SETTER:\n   * With at least one argument, this method sets url to new value.\n   * If html5 history api supported, pushState/replaceState is used, otherwise\n   * location.href/location.replace is used.\n   * Returns its own instance to allow chaining\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to change url.\n   *\n   * @param {string} url New url (when used as setter)\n   * @param {boolean=} replace Should new url replace current history record?\n   * @param {object=} state object to use with pushState/replaceState\n   */\n  self.url = function(url, replace, state) {\n    // In modern browsers `history.state` is `null` by default; treating it separately\n    // from `undefined` would cause `$browser.url('/foo')` to change `history.state`\n    // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.\n    if (isUndefined(state)) {\n      state = null;\n    }\n\n    // Android Browser BFCache causes location, history reference to become stale.\n    if (location !== window.location) location = window.location;\n    if (history !== window.history) history = window.history;\n\n    // setter\n    if (url) {\n      var sameState = lastHistoryState === state;\n\n      // Don't change anything if previous and current URLs and states match. This also prevents\n      // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.\n      // See https://github.com/angular/angular.js/commit/ffb2701\n      if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {\n        return self;\n      }\n      var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);\n      lastBrowserUrl = url;\n      lastHistoryState = state;\n      // Don't use history API if only the hash changed\n      // due to a bug in IE10/IE11 which leads\n      // to not firing a `hashchange` nor `popstate` event\n      // in some cases (see #9143).\n      if ($sniffer.history && (!sameBase || !sameState)) {\n        history[replace ? 'replaceState' : 'pushState'](state, '', url);\n        cacheState();\n        // Do the assignment again so that those two variables are referentially identical.\n        lastHistoryState = cachedState;\n      } else {\n        if (!sameBase || reloadLocation) {\n          reloadLocation = url;\n        }\n        if (replace) {\n          location.replace(url);\n        } else if (!sameBase) {\n          location.href = url;\n        } else {\n          location.hash = getHash(url);\n        }\n      }\n      return self;\n    // getter\n    } else {\n      // - reloadLocation is needed as browsers don't allow to read out\n      //   the new location.href if a reload happened.\n      // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172\n      return reloadLocation || location.href.replace(/%27/g,\"'\");\n    }\n  };\n\n  /**\n   * @name $browser#state\n   *\n   * @description\n   * This method is a getter.\n   *\n   * Return history.state or null if history.state is undefined.\n   *\n   * @returns {object} state\n   */\n  self.state = function() {\n    return cachedState;\n  };\n\n  var urlChangeListeners = [],\n      urlChangeInit = false;\n\n  function cacheStateAndFireUrlChange() {\n    cacheState();\n    fireUrlChange();\n  }\n\n  function getCurrentState() {\n    try {\n      return history.state;\n    } catch (e) {\n      // MSIE can reportedly throw when there is no state (UNCONFIRMED).\n    }\n  }\n\n  // This variable should be used *only* inside the cacheState function.\n  var lastCachedState = null;\n  function cacheState() {\n    // This should be the only place in $browser where `history.state` is read.\n    cachedState = getCurrentState();\n    cachedState = isUndefined(cachedState) ? null : cachedState;\n\n    // Prevent callbacks fo fire twice if both hashchange & popstate were fired.\n    if (equals(cachedState, lastCachedState)) {\n      cachedState = lastCachedState;\n    }\n    lastCachedState = cachedState;\n  }\n\n  function fireUrlChange() {\n    if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {\n      return;\n    }\n\n    lastBrowserUrl = self.url();\n    lastHistoryState = cachedState;\n    forEach(urlChangeListeners, function(listener) {\n      listener(self.url(), cachedState);\n    });\n  }\n\n  /**\n   * @name $browser#onUrlChange\n   *\n   * @description\n   * Register callback function that will be called, when url changes.\n   *\n   * It's only called when the url is changed from outside of angular:\n   * - user types different url into address bar\n   * - user clicks on history (forward/back) button\n   * - user clicks on a link\n   *\n   * It's not called when url is changed by $browser.url() method\n   *\n   * The listener gets called with new url as parameter.\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to monitor url changes in angular apps.\n   *\n   * @param {function(string)} listener Listener function to be called when url changes.\n   * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\n   */\n  self.onUrlChange = function(callback) {\n    // TODO(vojta): refactor to use node's syntax for events\n    if (!urlChangeInit) {\n      // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)\n      // don't fire popstate when user change the address bar and don't fire hashchange when url\n      // changed by push/replaceState\n\n      // html5 history api - popstate event\n      if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);\n      // hashchange event\n      jqLite(window).on('hashchange', cacheStateAndFireUrlChange);\n\n      urlChangeInit = true;\n    }\n\n    urlChangeListeners.push(callback);\n    return callback;\n  };\n\n  /**\n   * @private\n   * Remove popstate and hashchange handler from window.\n   *\n   * NOTE: this api is intended for use only by $rootScope.\n   */\n  self.$$applicationDestroyed = function() {\n    jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);\n  };\n\n  /**\n   * Checks whether the url has changed outside of Angular.\n   * Needs to be exported to be able to check for changes that have been done in sync,\n   * as hashchange/popstate events fire in async.\n   */\n  self.$$checkUrlChange = fireUrlChange;\n\n  //////////////////////////////////////////////////////////////\n  // Misc API\n  //////////////////////////////////////////////////////////////\n\n  /**\n   * @name $browser#baseHref\n   *\n   * @description\n   * Returns current <base href>\n   * (always relative - without domain)\n   *\n   * @returns {string} The current base href\n   */\n  self.baseHref = function() {\n    var href = baseElement.attr('href');\n    return href ? href.replace(/^(https?\\:)?\\/\\/[^\\/]*/, '') : '';\n  };\n\n  /**\n   * @name $browser#defer\n   * @param {function()} fn A function, who's execution should be deferred.\n   * @param {number=} [delay=0] of milliseconds to defer the function execution.\n   * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\n   *\n   * @description\n   * Executes a fn asynchronously via `setTimeout(fn, delay)`.\n   *\n   * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\n   * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\n   * via `$browser.defer.flush()`.\n   *\n   */\n  self.defer = function(fn, delay) {\n    var timeoutId;\n    outstandingRequestCount++;\n    timeoutId = setTimeout(function() {\n      delete pendingDeferIds[timeoutId];\n      completeOutstandingRequest(fn);\n    }, delay || 0);\n    pendingDeferIds[timeoutId] = true;\n    return timeoutId;\n  };\n\n\n  /**\n   * @name $browser#defer.cancel\n   *\n   * @description\n   * Cancels a deferred task identified with `deferId`.\n   *\n   * @param {*} deferId Token returned by the `$browser.defer` function.\n   * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n   *                    canceled.\n   */\n  self.defer.cancel = function(deferId) {\n    if (pendingDeferIds[deferId]) {\n      delete pendingDeferIds[deferId];\n      clearTimeout(deferId);\n      completeOutstandingRequest(noop);\n      return true;\n    }\n    return false;\n  };\n\n}\n\nfunction $BrowserProvider() {\n  this.$get = ['$window', '$log', '$sniffer', '$document',\n      function($window, $log, $sniffer, $document) {\n        return new Browser($window, $document, $log, $sniffer);\n      }];\n}\n\n/**\n * @ngdoc service\n * @name $cacheFactory\n *\n * @description\n * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to\n * them.\n *\n * ```js\n *\n *  var cache = $cacheFactory('cacheId');\n *  expect($cacheFactory.get('cacheId')).toBe(cache);\n *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();\n *\n *  cache.put(\"key\", \"value\");\n *  cache.put(\"another key\", \"another value\");\n *\n *  // We've specified no options on creation\n *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});\n *\n * ```\n *\n *\n * @param {string} cacheId Name or id of the newly created cache.\n * @param {object=} options Options object that specifies the cache behavior. Properties:\n *\n *   - `{number=}` `capacity` — turns the cache into LRU cache.\n *\n * @returns {object} Newly created cache object with the following set of methods:\n *\n * - `{object}` `info()` — Returns id, size, and options of cache.\n * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns\n *   it.\n * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.\n * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.\n * - `{void}` `removeAll()` — Removes all cached values.\n * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.\n *\n * @example\n   <example module=\"cacheExampleApp\">\n     <file name=\"index.html\">\n       <div ng-controller=\"CacheController\">\n         <input ng-model=\"newCacheKey\" placeholder=\"Key\">\n         <input ng-model=\"newCacheValue\" placeholder=\"Value\">\n         <button ng-click=\"put(newCacheKey, newCacheValue)\">Cache</button>\n\n         <p ng-if=\"keys.length\">Cached Values</p>\n         <div ng-repeat=\"key in keys\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"cache.get(key)\"></b>\n         </div>\n\n         <p>Cache Info</p>\n         <div ng-repeat=\"(key, value) in cache.info()\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"value\"></b>\n         </div>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('cacheExampleApp', []).\n         controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {\n           $scope.keys = [];\n           $scope.cache = $cacheFactory('cacheId');\n           $scope.put = function(key, value) {\n             if ($scope.cache.get(key) === undefined) {\n               $scope.keys.push(key);\n             }\n             $scope.cache.put(key, value === undefined ? null : value);\n           };\n         }]);\n     </file>\n     <file name=\"style.css\">\n       p {\n         margin: 10px 0 3px;\n       }\n     </file>\n   </example>\n */\nfunction $CacheFactoryProvider() {\n\n  this.$get = function() {\n    var caches = {};\n\n    function cacheFactory(cacheId, options) {\n      if (cacheId in caches) {\n        throw minErr('$cacheFactory')('iid', \"CacheId '{0}' is already taken!\", cacheId);\n      }\n\n      var size = 0,\n          stats = extend({}, options, {id: cacheId}),\n          data = {},\n          capacity = (options && options.capacity) || Number.MAX_VALUE,\n          lruHash = {},\n          freshEnd = null,\n          staleEnd = null;\n\n      /**\n       * @ngdoc type\n       * @name $cacheFactory.Cache\n       *\n       * @description\n       * A cache object used to store and retrieve data, primarily used by\n       * {@link $http $http} and the {@link ng.directive:script script} directive to cache\n       * templates and other data.\n       *\n       * ```js\n       *  angular.module('superCache')\n       *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {\n       *      return $cacheFactory('super-cache');\n       *    }]);\n       * ```\n       *\n       * Example test:\n       *\n       * ```js\n       *  it('should behave like a cache', inject(function(superCache) {\n       *    superCache.put('key', 'value');\n       *    superCache.put('another key', 'another value');\n       *\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 2\n       *    });\n       *\n       *    superCache.remove('another key');\n       *    expect(superCache.get('another key')).toBeUndefined();\n       *\n       *    superCache.removeAll();\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 0\n       *    });\n       *  }));\n       * ```\n       */\n      return caches[cacheId] = {\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#put\n         * @kind function\n         *\n         * @description\n         * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be\n         * retrieved later, and incrementing the size of the cache if the key was not already\n         * present in the cache. If behaving like an LRU cache, it will also remove stale\n         * entries from the set.\n         *\n         * It will not insert undefined values into the cache.\n         *\n         * @param {string} key the key under which the cached data is stored.\n         * @param {*} value the value to store alongside the key. If it is undefined, the key\n         *    will not be stored.\n         * @returns {*} the value stored.\n         */\n        put: function(key, value) {\n          if (isUndefined(value)) return;\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key] || (lruHash[key] = {key: key});\n\n            refresh(lruEntry);\n          }\n\n          if (!(key in data)) size++;\n          data[key] = value;\n\n          if (size > capacity) {\n            this.remove(staleEnd.key);\n          }\n\n          return value;\n        },\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#get\n         * @kind function\n         *\n         * @description\n         * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the data to be retrieved\n         * @returns {*} the value stored.\n         */\n        get: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            refresh(lruEntry);\n          }\n\n          return data[key];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#remove\n         * @kind function\n         *\n         * @description\n         * Removes an entry from the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the entry to be removed\n         */\n        remove: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            if (lruEntry == freshEnd) freshEnd = lruEntry.p;\n            if (lruEntry == staleEnd) staleEnd = lruEntry.n;\n            link(lruEntry.n,lruEntry.p);\n\n            delete lruHash[key];\n          }\n\n          delete data[key];\n          size--;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#removeAll\n         * @kind function\n         *\n         * @description\n         * Clears the cache object of any entries.\n         */\n        removeAll: function() {\n          data = {};\n          size = 0;\n          lruHash = {};\n          freshEnd = staleEnd = null;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#destroy\n         * @kind function\n         *\n         * @description\n         * Destroys the {@link $cacheFactory.Cache Cache} object entirely,\n         * removing it from the {@link $cacheFactory $cacheFactory} set.\n         */\n        destroy: function() {\n          data = null;\n          stats = null;\n          lruHash = null;\n          delete caches[cacheId];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#info\n         * @kind function\n         *\n         * @description\n         * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.\n         *\n         * @returns {object} an object with the following properties:\n         *   <ul>\n         *     <li>**id**: the id of the cache instance</li>\n         *     <li>**size**: the number of entries kept in the cache instance</li>\n         *     <li>**...**: any additional properties from the options object when creating the\n         *       cache.</li>\n         *   </ul>\n         */\n        info: function() {\n          return extend({}, stats, {size: size});\n        }\n      };\n\n\n      /**\n       * makes the `entry` the freshEnd of the LRU linked list\n       */\n      function refresh(entry) {\n        if (entry != freshEnd) {\n          if (!staleEnd) {\n            staleEnd = entry;\n          } else if (staleEnd == entry) {\n            staleEnd = entry.n;\n          }\n\n          link(entry.n, entry.p);\n          link(entry, freshEnd);\n          freshEnd = entry;\n          freshEnd.n = null;\n        }\n      }\n\n\n      /**\n       * bidirectionally links two entries of the LRU linked list\n       */\n      function link(nextEntry, prevEntry) {\n        if (nextEntry != prevEntry) {\n          if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify\n          if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify\n        }\n      }\n    }\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#info\n   *\n   * @description\n   * Get information about all the caches that have been created\n   *\n   * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`\n   */\n    cacheFactory.info = function() {\n      var info = {};\n      forEach(caches, function(cache, cacheId) {\n        info[cacheId] = cache.info();\n      });\n      return info;\n    };\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#get\n   *\n   * @description\n   * Get access to a cache object by the `cacheId` used when it was created.\n   *\n   * @param {string} cacheId Name or id of a cache to access.\n   * @returns {object} Cache object identified by the cacheId or undefined if no such cache.\n   */\n    cacheFactory.get = function(cacheId) {\n      return caches[cacheId];\n    };\n\n\n    return cacheFactory;\n  };\n}\n\n/**\n * @ngdoc service\n * @name $templateCache\n *\n * @description\n * The first time a template is used, it is loaded in the template cache for quick retrieval. You\n * can load templates directly into the cache in a `script` tag, or by consuming the\n * `$templateCache` service directly.\n *\n * Adding via the `script` tag:\n *\n * ```html\n *   <script type=\"text/ng-template\" id=\"templateId.html\">\n *     <p>This is the content of the template</p>\n *   </script>\n * ```\n *\n * **Note:** the `script` tag containing the template does not need to be included in the `head` of\n * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,\n * element with ng-app attribute), otherwise the template will be ignored.\n *\n * Adding via the `$templateCache` service:\n *\n * ```js\n * var myApp = angular.module('myApp', []);\n * myApp.run(function($templateCache) {\n *   $templateCache.put('templateId.html', 'This is the content of the template');\n * });\n * ```\n *\n * To retrieve the template later, simply use it in your HTML:\n * ```html\n * <div ng-include=\" 'templateId.html' \"></div>\n * ```\n *\n * or get it via Javascript:\n * ```js\n * $templateCache.get('templateId.html')\n * ```\n *\n * See {@link ng.$cacheFactory $cacheFactory}.\n *\n */\nfunction $TemplateCacheProvider() {\n  this.$get = ['$cacheFactory', function($cacheFactory) {\n    return $cacheFactory('templates');\n  }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!\n *\n * DOM-related variables:\n *\n * - \"node\" - DOM Node\n * - \"element\" - DOM Element or Node\n * - \"$node\" or \"$element\" - jqLite-wrapped node or element\n *\n *\n * Compiler related stuff:\n *\n * - \"linkFn\" - linking fn of a single directive\n * - \"nodeLinkFn\" - function that aggregates all linking fns for a particular node\n * - \"childLinkFn\" -  function that aggregates all linking fns for child nodes of a particular node\n * - \"compositeLinkFn\" - function that aggregates all linking fns for a compilation root (nodeList)\n */\n\n\n/**\n * @ngdoc service\n * @name $compile\n * @kind function\n *\n * @description\n * Compiles an HTML string or DOM into a template and produces a template function, which\n * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.\n *\n * The compilation is a process of walking the DOM tree and matching DOM elements to\n * {@link ng.$compileProvider#directive directives}.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** This document is an in-depth reference of all directive options.\n * For a gentle introduction to directives with examples of common use cases,\n * see the {@link guide/directive directive guide}.\n * </div>\n *\n * ## Comprehensive Directive API\n *\n * There are many different options for a directive.\n *\n * The difference resides in the return value of the factory function.\n * You can either return a \"Directive Definition Object\" (see below) that defines the directive properties,\n * or just the `postLink` function (all other properties will have the default values).\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's recommended to use the \"directive definition object\" form.\n * </div>\n *\n * Here's an example directive declared with a Directive Definition Object:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       priority: 0,\n *       template: '<div></div>', // or // function(tElement, tAttrs) { ... },\n *       // or\n *       // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },\n *       transclude: false,\n *       restrict: 'A',\n *       templateNamespace: 'html',\n *       scope: false,\n *       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },\n *       controllerAs: 'stringIdentifier',\n *       bindToController: false,\n *       require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],\n *       compile: function compile(tElement, tAttrs, transclude) {\n *         return {\n *           pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *           post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *         }\n *         // or\n *         // return function postLink( ... ) { ... }\n *       },\n *       // or\n *       // link: {\n *       //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *       //  post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *       // }\n *       // or\n *       // link: function postLink( ... ) { ... }\n *     };\n *     return directiveDefinitionObject;\n *   });\n * ```\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Any unspecified options will use the default value. You can see the default values below.\n * </div>\n *\n * Therefore the above can be simplified as:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       link: function postLink(scope, iElement, iAttrs) { ... }\n *     };\n *     return directiveDefinitionObject;\n *     // or\n *     // return function postLink(scope, iElement, iAttrs) { ... }\n *   });\n * ```\n *\n *\n *\n * ### Directive Definition Object\n *\n * The directive definition object provides instructions to the {@link ng.$compile\n * compiler}. The attributes are:\n *\n * #### `multiElement`\n * When this property is set to true, the HTML compiler will collect DOM nodes between\n * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them\n * together as the directive elements. It is recommended that this feature be used on directives\n * which are not strictly behavioural (such as {@link ngClick}), and which\n * do not manipulate or replace child nodes (such as {@link ngInclude}).\n *\n * #### `priority`\n * When there are multiple directives defined on a single DOM element, sometimes it\n * is necessary to specify the order in which the directives are applied. The `priority` is used\n * to sort the directives before their `compile` functions get called. Priority is defined as a\n * number. Directives with greater numerical `priority` are compiled first. Pre-link functions\n * are also run in priority order, but post-link functions are run in reverse order. The order\n * of directives with the same priority is undefined. The default priority is `0`.\n *\n * #### `terminal`\n * If set to true then the current `priority` will be the last set of directives\n * which will execute (any directives at the current priority will still execute\n * as the order of execution on same `priority` is undefined). Note that expressions\n * and other directives used in the directive's template will also be excluded from execution.\n *\n * #### `scope`\n * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the\n * same element request a new scope, only one new scope is created. The new scope rule does not\n * apply for the root of the template since the root of the template always gets a new scope.\n *\n * **If set to `{}` (object hash),** then a new \"isolate\" scope is created. The 'isolate' scope differs from\n * normal scope in that it does not prototypically inherit from the parent scope. This is useful\n * when creating reusable components, which should not accidentally read or modify data in the\n * parent scope.\n *\n * The 'isolate' scope takes an object hash which defines a set of local scope properties\n * derived from the parent scope. These local properties are useful for aliasing values for\n * templates. Locals definition is a hash of local scope property to its source:\n *\n * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is\n *   always a string since DOM attributes are strings. If no `attr` name is specified  then the\n *   attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"hello {{name}}\">` and widget definition\n *   of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect\n *   the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the\n *   `localName` property on the widget scope. The `name` is read from the parent scope (not\n *   component scope).\n *\n * * `=` or `=attr` - set up bi-directional binding between a local scope property and the\n *   parent scope property of name defined via the value of the `attr` attribute. If no `attr`\n *   name is specified then the attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"parentModel\">` and widget definition of\n *   `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the\n *   value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected\n *   in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent\n *   scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You\n *   can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If\n *   you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use\n *   `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).\n *\n * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.\n *   If no `attr` name is specified then the attribute name is assumed to be the same as the\n *   local name. Given `<widget my-attr=\"count = count + value\">` and widget definition of\n *   `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to\n *   a function wrapper for the `count = count + value` expression. Often it's desirable to\n *   pass data from the isolated scope via an expression to the parent scope, this can be\n *   done by passing a map of local variable names and values into the expression wrapper fn.\n *   For example, if the expression is `increment(amount)` then we can specify the amount value\n *   by calling the `localFn` as `localFn({amount: 22})`.\n *\n *\n * #### `bindToController`\n * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will\n * allow a component to have its properties bound to the controller, rather than to scope. When the controller\n * is instantiated, the initial values of the isolate scope bindings are already available.\n *\n * #### `controller`\n * Controller constructor function. The controller is instantiated before the\n * pre-linking phase and it is shared with other directives (see\n * `require` attribute). This allows the directives to communicate with each other and augment\n * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:\n *\n * * `$scope` - Current scope associated with the element\n * * `$element` - Current element\n * * `$attrs` - Current attributes object for the element\n * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:\n *   `function([scope], cloneLinkingFn, futureParentElement)`.\n *    * `scope`: optional argument to override the scope.\n *    * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.\n *    * `futureParentElement`:\n *        * defines the parent to which the `cloneLinkingFn` will add the cloned elements.\n *        * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.\n *        * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)\n *          and when the `cloneLinkinFn` is passed,\n *          as those elements need to created and cloned in a special way when they are defined outside their\n *          usual containers (e.g. like `<svg>`).\n *        * See also the `directive.templateNamespace` property.\n *\n *\n * #### `require`\n * Require another directive and inject its controller as the fourth argument to the linking function. The\n * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the\n * injected argument will be an array in corresponding order. If no such directive can be\n * found, or if the directive does not have a controller, then an error is raised (unless no link function\n * is specified, in which case error checking is skipped). The name can be prefixed with:\n *\n * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.\n * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.\n * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.\n * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.\n * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass\n *   `null` to the `link` fn if not found.\n * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass\n *   `null` to the `link` fn if not found.\n *\n *\n * #### `controllerAs`\n * Identifier name for a reference to the controller in the directive's scope.\n * This allows the controller to be referenced from the directive template. The directive\n * needs to define a scope for this configuration to be used. Useful in the case when\n * directive is used as component.\n *\n *\n * #### `restrict`\n * String of subset of `EACM` which restricts the directive to a specific directive\n * declaration style. If omitted, the defaults (elements and attributes) are used.\n *\n * * `E` - Element name (default): `<my-directive></my-directive>`\n * * `A` - Attribute (default): `<div my-directive=\"exp\"></div>`\n * * `C` - Class: `<div class=\"my-directive: exp;\"></div>`\n * * `M` - Comment: `<!-- directive: my-directive exp -->`\n *\n *\n * #### `templateNamespace`\n * String representing the document type used by the markup in the template.\n * AngularJS needs this information as those elements need to be created and cloned\n * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.\n *\n * * `html` - All root nodes in the template are HTML. Root nodes may also be\n *   top-level elements such as `<svg>` or `<math>`.\n * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).\n * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).\n *\n * If no `templateNamespace` is specified, then the namespace is considered to be `html`.\n *\n * #### `template`\n * HTML markup that may:\n * * Replace the contents of the directive's element (default).\n * * Replace the directive's element itself (if `replace` is true - DEPRECATED).\n * * Wrap the contents of the directive's element (if `transclude` is true).\n *\n * Value may be:\n *\n * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.\n * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`\n *   function api below) and returns a string value.\n *\n *\n * #### `templateUrl`\n * This is similar to `template` but the template is loaded from the specified URL, asynchronously.\n *\n * Because template loading is asynchronous the compiler will suspend compilation of directives on that element\n * for later when the template has been resolved.  In the meantime it will continue to compile and link\n * sibling and parent elements as though this element had not contained any directives.\n *\n * The compiler does not suspend the entire compilation to wait for templates to be loaded because this\n * would result in the whole app \"stalling\" until all templates are loaded asynchronously - even in the\n * case when only one deeply nested directive has `templateUrl`.\n *\n * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}\n *\n * You can specify `templateUrl` as a string representing the URL or as a function which takes two\n * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns\n * a string value representing the url.  In either case, the template URL is passed through {@link\n * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.\n *\n *\n * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)\n * specify what the template should replace. Defaults to `false`.\n *\n * * `true` - the template will replace the directive's element.\n * * `false` - the template will replace the contents of the directive's element.\n *\n * The replacement process migrates all of the attributes / classes from the old element to the new\n * one. See the {@link guide/directive#template-expanding-directive\n * Directives Guide} for an example.\n *\n * There are very few scenarios where element replacement is required for the application function,\n * the main one being reusable custom components that are used within SVG contexts\n * (because SVG doesn't work with custom elements in the DOM tree).\n *\n * #### `transclude`\n * Extract the contents of the element where the directive appears and make it available to the directive.\n * The contents are compiled and provided to the directive as a **transclusion function**. See the\n * {@link $compile#transclusion Transclusion} section below.\n *\n * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the\n * directive's element or the entire element:\n *\n * * `true` - transclude the content (i.e. the child nodes) of the directive's element.\n * * `'element'` - transclude the whole of the directive's element including any directives on this\n *   element that defined at a lower priority than this directive. When used, the `template`\n *   property is ignored.\n *\n *\n * #### `compile`\n *\n * ```js\n *   function compile(tElement, tAttrs, transclude) { ... }\n * ```\n *\n * The compile function deals with transforming the template DOM. Since most directives do not do\n * template transformation, it is not used often. The compile function takes the following arguments:\n *\n *   * `tElement` - template element - The element where the directive has been declared. It is\n *     safe to do template transformation on the element and child elements only.\n *\n *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared\n *     between all directive compile functions.\n *\n *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`\n *\n * <div class=\"alert alert-warning\">\n * **Note:** The template instance and the link instance may be different objects if the template has\n * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that\n * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration\n * should be done in a linking function rather than in a compile function.\n * </div>\n\n * <div class=\"alert alert-warning\">\n * **Note:** The compile function cannot handle directives that recursively use themselves in their\n * own templates or compile functions. Compiling these directives results in an infinite loop and a\n * stack overflow errors.\n *\n * This can be avoided by manually using $compile in the postLink function to imperatively compile\n * a directive's template instead of relying on automatic template compilation via `template` or\n * `templateUrl` declaration or manual compilation inside the compile function.\n * </div>\n *\n * <div class=\"alert alert-danger\">\n * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it\n *   e.g. does not know about the right outer scope. Please use the transclude function that is passed\n *   to the link function instead.\n * </div>\n\n * A compile function can have a return value which can be either a function or an object.\n *\n * * returning a (post-link) function - is equivalent to registering the linking function via the\n *   `link` property of the config object when the compile function is empty.\n *\n * * returning an object with function(s) registered via `pre` and `post` properties - allows you to\n *   control when a linking function should be called during the linking phase. See info about\n *   pre-linking and post-linking functions below.\n *\n *\n * #### `link`\n * This property is used only if the `compile` property is not defined.\n *\n * ```js\n *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }\n * ```\n *\n * The link function is responsible for registering DOM listeners as well as updating the DOM. It is\n * executed after the template has been cloned. This is where most of the directive logic will be\n * put.\n *\n *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the\n *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.\n *\n *   * `iElement` - instance element - The element where the directive is to be used. It is safe to\n *     manipulate the children of the element only in `postLink` function since the children have\n *     already been linked.\n *\n *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared\n *     between all directive linking functions.\n *\n *   * `controller` - the directive's required controller instance(s) - Instances are shared\n *     among all directives, which allows the directives to use the controllers as a communication\n *     channel. The exact value depends on the directive's `require` property:\n *       * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one\n *       * `string`: the controller instance\n *       * `array`: array of controller instances\n *\n *     If a required controller cannot be found, and it is optional, the instance is `null`,\n *     otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.\n *\n *     Note that you can also require the directive's own controller - it will be made available like\n *     any other controller.\n *\n *   * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.\n *     This is the same as the `$transclude`\n *     parameter of directive controllers, see there for details.\n *     `function([scope], cloneLinkingFn, futureParentElement)`.\n *\n * #### Pre-linking function\n *\n * Executed before the child elements are linked. Not safe to do DOM transformation since the\n * compiler linking function will fail to locate the correct elements for linking.\n *\n * #### Post-linking function\n *\n * Executed after the child elements are linked.\n *\n * Note that child elements that contain `templateUrl` directives will not have been compiled\n * and linked since they are waiting for their template to load asynchronously and their own\n * compilation and linking has been suspended until that occurs.\n *\n * It is safe to do DOM transformation in the post-linking function on elements that are not waiting\n * for their async templates to be resolved.\n *\n *\n * ### Transclusion\n *\n * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and\n * copying them to another part of the DOM, while maintaining their connection to the original AngularJS\n * scope from where they were taken.\n *\n * Transclusion is used (often with {@link ngTransclude}) to insert the\n * original contents of a directive's element into a specified place in the template of the directive.\n * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded\n * content has access to the properties on the scope from which it was taken, even if the directive\n * has isolated scope.\n * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.\n *\n * This makes it possible for the widget to have private state for its template, while the transcluded\n * content has access to its originating scope.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** When testing an element transclude directive you must not place the directive at the root of the\n * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives\n * Testing Transclusion Directives}.\n * </div>\n *\n * #### Transclusion Functions\n *\n * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion\n * function** to the directive's `link` function and `controller`. This transclusion function is a special\n * **linking function** that will return the compiled contents linked to a new transclusion scope.\n *\n * <div class=\"alert alert-info\">\n * If you are just using {@link ngTransclude} then you don't need to worry about this function, since\n * ngTransclude will deal with it for us.\n * </div>\n *\n * If you want to manually control the insertion and removal of the transcluded content in your directive\n * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery\n * object that contains the compiled DOM, which is linked to the correct transclusion scope.\n *\n * When you call a transclusion function you can pass in a **clone attach function**. This function accepts\n * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded\n * content and the `scope` is the newly created transclusion scope, to which the clone is bound.\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function\n * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.\n * </div>\n *\n * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone\n * attach function**:\n *\n * ```js\n * var transcludedContent, transclusionScope;\n *\n * $transclude(function(clone, scope) {\n *   element.append(clone);\n *   transcludedContent = clone;\n *   transclusionScope = scope;\n * });\n * ```\n *\n * Later, if you want to remove the transcluded content from your DOM then you should also destroy the\n * associated transclusion scope:\n *\n * ```js\n * transcludedContent.remove();\n * transclusionScope.$destroy();\n * ```\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: if you intend to add and remove transcluded content manually in your directive\n * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),\n * then you are also responsible for calling `$destroy` on the transclusion scope.\n * </div>\n *\n * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}\n * automatically destroy their transluded clones as necessary so you do not need to worry about this if\n * you are simply using {@link ngTransclude} to inject the transclusion into your directive.\n *\n *\n * #### Transclusion Scopes\n *\n * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion\n * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed\n * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it\n * was taken.\n *\n * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look\n * like this:\n *\n * ```html\n * <div ng-app>\n *   <div isolate>\n *     <div transclusion>\n *     </div>\n *   </div>\n * </div>\n * ```\n *\n * The `$parent` scope hierarchy will look like this:\n *\n * ```\n * - $rootScope\n *   - isolate\n *     - transclusion\n * ```\n *\n * but the scopes will inherit prototypically from different scopes to their `$parent`.\n *\n * ```\n * - $rootScope\n *   - transclusion\n * - isolate\n * ```\n *\n *\n * ### Attributes\n *\n * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the\n * `link()` or `compile()` functions. It has a variety of uses.\n *\n * accessing *Normalized attribute names:*\n * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.\n * the attributes object allows for normalized access to\n *   the attributes.\n *\n * * *Directive inter-communication:* All directives share the same instance of the attributes\n *   object which allows the directives to use the attributes object as inter directive\n *   communication.\n *\n * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object\n *   allowing other directives to read the interpolated value.\n *\n * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes\n *   that contain interpolation (e.g. `src=\"{{bar}}\"`). Not only is this very efficient but it's also\n *   the only way to easily get the actual value because during the linking phase the interpolation\n *   hasn't been evaluated yet and so the value is at this time set to `undefined`.\n *\n * ```js\n * function linkingFn(scope, elm, attrs, ctrl) {\n *   // get the attribute value\n *   console.log(attrs.ngModel);\n *\n *   // change the attribute\n *   attrs.$set('ngModel', 'new value');\n *\n *   // observe changes to interpolated attribute\n *   attrs.$observe('ngModel', function(value) {\n *     console.log('ngModel has changed value to ' + value);\n *   });\n * }\n * ```\n *\n * ## Example\n *\n * <div class=\"alert alert-warning\">\n * **Note**: Typically directives are registered with `module.directive`. The example below is\n * to illustrate how `$compile` works.\n * </div>\n *\n <example module=\"compileExample\">\n   <file name=\"index.html\">\n    <script>\n      angular.module('compileExample', [], function($compileProvider) {\n        // configure new 'compile' directive by passing a directive\n        // factory function. The factory function injects the '$compile'\n        $compileProvider.directive('compile', function($compile) {\n          // directive factory creates a link function\n          return function(scope, element, attrs) {\n            scope.$watch(\n              function(scope) {\n                 // watch the 'compile' expression for changes\n                return scope.$eval(attrs.compile);\n              },\n              function(value) {\n                // when the 'compile' expression changes\n                // assign it into the current DOM\n                element.html(value);\n\n                // compile the new DOM and link it to the current\n                // scope.\n                // NOTE: we only compile .childNodes so that\n                // we don't get into infinite loop compiling ourselves\n                $compile(element.contents())(scope);\n              }\n            );\n          };\n        });\n      })\n      .controller('GreeterController', ['$scope', function($scope) {\n        $scope.name = 'Angular';\n        $scope.html = 'Hello {{name}}';\n      }]);\n    </script>\n    <div ng-controller=\"GreeterController\">\n      <input ng-model=\"name\"> <br/>\n      <textarea ng-model=\"html\"></textarea> <br/>\n      <div compile=\"html\"></div>\n    </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should auto compile', function() {\n       var textarea = $('textarea');\n       var output = $('div[compile]');\n       // The initial state reads 'Hello Angular'.\n       expect(output.getText()).toBe('Hello Angular');\n       textarea.clear();\n       textarea.sendKeys('{{name}}!');\n       expect(output.getText()).toBe('Angular!');\n     });\n   </file>\n </example>\n\n *\n *\n * @param {string|DOMElement} element Element or HTML string to compile into a template function.\n * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.\n *\n * <div class=\"alert alert-danger\">\n * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it\n *   e.g. will not use the right outer scope. Please pass the transclude function as a\n *   `parentBoundTranscludeFn` to the link function instead.\n * </div>\n *\n * @param {number} maxPriority only apply directives lower than given priority (Only effects the\n *                 root element(s), not their children)\n * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template\n * (a DOM element/tree) to a scope. Where:\n *\n *  * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.\n *  * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the\n *  `template` and call the `cloneAttachFn` function allowing the caller to attach the\n *  cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is\n *  called as: <br/> `cloneAttachFn(clonedElement, scope)` where:\n *\n *      * `clonedElement` - is a clone of the original `element` passed into the compiler.\n *      * `scope` - is the current scope with which the linking function is working with.\n *\n *  * `options` - An optional object hash with linking options. If `options` is provided, then the following\n *  keys may be used to control linking behavior:\n *\n *      * `parentBoundTranscludeFn` - the transclude function made available to\n *        directives; if given, it will be passed through to the link functions of\n *        directives found in `element` during compilation.\n *      * `transcludeControllers` - an object hash with keys that map controller names\n *        to controller instances; if given, it will make the controllers\n *        available to directives.\n *      * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add\n *        the cloned elements; only needed for transcludes that are allowed to contain non html\n *        elements (e.g. SVG elements). See also the directive.controller property.\n *\n * Calling the linking function returns the element of the template. It is either the original\n * element passed in, or the clone of the element if the `cloneAttachFn` is provided.\n *\n * After linking the view is not updated until after a call to $digest which typically is done by\n * Angular automatically.\n *\n * If you need access to the bound view, there are two ways to do it:\n *\n * - If you are not asking the linking function to clone the template, create the DOM element(s)\n *   before you send them to the compiler and keep this reference around.\n *   ```js\n *     var element = $compile('<p>{{total}}</p>')(scope);\n *   ```\n *\n * - if on the other hand, you need the element to be cloned, the view reference from the original\n *   example would not point to the clone, but rather to the original template that was cloned. In\n *   this case, you can access the clone via the cloneAttachFn:\n *   ```js\n *     var templateElement = angular.element('<p>{{total}}</p>'),\n *         scope = ....;\n *\n *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {\n *       //attach the clone to DOM document at the right place\n *     });\n *\n *     //now we have reference to the cloned DOM via `clonedElement`\n *   ```\n *\n *\n * For information on how the compiler works, see the\n * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.\n */\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc provider\n * @name $compileProvider\n *\n * @description\n */\n$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];\nfunction $CompileProvider($provide, $$sanitizeUriProvider) {\n  var hasDirectives = {},\n      Suffix = 'Directive',\n      COMMENT_DIRECTIVE_REGEXP = /^\\s*directive\\:\\s*([\\w\\-]+)\\s+(.*)$/,\n      CLASS_DIRECTIVE_REGEXP = /(([\\w\\-]+)(?:\\:([^;]+))?;?)/,\n      ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),\n      REQUIRE_PREFIX_REGEXP = /^(?:(\\^\\^?)?(\\?)?(\\^\\^?)?)?/;\n\n  // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes\n  // The assumption is that future DOM event attribute names will begin with\n  // 'on' and be composed of only English letters.\n  var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;\n\n  function parseIsolateBindings(scope, directiveName, isController) {\n    var LOCAL_REGEXP = /^\\s*([@&]|=(\\*?))(\\??)\\s*(\\w*)\\s*$/;\n\n    var bindings = {};\n\n    forEach(scope, function(definition, scopeName) {\n      var match = definition.match(LOCAL_REGEXP);\n\n      if (!match) {\n        throw $compileMinErr('iscp',\n            \"Invalid {3} for directive '{0}'.\" +\n            \" Definition: {... {1}: '{2}' ...}\",\n            directiveName, scopeName, definition,\n            (isController ? \"controller bindings definition\" :\n            \"isolate scope definition\"));\n      }\n\n      bindings[scopeName] = {\n        mode: match[1][0],\n        collection: match[2] === '*',\n        optional: match[3] === '?',\n        attrName: match[4] || scopeName\n      };\n    });\n\n    return bindings;\n  }\n\n  function parseDirectiveBindings(directive, directiveName) {\n    var bindings = {\n      isolateScope: null,\n      bindToController: null\n    };\n    if (isObject(directive.scope)) {\n      if (directive.bindToController === true) {\n        bindings.bindToController = parseIsolateBindings(directive.scope,\n                                                         directiveName, true);\n        bindings.isolateScope = {};\n      } else {\n        bindings.isolateScope = parseIsolateBindings(directive.scope,\n                                                     directiveName, false);\n      }\n    }\n    if (isObject(directive.bindToController)) {\n      bindings.bindToController =\n          parseIsolateBindings(directive.bindToController, directiveName, true);\n    }\n    if (isObject(bindings.bindToController)) {\n      var controller = directive.controller;\n      var controllerAs = directive.controllerAs;\n      if (!controller) {\n        // There is no controller, there may or may not be a controllerAs property\n        throw $compileMinErr('noctrl',\n              \"Cannot bind to controller without directive '{0}'s controller.\",\n              directiveName);\n      } else if (!identifierForController(controller, controllerAs)) {\n        // There is a controller, but no identifier or controllerAs property\n        throw $compileMinErr('noident',\n              \"Cannot bind to controller without identifier for directive '{0}'.\",\n              directiveName);\n      }\n    }\n    return bindings;\n  }\n\n  function assertValidDirectiveName(name) {\n    var letter = name.charAt(0);\n    if (!letter || letter !== lowercase(letter)) {\n      throw $compileMinErr('baddir', \"Directive name '{0}' is invalid. The first character must be a lowercase letter\", name);\n    }\n    if (name !== name.trim()) {\n      throw $compileMinErr('baddir',\n            \"Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces\",\n            name);\n    }\n  }\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#directive\n   * @kind function\n   *\n   * @description\n   * Register a new directive with the compiler.\n   *\n   * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which\n   *    will match as <code>ng-bind</code>), or an object map of directives where the keys are the\n   *    names and the values are the factories.\n   * @param {Function|Array} directiveFactory An injectable directive factory function. See\n   *    {@link guide/directive} for more info.\n   * @returns {ng.$compileProvider} Self for chaining.\n   */\n   this.directive = function registerDirective(name, directiveFactory) {\n    assertNotHasOwnProperty(name, 'directive');\n    if (isString(name)) {\n      assertValidDirectiveName(name);\n      assertArg(directiveFactory, 'directiveFactory');\n      if (!hasDirectives.hasOwnProperty(name)) {\n        hasDirectives[name] = [];\n        $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',\n          function($injector, $exceptionHandler) {\n            var directives = [];\n            forEach(hasDirectives[name], function(directiveFactory, index) {\n              try {\n                var directive = $injector.invoke(directiveFactory);\n                if (isFunction(directive)) {\n                  directive = { compile: valueFn(directive) };\n                } else if (!directive.compile && directive.link) {\n                  directive.compile = valueFn(directive.link);\n                }\n                directive.priority = directive.priority || 0;\n                directive.index = index;\n                directive.name = directive.name || name;\n                directive.require = directive.require || (directive.controller && directive.name);\n                directive.restrict = directive.restrict || 'EA';\n                var bindings = directive.$$bindings =\n                    parseDirectiveBindings(directive, directive.name);\n                if (isObject(bindings.isolateScope)) {\n                  directive.$$isolateBindings = bindings.isolateScope;\n                }\n                directive.$$moduleName = directiveFactory.$$moduleName;\n                directives.push(directive);\n              } catch (e) {\n                $exceptionHandler(e);\n              }\n            });\n            return directives;\n          }]);\n      }\n      hasDirectives[name].push(directiveFactory);\n    } else {\n      forEach(name, reverseParams(registerDirective));\n    }\n    return this;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#aHrefSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at preventing XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.aHrefSanitizationWhitelist();\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#imgSrcSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name  $compileProvider#debugInfoEnabled\n   *\n   * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the\n   * current debugInfoEnabled state\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   *\n   * @kind function\n   *\n   * @description\n   * Call this method to enable/disable various debug runtime information in the compiler such as adding\n   * binding information and a reference to the current scope on to DOM elements.\n   * If enabled, the compiler will add the following to DOM elements that have been bound to the scope\n   * * `ng-binding` CSS class\n   * * `$binding` data property containing an array of the binding expressions\n   *\n   * You may want to disable this in production for a significant performance boost. See\n   * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.\n   *\n   * The default value is true.\n   */\n  var debugInfoEnabled = true;\n  this.debugInfoEnabled = function(enabled) {\n    if (isDefined(enabled)) {\n      debugInfoEnabled = enabled;\n      return this;\n    }\n    return debugInfoEnabled;\n  };\n\n  this.$get = [\n            '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',\n            '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',\n    function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,\n             $controller,   $rootScope,   $document,   $sce,   $animate,   $$sanitizeUri) {\n\n    var Attributes = function(element, attributesToCopy) {\n      if (attributesToCopy) {\n        var keys = Object.keys(attributesToCopy);\n        var i, l, key;\n\n        for (i = 0, l = keys.length; i < l; i++) {\n          key = keys[i];\n          this[key] = attributesToCopy[key];\n        }\n      } else {\n        this.$attr = {};\n      }\n\n      this.$$element = element;\n    };\n\n    Attributes.prototype = {\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$normalize\n       * @kind function\n       *\n       * @description\n       * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or\n       * `data-`) to its normalized, camelCase form.\n       *\n       * Also there is special case for Moz prefix starting with upper case letter.\n       *\n       * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\n       *\n       * @param {string} name Name to normalize\n       */\n      $normalize: directiveNormalize,\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$addClass\n       * @kind function\n       *\n       * @description\n       * Adds the CSS class value specified by the classVal parameter to the element. If animations\n       * are enabled then an animation will be triggered for the class addition.\n       *\n       * @param {string} classVal The className value that will be added to the element\n       */\n      $addClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.addClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$removeClass\n       * @kind function\n       *\n       * @description\n       * Removes the CSS class value specified by the classVal parameter from the element. If\n       * animations are enabled then an animation will be triggered for the class removal.\n       *\n       * @param {string} classVal The className value that will be removed from the element\n       */\n      $removeClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.removeClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$updateClass\n       * @kind function\n       *\n       * @description\n       * Adds and removes the appropriate CSS class values to the element based on the difference\n       * between the new and old CSS class values (specified as newClasses and oldClasses).\n       *\n       * @param {string} newClasses The current CSS className value\n       * @param {string} oldClasses The former CSS className value\n       */\n      $updateClass: function(newClasses, oldClasses) {\n        var toAdd = tokenDifference(newClasses, oldClasses);\n        if (toAdd && toAdd.length) {\n          $animate.addClass(this.$$element, toAdd);\n        }\n\n        var toRemove = tokenDifference(oldClasses, newClasses);\n        if (toRemove && toRemove.length) {\n          $animate.removeClass(this.$$element, toRemove);\n        }\n      },\n\n      /**\n       * Set a normalized attribute on the element in a way such that all directives\n       * can share the attribute. This function properly handles boolean attributes.\n       * @param {string} key Normalized key. (ie ngAttribute)\n       * @param {string|boolean} value The value to set. If `null` attribute will be deleted.\n       * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.\n       *     Defaults to true.\n       * @param {string=} attrName Optional none normalized name. Defaults to key.\n       */\n      $set: function(key, value, writeAttr, attrName) {\n        // TODO: decide whether or not to throw an error if \"class\"\n        //is set through this function since it may cause $updateClass to\n        //become unstable.\n\n        var node = this.$$element[0],\n            booleanKey = getBooleanAttrName(node, key),\n            aliasedKey = getAliasedAttrName(node, key),\n            observer = key,\n            nodeName;\n\n        if (booleanKey) {\n          this.$$element.prop(key, value);\n          attrName = booleanKey;\n        } else if (aliasedKey) {\n          this[aliasedKey] = value;\n          observer = aliasedKey;\n        }\n\n        this[key] = value;\n\n        // translate normalized key to actual key\n        if (attrName) {\n          this.$attr[key] = attrName;\n        } else {\n          attrName = this.$attr[key];\n          if (!attrName) {\n            this.$attr[key] = attrName = snake_case(key, '-');\n          }\n        }\n\n        nodeName = nodeName_(this.$$element);\n\n        if ((nodeName === 'a' && key === 'href') ||\n            (nodeName === 'img' && key === 'src')) {\n          // sanitize a[href] and img[src] values\n          this[key] = value = $$sanitizeUri(value, key === 'src');\n        } else if (nodeName === 'img' && key === 'srcset') {\n          // sanitize img[srcset] values\n          var result = \"\";\n\n          // first check if there are spaces because it's not the same pattern\n          var trimmedSrcset = trim(value);\n          //                (   999x   ,|   999w   ,|   ,|,   )\n          var srcPattern = /(\\s+\\d+x\\s*,|\\s+\\d+w\\s*,|\\s+,|,\\s+)/;\n          var pattern = /\\s/.test(trimmedSrcset) ? srcPattern : /(,)/;\n\n          // split srcset into tuple of uri and descriptor except for the last item\n          var rawUris = trimmedSrcset.split(pattern);\n\n          // for each tuples\n          var nbrUrisWith2parts = Math.floor(rawUris.length / 2);\n          for (var i = 0; i < nbrUrisWith2parts; i++) {\n            var innerIdx = i * 2;\n            // sanitize the uri\n            result += $$sanitizeUri(trim(rawUris[innerIdx]), true);\n            // add the descriptor\n            result += (\" \" + trim(rawUris[innerIdx + 1]));\n          }\n\n          // split the last item into uri and descriptor\n          var lastTuple = trim(rawUris[i * 2]).split(/\\s/);\n\n          // sanitize the last uri\n          result += $$sanitizeUri(trim(lastTuple[0]), true);\n\n          // and add the last descriptor if any\n          if (lastTuple.length === 2) {\n            result += (\" \" + trim(lastTuple[1]));\n          }\n          this[key] = value = result;\n        }\n\n        if (writeAttr !== false) {\n          if (value === null || value === undefined) {\n            this.$$element.removeAttr(attrName);\n          } else {\n            this.$$element.attr(attrName, value);\n          }\n        }\n\n        // fire observers\n        var $$observers = this.$$observers;\n        $$observers && forEach($$observers[observer], function(fn) {\n          try {\n            fn(value);\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        });\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$observe\n       * @kind function\n       *\n       * @description\n       * Observes an interpolated attribute.\n       *\n       * The observer function will be invoked once during the next `$digest` following\n       * compilation. The observer is then invoked whenever the interpolated value\n       * changes.\n       *\n       * @param {string} key Normalized key. (ie ngAttribute) .\n       * @param {function(interpolatedValue)} fn Function that will be called whenever\n                the interpolated value of the attribute changes.\n       *        See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.\n       * @returns {function()} Returns a deregistration function for this observer.\n       */\n      $observe: function(key, fn) {\n        var attrs = this,\n            $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),\n            listeners = ($$observers[key] || ($$observers[key] = []));\n\n        listeners.push(fn);\n        $rootScope.$evalAsync(function() {\n          if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {\n            // no one registered attribute interpolation function, so lets call it manually\n            fn(attrs[key]);\n          }\n        });\n\n        return function() {\n          arrayRemove(listeners, fn);\n        };\n      }\n    };\n\n\n    function safeAddClass($element, className) {\n      try {\n        $element.addClass(className);\n      } catch (e) {\n        // ignore, since it means that we are trying to set class on\n        // SVG element, where class name is read-only.\n      }\n    }\n\n\n    var startSymbol = $interpolate.startSymbol(),\n        endSymbol = $interpolate.endSymbol(),\n        denormalizeTemplate = (startSymbol == '{{' || endSymbol  == '}}')\n            ? identity\n            : function denormalizeTemplate(template) {\n              return template.replace(/\\{\\{/g, startSymbol).replace(/}}/g, endSymbol);\n        },\n        NG_ATTR_BINDING = /^ngAttr[A-Z]/;\n\n    compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {\n      var bindings = $element.data('$binding') || [];\n\n      if (isArray(binding)) {\n        bindings = bindings.concat(binding);\n      } else {\n        bindings.push(binding);\n      }\n\n      $element.data('$binding', bindings);\n    } : noop;\n\n    compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {\n      safeAddClass($element, 'ng-binding');\n    } : noop;\n\n    compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {\n      var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n      $element.data(dataName, scope);\n    } : noop;\n\n    compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {\n      safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');\n    } : noop;\n\n    return compile;\n\n    //================================\n\n    function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,\n                        previousCompileContext) {\n      if (!($compileNodes instanceof jqLite)) {\n        // jquery always rewraps, whereas we need to preserve the original selector so that we can\n        // modify it.\n        $compileNodes = jqLite($compileNodes);\n      }\n      // We can not compile top level text elements since text nodes can be merged and we will\n      // not be able to attach scope data to them, so we will wrap them in <span>\n      forEach($compileNodes, function(node, index) {\n        if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\\S+/) /* non-empty */ ) {\n          $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];\n        }\n      });\n      var compositeLinkFn =\n              compileNodes($compileNodes, transcludeFn, $compileNodes,\n                           maxPriority, ignoreDirective, previousCompileContext);\n      compile.$$addScopeClass($compileNodes);\n      var namespace = null;\n      return function publicLinkFn(scope, cloneConnectFn, options) {\n        assertArg(scope, 'scope');\n\n        options = options || {};\n        var parentBoundTranscludeFn = options.parentBoundTranscludeFn,\n          transcludeControllers = options.transcludeControllers,\n          futureParentElement = options.futureParentElement;\n\n        // When `parentBoundTranscludeFn` is passed, it is a\n        // `controllersBoundTransclude` function (it was previously passed\n        // as `transclude` to directive.link) so we must unwrap it to get\n        // its `boundTranscludeFn`\n        if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {\n          parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;\n        }\n\n        if (!namespace) {\n          namespace = detectNamespaceForChildElements(futureParentElement);\n        }\n        var $linkNode;\n        if (namespace !== 'html') {\n          // When using a directive with replace:true and templateUrl the $compileNodes\n          // (or a child element inside of them)\n          // might change, so we need to recreate the namespace adapted compileNodes\n          // for call to the link function.\n          // Note: This will already clone the nodes...\n          $linkNode = jqLite(\n            wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())\n          );\n        } else if (cloneConnectFn) {\n          // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart\n          // and sometimes changes the structure of the DOM.\n          $linkNode = JQLitePrototype.clone.call($compileNodes);\n        } else {\n          $linkNode = $compileNodes;\n        }\n\n        if (transcludeControllers) {\n          for (var controllerName in transcludeControllers) {\n            $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);\n          }\n        }\n\n        compile.$$addScopeInfo($linkNode, scope);\n\n        if (cloneConnectFn) cloneConnectFn($linkNode, scope);\n        if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);\n        return $linkNode;\n      };\n    }\n\n    function detectNamespaceForChildElements(parentElement) {\n      // TODO: Make this detect MathML as well...\n      var node = parentElement && parentElement[0];\n      if (!node) {\n        return 'html';\n      } else {\n        return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';\n      }\n    }\n\n    /**\n     * Compile function matches each node in nodeList against the directives. Once all directives\n     * for a particular node are collected their compile functions are executed. The compile\n     * functions return values - the linking functions - are combined into a composite linking\n     * function, which is the a linking function for the node.\n     *\n     * @param {NodeList} nodeList an array of nodes or NodeList to compile\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *        scope argument is auto-generated to the new child of the transcluded parent scope.\n     * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then\n     *        the rootElement must be set the jqLite collection of the compile root. This is\n     *        needed so that the jqLite collection items can be replaced with widgets.\n     * @param {number=} maxPriority Max directive priority.\n     * @returns {Function} A composite linking function of all of the matched directives or null.\n     */\n    function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,\n                            previousCompileContext) {\n      var linkFns = [],\n          attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;\n\n      for (var i = 0; i < nodeList.length; i++) {\n        attrs = new Attributes();\n\n        // we must always refer to nodeList[i] since the nodes can be replaced underneath us.\n        directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,\n                                        ignoreDirective);\n\n        nodeLinkFn = (directives.length)\n            ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,\n                                      null, [], [], previousCompileContext)\n            : null;\n\n        if (nodeLinkFn && nodeLinkFn.scope) {\n          compile.$$addScopeClass(attrs.$$element);\n        }\n\n        childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||\n                      !(childNodes = nodeList[i].childNodes) ||\n                      !childNodes.length)\n            ? null\n            : compileNodes(childNodes,\n                 nodeLinkFn ? (\n                  (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)\n                     && nodeLinkFn.transclude) : transcludeFn);\n\n        if (nodeLinkFn || childLinkFn) {\n          linkFns.push(i, nodeLinkFn, childLinkFn);\n          linkFnFound = true;\n          nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;\n        }\n\n        //use the previous context only for the first element in the virtual group\n        previousCompileContext = null;\n      }\n\n      // return a linking function if we have found anything, null otherwise\n      return linkFnFound ? compositeLinkFn : null;\n\n      function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {\n        var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;\n        var stableNodeList;\n\n\n        if (nodeLinkFnFound) {\n          // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our\n          // offsets don't get screwed up\n          var nodeListLength = nodeList.length;\n          stableNodeList = new Array(nodeListLength);\n\n          // create a sparse array by only copying the elements which have a linkFn\n          for (i = 0; i < linkFns.length; i+=3) {\n            idx = linkFns[i];\n            stableNodeList[idx] = nodeList[idx];\n          }\n        } else {\n          stableNodeList = nodeList;\n        }\n\n        for (i = 0, ii = linkFns.length; i < ii;) {\n          node = stableNodeList[linkFns[i++]];\n          nodeLinkFn = linkFns[i++];\n          childLinkFn = linkFns[i++];\n\n          if (nodeLinkFn) {\n            if (nodeLinkFn.scope) {\n              childScope = scope.$new();\n              compile.$$addScopeInfo(jqLite(node), childScope);\n              var destroyBindings = nodeLinkFn.$$destroyBindings;\n              if (destroyBindings) {\n                nodeLinkFn.$$destroyBindings = null;\n                childScope.$on('$destroyed', destroyBindings);\n              }\n            } else {\n              childScope = scope;\n            }\n\n            if (nodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(\n                  scope, nodeLinkFn.transclude, parentBoundTranscludeFn);\n\n            } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {\n              childBoundTranscludeFn = parentBoundTranscludeFn;\n\n            } else if (!parentBoundTranscludeFn && transcludeFn) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);\n\n            } else {\n              childBoundTranscludeFn = null;\n            }\n\n            nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,\n                       nodeLinkFn);\n\n          } else if (childLinkFn) {\n            childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);\n          }\n        }\n      }\n    }\n\n    function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {\n\n      var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {\n\n        if (!transcludedScope) {\n          transcludedScope = scope.$new(false, containingScope);\n          transcludedScope.$$transcluded = true;\n        }\n\n        return transcludeFn(transcludedScope, cloneFn, {\n          parentBoundTranscludeFn: previousBoundTranscludeFn,\n          transcludeControllers: controllers,\n          futureParentElement: futureParentElement\n        });\n      };\n\n      return boundTranscludeFn;\n    }\n\n    /**\n     * Looks for directives on the given node and adds them to the directive collection which is\n     * sorted.\n     *\n     * @param node Node to search.\n     * @param directives An array to which the directives are added to. This array is sorted before\n     *        the function returns.\n     * @param attrs The shared attrs object which is used to populate the normalized attributes.\n     * @param {number=} maxPriority Max directive priority.\n     */\n    function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n      var nodeType = node.nodeType,\n          attrsMap = attrs.$attr,\n          match,\n          className;\n\n      switch (nodeType) {\n        case NODE_TYPE_ELEMENT: /* Element */\n          // use the node name: <directive>\n          addDirective(directives,\n              directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);\n\n          // iterate over the attributes\n          for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,\n                   j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {\n            var attrStartName = false;\n            var attrEndName = false;\n\n            attr = nAttrs[j];\n            name = attr.name;\n            value = trim(attr.value);\n\n            // support ngAttr attribute binding\n            ngAttrName = directiveNormalize(name);\n            if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {\n              name = name.replace(PREFIX_REGEXP, '')\n                .substr(8).replace(/_(.)/g, function(match, letter) {\n                  return letter.toUpperCase();\n                });\n            }\n\n            var directiveNName = ngAttrName.replace(/(Start|End)$/, '');\n            if (directiveIsMultiElement(directiveNName)) {\n              if (ngAttrName === directiveNName + 'Start') {\n                attrStartName = name;\n                attrEndName = name.substr(0, name.length - 5) + 'end';\n                name = name.substr(0, name.length - 6);\n              }\n            }\n\n            nName = directiveNormalize(name.toLowerCase());\n            attrsMap[nName] = name;\n            if (isNgAttr || !attrs.hasOwnProperty(nName)) {\n                attrs[nName] = value;\n                if (getBooleanAttrName(node, nName)) {\n                  attrs[nName] = true; // presence means true\n                }\n            }\n            addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);\n            addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,\n                          attrEndName);\n          }\n\n          // use class as directive\n          className = node.className;\n          if (isObject(className)) {\n              // Maybe SVGAnimatedString\n              className = className.animVal;\n          }\n          if (isString(className) && className !== '') {\n            while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {\n              nName = directiveNormalize(match[2]);\n              if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[3]);\n              }\n              className = className.substr(match.index + match[0].length);\n            }\n          }\n          break;\n        case NODE_TYPE_TEXT: /* Text Node */\n          if (msie === 11) {\n            // Workaround for #11781\n            while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {\n              node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;\n              node.parentNode.removeChild(node.nextSibling);\n            }\n          }\n          addTextInterpolateDirective(directives, node.nodeValue);\n          break;\n        case NODE_TYPE_COMMENT: /* Comment */\n          try {\n            match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);\n            if (match) {\n              nName = directiveNormalize(match[1]);\n              if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[2]);\n              }\n            }\n          } catch (e) {\n            // turns out that under some circumstances IE9 throws errors when one attempts to read\n            // comment's node value.\n            // Just ignore it and continue. (Can't seem to reproduce in test case.)\n          }\n          break;\n      }\n\n      directives.sort(byPriority);\n      return directives;\n    }\n\n    /**\n     * Given a node with an directive-start it collects all of the siblings until it finds\n     * directive-end.\n     * @param node\n     * @param attrStart\n     * @param attrEnd\n     * @returns {*}\n     */\n    function groupScan(node, attrStart, attrEnd) {\n      var nodes = [];\n      var depth = 0;\n      if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {\n        do {\n          if (!node) {\n            throw $compileMinErr('uterdir',\n                      \"Unterminated attribute, found '{0}' but no matching '{1}' found.\",\n                      attrStart, attrEnd);\n          }\n          if (node.nodeType == NODE_TYPE_ELEMENT) {\n            if (node.hasAttribute(attrStart)) depth++;\n            if (node.hasAttribute(attrEnd)) depth--;\n          }\n          nodes.push(node);\n          node = node.nextSibling;\n        } while (depth > 0);\n      } else {\n        nodes.push(node);\n      }\n\n      return jqLite(nodes);\n    }\n\n    /**\n     * Wrapper for linking function which converts normal linking function into a grouped\n     * linking function.\n     * @param linkFn\n     * @param attrStart\n     * @param attrEnd\n     * @returns {Function}\n     */\n    function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {\n      return function(scope, element, attrs, controllers, transcludeFn) {\n        element = groupScan(element[0], attrStart, attrEnd);\n        return linkFn(scope, element, attrs, controllers, transcludeFn);\n      };\n    }\n\n    /**\n     * Once the directives have been collected, their compile functions are executed. This method\n     * is responsible for inlining directive templates as well as terminating the application\n     * of the directives if the terminal directive has been reached.\n     *\n     * @param {Array} directives Array of collected directives to execute their compile function.\n     *        this needs to be pre-sorted by priority order.\n     * @param {Node} compileNode The raw DOM node to apply the compile functions to\n     * @param {Object} templateAttrs The shared attribute function\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *                                                  scope argument is auto-generated to the new\n     *                                                  child of the transcluded parent scope.\n     * @param {JQLite} jqCollection If we are working on the root of the compile tree then this\n     *                              argument has the root jqLite array so that we can replace nodes\n     *                              on it.\n     * @param {Object=} originalReplaceDirective An optional directive that will be ignored when\n     *                                           compiling the transclusion.\n     * @param {Array.<Function>} preLinkFns\n     * @param {Array.<Function>} postLinkFns\n     * @param {Object} previousCompileContext Context used for previous compilation of the current\n     *                                        node\n     * @returns {Function} linkFn\n     */\n    function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,\n                                   jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,\n                                   previousCompileContext) {\n      previousCompileContext = previousCompileContext || {};\n\n      var terminalPriority = -Number.MAX_VALUE,\n          newScopeDirective = previousCompileContext.newScopeDirective,\n          controllerDirectives = previousCompileContext.controllerDirectives,\n          newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,\n          templateDirective = previousCompileContext.templateDirective,\n          nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,\n          hasTranscludeDirective = false,\n          hasTemplate = false,\n          hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,\n          $compileNode = templateAttrs.$$element = jqLite(compileNode),\n          directive,\n          directiveName,\n          $template,\n          replaceDirective = originalReplaceDirective,\n          childTranscludeFn = transcludeFn,\n          linkFn,\n          directiveValue;\n\n      // executes all directives on the current element\n      for (var i = 0, ii = directives.length; i < ii; i++) {\n        directive = directives[i];\n        var attrStart = directive.$$start;\n        var attrEnd = directive.$$end;\n\n        // collect multiblock sections\n        if (attrStart) {\n          $compileNode = groupScan(compileNode, attrStart, attrEnd);\n        }\n        $template = undefined;\n\n        if (terminalPriority > directive.priority) {\n          break; // prevent further processing of directives\n        }\n\n        if (directiveValue = directive.scope) {\n\n          // skip the check for directives with async templates, we'll check the derived sync\n          // directive when the template arrives\n          if (!directive.templateUrl) {\n            if (isObject(directiveValue)) {\n              // This directive is trying to add an isolated scope.\n              // Check that there is no scope of any kind already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,\n                                directive, $compileNode);\n              newIsolateScopeDirective = directive;\n            } else {\n              // This directive is trying to add a child scope.\n              // Check that there is no isolated scope already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,\n                                $compileNode);\n            }\n          }\n\n          newScopeDirective = newScopeDirective || directive;\n        }\n\n        directiveName = directive.name;\n\n        if (!directive.templateUrl && directive.controller) {\n          directiveValue = directive.controller;\n          controllerDirectives = controllerDirectives || createMap();\n          assertNoDuplicate(\"'\" + directiveName + \"' controller\",\n              controllerDirectives[directiveName], directive, $compileNode);\n          controllerDirectives[directiveName] = directive;\n        }\n\n        if (directiveValue = directive.transclude) {\n          hasTranscludeDirective = true;\n\n          // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.\n          // This option should only be used by directives that know how to safely handle element transclusion,\n          // where the transcluded nodes are added or replaced after linking.\n          if (!directive.$$tlb) {\n            assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);\n            nonTlbTranscludeDirective = directive;\n          }\n\n          if (directiveValue == 'element') {\n            hasElementTranscludeDirective = true;\n            terminalPriority = directive.priority;\n            $template = $compileNode;\n            $compileNode = templateAttrs.$$element =\n                jqLite(document.createComment(' ' + directiveName + ': ' +\n                                              templateAttrs[directiveName] + ' '));\n            compileNode = $compileNode[0];\n            replaceWith(jqCollection, sliceArgs($template), compileNode);\n\n            childTranscludeFn = compile($template, transcludeFn, terminalPriority,\n                                        replaceDirective && replaceDirective.name, {\n                                          // Don't pass in:\n                                          // - controllerDirectives - otherwise we'll create duplicates controllers\n                                          // - newIsolateScopeDirective or templateDirective - combining templates with\n                                          //   element transclusion doesn't make sense.\n                                          //\n                                          // We need only nonTlbTranscludeDirective so that we prevent putting transclusion\n                                          // on the same element more than once.\n                                          nonTlbTranscludeDirective: nonTlbTranscludeDirective\n                                        });\n          } else {\n            $template = jqLite(jqLiteClone(compileNode)).contents();\n            $compileNode.empty(); // clear contents\n            childTranscludeFn = compile($template, transcludeFn);\n          }\n        }\n\n        if (directive.template) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          directiveValue = (isFunction(directive.template))\n              ? directive.template($compileNode, templateAttrs)\n              : directive.template;\n\n          directiveValue = denormalizeTemplate(directiveValue);\n\n          if (directive.replace) {\n            replaceDirective = directive;\n            if (jqLiteIsTextNode(directiveValue)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  directiveName, '');\n            }\n\n            replaceWith(jqCollection, $compileNode, compileNode);\n\n            var newTemplateAttrs = {$attr: {}};\n\n            // combine directives from the original node and from the template:\n            // - take the array of directives for this element\n            // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)\n            // - collect directives from the template and sort them by priority\n            // - combine directives as: processed + template + unprocessed\n            var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);\n            var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));\n\n            if (newIsolateScopeDirective) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = directives.concat(templateDirectives).concat(unprocessedDirectives);\n            mergeTemplateAttributes(templateAttrs, newTemplateAttrs);\n\n            ii = directives.length;\n          } else {\n            $compileNode.html(directiveValue);\n          }\n        }\n\n        if (directive.templateUrl) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          if (directive.replace) {\n            replaceDirective = directive;\n          }\n\n          nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,\n              templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {\n                controllerDirectives: controllerDirectives,\n                newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,\n                newIsolateScopeDirective: newIsolateScopeDirective,\n                templateDirective: templateDirective,\n                nonTlbTranscludeDirective: nonTlbTranscludeDirective\n              });\n          ii = directives.length;\n        } else if (directive.compile) {\n          try {\n            linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);\n            if (isFunction(linkFn)) {\n              addLinkFns(null, linkFn, attrStart, attrEnd);\n            } else if (linkFn) {\n              addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);\n            }\n          } catch (e) {\n            $exceptionHandler(e, startingTag($compileNode));\n          }\n        }\n\n        if (directive.terminal) {\n          nodeLinkFn.terminal = true;\n          terminalPriority = Math.max(terminalPriority, directive.priority);\n        }\n\n      }\n\n      nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;\n      nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;\n      nodeLinkFn.templateOnThisElement = hasTemplate;\n      nodeLinkFn.transclude = childTranscludeFn;\n\n      previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;\n\n      // might be normal or delayed nodeLinkFn depending on if templateUrl is present\n      return nodeLinkFn;\n\n      ////////////////////\n\n      function addLinkFns(pre, post, attrStart, attrEnd) {\n        if (pre) {\n          if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);\n          pre.require = directive.require;\n          pre.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            pre = cloneAndAnnotateFn(pre, {isolateScope: true});\n          }\n          preLinkFns.push(pre);\n        }\n        if (post) {\n          if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);\n          post.require = directive.require;\n          post.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            post = cloneAndAnnotateFn(post, {isolateScope: true});\n          }\n          postLinkFns.push(post);\n        }\n      }\n\n\n      function getControllers(directiveName, require, $element, elementControllers) {\n        var value;\n\n        if (isString(require)) {\n          var match = require.match(REQUIRE_PREFIX_REGEXP);\n          var name = require.substring(match[0].length);\n          var inheritType = match[1] || match[3];\n          var optional = match[2] === '?';\n\n          //If only parents then start at the parent element\n          if (inheritType === '^^') {\n            $element = $element.parent();\n          //Otherwise attempt getting the controller from elementControllers in case\n          //the element is transcluded (and has no data) and to avoid .data if possible\n          } else {\n            value = elementControllers && elementControllers[name];\n            value = value && value.instance;\n          }\n\n          if (!value) {\n            var dataName = '$' + name + 'Controller';\n            value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);\n          }\n\n          if (!value && !optional) {\n            throw $compileMinErr('ctreq',\n                \"Controller '{0}', required by directive '{1}', can't be found!\",\n                name, directiveName);\n          }\n        } else if (isArray(require)) {\n          value = [];\n          for (var i = 0, ii = require.length; i < ii; i++) {\n            value[i] = getControllers(directiveName, require[i], $element, elementControllers);\n          }\n        }\n\n        return value || null;\n      }\n\n      function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {\n        var elementControllers = createMap();\n        for (var controllerKey in controllerDirectives) {\n          var directive = controllerDirectives[controllerKey];\n          var locals = {\n            $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,\n            $element: $element,\n            $attrs: attrs,\n            $transclude: transcludeFn\n          };\n\n          var controller = directive.controller;\n          if (controller == '@') {\n            controller = attrs[directive.name];\n          }\n\n          var controllerInstance = $controller(controller, locals, true, directive.controllerAs);\n\n          // For directives with element transclusion the element is a comment,\n          // but jQuery .data doesn't support attaching data to comment nodes as it's hard to\n          // clean up (http://bugs.jquery.com/ticket/8335).\n          // Instead, we save the controllers for the element in a local hash and attach to .data\n          // later, once we have the actual element.\n          elementControllers[directive.name] = controllerInstance;\n          if (!hasElementTranscludeDirective) {\n            $element.data('$' + directive.name + 'Controller', controllerInstance.instance);\n          }\n        }\n        return elementControllers;\n      }\n\n      function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,\n                          thisLinkFn) {\n        var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,\n            attrs;\n\n        if (compileNode === linkNode) {\n          attrs = templateAttrs;\n          $element = templateAttrs.$$element;\n        } else {\n          $element = jqLite(linkNode);\n          attrs = new Attributes($element, templateAttrs);\n        }\n\n        if (newIsolateScopeDirective) {\n          isolateScope = scope.$new(true);\n        }\n\n        if (boundTranscludeFn) {\n          // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`\n          // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`\n          transcludeFn = controllersBoundTransclude;\n          transcludeFn.$$boundTransclude = boundTranscludeFn;\n        }\n\n        if (controllerDirectives) {\n          elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);\n        }\n\n        if (newIsolateScopeDirective) {\n          // Initialize isolate scope bindings for new isolate scope directive.\n          compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||\n              templateDirective === newIsolateScopeDirective.$$originalDirective)));\n          compile.$$addScopeClass($element, true);\n          isolateScope.$$isolateBindings =\n              newIsolateScopeDirective.$$isolateBindings;\n          initializeDirectiveBindings(scope, attrs, isolateScope,\n                                      isolateScope.$$isolateBindings,\n                                      newIsolateScopeDirective, isolateScope);\n        }\n        if (elementControllers) {\n          // Initialize bindToController bindings for new/isolate scopes\n          var scopeDirective = newIsolateScopeDirective || newScopeDirective;\n          var bindings;\n          var controllerForBindings;\n          if (scopeDirective && elementControllers[scopeDirective.name]) {\n            bindings = scopeDirective.$$bindings.bindToController;\n            controller = elementControllers[scopeDirective.name];\n\n            if (controller && controller.identifier && bindings) {\n              controllerForBindings = controller;\n              thisLinkFn.$$destroyBindings =\n                  initializeDirectiveBindings(scope, attrs, controller.instance,\n                                              bindings, scopeDirective);\n            }\n          }\n          for (i in elementControllers) {\n            controller = elementControllers[i];\n            var controllerResult = controller();\n\n            if (controllerResult !== controller.instance) {\n              // If the controller constructor has a return value, overwrite the instance\n              // from setupControllers and update the element data\n              controller.instance = controllerResult;\n              $element.data('$' + i + 'Controller', controllerResult);\n              if (controller === controllerForBindings) {\n                // Remove and re-install bindToController bindings\n                thisLinkFn.$$destroyBindings();\n                thisLinkFn.$$destroyBindings =\n                  initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);\n              }\n            }\n          }\n        }\n\n        // PRELINKING\n        for (i = 0, ii = preLinkFns.length; i < ii; i++) {\n          linkFn = preLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // RECURSION\n        // We only pass the isolate scope, if the isolate directive has a template,\n        // otherwise the child elements do not belong to the isolate directive.\n        var scopeToChild = scope;\n        if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {\n          scopeToChild = isolateScope;\n        }\n        childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);\n\n        // POSTLINKING\n        for (i = postLinkFns.length - 1; i >= 0; i--) {\n          linkFn = postLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // This is the function that is injected as `$transclude`.\n        // Note: all arguments are optional!\n        function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {\n          var transcludeControllers;\n\n          // No scope passed in:\n          if (!isScope(scope)) {\n            futureParentElement = cloneAttachFn;\n            cloneAttachFn = scope;\n            scope = undefined;\n          }\n\n          if (hasElementTranscludeDirective) {\n            transcludeControllers = elementControllers;\n          }\n          if (!futureParentElement) {\n            futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;\n          }\n          return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n        }\n      }\n    }\n\n    function markDirectivesAsIsolate(directives) {\n      // mark all directives as needing isolate scope.\n      for (var j = 0, jj = directives.length; j < jj; j++) {\n        directives[j] = inherit(directives[j], {$$isolateScope: true});\n      }\n    }\n\n    /**\n     * looks up the directive and decorates it with exception handling and proper parameters. We\n     * call this the boundDirective.\n     *\n     * @param {string} name name of the directive to look up.\n     * @param {string} location The directive must be found in specific format.\n     *   String containing any of theses characters:\n     *\n     *   * `E`: element name\n     *   * `A': attribute\n     *   * `C`: class\n     *   * `M`: comment\n     * @returns {boolean} true if directive was added.\n     */\n    function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,\n                          endAttrName) {\n      if (name === ignoreDirective) return null;\n      var match = null;\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          try {\n            directive = directives[i];\n            if ((maxPriority === undefined || maxPriority > directive.priority) &&\n                 directive.restrict.indexOf(location) != -1) {\n              if (startAttrName) {\n                directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});\n              }\n              tDirectives.push(directive);\n              match = directive;\n            }\n          } catch (e) { $exceptionHandler(e); }\n        }\n      }\n      return match;\n    }\n\n\n    /**\n     * looks up the directive and returns true if it is a multi-element directive,\n     * and therefore requires DOM nodes between -start and -end markers to be grouped\n     * together.\n     *\n     * @param {string} name name of the directive to look up.\n     * @returns true if directive was registered as multi-element.\n     */\n    function directiveIsMultiElement(name) {\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          directive = directives[i];\n          if (directive.multiElement) {\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n\n    /**\n     * When the element is replaced with HTML template then the new attributes\n     * on the template need to be merged with the existing attributes in the DOM.\n     * The desired effect is to have both of the attributes present.\n     *\n     * @param {object} dst destination attributes (original DOM)\n     * @param {object} src source attributes (from the directive template)\n     */\n    function mergeTemplateAttributes(dst, src) {\n      var srcAttr = src.$attr,\n          dstAttr = dst.$attr,\n          $element = dst.$$element;\n\n      // reapply the old attributes to the new element\n      forEach(dst, function(value, key) {\n        if (key.charAt(0) != '$') {\n          if (src[key] && src[key] !== value) {\n            value += (key === 'style' ? ';' : ' ') + src[key];\n          }\n          dst.$set(key, value, true, srcAttr[key]);\n        }\n      });\n\n      // copy the new attributes on the old attrs object\n      forEach(src, function(value, key) {\n        if (key == 'class') {\n          safeAddClass($element, value);\n          dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;\n        } else if (key == 'style') {\n          $element.attr('style', $element.attr('style') + ';' + value);\n          dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;\n          // `dst` will never contain hasOwnProperty as DOM parser won't let it.\n          // You will get an \"InvalidCharacterError: DOM Exception 5\" error if you\n          // have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.\n        } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {\n          dst[key] = value;\n          dstAttr[key] = srcAttr[key];\n        }\n      });\n    }\n\n\n    function compileTemplateUrl(directives, $compileNode, tAttrs,\n        $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {\n      var linkQueue = [],\n          afterTemplateNodeLinkFn,\n          afterTemplateChildLinkFn,\n          beforeTemplateCompileNode = $compileNode[0],\n          origAsyncDirective = directives.shift(),\n          derivedSyncDirective = inherit(origAsyncDirective, {\n            templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective\n          }),\n          templateUrl = (isFunction(origAsyncDirective.templateUrl))\n              ? origAsyncDirective.templateUrl($compileNode, tAttrs)\n              : origAsyncDirective.templateUrl,\n          templateNamespace = origAsyncDirective.templateNamespace;\n\n      $compileNode.empty();\n\n      $templateRequest(templateUrl)\n        .then(function(content) {\n          var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;\n\n          content = denormalizeTemplate(content);\n\n          if (origAsyncDirective.replace) {\n            if (jqLiteIsTextNode(content)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(templateNamespace, trim(content)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  origAsyncDirective.name, templateUrl);\n            }\n\n            tempTemplateAttrs = {$attr: {}};\n            replaceWith($rootElement, $compileNode, compileNode);\n            var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);\n\n            if (isObject(origAsyncDirective.scope)) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = templateDirectives.concat(directives);\n            mergeTemplateAttributes(tAttrs, tempTemplateAttrs);\n          } else {\n            compileNode = beforeTemplateCompileNode;\n            $compileNode.html(content);\n          }\n\n          directives.unshift(derivedSyncDirective);\n\n          afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,\n              childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,\n              previousCompileContext);\n          forEach($rootElement, function(node, i) {\n            if (node == compileNode) {\n              $rootElement[i] = $compileNode[0];\n            }\n          });\n          afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);\n\n          while (linkQueue.length) {\n            var scope = linkQueue.shift(),\n                beforeTemplateLinkNode = linkQueue.shift(),\n                linkRootElement = linkQueue.shift(),\n                boundTranscludeFn = linkQueue.shift(),\n                linkNode = $compileNode[0];\n\n            if (scope.$$destroyed) continue;\n\n            if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {\n              var oldClasses = beforeTemplateLinkNode.className;\n\n              if (!(previousCompileContext.hasElementTranscludeDirective &&\n                  origAsyncDirective.replace)) {\n                // it was cloned therefore we have to clone as well.\n                linkNode = jqLiteClone(compileNode);\n              }\n              replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);\n\n              // Copy in CSS classes from original node\n              safeAddClass(jqLite(linkNode), oldClasses);\n            }\n            if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n            } else {\n              childBoundTranscludeFn = boundTranscludeFn;\n            }\n            afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,\n              childBoundTranscludeFn, afterTemplateNodeLinkFn);\n          }\n          linkQueue = null;\n        });\n\n      return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {\n        var childBoundTranscludeFn = boundTranscludeFn;\n        if (scope.$$destroyed) return;\n        if (linkQueue) {\n          linkQueue.push(scope,\n                         node,\n                         rootElement,\n                         childBoundTranscludeFn);\n        } else {\n          if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n            childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n          }\n          afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,\n                                  afterTemplateNodeLinkFn);\n        }\n      };\n    }\n\n\n    /**\n     * Sorting function for bound directives.\n     */\n    function byPriority(a, b) {\n      var diff = b.priority - a.priority;\n      if (diff !== 0) return diff;\n      if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;\n      return a.index - b.index;\n    }\n\n    function assertNoDuplicate(what, previousDirective, directive, element) {\n\n      function wrapModuleNameIfDefined(moduleName) {\n        return moduleName ?\n          (' (module: ' + moduleName + ')') :\n          '';\n      }\n\n      if (previousDirective) {\n        throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',\n            previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),\n            directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));\n      }\n    }\n\n\n    function addTextInterpolateDirective(directives, text) {\n      var interpolateFn = $interpolate(text, true);\n      if (interpolateFn) {\n        directives.push({\n          priority: 0,\n          compile: function textInterpolateCompileFn(templateNode) {\n            var templateNodeParent = templateNode.parent(),\n                hasCompileParent = !!templateNodeParent.length;\n\n            // When transcluding a template that has bindings in the root\n            // we don't have a parent and thus need to add the class during linking fn.\n            if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);\n\n            return function textInterpolateLinkFn(scope, node) {\n              var parent = node.parent();\n              if (!hasCompileParent) compile.$$addBindingClass(parent);\n              compile.$$addBindingInfo(parent, interpolateFn.expressions);\n              scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {\n                node[0].nodeValue = value;\n              });\n            };\n          }\n        });\n      }\n    }\n\n\n    function wrapTemplate(type, template) {\n      type = lowercase(type || 'html');\n      switch (type) {\n      case 'svg':\n      case 'math':\n        var wrapper = document.createElement('div');\n        wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';\n        return wrapper.childNodes[0].childNodes;\n      default:\n        return template;\n      }\n    }\n\n\n    function getTrustedContext(node, attrNormalizedName) {\n      if (attrNormalizedName == \"srcdoc\") {\n        return $sce.HTML;\n      }\n      var tag = nodeName_(node);\n      // maction[xlink:href] can source SVG.  It's not limited to <maction>.\n      if (attrNormalizedName == \"xlinkHref\" ||\n          (tag == \"form\" && attrNormalizedName == \"action\") ||\n          (tag != \"img\" && (attrNormalizedName == \"src\" ||\n                            attrNormalizedName == \"ngSrc\"))) {\n        return $sce.RESOURCE_URL;\n      }\n    }\n\n\n    function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {\n      var trustedContext = getTrustedContext(node, name);\n      allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;\n\n      var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);\n\n      // no interpolation found -> ignore\n      if (!interpolateFn) return;\n\n\n      if (name === \"multiple\" && nodeName_(node) === \"select\") {\n        throw $compileMinErr(\"selmulti\",\n            \"Binding to the 'multiple' attribute is not supported. Element: {0}\",\n            startingTag(node));\n      }\n\n      directives.push({\n        priority: 100,\n        compile: function() {\n            return {\n              pre: function attrInterpolatePreLinkFn(scope, element, attr) {\n                var $$observers = (attr.$$observers || (attr.$$observers = {}));\n\n                if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {\n                  throw $compileMinErr('nodomevents',\n                      \"Interpolations for HTML DOM event attributes are disallowed.  Please use the \" +\n                          \"ng- versions (such as ng-click instead of onclick) instead.\");\n                }\n\n                // If the attribute has changed since last $interpolate()ed\n                var newValue = attr[name];\n                if (newValue !== value) {\n                  // we need to interpolate again since the attribute value has been updated\n                  // (e.g. by another directive's compile function)\n                  // ensure unset/empty values make interpolateFn falsy\n                  interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);\n                  value = newValue;\n                }\n\n                // if attribute was updated so that there is no interpolation going on we don't want to\n                // register any observers\n                if (!interpolateFn) return;\n\n                // initialize attr object so that it's ready in case we need the value for isolate\n                // scope initialization, otherwise the value would not be available from isolate\n                // directive's linking fn during linking phase\n                attr[name] = interpolateFn(scope);\n\n                ($$observers[name] || ($$observers[name] = [])).$$inter = true;\n                (attr.$$observers && attr.$$observers[name].$$scope || scope).\n                  $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {\n                    //special case for class attribute addition + removal\n                    //so that class changes can tap into the animation\n                    //hooks provided by the $animate service. Be sure to\n                    //skip animations when the first digest occurs (when\n                    //both the new and the old values are the same) since\n                    //the CSS classes are the non-interpolated values\n                    if (name === 'class' && newValue != oldValue) {\n                      attr.$updateClass(newValue, oldValue);\n                    } else {\n                      attr.$set(name, newValue);\n                    }\n                  });\n              }\n            };\n          }\n      });\n    }\n\n\n    /**\n     * This is a special jqLite.replaceWith, which can replace items which\n     * have no parents, provided that the containing jqLite collection is provided.\n     *\n     * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes\n     *                               in the root of the tree.\n     * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep\n     *                                  the shell, but replace its DOM node reference.\n     * @param {Node} newNode The new DOM node.\n     */\n    function replaceWith($rootElement, elementsToRemove, newNode) {\n      var firstElementToRemove = elementsToRemove[0],\n          removeCount = elementsToRemove.length,\n          parent = firstElementToRemove.parentNode,\n          i, ii;\n\n      if ($rootElement) {\n        for (i = 0, ii = $rootElement.length; i < ii; i++) {\n          if ($rootElement[i] == firstElementToRemove) {\n            $rootElement[i++] = newNode;\n            for (var j = i, j2 = j + removeCount - 1,\n                     jj = $rootElement.length;\n                 j < jj; j++, j2++) {\n              if (j2 < jj) {\n                $rootElement[j] = $rootElement[j2];\n              } else {\n                delete $rootElement[j];\n              }\n            }\n            $rootElement.length -= removeCount - 1;\n\n            // If the replaced element is also the jQuery .context then replace it\n            // .context is a deprecated jQuery api, so we should set it only when jQuery set it\n            // http://api.jquery.com/context/\n            if ($rootElement.context === firstElementToRemove) {\n              $rootElement.context = newNode;\n            }\n            break;\n          }\n        }\n      }\n\n      if (parent) {\n        parent.replaceChild(newNode, firstElementToRemove);\n      }\n\n      // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?\n      var fragment = document.createDocumentFragment();\n      fragment.appendChild(firstElementToRemove);\n\n      if (jqLite.hasData(firstElementToRemove)) {\n        // Copy over user data (that includes Angular's $scope etc.). Don't copy private\n        // data here because there's no public interface in jQuery to do that and copying over\n        // event listeners (which is the main use of private data) wouldn't work anyway.\n        jqLite(newNode).data(jqLite(firstElementToRemove).data());\n\n        // Remove data of the replaced element. We cannot just call .remove()\n        // on the element it since that would deallocate scope that is needed\n        // for the new node. Instead, remove the data \"manually\".\n        if (!jQuery) {\n          delete jqLite.cache[firstElementToRemove[jqLite.expando]];\n        } else {\n          // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after\n          // the replaced element. The cleanData version monkey-patched by Angular would cause\n          // the scope to be trashed and we do need the very same scope to work with the new\n          // element. However, we cannot just cache the non-patched version and use it here as\n          // that would break if another library patches the method after Angular does (one\n          // example is jQuery UI). Instead, set a flag indicating scope destroying should be\n          // skipped this one time.\n          skipDestroyOnNextJQueryCleanData = true;\n          jQuery.cleanData([firstElementToRemove]);\n        }\n      }\n\n      for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {\n        var element = elementsToRemove[k];\n        jqLite(element).remove(); // must do this way to clean up expando\n        fragment.appendChild(element);\n        delete elementsToRemove[k];\n      }\n\n      elementsToRemove[0] = newNode;\n      elementsToRemove.length = 1;\n    }\n\n\n    function cloneAndAnnotateFn(fn, annotation) {\n      return extend(function() { return fn.apply(null, arguments); }, fn, annotation);\n    }\n\n\n    function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {\n      try {\n        linkFn(scope, $element, attrs, controllers, transcludeFn);\n      } catch (e) {\n        $exceptionHandler(e, startingTag($element));\n      }\n    }\n\n\n    // Set up $watches for isolate scope and controller bindings. This process\n    // only occurs for isolate scopes and new scopes with controllerAs.\n    function initializeDirectiveBindings(scope, attrs, destination, bindings,\n                                         directive, newScope) {\n      var onNewScopeDestroyed;\n      forEach(bindings, function(definition, scopeName) {\n        var attrName = definition.attrName,\n        optional = definition.optional,\n        mode = definition.mode, // @, =, or &\n        lastValue,\n        parentGet, parentSet, compare;\n\n        switch (mode) {\n\n          case '@':\n            if (!optional && !hasOwnProperty.call(attrs, attrName)) {\n              destination[scopeName] = attrs[attrName] = void 0;\n            }\n            attrs.$observe(attrName, function(value) {\n              if (isString(value)) {\n                destination[scopeName] = value;\n              }\n            });\n            attrs.$$observers[attrName].$$scope = scope;\n            if (isString(attrs[attrName])) {\n              // If the attribute has been provided then we trigger an interpolation to ensure\n              // the value is there for use in the link fn\n              destination[scopeName] = $interpolate(attrs[attrName])(scope);\n            }\n            break;\n\n          case '=':\n            if (!hasOwnProperty.call(attrs, attrName)) {\n              if (optional) break;\n              attrs[attrName] = void 0;\n            }\n            if (optional && !attrs[attrName]) break;\n\n            parentGet = $parse(attrs[attrName]);\n            if (parentGet.literal) {\n              compare = equals;\n            } else {\n              compare = function(a, b) { return a === b || (a !== a && b !== b); };\n            }\n            parentSet = parentGet.assign || function() {\n              // reset the change, or we will throw this exception on every $digest\n              lastValue = destination[scopeName] = parentGet(scope);\n              throw $compileMinErr('nonassign',\n                  \"Expression '{0}' used with directive '{1}' is non-assignable!\",\n                  attrs[attrName], directive.name);\n            };\n            lastValue = destination[scopeName] = parentGet(scope);\n            var parentValueWatch = function parentValueWatch(parentValue) {\n              if (!compare(parentValue, destination[scopeName])) {\n                // we are out of sync and need to copy\n                if (!compare(parentValue, lastValue)) {\n                  // parent changed and it has precedence\n                  destination[scopeName] = parentValue;\n                } else {\n                  // if the parent can be assigned then do so\n                  parentSet(scope, parentValue = destination[scopeName]);\n                }\n              }\n              return lastValue = parentValue;\n            };\n            parentValueWatch.$stateful = true;\n            var unwatch;\n            if (definition.collection) {\n              unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);\n            } else {\n              unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);\n            }\n            onNewScopeDestroyed = (onNewScopeDestroyed || []);\n            onNewScopeDestroyed.push(unwatch);\n            break;\n\n          case '&':\n            // Don't assign Object.prototype method to scope\n            parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;\n\n            // Don't assign noop to destination if expression is not valid\n            if (parentGet === noop && optional) break;\n\n            destination[scopeName] = function(locals) {\n              return parentGet(scope, locals);\n            };\n            break;\n        }\n      });\n      var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {\n        for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {\n          onNewScopeDestroyed[i]();\n        }\n      } : noop;\n      if (newScope && destroyBindings !== noop) {\n        newScope.$on('$destroy', destroyBindings);\n        return noop;\n      }\n      return destroyBindings;\n    }\n  }];\n}\n\nvar PREFIX_REGEXP = /^((?:x|data)[\\:\\-_])/i;\n/**\n * Converts all accepted directives format into proper directive name.\n * @param name Name to normalize\n */\nfunction directiveNormalize(name) {\n  return camelCase(name.replace(PREFIX_REGEXP, ''));\n}\n\n/**\n * @ngdoc type\n * @name $compile.directive.Attributes\n *\n * @description\n * A shared object between directive compile / linking functions which contains normalized DOM\n * element attributes. The values reflect current binding state `{{ }}`. The normalization is\n * needed since all of these are treated as equivalent in Angular:\n *\n * ```\n *    <span ng:bind=\"a\" ng-bind=\"a\" data-ng-bind=\"a\" x-ng-bind=\"a\">\n * ```\n */\n\n/**\n * @ngdoc property\n * @name $compile.directive.Attributes#$attr\n *\n * @description\n * A map of DOM element attribute names to the normalized name. This is\n * needed to do reverse lookup from normalized name back to actual name.\n */\n\n\n/**\n * @ngdoc method\n * @name $compile.directive.Attributes#$set\n * @kind function\n *\n * @description\n * Set DOM element attribute value.\n *\n *\n * @param {string} name Normalized element attribute name of the property to modify. The name is\n *          reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}\n *          property to the original name.\n * @param {string} value Value to set the attribute to. The value can be an interpolated string.\n */\n\n\n\n/**\n * Closure compiler type information\n */\n\nfunction nodesetLinkingFn(\n  /* angular.Scope */ scope,\n  /* NodeList */ nodeList,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction directiveLinkingFn(\n  /* nodesetLinkingFn */ nodesetLinkingFn,\n  /* angular.Scope */ scope,\n  /* Node */ node,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction tokenDifference(str1, str2) {\n  var values = '',\n      tokens1 = str1.split(/\\s+/),\n      tokens2 = str2.split(/\\s+/);\n\n  outer:\n  for (var i = 0; i < tokens1.length; i++) {\n    var token = tokens1[i];\n    for (var j = 0; j < tokens2.length; j++) {\n      if (token == tokens2[j]) continue outer;\n    }\n    values += (values.length > 0 ? ' ' : '') + token;\n  }\n  return values;\n}\n\nfunction removeComments(jqNodes) {\n  jqNodes = jqLite(jqNodes);\n  var i = jqNodes.length;\n\n  if (i <= 1) {\n    return jqNodes;\n  }\n\n  while (i--) {\n    var node = jqNodes[i];\n    if (node.nodeType === NODE_TYPE_COMMENT) {\n      splice.call(jqNodes, i, 1);\n    }\n  }\n  return jqNodes;\n}\n\nvar $controllerMinErr = minErr('$controller');\n\n\nvar CNTRL_REG = /^(\\S+)(\\s+as\\s+(\\w+))?$/;\nfunction identifierForController(controller, ident) {\n  if (ident && isString(ident)) return ident;\n  if (isString(controller)) {\n    var match = CNTRL_REG.exec(controller);\n    if (match) return match[3];\n  }\n}\n\n\n/**\n * @ngdoc provider\n * @name $controllerProvider\n * @description\n * The {@link ng.$controller $controller service} is used by Angular to create new\n * controllers.\n *\n * This provider allows controller registration via the\n * {@link ng.$controllerProvider#register register} method.\n */\nfunction $ControllerProvider() {\n  var controllers = {},\n      globals = false;\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#register\n   * @param {string|Object} name Controller name, or an object map of controllers where the keys are\n   *    the names and the values are the constructors.\n   * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\n   *    annotations in the array notation).\n   */\n  this.register = function(name, constructor) {\n    assertNotHasOwnProperty(name, 'controller');\n    if (isObject(name)) {\n      extend(controllers, name);\n    } else {\n      controllers[name] = constructor;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#allowGlobals\n   * @description If called, allows `$controller` to find controller constructors on `window`\n   */\n  this.allowGlobals = function() {\n    globals = true;\n  };\n\n\n  this.$get = ['$injector', '$window', function($injector, $window) {\n\n    /**\n     * @ngdoc service\n     * @name $controller\n     * @requires $injector\n     *\n     * @param {Function|string} constructor If called with a function then it's considered to be the\n     *    controller constructor function. Otherwise it's considered to be a string which is used\n     *    to retrieve the controller constructor using the following steps:\n     *\n     *    * check if a controller with given name is registered via `$controllerProvider`\n     *    * check if evaluating the string on the current scope returns a constructor\n     *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\n     *      `window` object (not recommended)\n     *\n     *    The string can use the `controller as property` syntax, where the controller instance is published\n     *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n     *    to work correctly.\n     *\n     * @param {Object} locals Injection locals for Controller.\n     * @return {Object} Instance of given controller.\n     *\n     * @description\n     * `$controller` service is responsible for instantiating controllers.\n     *\n     * It's just a simple call to {@link auto.$injector $injector}, but extracted into\n     * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).\n     */\n    return function(expression, locals, later, ident) {\n      // PRIVATE API:\n      //   param `later` --- indicates that the controller's constructor is invoked at a later time.\n      //                     If true, $controller will allocate the object with the correct\n      //                     prototype chain, but will not invoke the controller until a returned\n      //                     callback is invoked.\n      //   param `ident` --- An optional label which overrides the label parsed from the controller\n      //                     expression, if any.\n      var instance, match, constructor, identifier;\n      later = later === true;\n      if (ident && isString(ident)) {\n        identifier = ident;\n      }\n\n      if (isString(expression)) {\n        match = expression.match(CNTRL_REG);\n        if (!match) {\n          throw $controllerMinErr('ctrlfmt',\n            \"Badly formed controller string '{0}'. \" +\n            \"Must match `__name__ as __id__` or `__name__`.\", expression);\n        }\n        constructor = match[1],\n        identifier = identifier || match[3];\n        expression = controllers.hasOwnProperty(constructor)\n            ? controllers[constructor]\n            : getter(locals.$scope, constructor, true) ||\n                (globals ? getter($window, constructor, true) : undefined);\n\n        assertArgFn(expression, constructor, true);\n      }\n\n      if (later) {\n        // Instantiate controller later:\n        // This machinery is used to create an instance of the object before calling the\n        // controller's constructor itself.\n        //\n        // This allows properties to be added to the controller before the constructor is\n        // invoked. Primarily, this is used for isolate scope bindings in $compile.\n        //\n        // This feature is not intended for use by applications, and is thus not documented\n        // publicly.\n        // Object creation: http://jsperf.com/create-constructor/2\n        var controllerPrototype = (isArray(expression) ?\n          expression[expression.length - 1] : expression).prototype;\n        instance = Object.create(controllerPrototype || null);\n\n        if (identifier) {\n          addIdentifier(locals, identifier, instance, constructor || expression.name);\n        }\n\n        var instantiate;\n        return instantiate = extend(function() {\n          var result = $injector.invoke(expression, instance, locals, constructor);\n          if (result !== instance && (isObject(result) || isFunction(result))) {\n            instance = result;\n            if (identifier) {\n              // If result changed, re-assign controllerAs value to scope.\n              addIdentifier(locals, identifier, instance, constructor || expression.name);\n            }\n          }\n          return instance;\n        }, {\n          instance: instance,\n          identifier: identifier\n        });\n      }\n\n      instance = $injector.instantiate(expression, locals, constructor);\n\n      if (identifier) {\n        addIdentifier(locals, identifier, instance, constructor || expression.name);\n      }\n\n      return instance;\n    };\n\n    function addIdentifier(locals, identifier, instance, name) {\n      if (!(locals && isObject(locals.$scope))) {\n        throw minErr('$controller')('noscp',\n          \"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.\",\n          name, identifier);\n      }\n\n      locals.$scope[identifier] = instance;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $document\n * @requires $window\n *\n * @description\n * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.\n *\n * @example\n   <example module=\"documentExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <p>$document title: <b ng-bind=\"title\"></b></p>\n         <p>window.document title: <b ng-bind=\"windowTitle\"></b></p>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('documentExample', [])\n         .controller('ExampleController', ['$scope', '$document', function($scope, $document) {\n           $scope.title = $document[0].title;\n           $scope.windowTitle = angular.element(window.document)[0].title;\n         }]);\n     </file>\n   </example>\n */\nfunction $DocumentProvider() {\n  this.$get = ['$window', function(window) {\n    return jqLite(window.document);\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n * @requires ng.$log\n *\n * @description\n * Any uncaught exception in angular expressions is delegated to this service.\n * The default implementation simply delegates to `$log.error` which logs it into\n * the browser console.\n *\n * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by\n * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.\n *\n * ## Example:\n *\n * ```js\n *   angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {\n *     return function(exception, cause) {\n *       exception.message += ' (caused by \"' + cause + '\")';\n *       throw exception;\n *     };\n *   });\n * ```\n *\n * This example will override the normal action of `$exceptionHandler`, to make angular\n * exceptions fail hard when they happen, instead of just logging to the console.\n *\n * <hr />\n * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`\n * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}\n * (unless executed during a digest).\n *\n * If you wish, you can manually delegate exceptions, e.g.\n * `try { ... } catch(e) { $exceptionHandler(e); }`\n *\n * @param {Error} exception Exception associated with the error.\n * @param {string=} cause optional information about the context in which\n *       the error was thrown.\n *\n */\nfunction $ExceptionHandlerProvider() {\n  this.$get = ['$log', function($log) {\n    return function(exception, cause) {\n      $log.error.apply($log, arguments);\n    };\n  }];\n}\n\nvar $$ForceReflowProvider = function() {\n  this.$get = ['$document', function($document) {\n    return function(domNode) {\n      //the line below will force the browser to perform a repaint so\n      //that all the animated elements within the animation frame will\n      //be properly updated and drawn on screen. This is required to\n      //ensure that the preparation animation is properly flushed so that\n      //the active state picks up from there. DO NOT REMOVE THIS LINE.\n      //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH\n      //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND\n      //WILL TAKE YEARS AWAY FROM YOUR LIFE.\n      if (domNode) {\n        if (!domNode.nodeType && domNode instanceof jqLite) {\n          domNode = domNode[0];\n        }\n      } else {\n        domNode = $document[0].body;\n      }\n      return domNode.offsetWidth + 1;\n    };\n  }];\n};\n\nvar APPLICATION_JSON = 'application/json';\nvar CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};\nvar JSON_START = /^\\[|^\\{(?!\\{)/;\nvar JSON_ENDS = {\n  '[': /]$/,\n  '{': /}$/\n};\nvar JSON_PROTECTION_PREFIX = /^\\)\\]\\}',?\\n/;\nvar $httpMinErr = minErr('$http');\nvar $httpMinErrLegacyFn = function(method) {\n  return function() {\n    throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);\n  };\n};\n\nfunction serializeValue(v) {\n  if (isObject(v)) {\n    return isDate(v) ? v.toISOString() : toJson(v);\n  }\n  return v;\n}\n\n\nfunction $HttpParamSerializerProvider() {\n  /**\n   * @ngdoc service\n   * @name $httpParamSerializer\n   * @description\n   *\n   * Default {@link $http `$http`} params serializer that converts objects to strings\n   * according to the following rules:\n   *\n   * * `{'foo': 'bar'}` results in `foo=bar`\n   * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)\n   * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)\n   * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D\"` (stringified and encoded representation of an object)\n   *\n   * Note that serializer will sort the request parameters alphabetically.\n   * */\n\n  this.$get = function() {\n    return function ngParamSerializer(params) {\n      if (!params) return '';\n      var parts = [];\n      forEachSorted(params, function(value, key) {\n        if (value === null || isUndefined(value)) return;\n        if (isArray(value)) {\n          forEach(value, function(v, k) {\n            parts.push(encodeUriQuery(key)  + '=' + encodeUriQuery(serializeValue(v)));\n          });\n        } else {\n          parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));\n        }\n      });\n\n      return parts.join('&');\n    };\n  };\n}\n\nfunction $HttpParamSerializerJQLikeProvider() {\n  /**\n   * @ngdoc service\n   * @name $httpParamSerializerJQLike\n   * @description\n   *\n   * Alternative {@link $http `$http`} params serializer that follows\n   * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.\n   * The serializer will also sort the params alphabetically.\n   *\n   * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:\n   *\n   * ```js\n   * $http({\n   *   url: myUrl,\n   *   method: 'GET',\n   *   params: myParams,\n   *   paramSerializer: '$httpParamSerializerJQLike'\n   * });\n   * ```\n   *\n   * It is also possible to set it as the default `paramSerializer` in the\n   * {@link $httpProvider#defaults `$httpProvider`}.\n   *\n   * Additionally, you can inject the serializer and use it explicitly, for example to serialize\n   * form data for submission:\n   *\n   * ```js\n   * .controller(function($http, $httpParamSerializerJQLike) {\n   *   //...\n   *\n   *   $http({\n   *     url: myUrl,\n   *     method: 'POST',\n   *     data: $httpParamSerializerJQLike(myData),\n   *     headers: {\n   *       'Content-Type': 'application/x-www-form-urlencoded'\n   *     }\n   *   });\n   *\n   * });\n   * ```\n   *\n   * */\n  this.$get = function() {\n    return function jQueryLikeParamSerializer(params) {\n      if (!params) return '';\n      var parts = [];\n      serialize(params, '', true);\n      return parts.join('&');\n\n      function serialize(toSerialize, prefix, topLevel) {\n        if (toSerialize === null || isUndefined(toSerialize)) return;\n        if (isArray(toSerialize)) {\n          forEach(toSerialize, function(value, index) {\n            serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');\n          });\n        } else if (isObject(toSerialize) && !isDate(toSerialize)) {\n          forEachSorted(toSerialize, function(value, key) {\n            serialize(value, prefix +\n                (topLevel ? '' : '[') +\n                key +\n                (topLevel ? '' : ']'));\n          });\n        } else {\n          parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));\n        }\n      }\n    };\n  };\n}\n\nfunction defaultHttpResponseTransform(data, headers) {\n  if (isString(data)) {\n    // Strip json vulnerability protection prefix and trim whitespace\n    var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();\n\n    if (tempData) {\n      var contentType = headers('Content-Type');\n      if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {\n        data = fromJson(tempData);\n      }\n    }\n  }\n\n  return data;\n}\n\nfunction isJsonLike(str) {\n    var jsonStart = str.match(JSON_START);\n    return jsonStart && JSON_ENDS[jsonStart[0]].test(str);\n}\n\n/**\n * Parse headers into key value object\n *\n * @param {string} headers Raw headers as a string\n * @returns {Object} Parsed headers as key value object\n */\nfunction parseHeaders(headers) {\n  var parsed = createMap(), i;\n\n  function fillInParsed(key, val) {\n    if (key) {\n      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n    }\n  }\n\n  if (isString(headers)) {\n    forEach(headers.split('\\n'), function(line) {\n      i = line.indexOf(':');\n      fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));\n    });\n  } else if (isObject(headers)) {\n    forEach(headers, function(headerVal, headerKey) {\n      fillInParsed(lowercase(headerKey), trim(headerVal));\n    });\n  }\n\n  return parsed;\n}\n\n\n/**\n * Returns a function that provides access to parsed headers.\n *\n * Headers are lazy parsed when first requested.\n * @see parseHeaders\n *\n * @param {(string|Object)} headers Headers to provide access to.\n * @returns {function(string=)} Returns a getter function which if called with:\n *\n *   - if called with single an argument returns a single header value or null\n *   - if called with no arguments returns an object containing all headers.\n */\nfunction headersGetter(headers) {\n  var headersObj;\n\n  return function(name) {\n    if (!headersObj) headersObj =  parseHeaders(headers);\n\n    if (name) {\n      var value = headersObj[lowercase(name)];\n      if (value === void 0) {\n        value = null;\n      }\n      return value;\n    }\n\n    return headersObj;\n  };\n}\n\n\n/**\n * Chain all given functions\n *\n * This function is used for both request and response transforming\n *\n * @param {*} data Data to transform.\n * @param {function(string=)} headers HTTP headers getter fn.\n * @param {number} status HTTP status code of the response.\n * @param {(Function|Array.<Function>)} fns Function or an array of functions.\n * @returns {*} Transformed data.\n */\nfunction transformData(data, headers, status, fns) {\n  if (isFunction(fns)) {\n    return fns(data, headers, status);\n  }\n\n  forEach(fns, function(fn) {\n    data = fn(data, headers, status);\n  });\n\n  return data;\n}\n\n\nfunction isSuccess(status) {\n  return 200 <= status && status < 300;\n}\n\n\n/**\n * @ngdoc provider\n * @name $httpProvider\n * @description\n * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.\n * */\nfunction $HttpProvider() {\n  /**\n   * @ngdoc property\n   * @name $httpProvider#defaults\n   * @description\n   *\n   * Object containing default values for all {@link ng.$http $http} requests.\n   *\n   * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}\n   * that will provide the cache for all requests who set their `cache` property to `true`.\n   * If you set the `defaults.cache = false` then only requests that specify their own custom\n   * cache object will be cached. See {@link $http#caching $http Caching} for more information.\n   *\n   * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.\n   * Defaults value is `'XSRF-TOKEN'`.\n   *\n   * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the\n   * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.\n   *\n   * - **`defaults.headers`** - {Object} - Default headers for all $http requests.\n   * Refer to {@link ng.$http#setting-http-headers $http} for documentation on\n   * setting default headers.\n   *     - **`defaults.headers.common`**\n   *     - **`defaults.headers.post`**\n   *     - **`defaults.headers.put`**\n   *     - **`defaults.headers.patch`**\n   *\n   *\n   * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function\n   *  used to the prepare string representation of request parameters (specified as an object).\n   *  If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.\n   *  Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.\n   *\n   **/\n  var defaults = this.defaults = {\n    // transform incoming response data\n    transformResponse: [defaultHttpResponseTransform],\n\n    // transform outgoing request data\n    transformRequest: [function(d) {\n      return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;\n    }],\n\n    // default headers\n    headers: {\n      common: {\n        'Accept': 'application/json, text/plain, */*'\n      },\n      post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)\n    },\n\n    xsrfCookieName: 'XSRF-TOKEN',\n    xsrfHeaderName: 'X-XSRF-TOKEN',\n\n    paramSerializer: '$httpParamSerializer'\n  };\n\n  var useApplyAsync = false;\n  /**\n   * @ngdoc method\n   * @name $httpProvider#useApplyAsync\n   * @description\n   *\n   * Configure $http service to combine processing of multiple http responses received at around\n   * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in\n   * significant performance improvement for bigger applications that make many HTTP requests\n   * concurrently (common during application bootstrap).\n   *\n   * Defaults to false. If no value is specified, returns the current configured value.\n   *\n   * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred\n   *    \"apply\" on the next tick, giving time for subsequent requests in a roughly ~10ms window\n   *    to load and share the same digest cycle.\n   *\n   * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n   *    otherwise, returns the current configured value.\n   **/\n  this.useApplyAsync = function(value) {\n    if (isDefined(value)) {\n      useApplyAsync = !!value;\n      return this;\n    }\n    return useApplyAsync;\n  };\n\n  var useLegacyPromise = true;\n  /**\n   * @ngdoc method\n   * @name $httpProvider#useLegacyPromiseExtensions\n   * @description\n   *\n   * Configure `$http` service to return promises without the shorthand methods `success` and `error`.\n   * This should be used to make sure that applications work without these methods.\n   *\n   * Defaults to false. If no value is specified, returns the current configured value.\n   *\n   * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.\n   *\n   * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n   *    otherwise, returns the current configured value.\n   **/\n  this.useLegacyPromiseExtensions = function(value) {\n    if (isDefined(value)) {\n      useLegacyPromise = !!value;\n      return this;\n    }\n    return useLegacyPromise;\n  };\n\n  /**\n   * @ngdoc property\n   * @name $httpProvider#interceptors\n   * @description\n   *\n   * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}\n   * pre-processing of request or postprocessing of responses.\n   *\n   * These service factories are ordered by request, i.e. they are applied in the same order as the\n   * array, on request, but reverse order, on response.\n   *\n   * {@link ng.$http#interceptors Interceptors detailed info}\n   **/\n  var interceptorFactories = this.interceptors = [];\n\n  this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',\n      function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {\n\n    var defaultCache = $cacheFactory('$http');\n\n    /**\n     * Make sure that default param serializer is exposed as a function\n     */\n    defaults.paramSerializer = isString(defaults.paramSerializer) ?\n      $injector.get(defaults.paramSerializer) : defaults.paramSerializer;\n\n    /**\n     * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\n     * The reversal is needed so that we can build up the interception chain around the\n     * server request.\n     */\n    var reversedInterceptors = [];\n\n    forEach(interceptorFactories, function(interceptorFactory) {\n      reversedInterceptors.unshift(isString(interceptorFactory)\n          ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\n    });\n\n    /**\n     * @ngdoc service\n     * @kind function\n     * @name $http\n     * @requires ng.$httpBackend\n     * @requires $cacheFactory\n     * @requires $rootScope\n     * @requires $q\n     * @requires $injector\n     *\n     * @description\n     * The `$http` service is a core Angular service that facilitates communication with the remote\n     * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)\n     * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).\n     *\n     * For unit testing applications that use `$http` service, see\n     * {@link ngMock.$httpBackend $httpBackend mock}.\n     *\n     * For a higher level of abstraction, please check out the {@link ngResource.$resource\n     * $resource} service.\n     *\n     * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by\n     * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage\n     * it is important to familiarize yourself with these APIs and the guarantees they provide.\n     *\n     *\n     * ## General usage\n     * The `$http` service is a function which takes a single argument — a configuration object —\n     * that is used to generate an HTTP request and returns  a {@link ng.$q promise}.\n     *\n     * ```js\n     *   // Simple GET request example :\n     *   $http.get('/someUrl').\n     *     then(function(response) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }, function(response) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     * ```js\n     *   // Simple POST request example (passing data) :\n     *   $http.post('/someUrl', {msg:'hello word!'}).\n     *     then(function(response) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }, function(response) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     * The response object has these properties:\n     *\n     *   - **data** – `{string|Object}` – The response body transformed with the transform\n     *     functions.\n     *   - **status** – `{number}` – HTTP status code of the response.\n     *   - **headers** – `{function([headerName])}` – Header getter function.\n     *   - **config** – `{Object}` – The configuration object that was used to generate the request.\n     *   - **statusText** – `{string}` – HTTP status text of the response.\n     *\n     * A response status code between 200 and 299 is considered a success status and\n     * will result in the success callback being called. Note that if the response is a redirect,\n     * XMLHttpRequest will transparently follow it, meaning that the error callback will not be\n     * called for such responses.\n     *\n     * ## Writing Unit Tests that use $http\n     * When unit testing (using {@link ngMock ngMock}), it is necessary to call\n     * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending\n     * request using trained responses.\n     *\n     * ```\n     * $httpBackend.expectGET(...);\n     * $http.get(...);\n     * $httpBackend.flush();\n     * ```\n     *\n     * ## Shortcut methods\n     *\n     * Shortcut methods are also available. All shortcut methods require passing in the URL, and\n     * request data must be passed in for POST/PUT requests.\n     *\n     * ```js\n     *   $http.get('/someUrl').then(successCallback);\n     *   $http.post('/someUrl', data).then(successCallback);\n     * ```\n     *\n     * Complete list of shortcut methods:\n     *\n     * - {@link ng.$http#get $http.get}\n     * - {@link ng.$http#head $http.head}\n     * - {@link ng.$http#post $http.post}\n     * - {@link ng.$http#put $http.put}\n     * - {@link ng.$http#delete $http.delete}\n     * - {@link ng.$http#jsonp $http.jsonp}\n     * - {@link ng.$http#patch $http.patch}\n     *\n     *\n     * ## Deprecation Notice\n     * <div class=\"alert alert-danger\">\n     *   The `$http` legacy promise methods `success` and `error` have been deprecated.\n     *   Use the standard `then` method instead.\n     *   If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to\n     *   `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.\n     * </div>\n     *\n     * ## Setting HTTP Headers\n     *\n     * The $http service will automatically add certain HTTP headers to all requests. These defaults\n     * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration\n     * object, which currently contains this default configuration:\n     *\n     * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):\n     *   - `Accept: application/json, text/plain, * / *`\n     * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)\n     *   - `Content-Type: application/json`\n     * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)\n     *   - `Content-Type: application/json`\n     *\n     * To add or overwrite these defaults, simply add or remove a property from these configuration\n     * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object\n     * with the lowercased HTTP method name as the key, e.g.\n     * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.\n     *\n     * The defaults can also be set at runtime via the `$http.defaults` object in the same\n     * fashion. For example:\n     *\n     * ```\n     * module.run(function($http) {\n     *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'\n     * });\n     * ```\n     *\n     * In addition, you can supply a `headers` property in the config object passed when\n     * calling `$http(config)`, which overrides the defaults without changing them globally.\n     *\n     * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,\n     * Use the `headers` property, setting the desired header to `undefined`. For example:\n     *\n     * ```js\n     * var req = {\n     *  method: 'POST',\n     *  url: 'http://example.com',\n     *  headers: {\n     *    'Content-Type': undefined\n     *  },\n     *  data: { test: 'test' }\n     * }\n     *\n     * $http(req).then(function(){...}, function(){...});\n     * ```\n     *\n     * ## Transforming Requests and Responses\n     *\n     * Both requests and responses can be transformed using transformation functions: `transformRequest`\n     * and `transformResponse`. These properties can be a single function that returns\n     * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,\n     * which allows you to `push` or `unshift` a new transformation function into the transformation chain.\n     *\n     * ### Default Transformations\n     *\n     * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and\n     * `defaults.transformResponse` properties. If a request does not provide its own transformations\n     * then these will be applied.\n     *\n     * You can augment or replace the default transformations by modifying these properties by adding to or\n     * replacing the array.\n     *\n     * Angular provides the following default transformations:\n     *\n     * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):\n     *\n     * - If the `data` property of the request configuration object contains an object, serialize it\n     *   into JSON format.\n     *\n     * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):\n     *\n     *  - If XSRF prefix is detected, strip it (see Security Considerations section below).\n     *  - If JSON response is detected, deserialize it using a JSON parser.\n     *\n     *\n     * ### Overriding the Default Transformations Per Request\n     *\n     * If you wish override the request/response transformations only for a single request then provide\n     * `transformRequest` and/or `transformResponse` properties on the configuration object passed\n     * into `$http`.\n     *\n     * Note that if you provide these properties on the config object the default transformations will be\n     * overwritten. If you wish to augment the default transformations then you must include them in your\n     * local transformation array.\n     *\n     * The following code demonstrates adding a new response transformation to be run after the default response\n     * transformations have been run.\n     *\n     * ```js\n     * function appendTransform(defaults, transform) {\n     *\n     *   // We can't guarantee that the default transformation is an array\n     *   defaults = angular.isArray(defaults) ? defaults : [defaults];\n     *\n     *   // Append the new transformation to the defaults\n     *   return defaults.concat(transform);\n     * }\n     *\n     * $http({\n     *   url: '...',\n     *   method: 'GET',\n     *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {\n     *     return doTransform(value);\n     *   })\n     * });\n     * ```\n     *\n     *\n     * ## Caching\n     *\n     * To enable caching, set the request configuration `cache` property to `true` (to use default\n     * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).\n     * When the cache is enabled, `$http` stores the response from the server in the specified\n     * cache. The next time the same request is made, the response is served from the cache without\n     * sending a request to the server.\n     *\n     * Note that even if the response is served from cache, delivery of the data is asynchronous in\n     * the same way that real requests are.\n     *\n     * If there are multiple GET requests for the same URL that should be cached using the same\n     * cache, but the cache is not populated yet, only one request to the server will be made and\n     * the remaining requests will be fulfilled using the response from the first request.\n     *\n     * You can change the default cache to a new object (built with\n     * {@link ng.$cacheFactory `$cacheFactory`}) by updating the\n     * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set\n     * their `cache` property to `true` will now use this cache object.\n     *\n     * If you set the default cache to `false` then only requests that specify their own custom\n     * cache object will be cached.\n     *\n     * ## Interceptors\n     *\n     * Before you start creating interceptors, be sure to understand the\n     * {@link ng.$q $q and deferred/promise APIs}.\n     *\n     * For purposes of global error handling, authentication, or any kind of synchronous or\n     * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be\n     * able to intercept requests before they are handed to the server and\n     * responses before they are handed over to the application code that\n     * initiated these requests. The interceptors leverage the {@link ng.$q\n     * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.\n     *\n     * The interceptors are service factories that are registered with the `$httpProvider` by\n     * adding them to the `$httpProvider.interceptors` array. The factory is called and\n     * injected with dependencies (if specified) and returns the interceptor.\n     *\n     * There are two kinds of interceptors (and two kinds of rejection interceptors):\n     *\n     *   * `request`: interceptors get called with a http `config` object. The function is free to\n     *     modify the `config` object or create a new one. The function needs to return the `config`\n     *     object directly, or a promise containing the `config` or a new `config` object.\n     *   * `requestError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *   * `response`: interceptors get called with http `response` object. The function is free to\n     *     modify the `response` object or create a new one. The function needs to return the `response`\n     *     object directly, or as a promise containing the `response` or a new `response` object.\n     *   * `responseError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *\n     *\n     * ```js\n     *   // register the interceptor as a service\n     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {\n     *     return {\n     *       // optional method\n     *       'request': function(config) {\n     *         // do something on success\n     *         return config;\n     *       },\n     *\n     *       // optional method\n     *      'requestError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       },\n     *\n     *\n     *\n     *       // optional method\n     *       'response': function(response) {\n     *         // do something on success\n     *         return response;\n     *       },\n     *\n     *       // optional method\n     *      'responseError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       }\n     *     };\n     *   });\n     *\n     *   $httpProvider.interceptors.push('myHttpInterceptor');\n     *\n     *\n     *   // alternatively, register the interceptor via an anonymous factory\n     *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {\n     *     return {\n     *      'request': function(config) {\n     *          // same as above\n     *       },\n     *\n     *       'response': function(response) {\n     *          // same as above\n     *       }\n     *     };\n     *   });\n     * ```\n     *\n     * ## Security Considerations\n     *\n     * When designing web applications, consider security threats from:\n     *\n     * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\n     *\n     * Both server and the client must cooperate in order to eliminate these threats. Angular comes\n     * pre-configured with strategies that address these issues, but for this to work backend server\n     * cooperation is required.\n     *\n     * ### JSON Vulnerability Protection\n     *\n     * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * allows third party website to turn your JSON resource URL into\n     * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To\n     * counter this your server can prefix all JSON requests with following string `\")]}',\\n\"`.\n     * Angular will automatically strip the prefix before processing it as JSON.\n     *\n     * For example if your server needs to return:\n     * ```js\n     * ['one','two']\n     * ```\n     *\n     * which is vulnerable to attack, your server can return:\n     * ```js\n     * )]}',\n     * ['one','two']\n     * ```\n     *\n     * Angular will strip the prefix, before processing the JSON.\n     *\n     *\n     * ### Cross Site Request Forgery (XSRF) Protection\n     *\n     * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which\n     * an unauthorized site can gain your user's private data. Angular provides a mechanism\n     * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie\n     * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only\n     * JavaScript that runs on your domain could read the cookie, your server can be assured that\n     * the XHR came from JavaScript running on your domain. The header will not be set for\n     * cross-domain requests.\n     *\n     * To take advantage of this, your server needs to set a token in a JavaScript readable session\n     * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the\n     * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure\n     * that only JavaScript running on your domain could have sent the request. The token must be\n     * unique for each user and must be verifiable by the server (to prevent the JavaScript from\n     * making up its own tokens). We recommend that the token is a digest of your site's\n     * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)\n     * for added security.\n     *\n     * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName\n     * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,\n     * or the per-request config object.\n     *\n     * In order to prevent collisions in environments where multiple Angular apps share the\n     * same domain or subdomain, we recommend that each application uses unique cookie name.\n     *\n     * @param {object} config Object describing the request to be made and how it should be\n     *    processed. The object has following properties:\n     *\n     *    - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)\n     *    - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.\n     *    - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized\n     *      with the `paramSerializer` and appended as GET parameters.\n     *    - **data** – `{string|Object}` – Data to be sent as the request message data.\n     *    - **headers** – `{Object}` – Map of strings or functions which return strings representing\n     *      HTTP headers to send to the server. If the return value of a function is null, the\n     *      header will not be sent. Functions accept a config object as an argument.\n     *    - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.\n     *    - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.\n     *    - **transformRequest** –\n     *      `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      request body and headers and returns its transformed (typically serialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default Transformations}\n     *    - **transformResponse** –\n     *      `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      response body, headers and status and returns its transformed (typically deserialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default TransformationjqLiks}\n     *    - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to\n     *      prepare the string representation of request parameters (specified as an object).\n     *      If specified as string, it is interpreted as function registered with the\n     *      {@link $injector $injector}, which means you can create your own serializer\n     *      by registering it as a {@link auto.$provide#service service}.\n     *      The default serializer is the {@link $httpParamSerializer $httpParamSerializer};\n     *      alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}\n     *    - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\n     *      GET request, otherwise if a cache instance built with\n     *      {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\n     *      caching.\n     *    - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}\n     *      that should abort the request when resolved.\n     *    - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the\n     *      XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)\n     *      for more information.\n     *    - **responseType** - `{string}` - see\n     *      [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).\n     *\n     * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object\n     *                        when the request succeeds or fails.\n     *\n     *\n     * @property {Array.<Object>} pendingRequests Array of config objects for currently pending\n     *   requests. This is primarily meant to be used for debugging purposes.\n     *\n     *\n     * @example\n<example module=\"httpExample\">\n<file name=\"index.html\">\n  <div ng-controller=\"FetchController\">\n    <select ng-model=\"method\" aria-label=\"Request method\">\n      <option>GET</option>\n      <option>JSONP</option>\n    </select>\n    <input type=\"text\" ng-model=\"url\" size=\"80\" aria-label=\"URL\" />\n    <button id=\"fetchbtn\" ng-click=\"fetch()\">fetch</button><br>\n    <button id=\"samplegetbtn\" ng-click=\"updateModel('GET', 'http-hello.html')\">Sample GET</button>\n    <button id=\"samplejsonpbtn\"\n      ng-click=\"updateModel('JSONP',\n                    'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')\">\n      Sample JSONP\n    </button>\n    <button id=\"invalidjsonpbtn\"\n      ng-click=\"updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')\">\n        Invalid JSONP\n      </button>\n    <pre>http status code: {{status}}</pre>\n    <pre>http response data: {{data}}</pre>\n  </div>\n</file>\n<file name=\"script.js\">\n  angular.module('httpExample', [])\n    .controller('FetchController', ['$scope', '$http', '$templateCache',\n      function($scope, $http, $templateCache) {\n        $scope.method = 'GET';\n        $scope.url = 'http-hello.html';\n\n        $scope.fetch = function() {\n          $scope.code = null;\n          $scope.response = null;\n\n          $http({method: $scope.method, url: $scope.url, cache: $templateCache}).\n            then(function(response) {\n              $scope.status = response.status;\n              $scope.data = response.data;\n            }, function(response) {\n              $scope.data = response.data || \"Request failed\";\n              $scope.status = response.status;\n          });\n        };\n\n        $scope.updateModel = function(method, url) {\n          $scope.method = method;\n          $scope.url = url;\n        };\n      }]);\n</file>\n<file name=\"http-hello.html\">\n  Hello, $http!\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  var status = element(by.binding('status'));\n  var data = element(by.binding('data'));\n  var fetchBtn = element(by.id('fetchbtn'));\n  var sampleGetBtn = element(by.id('samplegetbtn'));\n  var sampleJsonpBtn = element(by.id('samplejsonpbtn'));\n  var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));\n\n  it('should make an xhr GET request', function() {\n    sampleGetBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('200');\n    expect(data.getText()).toMatch(/Hello, \\$http!/);\n  });\n\n// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185\n// it('should make a JSONP request to angularjs.org', function() {\n//   sampleJsonpBtn.click();\n//   fetchBtn.click();\n//   expect(status.getText()).toMatch('200');\n//   expect(data.getText()).toMatch(/Super Hero!/);\n// });\n\n  it('should make JSONP request to invalid URL and invoke the error handler',\n      function() {\n    invalidJsonpBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('0');\n    expect(data.getText()).toMatch('Request failed');\n  });\n</file>\n</example>\n     */\n    function $http(requestConfig) {\n\n      if (!angular.isObject(requestConfig)) {\n        throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);\n      }\n\n      var config = extend({\n        method: 'get',\n        transformRequest: defaults.transformRequest,\n        transformResponse: defaults.transformResponse,\n        paramSerializer: defaults.paramSerializer\n      }, requestConfig);\n\n      config.headers = mergeHeaders(requestConfig);\n      config.method = uppercase(config.method);\n      config.paramSerializer = isString(config.paramSerializer) ?\n        $injector.get(config.paramSerializer) : config.paramSerializer;\n\n      var serverRequest = function(config) {\n        var headers = config.headers;\n        var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);\n\n        // strip content-type if data is undefined\n        if (isUndefined(reqData)) {\n          forEach(headers, function(value, header) {\n            if (lowercase(header) === 'content-type') {\n                delete headers[header];\n            }\n          });\n        }\n\n        if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {\n          config.withCredentials = defaults.withCredentials;\n        }\n\n        // send request\n        return sendReq(config, reqData).then(transformResponse, transformResponse);\n      };\n\n      var chain = [serverRequest, undefined];\n      var promise = $q.when(config);\n\n      // apply interceptors\n      forEach(reversedInterceptors, function(interceptor) {\n        if (interceptor.request || interceptor.requestError) {\n          chain.unshift(interceptor.request, interceptor.requestError);\n        }\n        if (interceptor.response || interceptor.responseError) {\n          chain.push(interceptor.response, interceptor.responseError);\n        }\n      });\n\n      while (chain.length) {\n        var thenFn = chain.shift();\n        var rejectFn = chain.shift();\n\n        promise = promise.then(thenFn, rejectFn);\n      }\n\n      if (useLegacyPromise) {\n        promise.success = function(fn) {\n          assertArgFn(fn, 'fn');\n\n          promise.then(function(response) {\n            fn(response.data, response.status, response.headers, config);\n          });\n          return promise;\n        };\n\n        promise.error = function(fn) {\n          assertArgFn(fn, 'fn');\n\n          promise.then(null, function(response) {\n            fn(response.data, response.status, response.headers, config);\n          });\n          return promise;\n        };\n      } else {\n        promise.success = $httpMinErrLegacyFn('success');\n        promise.error = $httpMinErrLegacyFn('error');\n      }\n\n      return promise;\n\n      function transformResponse(response) {\n        // make a copy since the response must be cacheable\n        var resp = extend({}, response);\n        if (!response.data) {\n          resp.data = response.data;\n        } else {\n          resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);\n        }\n        return (isSuccess(response.status))\n          ? resp\n          : $q.reject(resp);\n      }\n\n      function executeHeaderFns(headers, config) {\n        var headerContent, processedHeaders = {};\n\n        forEach(headers, function(headerFn, header) {\n          if (isFunction(headerFn)) {\n            headerContent = headerFn(config);\n            if (headerContent != null) {\n              processedHeaders[header] = headerContent;\n            }\n          } else {\n            processedHeaders[header] = headerFn;\n          }\n        });\n\n        return processedHeaders;\n      }\n\n      function mergeHeaders(config) {\n        var defHeaders = defaults.headers,\n            reqHeaders = extend({}, config.headers),\n            defHeaderName, lowercaseDefHeaderName, reqHeaderName;\n\n        defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);\n\n        // using for-in instead of forEach to avoid unecessary iteration after header has been found\n        defaultHeadersIteration:\n        for (defHeaderName in defHeaders) {\n          lowercaseDefHeaderName = lowercase(defHeaderName);\n\n          for (reqHeaderName in reqHeaders) {\n            if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {\n              continue defaultHeadersIteration;\n            }\n          }\n\n          reqHeaders[defHeaderName] = defHeaders[defHeaderName];\n        }\n\n        // execute if header value is a function for merged headers\n        return executeHeaderFns(reqHeaders, shallowCopy(config));\n      }\n    }\n\n    $http.pendingRequests = [];\n\n    /**\n     * @ngdoc method\n     * @name $http#get\n     *\n     * @description\n     * Shortcut method to perform `GET` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#delete\n     *\n     * @description\n     * Shortcut method to perform `DELETE` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#head\n     *\n     * @description\n     * Shortcut method to perform `HEAD` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#jsonp\n     *\n     * @description\n     * Shortcut method to perform `JSONP` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request.\n     *                     The name of the callback should be the string `JSON_CALLBACK`.\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n    createShortMethods('get', 'delete', 'head', 'jsonp');\n\n    /**\n     * @ngdoc method\n     * @name $http#post\n     *\n     * @description\n     * Shortcut method to perform `POST` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#put\n     *\n     * @description\n     * Shortcut method to perform `PUT` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n     /**\n      * @ngdoc method\n      * @name $http#patch\n      *\n      * @description\n      * Shortcut method to perform `PATCH` request.\n      *\n      * @param {string} url Relative or absolute URL specifying the destination of the request\n      * @param {*} data Request content\n      * @param {Object=} config Optional configuration object\n      * @returns {HttpPromise} Future object\n      */\n    createShortMethodsWithData('post', 'put', 'patch');\n\n        /**\n         * @ngdoc property\n         * @name $http#defaults\n         *\n         * @description\n         * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of\n         * default headers, withCredentials as well as request and response transformations.\n         *\n         * See \"Setting HTTP Headers\" and \"Transforming Requests and Responses\" sections above.\n         */\n    $http.defaults = defaults;\n\n\n    return $http;\n\n\n    function createShortMethods(names) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, config) {\n          return $http(extend({}, config || {}, {\n            method: name,\n            url: url\n          }));\n        };\n      });\n    }\n\n\n    function createShortMethodsWithData(name) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, data, config) {\n          return $http(extend({}, config || {}, {\n            method: name,\n            url: url,\n            data: data\n          }));\n        };\n      });\n    }\n\n\n    /**\n     * Makes the request.\n     *\n     * !!! ACCESSES CLOSURE VARS:\n     * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests\n     */\n    function sendReq(config, reqData) {\n      var deferred = $q.defer(),\n          promise = deferred.promise,\n          cache,\n          cachedResp,\n          reqHeaders = config.headers,\n          url = buildUrl(config.url, config.paramSerializer(config.params));\n\n      $http.pendingRequests.push(config);\n      promise.then(removePendingReq, removePendingReq);\n\n\n      if ((config.cache || defaults.cache) && config.cache !== false &&\n          (config.method === 'GET' || config.method === 'JSONP')) {\n        cache = isObject(config.cache) ? config.cache\n              : isObject(defaults.cache) ? defaults.cache\n              : defaultCache;\n      }\n\n      if (cache) {\n        cachedResp = cache.get(url);\n        if (isDefined(cachedResp)) {\n          if (isPromiseLike(cachedResp)) {\n            // cached request has already been sent, but there is no response yet\n            cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);\n          } else {\n            // serving from cache\n            if (isArray(cachedResp)) {\n              resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);\n            } else {\n              resolvePromise(cachedResp, 200, {}, 'OK');\n            }\n          }\n        } else {\n          // put the promise for the non-transformed response into cache as a placeholder\n          cache.put(url, promise);\n        }\n      }\n\n\n      // if we won't have the response in cache, set the xsrf headers and\n      // send the request to the backend\n      if (isUndefined(cachedResp)) {\n        var xsrfValue = urlIsSameOrigin(config.url)\n            ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]\n            : undefined;\n        if (xsrfValue) {\n          reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;\n        }\n\n        $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,\n            config.withCredentials, config.responseType);\n      }\n\n      return promise;\n\n\n      /**\n       * Callback registered to $httpBackend():\n       *  - caches the response if desired\n       *  - resolves the raw $http promise\n       *  - calls $apply\n       */\n      function done(status, response, headersString, statusText) {\n        if (cache) {\n          if (isSuccess(status)) {\n            cache.put(url, [status, response, parseHeaders(headersString), statusText]);\n          } else {\n            // remove promise from the cache\n            cache.remove(url);\n          }\n        }\n\n        function resolveHttpPromise() {\n          resolvePromise(response, status, headersString, statusText);\n        }\n\n        if (useApplyAsync) {\n          $rootScope.$applyAsync(resolveHttpPromise);\n        } else {\n          resolveHttpPromise();\n          if (!$rootScope.$$phase) $rootScope.$apply();\n        }\n      }\n\n\n      /**\n       * Resolves the raw $http promise.\n       */\n      function resolvePromise(response, status, headers, statusText) {\n        // normalize internal statuses to 0\n        status = Math.max(status, 0);\n\n        (isSuccess(status) ? deferred.resolve : deferred.reject)({\n          data: response,\n          status: status,\n          headers: headersGetter(headers),\n          config: config,\n          statusText: statusText\n        });\n      }\n\n      function resolvePromiseWithResult(result) {\n        resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);\n      }\n\n      function removePendingReq() {\n        var idx = $http.pendingRequests.indexOf(config);\n        if (idx !== -1) $http.pendingRequests.splice(idx, 1);\n      }\n    }\n\n\n    function buildUrl(url, serializedParams) {\n      if (serializedParams.length > 0) {\n        url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;\n      }\n      return url;\n    }\n  }];\n}\n\nfunction createXhr() {\n    return new window.XMLHttpRequest();\n}\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @requires $window\n * @requires $document\n *\n * @description\n * HTTP backend used by the {@link ng.$http service} that delegates to\n * XMLHttpRequest object or JSONP and deals with browser incompatibilities.\n *\n * You should never need to use this service directly, instead use the higher-level abstractions:\n * {@link ng.$http $http} or {@link ngResource.$resource $resource}.\n *\n * During testing this implementation is swapped with {@link ngMock.$httpBackend mock\n * $httpBackend} which can be trained with responses.\n */\nfunction $HttpBackendProvider() {\n  this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {\n    return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);\n  }];\n}\n\nfunction createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {\n  // TODO(vojta): fix the signature\n  return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {\n    $browser.$$incOutstandingRequestCount();\n    url = url || $browser.url();\n\n    if (lowercase(method) == 'jsonp') {\n      var callbackId = '_' + (callbacks.counter++).toString(36);\n      callbacks[callbackId] = function(data) {\n        callbacks[callbackId].data = data;\n        callbacks[callbackId].called = true;\n      };\n\n      var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),\n          callbackId, function(status, text) {\n        completeRequest(callback, status, callbacks[callbackId].data, \"\", text);\n        callbacks[callbackId] = noop;\n      });\n    } else {\n\n      var xhr = createXhr();\n\n      xhr.open(method, url, true);\n      forEach(headers, function(value, key) {\n        if (isDefined(value)) {\n            xhr.setRequestHeader(key, value);\n        }\n      });\n\n      xhr.onload = function requestLoaded() {\n        var statusText = xhr.statusText || '';\n\n        // responseText is the old-school way of retrieving response (supported by IE9)\n        // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)\n        var response = ('response' in xhr) ? xhr.response : xhr.responseText;\n\n        // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)\n        var status = xhr.status === 1223 ? 204 : xhr.status;\n\n        // fix status code when it is 0 (0 status is undocumented).\n        // Occurs when accessing file resources or on Android 4.1 stock browser\n        // while retrieving files from application cache.\n        if (status === 0) {\n          status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;\n        }\n\n        completeRequest(callback,\n            status,\n            response,\n            xhr.getAllResponseHeaders(),\n            statusText);\n      };\n\n      var requestError = function() {\n        // The response is always empty\n        // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\n        completeRequest(callback, -1, null, null, '');\n      };\n\n      xhr.onerror = requestError;\n      xhr.onabort = requestError;\n\n      if (withCredentials) {\n        xhr.withCredentials = true;\n      }\n\n      if (responseType) {\n        try {\n          xhr.responseType = responseType;\n        } catch (e) {\n          // WebKit added support for the json responseType value on 09/03/2013\n          // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are\n          // known to throw when setting the value \"json\" as the response type. Other older\n          // browsers implementing the responseType\n          //\n          // The json response type can be ignored if not supported, because JSON payloads are\n          // parsed on the client-side regardless.\n          if (responseType !== 'json') {\n            throw e;\n          }\n        }\n      }\n\n      xhr.send(post);\n    }\n\n    if (timeout > 0) {\n      var timeoutId = $browserDefer(timeoutRequest, timeout);\n    } else if (isPromiseLike(timeout)) {\n      timeout.then(timeoutRequest);\n    }\n\n\n    function timeoutRequest() {\n      jsonpDone && jsonpDone();\n      xhr && xhr.abort();\n    }\n\n    function completeRequest(callback, status, response, headersString, statusText) {\n      // cancel timeout and subsequent timeout promise resolution\n      if (timeoutId !== undefined) {\n        $browserDefer.cancel(timeoutId);\n      }\n      jsonpDone = xhr = null;\n\n      callback(status, response, headersString, statusText);\n      $browser.$$completeOutstandingRequest(noop);\n    }\n  };\n\n  function jsonpReq(url, callbackId, done) {\n    // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:\n    // - fetches local scripts via XHR and evals them\n    // - adds and immediately removes script elements from the document\n    var script = rawDocument.createElement('script'), callback = null;\n    script.type = \"text/javascript\";\n    script.src = url;\n    script.async = true;\n\n    callback = function(event) {\n      removeEventListenerFn(script, \"load\", callback);\n      removeEventListenerFn(script, \"error\", callback);\n      rawDocument.body.removeChild(script);\n      script = null;\n      var status = -1;\n      var text = \"unknown\";\n\n      if (event) {\n        if (event.type === \"load\" && !callbacks[callbackId].called) {\n          event = { type: \"error\" };\n        }\n        text = event.type;\n        status = event.type === \"error\" ? 404 : 200;\n      }\n\n      if (done) {\n        done(status, text);\n      }\n    };\n\n    addEventListenerFn(script, \"load\", callback);\n    addEventListenerFn(script, \"error\", callback);\n    rawDocument.body.appendChild(script);\n    return callback;\n  }\n}\n\nvar $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');\n$interpolateMinErr.throwNoconcat = function(text) {\n  throw $interpolateMinErr('noconcat',\n      \"Error while interpolating: {0}\\nStrict Contextual Escaping disallows \" +\n      \"interpolations that concatenate multiple expressions when a trusted value is \" +\n      \"required.  See http://docs.angularjs.org/api/ng.$sce\", text);\n};\n\n$interpolateMinErr.interr = function(text, err) {\n  return $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text, err.toString());\n};\n\n/**\n * @ngdoc provider\n * @name $interpolateProvider\n *\n * @description\n *\n * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.\n *\n * @example\n<example module=\"customInterpolationApp\">\n<file name=\"index.html\">\n<script>\n  var customInterpolationApp = angular.module('customInterpolationApp', []);\n\n  customInterpolationApp.config(function($interpolateProvider) {\n    $interpolateProvider.startSymbol('//');\n    $interpolateProvider.endSymbol('//');\n  });\n\n\n  customInterpolationApp.controller('DemoController', function() {\n      this.label = \"This binding is brought you by // interpolation symbols.\";\n  });\n</script>\n<div ng-app=\"App\" ng-controller=\"DemoController as demo\">\n    //demo.label//\n</div>\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  it('should interpolate binding with custom symbols', function() {\n    expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');\n  });\n</file>\n</example>\n */\nfunction $InterpolateProvider() {\n  var startSymbol = '{{';\n  var endSymbol = '}}';\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#startSymbol\n   * @description\n   * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.\n   *\n   * @param {string=} value new value to set the starting symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.startSymbol = function(value) {\n    if (value) {\n      startSymbol = value;\n      return this;\n    } else {\n      return startSymbol;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#endSymbol\n   * @description\n   * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n   *\n   * @param {string=} value new value to set the ending symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.endSymbol = function(value) {\n    if (value) {\n      endSymbol = value;\n      return this;\n    } else {\n      return endSymbol;\n    }\n  };\n\n\n  this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {\n    var startSymbolLength = startSymbol.length,\n        endSymbolLength = endSymbol.length,\n        escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),\n        escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');\n\n    function escape(ch) {\n      return '\\\\\\\\\\\\' + ch;\n    }\n\n    function unescapeText(text) {\n      return text.replace(escapedStartRegexp, startSymbol).\n        replace(escapedEndRegexp, endSymbol);\n    }\n\n    function stringify(value) {\n      if (value == null) { // null || undefined\n        return '';\n      }\n      switch (typeof value) {\n        case 'string':\n          break;\n        case 'number':\n          value = '' + value;\n          break;\n        default:\n          value = toJson(value);\n      }\n\n      return value;\n    }\n\n    /**\n     * @ngdoc service\n     * @name $interpolate\n     * @kind function\n     *\n     * @requires $parse\n     * @requires $sce\n     *\n     * @description\n     *\n     * Compiles a string with markup into an interpolation function. This service is used by the\n     * HTML {@link ng.$compile $compile} service for data binding. See\n     * {@link ng.$interpolateProvider $interpolateProvider} for configuring the\n     * interpolation markup.\n     *\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var exp = $interpolate('Hello {{name | uppercase}}!');\n     *   expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');\n     * ```\n     *\n     * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is\n     * `true`, the interpolation function will return `undefined` unless all embedded expressions\n     * evaluate to a value other than `undefined`.\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var context = {greeting: 'Hello', name: undefined };\n     *\n     *   // default \"forgiving\" mode\n     *   var exp = $interpolate('{{greeting}} {{name}}!');\n     *   expect(exp(context)).toEqual('Hello !');\n     *\n     *   // \"allOrNothing\" mode\n     *   exp = $interpolate('{{greeting}} {{name}}!', false, null, true);\n     *   expect(exp(context)).toBeUndefined();\n     *   context.name = 'Angular';\n     *   expect(exp(context)).toEqual('Hello Angular!');\n     * ```\n     *\n     * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.\n     *\n     * ####Escaped Interpolation\n     * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers\n     * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).\n     * It will be rendered as a regular start/end marker, and will not be interpreted as an expression\n     * or binding.\n     *\n     * This enables web-servers to prevent script injection attacks and defacing attacks, to some\n     * degree, while also enabling code examples to work without relying on the\n     * {@link ng.directive:ngNonBindable ngNonBindable} directive.\n     *\n     * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,\n     * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all\n     * interpolation start/end markers with their escaped counterparts.**\n     *\n     * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered\n     * output when the $interpolate service processes the text. So, for HTML elements interpolated\n     * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter\n     * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,\n     * this is typically useful only when user-data is used in rendering a template from the server, or\n     * when otherwise untrusted data is used by a directive.\n     *\n     * <example>\n     *  <file name=\"index.html\">\n     *    <div ng-init=\"username='A user'\">\n     *      <p ng-init=\"apptitle='Escaping demo'\">{{apptitle}}: \\{\\{ username = \"defaced value\"; \\}\\}\n     *        </p>\n     *      <p><strong>{{username}}</strong> attempts to inject code which will deface the\n     *        application, but fails to accomplish their task, because the server has correctly\n     *        escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)\n     *        characters.</p>\n     *      <p>Instead, the result of the attempted script injection is visible, and can be removed\n     *        from the database by an administrator.</p>\n     *    </div>\n     *  </file>\n     * </example>\n     *\n     * @param {string} text The text with markup to interpolate.\n     * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have\n     *    embedded expression in order to return an interpolation function. Strings with no\n     *    embedded expression will return null for the interpolation function.\n     * @param {string=} trustedContext when provided, the returned function passes the interpolated\n     *    result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,\n     *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that\n     *    provides Strict Contextual Escaping for details.\n     * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined\n     *    unless all embedded expressions evaluate to a value other than `undefined`.\n     * @returns {function(context)} an interpolation function which is used to compute the\n     *    interpolated string. The function has these parameters:\n     *\n     * - `context`: evaluation context for all expressions embedded in the interpolated text\n     */\n    function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {\n      allOrNothing = !!allOrNothing;\n      var startIndex,\n          endIndex,\n          index = 0,\n          expressions = [],\n          parseFns = [],\n          textLength = text.length,\n          exp,\n          concat = [],\n          expressionPositions = [];\n\n      while (index < textLength) {\n        if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&\n             ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {\n          if (index !== startIndex) {\n            concat.push(unescapeText(text.substring(index, startIndex)));\n          }\n          exp = text.substring(startIndex + startSymbolLength, endIndex);\n          expressions.push(exp);\n          parseFns.push($parse(exp, parseStringifyInterceptor));\n          index = endIndex + endSymbolLength;\n          expressionPositions.push(concat.length);\n          concat.push('');\n        } else {\n          // we did not find an interpolation, so we have to add the remainder to the separators array\n          if (index !== textLength) {\n            concat.push(unescapeText(text.substring(index)));\n          }\n          break;\n        }\n      }\n\n      // Concatenating expressions makes it hard to reason about whether some combination of\n      // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a\n      // single expression be used for iframe[src], object[src], etc., we ensure that the value\n      // that's used is assigned or constructed by some JS code somewhere that is more testable or\n      // make it obvious that you bound the value to some user controlled value.  This helps reduce\n      // the load when auditing for XSS issues.\n      if (trustedContext && concat.length > 1) {\n          $interpolateMinErr.throwNoconcat(text);\n      }\n\n      if (!mustHaveExpression || expressions.length) {\n        var compute = function(values) {\n          for (var i = 0, ii = expressions.length; i < ii; i++) {\n            if (allOrNothing && isUndefined(values[i])) return;\n            concat[expressionPositions[i]] = values[i];\n          }\n          return concat.join('');\n        };\n\n        var getValue = function(value) {\n          return trustedContext ?\n            $sce.getTrusted(trustedContext, value) :\n            $sce.valueOf(value);\n        };\n\n        return extend(function interpolationFn(context) {\n            var i = 0;\n            var ii = expressions.length;\n            var values = new Array(ii);\n\n            try {\n              for (; i < ii; i++) {\n                values[i] = parseFns[i](context);\n              }\n\n              return compute(values);\n            } catch (err) {\n              $exceptionHandler($interpolateMinErr.interr(text, err));\n            }\n\n          }, {\n          // all of these properties are undocumented for now\n          exp: text, //just for compatibility with regular watchers created via $watch\n          expressions: expressions,\n          $$watchDelegate: function(scope, listener) {\n            var lastValue;\n            return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {\n              var currValue = compute(values);\n              if (isFunction(listener)) {\n                listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);\n              }\n              lastValue = currValue;\n            });\n          }\n        });\n      }\n\n      function parseStringifyInterceptor(value) {\n        try {\n          value = getValue(value);\n          return allOrNothing && !isDefined(value) ? value : stringify(value);\n        } catch (err) {\n          $exceptionHandler($interpolateMinErr.interr(text, err));\n        }\n      }\n    }\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#startSymbol\n     * @description\n     * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.\n     *\n     * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} start symbol.\n     */\n    $interpolate.startSymbol = function() {\n      return startSymbol;\n    };\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#endSymbol\n     * @description\n     * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n     *\n     * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} end symbol.\n     */\n    $interpolate.endSymbol = function() {\n      return endSymbol;\n    };\n\n    return $interpolate;\n  }];\n}\n\nfunction $IntervalProvider() {\n  this.$get = ['$rootScope', '$window', '$q', '$$q',\n       function($rootScope,   $window,   $q,   $$q) {\n    var intervals = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $interval\n      *\n      * @description\n      * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`\n      * milliseconds.\n      *\n      * The return value of registering an interval function is a promise. This promise will be\n      * notified upon each tick of the interval, and will be resolved after `count` iterations, or\n      * run indefinitely if `count` is not defined. The value of the notification will be the\n      * number of iterations that have run.\n      * To cancel an interval, call `$interval.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n      * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n      * time.\n      *\n      * <div class=\"alert alert-warning\">\n      * **Note**: Intervals created by this service must be explicitly destroyed when you are finished\n      * with them.  In particular they are not automatically destroyed when a controller's scope or a\n      * directive's element are destroyed.\n      * You should take this into consideration and make sure to always cancel the interval at the\n      * appropriate moment.  See the example below for more details on how and when to do this.\n      * </div>\n      *\n      * @param {function()} fn A function that should be called repeatedly.\n      * @param {number} delay Number of milliseconds between each function call.\n      * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n      *   indefinitely.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @param {...*=} Pass additional parameters to the executed function.\n      * @returns {promise} A promise which will be notified on each iteration.\n      *\n      * @example\n      * <example module=\"intervalExample\">\n      * <file name=\"index.html\">\n      *   <script>\n      *     angular.module('intervalExample', [])\n      *       .controller('ExampleController', ['$scope', '$interval',\n      *         function($scope, $interval) {\n      *           $scope.format = 'M/d/yy h:mm:ss a';\n      *           $scope.blood_1 = 100;\n      *           $scope.blood_2 = 120;\n      *\n      *           var stop;\n      *           $scope.fight = function() {\n      *             // Don't start a new fight if we are already fighting\n      *             if ( angular.isDefined(stop) ) return;\n      *\n      *             stop = $interval(function() {\n      *               if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {\n      *                 $scope.blood_1 = $scope.blood_1 - 3;\n      *                 $scope.blood_2 = $scope.blood_2 - 4;\n      *               } else {\n      *                 $scope.stopFight();\n      *               }\n      *             }, 100);\n      *           };\n      *\n      *           $scope.stopFight = function() {\n      *             if (angular.isDefined(stop)) {\n      *               $interval.cancel(stop);\n      *               stop = undefined;\n      *             }\n      *           };\n      *\n      *           $scope.resetFight = function() {\n      *             $scope.blood_1 = 100;\n      *             $scope.blood_2 = 120;\n      *           };\n      *\n      *           $scope.$on('$destroy', function() {\n      *             // Make sure that the interval is destroyed too\n      *             $scope.stopFight();\n      *           });\n      *         }])\n      *       // Register the 'myCurrentTime' directive factory method.\n      *       // We inject $interval and dateFilter service since the factory method is DI.\n      *       .directive('myCurrentTime', ['$interval', 'dateFilter',\n      *         function($interval, dateFilter) {\n      *           // return the directive link function. (compile function not needed)\n      *           return function(scope, element, attrs) {\n      *             var format,  // date format\n      *                 stopTime; // so that we can cancel the time updates\n      *\n      *             // used to update the UI\n      *             function updateTime() {\n      *               element.text(dateFilter(new Date(), format));\n      *             }\n      *\n      *             // watch the expression, and update the UI on change.\n      *             scope.$watch(attrs.myCurrentTime, function(value) {\n      *               format = value;\n      *               updateTime();\n      *             });\n      *\n      *             stopTime = $interval(updateTime, 1000);\n      *\n      *             // listen on DOM destroy (removal) event, and cancel the next UI update\n      *             // to prevent updating time after the DOM element was removed.\n      *             element.on('$destroy', function() {\n      *               $interval.cancel(stopTime);\n      *             });\n      *           }\n      *         }]);\n      *   </script>\n      *\n      *   <div>\n      *     <div ng-controller=\"ExampleController\">\n      *       <label>Date format: <input ng-model=\"format\"></label> <hr/>\n      *       Current time is: <span my-current-time=\"format\"></span>\n      *       <hr/>\n      *       Blood 1 : <font color='red'>{{blood_1}}</font>\n      *       Blood 2 : <font color='red'>{{blood_2}}</font>\n      *       <button type=\"button\" data-ng-click=\"fight()\">Fight</button>\n      *       <button type=\"button\" data-ng-click=\"stopFight()\">StopFight</button>\n      *       <button type=\"button\" data-ng-click=\"resetFight()\">resetFight</button>\n      *     </div>\n      *   </div>\n      *\n      * </file>\n      * </example>\n      */\n    function interval(fn, delay, count, invokeApply) {\n      var hasParams = arguments.length > 4,\n          args = hasParams ? sliceArgs(arguments, 4) : [],\n          setInterval = $window.setInterval,\n          clearInterval = $window.clearInterval,\n          iteration = 0,\n          skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise;\n\n      count = isDefined(count) ? count : 0;\n\n      promise.then(null, null, (!hasParams) ? fn : function() {\n        fn.apply(null, args);\n      });\n\n      promise.$$intervalId = setInterval(function tick() {\n        deferred.notify(iteration++);\n\n        if (count > 0 && iteration >= count) {\n          deferred.resolve(iteration);\n          clearInterval(promise.$$intervalId);\n          delete intervals[promise.$$intervalId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n\n      }, delay);\n\n      intervals[promise.$$intervalId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $interval#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`.\n      *\n      * @param {Promise=} promise returned by the `$interval` function.\n      * @returns {boolean} Returns `true` if the task was successfully canceled.\n      */\n    interval.cancel = function(promise) {\n      if (promise && promise.$$intervalId in intervals) {\n        intervals[promise.$$intervalId].reject('canceled');\n        $window.clearInterval(promise.$$intervalId);\n        delete intervals[promise.$$intervalId];\n        return true;\n      }\n      return false;\n    };\n\n    return interval;\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $locale\n *\n * @description\n * $locale service provides localization rules for various Angular components. As of right now the\n * only public api is:\n *\n * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)\n */\n\nvar PATH_MATCH = /^([^\\?#]*)(\\?([^#]*))?(#(.*))?$/,\n    DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};\nvar $locationMinErr = minErr('$location');\n\n\n/**\n * Encode path using encodeUriSegment, ignoring forward slashes\n *\n * @param {string} path Path to encode\n * @returns {string}\n */\nfunction encodePath(path) {\n  var segments = path.split('/'),\n      i = segments.length;\n\n  while (i--) {\n    segments[i] = encodeUriSegment(segments[i]);\n  }\n\n  return segments.join('/');\n}\n\nfunction parseAbsoluteUrl(absoluteUrl, locationObj) {\n  var parsedUrl = urlResolve(absoluteUrl);\n\n  locationObj.$$protocol = parsedUrl.protocol;\n  locationObj.$$host = parsedUrl.hostname;\n  locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;\n}\n\n\nfunction parseAppUrl(relativeUrl, locationObj) {\n  var prefixed = (relativeUrl.charAt(0) !== '/');\n  if (prefixed) {\n    relativeUrl = '/' + relativeUrl;\n  }\n  var match = urlResolve(relativeUrl);\n  locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?\n      match.pathname.substring(1) : match.pathname);\n  locationObj.$$search = parseKeyValue(match.search);\n  locationObj.$$hash = decodeURIComponent(match.hash);\n\n  // make sure path starts with '/';\n  if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {\n    locationObj.$$path = '/' + locationObj.$$path;\n  }\n}\n\n\n/**\n *\n * @param {string} begin\n * @param {string} whole\n * @returns {string} returns text from whole after begin or undefined if it does not begin with\n *                   expected string.\n */\nfunction beginsWith(begin, whole) {\n  if (whole.indexOf(begin) === 0) {\n    return whole.substr(begin.length);\n  }\n}\n\n\nfunction stripHash(url) {\n  var index = url.indexOf('#');\n  return index == -1 ? url : url.substr(0, index);\n}\n\nfunction trimEmptyHash(url) {\n  return url.replace(/(#.+)|#$/, '$1');\n}\n\n\nfunction stripFile(url) {\n  return url.substr(0, stripHash(url).lastIndexOf('/') + 1);\n}\n\n/* return the server only (scheme://host:port) */\nfunction serverBase(url) {\n  return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));\n}\n\n\n/**\n * LocationHtml5Url represents an url\n * This object is exposed as $location service when HTML5 mode is enabled and supported\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} basePrefix url path prefix\n */\nfunction LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {\n  this.$$html5 = true;\n  basePrefix = basePrefix || '';\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given html5 (regular) url string into properties\n   * @param {string} url HTML5 url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var pathUrl = beginsWith(appBaseNoFile, url);\n    if (!isString(pathUrl)) {\n      throw $locationMinErr('ipthprfx', 'Invalid url \"{0}\", missing path prefix \"{1}\".', url,\n          appBaseNoFile);\n    }\n\n    parseAppUrl(pathUrl, this);\n\n    if (!this.$$path) {\n      this.$$path = '/';\n    }\n\n    this.$$compose();\n  };\n\n  /**\n   * Compose url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n    var appUrl, prevAppUrl;\n    var rewrittenUrl;\n\n    if ((appUrl = beginsWith(appBase, url)) !== undefined) {\n      prevAppUrl = appUrl;\n      if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {\n        rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);\n      } else {\n        rewrittenUrl = appBase + prevAppUrl;\n      }\n    } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {\n      rewrittenUrl = appBaseNoFile + appUrl;\n    } else if (appBaseNoFile == url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when developer doesn't opt into html5 mode.\n * It also serves as the base class for html5 mode fallback on legacy browsers.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {\n\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given hashbang url into properties\n   * @param {string} url Hashbang url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);\n    var withoutHashUrl;\n\n    if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {\n\n      // The rest of the url starts with a hash so we have\n      // got either a hashbang path or a plain hash fragment\n      withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);\n      if (isUndefined(withoutHashUrl)) {\n        // There was no hashbang prefix so we just have a hash fragment\n        withoutHashUrl = withoutBaseUrl;\n      }\n\n    } else {\n      // There was no hashbang path nor hash fragment:\n      // If we are in HTML5 mode we use what is left as the path;\n      // Otherwise we ignore what is left\n      if (this.$$html5) {\n        withoutHashUrl = withoutBaseUrl;\n      } else {\n        withoutHashUrl = '';\n        if (isUndefined(withoutBaseUrl)) {\n          appBase = url;\n          this.replace();\n        }\n      }\n    }\n\n    parseAppUrl(withoutHashUrl, this);\n\n    this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);\n\n    this.$$compose();\n\n    /*\n     * In Windows, on an anchor node on documents loaded from\n     * the filesystem, the browser will return a pathname\n     * prefixed with the drive name ('/C:/path') when a\n     * pathname without a drive is set:\n     *  * a.setAttribute('href', '/foo')\n     *   * a.pathname === '/C:/foo' //true\n     *\n     * Inside of Angular, we're always using pathnames that\n     * do not include drive names for routing.\n     */\n    function removeWindowsDriveName(path, url, base) {\n      /*\n      Matches paths for file protocol on windows,\n      such as /C:/foo/bar, and captures only /foo/bar.\n      */\n      var windowsFilePathExp = /^\\/[A-Z]:(\\/.*)/;\n\n      var firstPathSegmentMatch;\n\n      //Get the relative path from the input URL.\n      if (url.indexOf(base) === 0) {\n        url = url.replace(base, '');\n      }\n\n      // The input URL intentionally contains a first path segment that ends with a colon.\n      if (windowsFilePathExp.exec(url)) {\n        return path;\n      }\n\n      firstPathSegmentMatch = windowsFilePathExp.exec(path);\n      return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;\n    }\n  };\n\n  /**\n   * Compose hashbang url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (stripHash(appBase) == stripHash(url)) {\n      this.$$parse(url);\n      return true;\n    }\n    return false;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when html5 history api is enabled but the browser\n * does not support it.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {\n  this.$$html5 = true;\n  LocationHashbangUrl.apply(this, arguments);\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n\n    var rewrittenUrl;\n    var appUrl;\n\n    if (appBase == stripHash(url)) {\n      rewrittenUrl = url;\n    } else if ((appUrl = beginsWith(appBaseNoFile, url))) {\n      rewrittenUrl = appBase + hashPrefix + appUrl;\n    } else if (appBaseNoFile === url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'\n    this.$$absUrl = appBase + hashPrefix + this.$$url;\n  };\n\n}\n\n\nvar locationPrototype = {\n\n  /**\n   * Are we in html5 mode?\n   * @private\n   */\n  $$html5: false,\n\n  /**\n   * Has any change been replacing?\n   * @private\n   */\n  $$replace: false,\n\n  /**\n   * @ngdoc method\n   * @name $location#absUrl\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return full url representation with all segments encoded according to rules specified in\n   * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var absUrl = $location.absUrl();\n   * // => \"http://example.com/#/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @return {string} full url\n   */\n  absUrl: locationGetter('$$absUrl'),\n\n  /**\n   * @ngdoc method\n   * @name $location#url\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return url (e.g. `/path?a=b#hash`) when called without any parameter.\n   *\n   * Change path, search and hash, when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var url = $location.url();\n   * // => \"/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)\n   * @return {string} url\n   */\n  url: function(url) {\n    if (isUndefined(url)) {\n      return this.$$url;\n    }\n\n    var match = PATH_MATCH.exec(url);\n    if (match[1] || url === '') this.path(decodeURIComponent(match[1]));\n    if (match[2] || match[1] || url === '') this.search(match[3] || '');\n    this.hash(match[5] || '');\n\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#protocol\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return protocol of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var protocol = $location.protocol();\n   * // => \"http\"\n   * ```\n   *\n   * @return {string} protocol of current url\n   */\n  protocol: locationGetter('$$protocol'),\n\n  /**\n   * @ngdoc method\n   * @name $location#host\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return host of current url.\n   *\n   * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var host = $location.host();\n   * // => \"example.com\"\n   *\n   * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo\n   * host = $location.host();\n   * // => \"example.com\"\n   * host = location.host;\n   * // => \"example.com:8080\"\n   * ```\n   *\n   * @return {string} host of current url.\n   */\n  host: locationGetter('$$host'),\n\n  /**\n   * @ngdoc method\n   * @name $location#port\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return port of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var port = $location.port();\n   * // => 80\n   * ```\n   *\n   * @return {Number} port\n   */\n  port: locationGetter('$$port'),\n\n  /**\n   * @ngdoc method\n   * @name $location#path\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return path of current url when called without any parameter.\n   *\n   * Change path when called with parameter and return `$location`.\n   *\n   * Note: Path should always begin with forward slash (/), this method will add the forward slash\n   * if it is missing.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var path = $location.path();\n   * // => \"/some/path\"\n   * ```\n   *\n   * @param {(string|number)=} path New path\n   * @return {string} path\n   */\n  path: locationGetterSetter('$$path', function(path) {\n    path = path !== null ? path.toString() : '';\n    return path.charAt(0) == '/' ? path : '/' + path;\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#search\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return search part (as object) of current url when called without any parameter.\n   *\n   * Change search part when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var searchObject = $location.search();\n   * // => {foo: 'bar', baz: 'xoxo'}\n   *\n   * // set foo to 'yipee'\n   * $location.search('foo', 'yipee');\n   * // $location.search() => {foo: 'yipee', baz: 'xoxo'}\n   * ```\n   *\n   * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or\n   * hash object.\n   *\n   * When called with a single argument the method acts as a setter, setting the `search` component\n   * of `$location` to the specified value.\n   *\n   * If the argument is a hash object containing an array of values, these values will be encoded\n   * as duplicate search parameters in the url.\n   *\n   * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`\n   * will override only a single search property.\n   *\n   * If `paramValue` is an array, it will override the property of the `search` component of\n   * `$location` specified via the first argument.\n   *\n   * If `paramValue` is `null`, the property specified via the first argument will be deleted.\n   *\n   * If `paramValue` is `true`, the property specified via the first argument will be added with no\n   * value nor trailing equal sign.\n   *\n   * @return {Object} If called with no arguments returns the parsed `search` object. If called with\n   * one or more arguments returns `$location` object itself.\n   */\n  search: function(search, paramValue) {\n    switch (arguments.length) {\n      case 0:\n        return this.$$search;\n      case 1:\n        if (isString(search) || isNumber(search)) {\n          search = search.toString();\n          this.$$search = parseKeyValue(search);\n        } else if (isObject(search)) {\n          search = copy(search, {});\n          // remove object undefined or null properties\n          forEach(search, function(value, key) {\n            if (value == null) delete search[key];\n          });\n\n          this.$$search = search;\n        } else {\n          throw $locationMinErr('isrcharg',\n              'The first argument of the `$location#search()` call must be a string or an object.');\n        }\n        break;\n      default:\n        if (isUndefined(paramValue) || paramValue === null) {\n          delete this.$$search[search];\n        } else {\n          this.$$search[search] = paramValue;\n        }\n    }\n\n    this.$$compose();\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#hash\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return hash fragment when called without any parameter.\n   *\n   * Change hash fragment when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue\n   * var hash = $location.hash();\n   * // => \"hashValue\"\n   * ```\n   *\n   * @param {(string|number)=} hash New hash fragment\n   * @return {string} hash\n   */\n  hash: locationGetterSetter('$$hash', function(hash) {\n    return hash !== null ? hash.toString() : '';\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#replace\n   *\n   * @description\n   * If called, all changes to $location during current `$digest` will be replacing current history\n   * record, instead of adding new one.\n   */\n  replace: function() {\n    this.$$replace = true;\n    return this;\n  }\n};\n\nforEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {\n  Location.prototype = Object.create(locationPrototype);\n\n  /**\n   * @ngdoc method\n   * @name $location#state\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return the history state object when called without any parameter.\n   *\n   * Change the history state object when called with one parameter and return `$location`.\n   * The state object is later passed to `pushState` or `replaceState`.\n   *\n   * NOTE: This method is supported only in HTML5 mode and only in browsers supporting\n   * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support\n   * older browsers (like IE9 or Android < 4.0), don't use this method.\n   *\n   * @param {object=} state State object for pushState or replaceState\n   * @return {object} state\n   */\n  Location.prototype.state = function(state) {\n    if (!arguments.length) {\n      return this.$$state;\n    }\n\n    if (Location !== LocationHtml5Url || !this.$$html5) {\n      throw $locationMinErr('nostate', 'History API state support is available only ' +\n        'in HTML5 mode and only in browsers supporting HTML5 History API');\n    }\n    // The user might modify `stateObject` after invoking `$location.state(stateObject)`\n    // but we're changing the $$state reference to $browser.state() during the $digest\n    // so the modification window is narrow.\n    this.$$state = isUndefined(state) ? null : state;\n\n    return this;\n  };\n});\n\n\nfunction locationGetter(property) {\n  return function() {\n    return this[property];\n  };\n}\n\n\nfunction locationGetterSetter(property, preprocess) {\n  return function(value) {\n    if (isUndefined(value)) {\n      return this[property];\n    }\n\n    this[property] = preprocess(value);\n    this.$$compose();\n\n    return this;\n  };\n}\n\n\n/**\n * @ngdoc service\n * @name $location\n *\n * @requires $rootElement\n *\n * @description\n * The $location service parses the URL in the browser address bar (based on the\n * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL\n * available to your application. Changes to the URL in the address bar are reflected into\n * $location service and changes to $location are reflected into the browser address bar.\n *\n * **The $location service:**\n *\n * - Exposes the current URL in the browser address bar, so you can\n *   - Watch and observe the URL.\n *   - Change the URL.\n * - Synchronizes the URL with the browser when the user\n *   - Changes the address bar.\n *   - Clicks the back or forward button (or clicks a History link).\n *   - Clicks on a link.\n * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).\n *\n * For more information see {@link guide/$location Developer Guide: Using $location}\n */\n\n/**\n * @ngdoc provider\n * @name $locationProvider\n * @description\n * Use the `$locationProvider` to configure how the application deep linking paths are stored.\n */\nfunction $LocationProvider() {\n  var hashPrefix = '',\n      html5Mode = {\n        enabled: false,\n        requireBase: true,\n        rewriteLinks: true\n      };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#hashPrefix\n   * @description\n   * @param {string=} prefix Prefix for hash part (containing path and search)\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.hashPrefix = function(prefix) {\n    if (isDefined(prefix)) {\n      hashPrefix = prefix;\n      return this;\n    } else {\n      return hashPrefix;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#html5Mode\n   * @description\n   * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.\n   *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported\n   *   properties:\n   *   - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to\n   *     change urls where supported. Will fall back to hash-prefixed paths in browsers that do not\n   *     support `pushState`.\n   *   - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies\n   *     whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are\n   *     true, and a base tag is not present, an error will be thrown when `$location` is injected.\n   *     See the {@link guide/$location $location guide for more information}\n   *   - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,\n   *     enables/disables url rewriting for relative links.\n   *\n   * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter\n   */\n  this.html5Mode = function(mode) {\n    if (isBoolean(mode)) {\n      html5Mode.enabled = mode;\n      return this;\n    } else if (isObject(mode)) {\n\n      if (isBoolean(mode.enabled)) {\n        html5Mode.enabled = mode.enabled;\n      }\n\n      if (isBoolean(mode.requireBase)) {\n        html5Mode.requireBase = mode.requireBase;\n      }\n\n      if (isBoolean(mode.rewriteLinks)) {\n        html5Mode.rewriteLinks = mode.rewriteLinks;\n      }\n\n      return this;\n    } else {\n      return html5Mode;\n    }\n  };\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeStart\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted before a URL will change.\n   *\n   * This change can be prevented by calling\n   * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more\n   * details about event object. Upon successful change\n   * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeSuccess\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted after a URL was changed.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',\n      function($rootScope, $browser, $sniffer, $rootElement, $window) {\n    var $location,\n        LocationMode,\n        baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''\n        initialUrl = $browser.url(),\n        appBase;\n\n    if (html5Mode.enabled) {\n      if (!baseHref && html5Mode.requireBase) {\n        throw $locationMinErr('nobase',\n          \"$location in HTML5 mode requires a <base> tag to be present!\");\n      }\n      appBase = serverBase(initialUrl) + (baseHref || '/');\n      LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;\n    } else {\n      appBase = stripHash(initialUrl);\n      LocationMode = LocationHashbangUrl;\n    }\n    var appBaseNoFile = stripFile(appBase);\n\n    $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);\n    $location.$$parseLinkUrl(initialUrl, initialUrl);\n\n    $location.$$state = $browser.state();\n\n    var IGNORE_URI_REGEXP = /^\\s*(javascript|mailto):/i;\n\n    function setBrowserUrlWithFallback(url, replace, state) {\n      var oldUrl = $location.url();\n      var oldState = $location.$$state;\n      try {\n        $browser.url(url, replace, state);\n\n        // Make sure $location.state() returns referentially identical (not just deeply equal)\n        // state object; this makes possible quick checking if the state changed in the digest\n        // loop. Checking deep equality would be too expensive.\n        $location.$$state = $browser.state();\n      } catch (e) {\n        // Restore old values if pushState fails\n        $location.url(oldUrl);\n        $location.$$state = oldState;\n\n        throw e;\n      }\n    }\n\n    $rootElement.on('click', function(event) {\n      // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)\n      // currently we open nice url link and redirect then\n\n      if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;\n\n      var elm = jqLite(event.target);\n\n      // traverse the DOM up to find first A tag\n      while (nodeName_(elm[0]) !== 'a') {\n        // ignore rewriting if no A tag (reached root element, or no parent - removed from document)\n        if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;\n      }\n\n      var absHref = elm.prop('href');\n      // get the actual href attribute - see\n      // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx\n      var relHref = elm.attr('href') || elm.attr('xlink:href');\n\n      if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {\n        // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during\n        // an animation.\n        absHref = urlResolve(absHref.animVal).href;\n      }\n\n      // Ignore when url is started with javascript: or mailto:\n      if (IGNORE_URI_REGEXP.test(absHref)) return;\n\n      if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {\n        if ($location.$$parseLinkUrl(absHref, relHref)) {\n          // We do a preventDefault for all urls that are part of the angular application,\n          // in html5mode and also without, so that we are able to abort navigation without\n          // getting double entries in the location history.\n          event.preventDefault();\n          // update location manually\n          if ($location.absUrl() != $browser.url()) {\n            $rootScope.$apply();\n            // hack to work around FF6 bug 684208 when scenario runner clicks on links\n            $window.angular['ff-684208-preventDefault'] = true;\n          }\n        }\n      }\n    });\n\n\n    // rewrite hashbang url <> html5 url\n    if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {\n      $browser.url($location.absUrl(), true);\n    }\n\n    var initializing = true;\n\n    // update $location when $browser url changes\n    $browser.onUrlChange(function(newUrl, newState) {\n\n      if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {\n        // If we are navigating outside of the app then force a reload\n        $window.location.href = newUrl;\n        return;\n      }\n\n      $rootScope.$evalAsync(function() {\n        var oldUrl = $location.absUrl();\n        var oldState = $location.$$state;\n        var defaultPrevented;\n\n        $location.$$parse(newUrl);\n        $location.$$state = newState;\n\n        defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n            newState, oldState).defaultPrevented;\n\n        // if the location was changed by a `$locationChangeStart` handler then stop\n        // processing this location change\n        if ($location.absUrl() !== newUrl) return;\n\n        if (defaultPrevented) {\n          $location.$$parse(oldUrl);\n          $location.$$state = oldState;\n          setBrowserUrlWithFallback(oldUrl, false, oldState);\n        } else {\n          initializing = false;\n          afterLocationChange(oldUrl, oldState);\n        }\n      });\n      if (!$rootScope.$$phase) $rootScope.$digest();\n    });\n\n    // update browser\n    $rootScope.$watch(function $locationWatch() {\n      var oldUrl = trimEmptyHash($browser.url());\n      var newUrl = trimEmptyHash($location.absUrl());\n      var oldState = $browser.state();\n      var currentReplace = $location.$$replace;\n      var urlOrStateChanged = oldUrl !== newUrl ||\n        ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);\n\n      if (initializing || urlOrStateChanged) {\n        initializing = false;\n\n        $rootScope.$evalAsync(function() {\n          var newUrl = $location.absUrl();\n          var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n              $location.$$state, oldState).defaultPrevented;\n\n          // if the location was changed by a `$locationChangeStart` handler then stop\n          // processing this location change\n          if ($location.absUrl() !== newUrl) return;\n\n          if (defaultPrevented) {\n            $location.$$parse(oldUrl);\n            $location.$$state = oldState;\n          } else {\n            if (urlOrStateChanged) {\n              setBrowserUrlWithFallback(newUrl, currentReplace,\n                                        oldState === $location.$$state ? null : $location.$$state);\n            }\n            afterLocationChange(oldUrl, oldState);\n          }\n        });\n      }\n\n      $location.$$replace = false;\n\n      // we don't need to return anything because $evalAsync will make the digest loop dirty when\n      // there is a change\n    });\n\n    return $location;\n\n    function afterLocationChange(oldUrl, oldState) {\n      $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,\n        $location.$$state, oldState);\n    }\n}];\n}\n\n/**\n * @ngdoc service\n * @name $log\n * @requires $window\n *\n * @description\n * Simple service for logging. Default implementation safely writes the message\n * into the browser's console (if present).\n *\n * The main purpose of this service is to simplify debugging and troubleshooting.\n *\n * The default is to log `debug` messages. You can use\n * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.\n *\n * @example\n   <example module=\"logExample\">\n     <file name=\"script.js\">\n       angular.module('logExample', [])\n         .controller('LogController', ['$scope', '$log', function($scope, $log) {\n           $scope.$log = $log;\n           $scope.message = 'Hello World!';\n         }]);\n     </file>\n     <file name=\"index.html\">\n       <div ng-controller=\"LogController\">\n         <p>Reload this page with open console, enter text and hit the log button...</p>\n         <label>Message:\n         <input type=\"text\" ng-model=\"message\" /></label>\n         <button ng-click=\"$log.log(message)\">log</button>\n         <button ng-click=\"$log.warn(message)\">warn</button>\n         <button ng-click=\"$log.info(message)\">info</button>\n         <button ng-click=\"$log.error(message)\">error</button>\n         <button ng-click=\"$log.debug(message)\">debug</button>\n       </div>\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc provider\n * @name $logProvider\n * @description\n * Use the `$logProvider` to configure how the application logs messages\n */\nfunction $LogProvider() {\n  var debug = true,\n      self = this;\n\n  /**\n   * @ngdoc method\n   * @name $logProvider#debugEnabled\n   * @description\n   * @param {boolean=} flag enable or disable debug level messages\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.debugEnabled = function(flag) {\n    if (isDefined(flag)) {\n      debug = flag;\n    return this;\n    } else {\n      return debug;\n    }\n  };\n\n  this.$get = ['$window', function($window) {\n    return {\n      /**\n       * @ngdoc method\n       * @name $log#log\n       *\n       * @description\n       * Write a log message\n       */\n      log: consoleLog('log'),\n\n      /**\n       * @ngdoc method\n       * @name $log#info\n       *\n       * @description\n       * Write an information message\n       */\n      info: consoleLog('info'),\n\n      /**\n       * @ngdoc method\n       * @name $log#warn\n       *\n       * @description\n       * Write a warning message\n       */\n      warn: consoleLog('warn'),\n\n      /**\n       * @ngdoc method\n       * @name $log#error\n       *\n       * @description\n       * Write an error message\n       */\n      error: consoleLog('error'),\n\n      /**\n       * @ngdoc method\n       * @name $log#debug\n       *\n       * @description\n       * Write a debug message\n       */\n      debug: (function() {\n        var fn = consoleLog('debug');\n\n        return function() {\n          if (debug) {\n            fn.apply(self, arguments);\n          }\n        };\n      }())\n    };\n\n    function formatError(arg) {\n      if (arg instanceof Error) {\n        if (arg.stack) {\n          arg = (arg.message && arg.stack.indexOf(arg.message) === -1)\n              ? 'Error: ' + arg.message + '\\n' + arg.stack\n              : arg.stack;\n        } else if (arg.sourceURL) {\n          arg = arg.message + '\\n' + arg.sourceURL + ':' + arg.line;\n        }\n      }\n      return arg;\n    }\n\n    function consoleLog(type) {\n      var console = $window.console || {},\n          logFn = console[type] || console.log || noop,\n          hasApply = false;\n\n      // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.\n      // The reason behind this is that console.log has type \"object\" in IE8...\n      try {\n        hasApply = !!logFn.apply;\n      } catch (e) {}\n\n      if (hasApply) {\n        return function() {\n          var args = [];\n          forEach(arguments, function(arg) {\n            args.push(formatError(arg));\n          });\n          return logFn.apply(console, args);\n        };\n      }\n\n      // we are IE which either doesn't have window.console => this is noop and we do nothing,\n      // or we are IE where console.log doesn't have apply so we log at least first 2 args\n      return function(arg1, arg2) {\n        logFn(arg1, arg2 == null ? '' : arg2);\n      };\n    }\n  }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $parseMinErr = minErr('$parse');\n\n// Sandboxing Angular Expressions\n// ------------------------------\n// Angular expressions are generally considered safe because these expressions only have direct\n// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by\n// obtaining a reference to native JS functions such as the Function constructor.\n//\n// As an example, consider the following Angular expression:\n//\n//   {}.toString.constructor('alert(\"evil JS code\")')\n//\n// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits\n// against the expression language, but not to prevent exploits that were enabled by exposing\n// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good\n// practice and therefore we are not even trying to protect against interaction with an object\n// explicitly exposed in this way.\n//\n// In general, it is not possible to access a Window object from an angular expression unless a\n// window or some DOM object that has a reference to window is published onto a Scope.\n// Similarly we prevent invocations of function known to be dangerous, as well as assignments to\n// native objects.\n//\n// See https://docs.angularjs.org/guide/security\n\n\nfunction ensureSafeMemberName(name, fullExpression) {\n  if (name === \"__defineGetter__\" || name === \"__defineSetter__\"\n      || name === \"__lookupGetter__\" || name === \"__lookupSetter__\"\n      || name === \"__proto__\") {\n    throw $parseMinErr('isecfld',\n        'Attempting to access a disallowed field in Angular expressions! '\n        + 'Expression: {0}', fullExpression);\n  }\n  return name;\n}\n\nfunction ensureSafeObject(obj, fullExpression) {\n  // nifty check if obj is Function that is fast and works across iframes and other contexts\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n          'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isWindow(obj)\n        obj.window === obj) {\n      throw $parseMinErr('isecwindow',\n          'Referencing the Window in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isElement(obj)\n        obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {\n      throw $parseMinErr('isecdom',\n          'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// block Object so that we can't get hold of dangerous Object.* methods\n        obj === Object) {\n      throw $parseMinErr('isecobj',\n          'Referencing Object in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    }\n  }\n  return obj;\n}\n\nvar CALL = Function.prototype.call;\nvar APPLY = Function.prototype.apply;\nvar BIND = Function.prototype.bind;\n\nfunction ensureSafeFunction(obj, fullExpression) {\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n        'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    } else if (obj === CALL || obj === APPLY || obj === BIND) {\n      throw $parseMinErr('isecff',\n        'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    }\n  }\n}\n\nvar OPERATORS = createMap();\nforEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });\nvar ESCAPE = {\"n\":\"\\n\", \"f\":\"\\f\", \"r\":\"\\r\", \"t\":\"\\t\", \"v\":\"\\v\", \"'\":\"'\", '\"':'\"'};\n\n\n/////////////////////////////////////////\n\n\n/**\n * @constructor\n */\nvar Lexer = function(options) {\n  this.options = options;\n};\n\nLexer.prototype = {\n  constructor: Lexer,\n\n  lex: function(text) {\n    this.text = text;\n    this.index = 0;\n    this.tokens = [];\n\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (ch === '\"' || ch === \"'\") {\n        this.readString(ch);\n      } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\n        this.readNumber();\n      } else if (this.isIdent(ch)) {\n        this.readIdent();\n      } else if (this.is(ch, '(){}[].,;:?')) {\n        this.tokens.push({index: this.index, text: ch});\n        this.index++;\n      } else if (this.isWhitespace(ch)) {\n        this.index++;\n      } else {\n        var ch2 = ch + this.peek();\n        var ch3 = ch2 + this.peek(2);\n        var op1 = OPERATORS[ch];\n        var op2 = OPERATORS[ch2];\n        var op3 = OPERATORS[ch3];\n        if (op1 || op2 || op3) {\n          var token = op3 ? ch3 : (op2 ? ch2 : ch);\n          this.tokens.push({index: this.index, text: token, operator: true});\n          this.index += token.length;\n        } else {\n          this.throwError('Unexpected next character ', this.index, this.index + 1);\n        }\n      }\n    }\n    return this.tokens;\n  },\n\n  is: function(ch, chars) {\n    return chars.indexOf(ch) !== -1;\n  },\n\n  peek: function(i) {\n    var num = i || 1;\n    return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\n  },\n\n  isNumber: function(ch) {\n    return ('0' <= ch && ch <= '9') && typeof ch === \"string\";\n  },\n\n  isWhitespace: function(ch) {\n    // IE treats non-breaking space as \\u00A0\n    return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\n            ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\n  },\n\n  isIdent: function(ch) {\n    return ('a' <= ch && ch <= 'z' ||\n            'A' <= ch && ch <= 'Z' ||\n            '_' === ch || ch === '$');\n  },\n\n  isExpOperator: function(ch) {\n    return (ch === '-' || ch === '+' || this.isNumber(ch));\n  },\n\n  throwError: function(error, start, end) {\n    end = end || this.index;\n    var colStr = (isDefined(start)\n            ? 's ' + start +  '-' + this.index + ' [' + this.text.substring(start, end) + ']'\n            : ' ' + end);\n    throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\n        error, colStr, this.text);\n  },\n\n  readNumber: function() {\n    var number = '';\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = lowercase(this.text.charAt(this.index));\n      if (ch == '.' || this.isNumber(ch)) {\n        number += ch;\n      } else {\n        var peekCh = this.peek();\n        if (ch == 'e' && this.isExpOperator(peekCh)) {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            peekCh && this.isNumber(peekCh) &&\n            number.charAt(number.length - 1) == 'e') {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            (!peekCh || !this.isNumber(peekCh)) &&\n            number.charAt(number.length - 1) == 'e') {\n          this.throwError('Invalid exponent');\n        } else {\n          break;\n        }\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: number,\n      constant: true,\n      value: Number(number)\n    });\n  },\n\n  readIdent: function() {\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (!(this.isIdent(ch) || this.isNumber(ch))) {\n        break;\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: this.text.slice(start, this.index),\n      identifier: true\n    });\n  },\n\n  readString: function(quote) {\n    var start = this.index;\n    this.index++;\n    var string = '';\n    var rawString = quote;\n    var escape = false;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      rawString += ch;\n      if (escape) {\n        if (ch === 'u') {\n          var hex = this.text.substring(this.index + 1, this.index + 5);\n          if (!hex.match(/[\\da-f]{4}/i)) {\n            this.throwError('Invalid unicode escape [\\\\u' + hex + ']');\n          }\n          this.index += 4;\n          string += String.fromCharCode(parseInt(hex, 16));\n        } else {\n          var rep = ESCAPE[ch];\n          string = string + (rep || ch);\n        }\n        escape = false;\n      } else if (ch === '\\\\') {\n        escape = true;\n      } else if (ch === quote) {\n        this.index++;\n        this.tokens.push({\n          index: start,\n          text: rawString,\n          constant: true,\n          value: string\n        });\n        return;\n      } else {\n        string += ch;\n      }\n      this.index++;\n    }\n    this.throwError('Unterminated quote', start);\n  }\n};\n\nvar AST = function(lexer, options) {\n  this.lexer = lexer;\n  this.options = options;\n};\n\nAST.Program = 'Program';\nAST.ExpressionStatement = 'ExpressionStatement';\nAST.AssignmentExpression = 'AssignmentExpression';\nAST.ConditionalExpression = 'ConditionalExpression';\nAST.LogicalExpression = 'LogicalExpression';\nAST.BinaryExpression = 'BinaryExpression';\nAST.UnaryExpression = 'UnaryExpression';\nAST.CallExpression = 'CallExpression';\nAST.MemberExpression = 'MemberExpression';\nAST.Identifier = 'Identifier';\nAST.Literal = 'Literal';\nAST.ArrayExpression = 'ArrayExpression';\nAST.Property = 'Property';\nAST.ObjectExpression = 'ObjectExpression';\nAST.ThisExpression = 'ThisExpression';\n\n// Internal use only\nAST.NGValueParameter = 'NGValueParameter';\n\nAST.prototype = {\n  ast: function(text) {\n    this.text = text;\n    this.tokens = this.lexer.lex(text);\n\n    var value = this.program();\n\n    if (this.tokens.length !== 0) {\n      this.throwError('is an unexpected token', this.tokens[0]);\n    }\n\n    return value;\n  },\n\n  program: function() {\n    var body = [];\n    while (true) {\n      if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))\n        body.push(this.expressionStatement());\n      if (!this.expect(';')) {\n        return { type: AST.Program, body: body};\n      }\n    }\n  },\n\n  expressionStatement: function() {\n    return { type: AST.ExpressionStatement, expression: this.filterChain() };\n  },\n\n  filterChain: function() {\n    var left = this.expression();\n    var token;\n    while ((token = this.expect('|'))) {\n      left = this.filter(left);\n    }\n    return left;\n  },\n\n  expression: function() {\n    return this.assignment();\n  },\n\n  assignment: function() {\n    var result = this.ternary();\n    if (this.expect('=')) {\n      result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};\n    }\n    return result;\n  },\n\n  ternary: function() {\n    var test = this.logicalOR();\n    var alternate;\n    var consequent;\n    if (this.expect('?')) {\n      alternate = this.expression();\n      if (this.consume(':')) {\n        consequent = this.expression();\n        return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};\n      }\n    }\n    return test;\n  },\n\n  logicalOR: function() {\n    var left = this.logicalAND();\n    while (this.expect('||')) {\n      left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };\n    }\n    return left;\n  },\n\n  logicalAND: function() {\n    var left = this.equality();\n    while (this.expect('&&')) {\n      left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};\n    }\n    return left;\n  },\n\n  equality: function() {\n    var left = this.relational();\n    var token;\n    while ((token = this.expect('==','!=','===','!=='))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };\n    }\n    return left;\n  },\n\n  relational: function() {\n    var left = this.additive();\n    var token;\n    while ((token = this.expect('<', '>', '<=', '>='))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };\n    }\n    return left;\n  },\n\n  additive: function() {\n    var left = this.multiplicative();\n    var token;\n    while ((token = this.expect('+','-'))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };\n    }\n    return left;\n  },\n\n  multiplicative: function() {\n    var left = this.unary();\n    var token;\n    while ((token = this.expect('*','/','%'))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };\n    }\n    return left;\n  },\n\n  unary: function() {\n    var token;\n    if ((token = this.expect('+', '-', '!'))) {\n      return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };\n    } else {\n      return this.primary();\n    }\n  },\n\n  primary: function() {\n    var primary;\n    if (this.expect('(')) {\n      primary = this.filterChain();\n      this.consume(')');\n    } else if (this.expect('[')) {\n      primary = this.arrayDeclaration();\n    } else if (this.expect('{')) {\n      primary = this.object();\n    } else if (this.constants.hasOwnProperty(this.peek().text)) {\n      primary = copy(this.constants[this.consume().text]);\n    } else if (this.peek().identifier) {\n      primary = this.identifier();\n    } else if (this.peek().constant) {\n      primary = this.constant();\n    } else {\n      this.throwError('not a primary expression', this.peek());\n    }\n\n    var next;\n    while ((next = this.expect('(', '[', '.'))) {\n      if (next.text === '(') {\n        primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };\n        this.consume(')');\n      } else if (next.text === '[') {\n        primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };\n        this.consume(']');\n      } else if (next.text === '.') {\n        primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };\n      } else {\n        this.throwError('IMPOSSIBLE');\n      }\n    }\n    return primary;\n  },\n\n  filter: function(baseExpression) {\n    var args = [baseExpression];\n    var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};\n\n    while (this.expect(':')) {\n      args.push(this.expression());\n    }\n\n    return result;\n  },\n\n  parseArguments: function() {\n    var args = [];\n    if (this.peekToken().text !== ')') {\n      do {\n        args.push(this.expression());\n      } while (this.expect(','));\n    }\n    return args;\n  },\n\n  identifier: function() {\n    var token = this.consume();\n    if (!token.identifier) {\n      this.throwError('is not a valid identifier', token);\n    }\n    return { type: AST.Identifier, name: token.text };\n  },\n\n  constant: function() {\n    // TODO check that it is a constant\n    return { type: AST.Literal, value: this.consume().value };\n  },\n\n  arrayDeclaration: function() {\n    var elements = [];\n    if (this.peekToken().text !== ']') {\n      do {\n        if (this.peek(']')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        elements.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume(']');\n\n    return { type: AST.ArrayExpression, elements: elements };\n  },\n\n  object: function() {\n    var properties = [], property;\n    if (this.peekToken().text !== '}') {\n      do {\n        if (this.peek('}')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        property = {type: AST.Property, kind: 'init'};\n        if (this.peek().constant) {\n          property.key = this.constant();\n        } else if (this.peek().identifier) {\n          property.key = this.identifier();\n        } else {\n          this.throwError(\"invalid key\", this.peek());\n        }\n        this.consume(':');\n        property.value = this.expression();\n        properties.push(property);\n      } while (this.expect(','));\n    }\n    this.consume('}');\n\n    return {type: AST.ObjectExpression, properties: properties };\n  },\n\n  throwError: function(msg, token) {\n    throw $parseMinErr('syntax',\n        'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\n          token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\n  },\n\n  consume: function(e1) {\n    if (this.tokens.length === 0) {\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    }\n\n    var token = this.expect(e1);\n    if (!token) {\n      this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\n    }\n    return token;\n  },\n\n  peekToken: function() {\n    if (this.tokens.length === 0) {\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    }\n    return this.tokens[0];\n  },\n\n  peek: function(e1, e2, e3, e4) {\n    return this.peekAhead(0, e1, e2, e3, e4);\n  },\n\n  peekAhead: function(i, e1, e2, e3, e4) {\n    if (this.tokens.length > i) {\n      var token = this.tokens[i];\n      var t = token.text;\n      if (t === e1 || t === e2 || t === e3 || t === e4 ||\n          (!e1 && !e2 && !e3 && !e4)) {\n        return token;\n      }\n    }\n    return false;\n  },\n\n  expect: function(e1, e2, e3, e4) {\n    var token = this.peek(e1, e2, e3, e4);\n    if (token) {\n      this.tokens.shift();\n      return token;\n    }\n    return false;\n  },\n\n\n  /* `undefined` is not a constant, it is an identifier,\n   * but using it as an identifier is not supported\n   */\n  constants: {\n    'true': { type: AST.Literal, value: true },\n    'false': { type: AST.Literal, value: false },\n    'null': { type: AST.Literal, value: null },\n    'undefined': {type: AST.Literal, value: undefined },\n    'this': {type: AST.ThisExpression }\n  }\n};\n\nfunction ifDefined(v, d) {\n  return typeof v !== 'undefined' ? v : d;\n}\n\nfunction plusFn(l, r) {\n  if (typeof l === 'undefined') return r;\n  if (typeof r === 'undefined') return l;\n  return l + r;\n}\n\nfunction isStateless($filter, filterName) {\n  var fn = $filter(filterName);\n  return !fn.$stateful;\n}\n\nfunction findConstantAndWatchExpressions(ast, $filter) {\n  var allConstants;\n  var argsToWatch;\n  switch (ast.type) {\n  case AST.Program:\n    allConstants = true;\n    forEach(ast.body, function(expr) {\n      findConstantAndWatchExpressions(expr.expression, $filter);\n      allConstants = allConstants && expr.expression.constant;\n    });\n    ast.constant = allConstants;\n    break;\n  case AST.Literal:\n    ast.constant = true;\n    ast.toWatch = [];\n    break;\n  case AST.UnaryExpression:\n    findConstantAndWatchExpressions(ast.argument, $filter);\n    ast.constant = ast.argument.constant;\n    ast.toWatch = ast.argument.toWatch;\n    break;\n  case AST.BinaryExpression:\n    findConstantAndWatchExpressions(ast.left, $filter);\n    findConstantAndWatchExpressions(ast.right, $filter);\n    ast.constant = ast.left.constant && ast.right.constant;\n    ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);\n    break;\n  case AST.LogicalExpression:\n    findConstantAndWatchExpressions(ast.left, $filter);\n    findConstantAndWatchExpressions(ast.right, $filter);\n    ast.constant = ast.left.constant && ast.right.constant;\n    ast.toWatch = ast.constant ? [] : [ast];\n    break;\n  case AST.ConditionalExpression:\n    findConstantAndWatchExpressions(ast.test, $filter);\n    findConstantAndWatchExpressions(ast.alternate, $filter);\n    findConstantAndWatchExpressions(ast.consequent, $filter);\n    ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;\n    ast.toWatch = ast.constant ? [] : [ast];\n    break;\n  case AST.Identifier:\n    ast.constant = false;\n    ast.toWatch = [ast];\n    break;\n  case AST.MemberExpression:\n    findConstantAndWatchExpressions(ast.object, $filter);\n    if (ast.computed) {\n      findConstantAndWatchExpressions(ast.property, $filter);\n    }\n    ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);\n    ast.toWatch = [ast];\n    break;\n  case AST.CallExpression:\n    allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;\n    argsToWatch = [];\n    forEach(ast.arguments, function(expr) {\n      findConstantAndWatchExpressions(expr, $filter);\n      allConstants = allConstants && expr.constant;\n      if (!expr.constant) {\n        argsToWatch.push.apply(argsToWatch, expr.toWatch);\n      }\n    });\n    ast.constant = allConstants;\n    ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];\n    break;\n  case AST.AssignmentExpression:\n    findConstantAndWatchExpressions(ast.left, $filter);\n    findConstantAndWatchExpressions(ast.right, $filter);\n    ast.constant = ast.left.constant && ast.right.constant;\n    ast.toWatch = [ast];\n    break;\n  case AST.ArrayExpression:\n    allConstants = true;\n    argsToWatch = [];\n    forEach(ast.elements, function(expr) {\n      findConstantAndWatchExpressions(expr, $filter);\n      allConstants = allConstants && expr.constant;\n      if (!expr.constant) {\n        argsToWatch.push.apply(argsToWatch, expr.toWatch);\n      }\n    });\n    ast.constant = allConstants;\n    ast.toWatch = argsToWatch;\n    break;\n  case AST.ObjectExpression:\n    allConstants = true;\n    argsToWatch = [];\n    forEach(ast.properties, function(property) {\n      findConstantAndWatchExpressions(property.value, $filter);\n      allConstants = allConstants && property.value.constant;\n      if (!property.value.constant) {\n        argsToWatch.push.apply(argsToWatch, property.value.toWatch);\n      }\n    });\n    ast.constant = allConstants;\n    ast.toWatch = argsToWatch;\n    break;\n  case AST.ThisExpression:\n    ast.constant = false;\n    ast.toWatch = [];\n    break;\n  }\n}\n\nfunction getInputs(body) {\n  if (body.length != 1) return;\n  var lastExpression = body[0].expression;\n  var candidate = lastExpression.toWatch;\n  if (candidate.length !== 1) return candidate;\n  return candidate[0] !== lastExpression ? candidate : undefined;\n}\n\nfunction isAssignable(ast) {\n  return ast.type === AST.Identifier || ast.type === AST.MemberExpression;\n}\n\nfunction assignableAST(ast) {\n  if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {\n    return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};\n  }\n}\n\nfunction isLiteral(ast) {\n  return ast.body.length === 0 ||\n      ast.body.length === 1 && (\n      ast.body[0].expression.type === AST.Literal ||\n      ast.body[0].expression.type === AST.ArrayExpression ||\n      ast.body[0].expression.type === AST.ObjectExpression);\n}\n\nfunction isConstant(ast) {\n  return ast.constant;\n}\n\nfunction ASTCompiler(astBuilder, $filter) {\n  this.astBuilder = astBuilder;\n  this.$filter = $filter;\n}\n\nASTCompiler.prototype = {\n  compile: function(expression, expensiveChecks) {\n    var self = this;\n    var ast = this.astBuilder.ast(expression);\n    this.state = {\n      nextId: 0,\n      filters: {},\n      expensiveChecks: expensiveChecks,\n      fn: {vars: [], body: [], own: {}},\n      assign: {vars: [], body: [], own: {}},\n      inputs: []\n    };\n    findConstantAndWatchExpressions(ast, self.$filter);\n    var extra = '';\n    var assignable;\n    this.stage = 'assign';\n    if ((assignable = assignableAST(ast))) {\n      this.state.computing = 'assign';\n      var result = this.nextId();\n      this.recurse(assignable, result);\n      extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');\n    }\n    var toWatch = getInputs(ast.body);\n    self.stage = 'inputs';\n    forEach(toWatch, function(watch, key) {\n      var fnKey = 'fn' + key;\n      self.state[fnKey] = {vars: [], body: [], own: {}};\n      self.state.computing = fnKey;\n      var intoId = self.nextId();\n      self.recurse(watch, intoId);\n      self.return_(intoId);\n      self.state.inputs.push(fnKey);\n      watch.watchId = key;\n    });\n    this.state.computing = 'fn';\n    this.stage = 'main';\n    this.recurse(ast);\n    var fnString =\n      // The build and minification steps remove the string \"use strict\" from the code, but this is done using a regex.\n      // This is a workaround for this until we do a better job at only removing the prefix only when we should.\n      '\"' + this.USE + ' ' + this.STRICT + '\";\\n' +\n      this.filterPrefix() +\n      'var fn=' + this.generateFunction('fn', 's,l,a,i') +\n      extra +\n      this.watchFns() +\n      'return fn;';\n\n    /* jshint -W054 */\n    var fn = (new Function('$filter',\n        'ensureSafeMemberName',\n        'ensureSafeObject',\n        'ensureSafeFunction',\n        'ifDefined',\n        'plus',\n        'text',\n        fnString))(\n          this.$filter,\n          ensureSafeMemberName,\n          ensureSafeObject,\n          ensureSafeFunction,\n          ifDefined,\n          plusFn,\n          expression);\n    /* jshint +W054 */\n    this.state = this.stage = undefined;\n    fn.literal = isLiteral(ast);\n    fn.constant = isConstant(ast);\n    return fn;\n  },\n\n  USE: 'use',\n\n  STRICT: 'strict',\n\n  watchFns: function() {\n    var result = [];\n    var fns = this.state.inputs;\n    var self = this;\n    forEach(fns, function(name) {\n      result.push('var ' + name + '=' + self.generateFunction(name, 's'));\n    });\n    if (fns.length) {\n      result.push('fn.inputs=[' + fns.join(',') + '];');\n    }\n    return result.join('');\n  },\n\n  generateFunction: function(name, params) {\n    return 'function(' + params + '){' +\n        this.varsPrefix(name) +\n        this.body(name) +\n        '};';\n  },\n\n  filterPrefix: function() {\n    var parts = [];\n    var self = this;\n    forEach(this.state.filters, function(id, filter) {\n      parts.push(id + '=$filter(' + self.escape(filter) + ')');\n    });\n    if (parts.length) return 'var ' + parts.join(',') + ';';\n    return '';\n  },\n\n  varsPrefix: function(section) {\n    return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';\n  },\n\n  body: function(section) {\n    return this.state[section].body.join('');\n  },\n\n  recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n    var left, right, self = this, args, expression;\n    recursionFn = recursionFn || noop;\n    if (!skipWatchIdCheck && isDefined(ast.watchId)) {\n      intoId = intoId || this.nextId();\n      this.if_('i',\n        this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),\n        this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)\n      );\n      return;\n    }\n    switch (ast.type) {\n    case AST.Program:\n      forEach(ast.body, function(expression, pos) {\n        self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });\n        if (pos !== ast.body.length - 1) {\n          self.current().body.push(right, ';');\n        } else {\n          self.return_(right);\n        }\n      });\n      break;\n    case AST.Literal:\n      expression = this.escape(ast.value);\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.UnaryExpression:\n      this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });\n      expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.BinaryExpression:\n      this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });\n      this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });\n      if (ast.operator === '+') {\n        expression = this.plus(left, right);\n      } else if (ast.operator === '-') {\n        expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);\n      } else {\n        expression = '(' + left + ')' + ast.operator + '(' + right + ')';\n      }\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.LogicalExpression:\n      intoId = intoId || this.nextId();\n      self.recurse(ast.left, intoId);\n      self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));\n      recursionFn(intoId);\n      break;\n    case AST.ConditionalExpression:\n      intoId = intoId || this.nextId();\n      self.recurse(ast.test, intoId);\n      self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));\n      recursionFn(intoId);\n      break;\n    case AST.Identifier:\n      intoId = intoId || this.nextId();\n      if (nameId) {\n        nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');\n        nameId.computed = false;\n        nameId.name = ast.name;\n      }\n      ensureSafeMemberName(ast.name);\n      self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),\n        function() {\n          self.if_(self.stage === 'inputs' || 's', function() {\n            if (create && create !== 1) {\n              self.if_(\n                self.not(self.nonComputedMember('s', ast.name)),\n                self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));\n            }\n            self.assign(intoId, self.nonComputedMember('s', ast.name));\n          });\n        }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))\n        );\n      if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {\n        self.addEnsureSafeObject(intoId);\n      }\n      recursionFn(intoId);\n      break;\n    case AST.MemberExpression:\n      left = nameId && (nameId.context = this.nextId()) || this.nextId();\n      intoId = intoId || this.nextId();\n      self.recurse(ast.object, left, undefined, function() {\n        self.if_(self.notNull(left), function() {\n          if (ast.computed) {\n            right = self.nextId();\n            self.recurse(ast.property, right);\n            self.addEnsureSafeMemberName(right);\n            if (create && create !== 1) {\n              self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));\n            }\n            expression = self.ensureSafeObject(self.computedMember(left, right));\n            self.assign(intoId, expression);\n            if (nameId) {\n              nameId.computed = true;\n              nameId.name = right;\n            }\n          } else {\n            ensureSafeMemberName(ast.property.name);\n            if (create && create !== 1) {\n              self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));\n            }\n            expression = self.nonComputedMember(left, ast.property.name);\n            if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {\n              expression = self.ensureSafeObject(expression);\n            }\n            self.assign(intoId, expression);\n            if (nameId) {\n              nameId.computed = false;\n              nameId.name = ast.property.name;\n            }\n          }\n        }, function() {\n          self.assign(intoId, 'undefined');\n        });\n        recursionFn(intoId);\n      }, !!create);\n      break;\n    case AST.CallExpression:\n      intoId = intoId || this.nextId();\n      if (ast.filter) {\n        right = self.filter(ast.callee.name);\n        args = [];\n        forEach(ast.arguments, function(expr) {\n          var argument = self.nextId();\n          self.recurse(expr, argument);\n          args.push(argument);\n        });\n        expression = right + '(' + args.join(',') + ')';\n        self.assign(intoId, expression);\n        recursionFn(intoId);\n      } else {\n        right = self.nextId();\n        left = {};\n        args = [];\n        self.recurse(ast.callee, right, left, function() {\n          self.if_(self.notNull(right), function() {\n            self.addEnsureSafeFunction(right);\n            forEach(ast.arguments, function(expr) {\n              self.recurse(expr, self.nextId(), undefined, function(argument) {\n                args.push(self.ensureSafeObject(argument));\n              });\n            });\n            if (left.name) {\n              if (!self.state.expensiveChecks) {\n                self.addEnsureSafeObject(left.context);\n              }\n              expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';\n            } else {\n              expression = right + '(' + args.join(',') + ')';\n            }\n            expression = self.ensureSafeObject(expression);\n            self.assign(intoId, expression);\n          }, function() {\n            self.assign(intoId, 'undefined');\n          });\n          recursionFn(intoId);\n        });\n      }\n      break;\n    case AST.AssignmentExpression:\n      right = this.nextId();\n      left = {};\n      if (!isAssignable(ast.left)) {\n        throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');\n      }\n      this.recurse(ast.left, undefined, left, function() {\n        self.if_(self.notNull(left.context), function() {\n          self.recurse(ast.right, right);\n          self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));\n          expression = self.member(left.context, left.name, left.computed) + ast.operator + right;\n          self.assign(intoId, expression);\n          recursionFn(intoId || expression);\n        });\n      }, 1);\n      break;\n    case AST.ArrayExpression:\n      args = [];\n      forEach(ast.elements, function(expr) {\n        self.recurse(expr, self.nextId(), undefined, function(argument) {\n          args.push(argument);\n        });\n      });\n      expression = '[' + args.join(',') + ']';\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.ObjectExpression:\n      args = [];\n      forEach(ast.properties, function(property) {\n        self.recurse(property.value, self.nextId(), undefined, function(expr) {\n          args.push(self.escape(\n              property.key.type === AST.Identifier ? property.key.name :\n                ('' + property.key.value)) +\n              ':' + expr);\n        });\n      });\n      expression = '{' + args.join(',') + '}';\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.ThisExpression:\n      this.assign(intoId, 's');\n      recursionFn('s');\n      break;\n    case AST.NGValueParameter:\n      this.assign(intoId, 'v');\n      recursionFn('v');\n      break;\n    }\n  },\n\n  getHasOwnProperty: function(element, property) {\n    var key = element + '.' + property;\n    var own = this.current().own;\n    if (!own.hasOwnProperty(key)) {\n      own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');\n    }\n    return own[key];\n  },\n\n  assign: function(id, value) {\n    if (!id) return;\n    this.current().body.push(id, '=', value, ';');\n    return id;\n  },\n\n  filter: function(filterName) {\n    if (!this.state.filters.hasOwnProperty(filterName)) {\n      this.state.filters[filterName] = this.nextId(true);\n    }\n    return this.state.filters[filterName];\n  },\n\n  ifDefined: function(id, defaultValue) {\n    return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';\n  },\n\n  plus: function(left, right) {\n    return 'plus(' + left + ',' + right + ')';\n  },\n\n  return_: function(id) {\n    this.current().body.push('return ', id, ';');\n  },\n\n  if_: function(test, alternate, consequent) {\n    if (test === true) {\n      alternate();\n    } else {\n      var body = this.current().body;\n      body.push('if(', test, '){');\n      alternate();\n      body.push('}');\n      if (consequent) {\n        body.push('else{');\n        consequent();\n        body.push('}');\n      }\n    }\n  },\n\n  not: function(expression) {\n    return '!(' + expression + ')';\n  },\n\n  notNull: function(expression) {\n    return expression + '!=null';\n  },\n\n  nonComputedMember: function(left, right) {\n    return left + '.' + right;\n  },\n\n  computedMember: function(left, right) {\n    return left + '[' + right + ']';\n  },\n\n  member: function(left, right, computed) {\n    if (computed) return this.computedMember(left, right);\n    return this.nonComputedMember(left, right);\n  },\n\n  addEnsureSafeObject: function(item) {\n    this.current().body.push(this.ensureSafeObject(item), ';');\n  },\n\n  addEnsureSafeMemberName: function(item) {\n    this.current().body.push(this.ensureSafeMemberName(item), ';');\n  },\n\n  addEnsureSafeFunction: function(item) {\n    this.current().body.push(this.ensureSafeFunction(item), ';');\n  },\n\n  ensureSafeObject: function(item) {\n    return 'ensureSafeObject(' + item + ',text)';\n  },\n\n  ensureSafeMemberName: function(item) {\n    return 'ensureSafeMemberName(' + item + ',text)';\n  },\n\n  ensureSafeFunction: function(item) {\n    return 'ensureSafeFunction(' + item + ',text)';\n  },\n\n  lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n    var self = this;\n    return function() {\n      self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);\n    };\n  },\n\n  lazyAssign: function(id, value) {\n    var self = this;\n    return function() {\n      self.assign(id, value);\n    };\n  },\n\n  stringEscapeRegex: /[^ a-zA-Z0-9]/g,\n\n  stringEscapeFn: function(c) {\n    return '\\\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);\n  },\n\n  escape: function(value) {\n    if (isString(value)) return \"'\" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + \"'\";\n    if (isNumber(value)) return value.toString();\n    if (value === true) return 'true';\n    if (value === false) return 'false';\n    if (value === null) return 'null';\n    if (typeof value === 'undefined') return 'undefined';\n\n    throw $parseMinErr('esc', 'IMPOSSIBLE');\n  },\n\n  nextId: function(skip, init) {\n    var id = 'v' + (this.state.nextId++);\n    if (!skip) {\n      this.current().vars.push(id + (init ? '=' + init : ''));\n    }\n    return id;\n  },\n\n  current: function() {\n    return this.state[this.state.computing];\n  }\n};\n\n\nfunction ASTInterpreter(astBuilder, $filter) {\n  this.astBuilder = astBuilder;\n  this.$filter = $filter;\n}\n\nASTInterpreter.prototype = {\n  compile: function(expression, expensiveChecks) {\n    var self = this;\n    var ast = this.astBuilder.ast(expression);\n    this.expression = expression;\n    this.expensiveChecks = expensiveChecks;\n    findConstantAndWatchExpressions(ast, self.$filter);\n    var assignable;\n    var assign;\n    if ((assignable = assignableAST(ast))) {\n      assign = this.recurse(assignable);\n    }\n    var toWatch = getInputs(ast.body);\n    var inputs;\n    if (toWatch) {\n      inputs = [];\n      forEach(toWatch, function(watch, key) {\n        var input = self.recurse(watch);\n        watch.input = input;\n        inputs.push(input);\n        watch.watchId = key;\n      });\n    }\n    var expressions = [];\n    forEach(ast.body, function(expression) {\n      expressions.push(self.recurse(expression.expression));\n    });\n    var fn = ast.body.length === 0 ? function() {} :\n             ast.body.length === 1 ? expressions[0] :\n             function(scope, locals) {\n               var lastValue;\n               forEach(expressions, function(exp) {\n                 lastValue = exp(scope, locals);\n               });\n               return lastValue;\n             };\n    if (assign) {\n      fn.assign = function(scope, value, locals) {\n        return assign(scope, locals, value);\n      };\n    }\n    if (inputs) {\n      fn.inputs = inputs;\n    }\n    fn.literal = isLiteral(ast);\n    fn.constant = isConstant(ast);\n    return fn;\n  },\n\n  recurse: function(ast, context, create) {\n    var left, right, self = this, args, expression;\n    if (ast.input) {\n      return this.inputs(ast.input, ast.watchId);\n    }\n    switch (ast.type) {\n    case AST.Literal:\n      return this.value(ast.value, context);\n    case AST.UnaryExpression:\n      right = this.recurse(ast.argument);\n      return this['unary' + ast.operator](right, context);\n    case AST.BinaryExpression:\n      left = this.recurse(ast.left);\n      right = this.recurse(ast.right);\n      return this['binary' + ast.operator](left, right, context);\n    case AST.LogicalExpression:\n      left = this.recurse(ast.left);\n      right = this.recurse(ast.right);\n      return this['binary' + ast.operator](left, right, context);\n    case AST.ConditionalExpression:\n      return this['ternary?:'](\n        this.recurse(ast.test),\n        this.recurse(ast.alternate),\n        this.recurse(ast.consequent),\n        context\n      );\n    case AST.Identifier:\n      ensureSafeMemberName(ast.name, self.expression);\n      return self.identifier(ast.name,\n                             self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),\n                             context, create, self.expression);\n    case AST.MemberExpression:\n      left = this.recurse(ast.object, false, !!create);\n      if (!ast.computed) {\n        ensureSafeMemberName(ast.property.name, self.expression);\n        right = ast.property.name;\n      }\n      if (ast.computed) right = this.recurse(ast.property);\n      return ast.computed ?\n        this.computedMember(left, right, context, create, self.expression) :\n        this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);\n    case AST.CallExpression:\n      args = [];\n      forEach(ast.arguments, function(expr) {\n        args.push(self.recurse(expr));\n      });\n      if (ast.filter) right = this.$filter(ast.callee.name);\n      if (!ast.filter) right = this.recurse(ast.callee, true);\n      return ast.filter ?\n        function(scope, locals, assign, inputs) {\n          var values = [];\n          for (var i = 0; i < args.length; ++i) {\n            values.push(args[i](scope, locals, assign, inputs));\n          }\n          var value = right.apply(undefined, values, inputs);\n          return context ? {context: undefined, name: undefined, value: value} : value;\n        } :\n        function(scope, locals, assign, inputs) {\n          var rhs = right(scope, locals, assign, inputs);\n          var value;\n          if (rhs.value != null) {\n            ensureSafeObject(rhs.context, self.expression);\n            ensureSafeFunction(rhs.value, self.expression);\n            var values = [];\n            for (var i = 0; i < args.length; ++i) {\n              values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));\n            }\n            value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);\n          }\n          return context ? {value: value} : value;\n        };\n    case AST.AssignmentExpression:\n      left = this.recurse(ast.left, true, 1);\n      right = this.recurse(ast.right);\n      return function(scope, locals, assign, inputs) {\n        var lhs = left(scope, locals, assign, inputs);\n        var rhs = right(scope, locals, assign, inputs);\n        ensureSafeObject(lhs.value, self.expression);\n        lhs.context[lhs.name] = rhs;\n        return context ? {value: rhs} : rhs;\n      };\n    case AST.ArrayExpression:\n      args = [];\n      forEach(ast.elements, function(expr) {\n        args.push(self.recurse(expr));\n      });\n      return function(scope, locals, assign, inputs) {\n        var value = [];\n        for (var i = 0; i < args.length; ++i) {\n          value.push(args[i](scope, locals, assign, inputs));\n        }\n        return context ? {value: value} : value;\n      };\n    case AST.ObjectExpression:\n      args = [];\n      forEach(ast.properties, function(property) {\n        args.push({key: property.key.type === AST.Identifier ?\n                        property.key.name :\n                        ('' + property.key.value),\n                   value: self.recurse(property.value)\n        });\n      });\n      return function(scope, locals, assign, inputs) {\n        var value = {};\n        for (var i = 0; i < args.length; ++i) {\n          value[args[i].key] = args[i].value(scope, locals, assign, inputs);\n        }\n        return context ? {value: value} : value;\n      };\n    case AST.ThisExpression:\n      return function(scope) {\n        return context ? {value: scope} : scope;\n      };\n    case AST.NGValueParameter:\n      return function(scope, locals, assign, inputs) {\n        return context ? {value: assign} : assign;\n      };\n    }\n  },\n\n  'unary+': function(argument, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = argument(scope, locals, assign, inputs);\n      if (isDefined(arg)) {\n        arg = +arg;\n      } else {\n        arg = 0;\n      }\n      return context ? {value: arg} : arg;\n    };\n  },\n  'unary-': function(argument, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = argument(scope, locals, assign, inputs);\n      if (isDefined(arg)) {\n        arg = -arg;\n      } else {\n        arg = 0;\n      }\n      return context ? {value: arg} : arg;\n    };\n  },\n  'unary!': function(argument, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = !argument(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary+': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      var rhs = right(scope, locals, assign, inputs);\n      var arg = plusFn(lhs, rhs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary-': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      var rhs = right(scope, locals, assign, inputs);\n      var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary*': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary/': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary%': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary===': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary!==': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary==': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary!=': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary<': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary>': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary<=': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary>=': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary&&': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary||': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'ternary?:': function(test, alternate, consequent, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  value: function(value, context) {\n    return function() { return context ? {context: undefined, name: undefined, value: value} : value; };\n  },\n  identifier: function(name, expensiveChecks, context, create, expression) {\n    return function(scope, locals, assign, inputs) {\n      var base = locals && (name in locals) ? locals : scope;\n      if (create && create !== 1 && base && !(base[name])) {\n        base[name] = {};\n      }\n      var value = base ? base[name] : undefined;\n      if (expensiveChecks) {\n        ensureSafeObject(value, expression);\n      }\n      if (context) {\n        return {context: base, name: name, value: value};\n      } else {\n        return value;\n      }\n    };\n  },\n  computedMember: function(left, right, context, create, expression) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      var rhs;\n      var value;\n      if (lhs != null) {\n        rhs = right(scope, locals, assign, inputs);\n        ensureSafeMemberName(rhs, expression);\n        if (create && create !== 1 && lhs && !(lhs[rhs])) {\n          lhs[rhs] = {};\n        }\n        value = lhs[rhs];\n        ensureSafeObject(value, expression);\n      }\n      if (context) {\n        return {context: lhs, name: rhs, value: value};\n      } else {\n        return value;\n      }\n    };\n  },\n  nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      if (create && create !== 1 && lhs && !(lhs[right])) {\n        lhs[right] = {};\n      }\n      var value = lhs != null ? lhs[right] : undefined;\n      if (expensiveChecks || isPossiblyDangerousMemberName(right)) {\n        ensureSafeObject(value, expression);\n      }\n      if (context) {\n        return {context: lhs, name: right, value: value};\n      } else {\n        return value;\n      }\n    };\n  },\n  inputs: function(input, watchId) {\n    return function(scope, value, locals, inputs) {\n      if (inputs) return inputs[watchId];\n      return input(scope, value, locals);\n    };\n  }\n};\n\n/**\n * @constructor\n */\nvar Parser = function(lexer, $filter, options) {\n  this.lexer = lexer;\n  this.$filter = $filter;\n  this.options = options;\n  this.ast = new AST(this.lexer);\n  this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :\n                                   new ASTCompiler(this.ast, $filter);\n};\n\nParser.prototype = {\n  constructor: Parser,\n\n  parse: function(text) {\n    return this.astCompiler.compile(text, this.options.expensiveChecks);\n  }\n};\n\nvar getterFnCacheDefault = createMap();\nvar getterFnCacheExpensive = createMap();\n\nfunction isPossiblyDangerousMemberName(name) {\n  return name == 'constructor';\n}\n\nvar objectValueOf = Object.prototype.valueOf;\n\nfunction getValueOf(value) {\n  return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);\n}\n\n///////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $parse\n * @kind function\n *\n * @description\n *\n * Converts Angular {@link guide/expression expression} into a function.\n *\n * ```js\n *   var getter = $parse('user.name');\n *   var setter = getter.assign;\n *   var context = {user:{name:'angular'}};\n *   var locals = {user:{name:'local'}};\n *\n *   expect(getter(context)).toEqual('angular');\n *   setter(context, 'newValue');\n *   expect(context.user.name).toEqual('newValue');\n *   expect(getter(context, locals)).toEqual('local');\n * ```\n *\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n *      are evaluated against (typically a scope object).\n *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n *      `context`.\n *\n *    The returned function also has the following properties:\n *      * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript\n *        literal.\n *      * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript\n *        constant literals.\n *      * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be\n *        set to a function to change its value on the given context.\n *\n */\n\n\n/**\n * @ngdoc provider\n * @name $parseProvider\n *\n * @description\n * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}\n *  service.\n */\nfunction $ParseProvider() {\n  var cacheDefault = createMap();\n  var cacheExpensive = createMap();\n\n  this.$get = ['$filter', function($filter) {\n    var noUnsafeEval = csp().noUnsafeEval;\n    var $parseOptions = {\n          csp: noUnsafeEval,\n          expensiveChecks: false\n        },\n        $parseOptionsExpensive = {\n          csp: noUnsafeEval,\n          expensiveChecks: true\n        };\n\n    return function $parse(exp, interceptorFn, expensiveChecks) {\n      var parsedExpression, oneTime, cacheKey;\n\n      switch (typeof exp) {\n        case 'string':\n          exp = exp.trim();\n          cacheKey = exp;\n\n          var cache = (expensiveChecks ? cacheExpensive : cacheDefault);\n          parsedExpression = cache[cacheKey];\n\n          if (!parsedExpression) {\n            if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {\n              oneTime = true;\n              exp = exp.substring(2);\n            }\n            var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;\n            var lexer = new Lexer(parseOptions);\n            var parser = new Parser(lexer, $filter, parseOptions);\n            parsedExpression = parser.parse(exp);\n            if (parsedExpression.constant) {\n              parsedExpression.$$watchDelegate = constantWatchDelegate;\n            } else if (oneTime) {\n              parsedExpression.$$watchDelegate = parsedExpression.literal ?\n                  oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;\n            } else if (parsedExpression.inputs) {\n              parsedExpression.$$watchDelegate = inputsWatchDelegate;\n            }\n            cache[cacheKey] = parsedExpression;\n          }\n          return addInterceptor(parsedExpression, interceptorFn);\n\n        case 'function':\n          return addInterceptor(exp, interceptorFn);\n\n        default:\n          return noop;\n      }\n    };\n\n    function expressionInputDirtyCheck(newValue, oldValueOfValue) {\n\n      if (newValue == null || oldValueOfValue == null) { // null/undefined\n        return newValue === oldValueOfValue;\n      }\n\n      if (typeof newValue === 'object') {\n\n        // attempt to convert the value to a primitive type\n        // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can\n        //             be cheaply dirty-checked\n        newValue = getValueOf(newValue);\n\n        if (typeof newValue === 'object') {\n          // objects/arrays are not supported - deep-watching them would be too expensive\n          return false;\n        }\n\n        // fall-through to the primitive equality check\n      }\n\n      //Primitive or NaN\n      return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);\n    }\n\n    function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {\n      var inputExpressions = parsedExpression.inputs;\n      var lastResult;\n\n      if (inputExpressions.length === 1) {\n        var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails\n        inputExpressions = inputExpressions[0];\n        return scope.$watch(function expressionInputWatch(scope) {\n          var newInputValue = inputExpressions(scope);\n          if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {\n            lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);\n            oldInputValueOf = newInputValue && getValueOf(newInputValue);\n          }\n          return lastResult;\n        }, listener, objectEquality, prettyPrintExpression);\n      }\n\n      var oldInputValueOfValues = [];\n      var oldInputValues = [];\n      for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n        oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails\n        oldInputValues[i] = null;\n      }\n\n      return scope.$watch(function expressionInputsWatch(scope) {\n        var changed = false;\n\n        for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n          var newInputValue = inputExpressions[i](scope);\n          if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {\n            oldInputValues[i] = newInputValue;\n            oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\n          }\n        }\n\n        if (changed) {\n          lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);\n        }\n\n        return lastResult;\n      }, listener, objectEquality, prettyPrintExpression);\n    }\n\n    function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        if (isDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isDefined(lastValue)) {\n              unwatch();\n            }\n          });\n        }\n      }, objectEquality);\n    }\n\n    function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.call(this, value, old, scope);\n        }\n        if (isAllDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isAllDefined(lastValue)) unwatch();\n          });\n        }\n      }, objectEquality);\n\n      function isAllDefined(value) {\n        var allDefined = true;\n        forEach(value, function(val) {\n          if (!isDefined(val)) allDefined = false;\n        });\n        return allDefined;\n      }\n    }\n\n    function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch;\n      return unwatch = scope.$watch(function constantWatch(scope) {\n        return parsedExpression(scope);\n      }, function constantListener(value, old, scope) {\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        unwatch();\n      }, objectEquality);\n    }\n\n    function addInterceptor(parsedExpression, interceptorFn) {\n      if (!interceptorFn) return parsedExpression;\n      var watchDelegate = parsedExpression.$$watchDelegate;\n\n      var regularWatch =\n          watchDelegate !== oneTimeLiteralWatchDelegate &&\n          watchDelegate !== oneTimeWatchDelegate;\n\n      var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {\n        var value = parsedExpression(scope, locals, assign, inputs);\n        return interceptorFn(value, scope, locals);\n      } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {\n        var value = parsedExpression(scope, locals, assign, inputs);\n        var result = interceptorFn(value, scope, locals);\n        // we only return the interceptor's result if the\n        // initial value is defined (for bind-once)\n        return isDefined(value) ? result : value;\n      };\n\n      // Propagate $$watchDelegates other then inputsWatchDelegate\n      if (parsedExpression.$$watchDelegate &&\n          parsedExpression.$$watchDelegate !== inputsWatchDelegate) {\n        fn.$$watchDelegate = parsedExpression.$$watchDelegate;\n      } else if (!interceptorFn.$stateful) {\n        // If there is an interceptor, but no watchDelegate then treat the interceptor like\n        // we treat filters - it is assumed to be a pure function unless flagged with $stateful\n        fn.$$watchDelegate = inputsWatchDelegate;\n        fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];\n      }\n\n      return fn;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $q\n * @requires $rootScope\n *\n * @description\n * A service that helps you run functions asynchronously, and use their return values (or exceptions)\n * when they are done processing.\n *\n * This is an implementation of promises/deferred objects inspired by\n * [Kris Kowal's Q](https://github.com/kriskowal/q).\n *\n * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred\n * implementations, and the other which resembles ES6 promises to some degree.\n *\n * # $q constructor\n *\n * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`\n * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,\n * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n *\n * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are\n * available yet.\n *\n * It can be used like so:\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     // perform some asynchronous operation, resolve or reject the promise when appropriate.\n *     return $q(function(resolve, reject) {\n *       setTimeout(function() {\n *         if (okToGreet(name)) {\n *           resolve('Hello, ' + name + '!');\n *         } else {\n *           reject('Greeting ' + name + ' is not allowed.');\n *         }\n *       }, 1000);\n *     });\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   });\n * ```\n *\n * Note: progress/notify callbacks are not currently supported via the ES6-style interface.\n *\n * However, the more traditional CommonJS-style usage is still available, and documented below.\n *\n * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an\n * interface for interacting with an object that represents the result of an action that is\n * performed asynchronously, and may or may not be finished at any given point in time.\n *\n * From the perspective of dealing with error handling, deferred and promise APIs are to\n * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     var deferred = $q.defer();\n *\n *     setTimeout(function() {\n *       deferred.notify('About to greet ' + name + '.');\n *\n *       if (okToGreet(name)) {\n *         deferred.resolve('Hello, ' + name + '!');\n *       } else {\n *         deferred.reject('Greeting ' + name + ' is not allowed.');\n *       }\n *     }, 1000);\n *\n *     return deferred.promise;\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   }, function(update) {\n *     alert('Got notification: ' + update);\n *   });\n * ```\n *\n * At first it might not be obvious why this extra complexity is worth the trouble. The payoff\n * comes in the way of guarantees that promise and deferred APIs make, see\n * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.\n *\n * Additionally the promise api allows for composition that is very hard to do with the\n * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.\n * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the\n * section on serial or parallel joining of promises.\n *\n * # The Deferred API\n *\n * A new instance of deferred is constructed by calling `$q.defer()`.\n *\n * The purpose of the deferred object is to expose the associated Promise instance as well as APIs\n * that can be used for signaling the successful or unsuccessful completion, as well as the status\n * of the task.\n *\n * **Methods**\n *\n * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection\n *   constructed via `$q.reject`, the promise will be rejected instead.\n * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to\n *   resolving it with a rejection constructed via `$q.reject`.\n * - `notify(value)` - provides updates on the status of the promise's execution. This may be called\n *   multiple times before the promise is either resolved or rejected.\n *\n * **Properties**\n *\n * - promise – `{Promise}` – promise object associated with this deferred.\n *\n *\n * # The Promise API\n *\n * A new promise instance is created when a deferred instance is created and can be retrieved by\n * calling `deferred.promise`.\n *\n * The purpose of the promise object is to allow for interested parties to get access to the result\n * of the deferred task when it completes.\n *\n * **Methods**\n *\n * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or\n *   will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously\n *   as soon as the result is available. The callbacks are called with a single argument: the result\n *   or rejection reason. Additionally, the notify callback may be called zero or more times to\n *   provide a progress indication, before the promise is resolved or rejected.\n *\n *   This method *returns a new promise* which is resolved or rejected via the return value of the\n *   `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved\n *   with the value which is resolved in that promise using\n *   [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).\n *   It also notifies via the return value of the `notifyCallback` method. The promise cannot be\n *   resolved or rejected from the notifyCallback method.\n *\n * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`\n *\n * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,\n *   but to do so without modifying the final value. This is useful to release resources or do some\n *   clean-up that needs to be done whether the promise was rejected or resolved. See the [full\n *   specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for\n *   more information.\n *\n * # Chaining promises\n *\n * Because calling the `then` method of a promise returns a new derived promise, it is easily\n * possible to create a chain of promises:\n *\n * ```js\n *   promiseB = promiseA.then(function(result) {\n *     return result + 1;\n *   });\n *\n *   // promiseB will be resolved immediately after promiseA is resolved and its value\n *   // will be the result of promiseA incremented by 1\n * ```\n *\n * It is possible to create chains of any length and since a promise can be resolved with another\n * promise (which will defer its resolution further), it is possible to pause/defer resolution of\n * the promises at any point in the chain. This makes it possible to implement powerful APIs like\n * $http's response interceptors.\n *\n *\n * # Differences between Kris Kowal's Q and $q\n *\n *  There are two main differences:\n *\n * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation\n *   mechanism in angular, which means faster propagation of resolution or rejection into your\n *   models and avoiding unnecessary browser repaints, which would result in flickering UI.\n * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains\n *   all the important functionality needed for common async tasks.\n *\n *  # Testing\n *\n *  ```js\n *    it('should simulate promise', inject(function($q, $rootScope) {\n *      var deferred = $q.defer();\n *      var promise = deferred.promise;\n *      var resolvedValue;\n *\n *      promise.then(function(value) { resolvedValue = value; });\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Simulate resolving of promise\n *      deferred.resolve(123);\n *      // Note that the 'then' function does not get called synchronously.\n *      // This is because we want the promise API to always be async, whether or not\n *      // it got called synchronously or asynchronously.\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Propagate promise resolution to 'then' functions using $apply().\n *      $rootScope.$apply();\n *      expect(resolvedValue).toEqual(123);\n *    }));\n *  ```\n *\n * @param {function(function, function)} resolver Function which is responsible for resolving or\n *   rejecting the newly created promise. The first parameter is a function which resolves the\n *   promise, the second parameter is a function which rejects the promise.\n *\n * @returns {Promise} The newly created promise.\n */\nfunction $QProvider() {\n\n  this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $rootScope.$evalAsync(callback);\n    }, $exceptionHandler);\n  }];\n}\n\nfunction $$QProvider() {\n  this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $browser.defer(callback);\n    }, $exceptionHandler);\n  }];\n}\n\n/**\n * Constructs a promise manager.\n *\n * @param {function(function)} nextTick Function for executing functions in the next turn.\n * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for\n *     debugging purposes.\n * @returns {object} Promise manager.\n */\nfunction qFactory(nextTick, exceptionHandler) {\n  var $qMinErr = minErr('$q', TypeError);\n  function callOnce(self, resolveFn, rejectFn) {\n    var called = false;\n    function wrap(fn) {\n      return function(value) {\n        if (called) return;\n        called = true;\n        fn.call(self, value);\n      };\n    }\n\n    return [wrap(resolveFn), wrap(rejectFn)];\n  }\n\n  /**\n   * @ngdoc method\n   * @name ng.$q#defer\n   * @kind function\n   *\n   * @description\n   * Creates a `Deferred` object which represents a task which will finish in the future.\n   *\n   * @returns {Deferred} Returns a new instance of deferred.\n   */\n  var defer = function() {\n    return new Deferred();\n  };\n\n  function Promise() {\n    this.$$state = { status: 0 };\n  }\n\n  extend(Promise.prototype, {\n    then: function(onFulfilled, onRejected, progressBack) {\n      if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {\n        return this;\n      }\n      var result = new Deferred();\n\n      this.$$state.pending = this.$$state.pending || [];\n      this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);\n      if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);\n\n      return result.promise;\n    },\n\n    \"catch\": function(callback) {\n      return this.then(null, callback);\n    },\n\n    \"finally\": function(callback, progressBack) {\n      return this.then(function(value) {\n        return handleCallback(value, true, callback);\n      }, function(error) {\n        return handleCallback(error, false, callback);\n      }, progressBack);\n    }\n  });\n\n  //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native\n  function simpleBind(context, fn) {\n    return function(value) {\n      fn.call(context, value);\n    };\n  }\n\n  function processQueue(state) {\n    var fn, deferred, pending;\n\n    pending = state.pending;\n    state.processScheduled = false;\n    state.pending = undefined;\n    for (var i = 0, ii = pending.length; i < ii; ++i) {\n      deferred = pending[i][0];\n      fn = pending[i][state.status];\n      try {\n        if (isFunction(fn)) {\n          deferred.resolve(fn(state.value));\n        } else if (state.status === 1) {\n          deferred.resolve(state.value);\n        } else {\n          deferred.reject(state.value);\n        }\n      } catch (e) {\n        deferred.reject(e);\n        exceptionHandler(e);\n      }\n    }\n  }\n\n  function scheduleProcessQueue(state) {\n    if (state.processScheduled || !state.pending) return;\n    state.processScheduled = true;\n    nextTick(function() { processQueue(state); });\n  }\n\n  function Deferred() {\n    this.promise = new Promise();\n    //Necessary to support unbound execution :/\n    this.resolve = simpleBind(this, this.resolve);\n    this.reject = simpleBind(this, this.reject);\n    this.notify = simpleBind(this, this.notify);\n  }\n\n  extend(Deferred.prototype, {\n    resolve: function(val) {\n      if (this.promise.$$state.status) return;\n      if (val === this.promise) {\n        this.$$reject($qMinErr(\n          'qcycle',\n          \"Expected promise to be resolved with value other than itself '{0}'\",\n          val));\n      } else {\n        this.$$resolve(val);\n      }\n\n    },\n\n    $$resolve: function(val) {\n      var then, fns;\n\n      fns = callOnce(this, this.$$resolve, this.$$reject);\n      try {\n        if ((isObject(val) || isFunction(val))) then = val && val.then;\n        if (isFunction(then)) {\n          this.promise.$$state.status = -1;\n          then.call(val, fns[0], fns[1], this.notify);\n        } else {\n          this.promise.$$state.value = val;\n          this.promise.$$state.status = 1;\n          scheduleProcessQueue(this.promise.$$state);\n        }\n      } catch (e) {\n        fns[1](e);\n        exceptionHandler(e);\n      }\n    },\n\n    reject: function(reason) {\n      if (this.promise.$$state.status) return;\n      this.$$reject(reason);\n    },\n\n    $$reject: function(reason) {\n      this.promise.$$state.value = reason;\n      this.promise.$$state.status = 2;\n      scheduleProcessQueue(this.promise.$$state);\n    },\n\n    notify: function(progress) {\n      var callbacks = this.promise.$$state.pending;\n\n      if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {\n        nextTick(function() {\n          var callback, result;\n          for (var i = 0, ii = callbacks.length; i < ii; i++) {\n            result = callbacks[i][0];\n            callback = callbacks[i][3];\n            try {\n              result.notify(isFunction(callback) ? callback(progress) : progress);\n            } catch (e) {\n              exceptionHandler(e);\n            }\n          }\n        });\n      }\n    }\n  });\n\n  /**\n   * @ngdoc method\n   * @name $q#reject\n   * @kind function\n   *\n   * @description\n   * Creates a promise that is resolved as rejected with the specified `reason`. This api should be\n   * used to forward rejection in a chain of promises. If you are dealing with the last promise in\n   * a promise chain, you don't need to worry about it.\n   *\n   * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of\n   * `reject` as the `throw` keyword in JavaScript. This also means that if you \"catch\" an error via\n   * a promise error callback and you want to forward the error to the promise derived from the\n   * current promise, you have to \"rethrow\" the error by returning a rejection constructed via\n   * `reject`.\n   *\n   * ```js\n   *   promiseB = promiseA.then(function(result) {\n   *     // success: do something and resolve promiseB\n   *     //          with the old or a new result\n   *     return result;\n   *   }, function(reason) {\n   *     // error: handle the error if possible and\n   *     //        resolve promiseB with newPromiseOrValue,\n   *     //        otherwise forward the rejection to promiseB\n   *     if (canHandle(reason)) {\n   *      // handle the error and recover\n   *      return newPromiseOrValue;\n   *     }\n   *     return $q.reject(reason);\n   *   });\n   * ```\n   *\n   * @param {*} reason Constant, message, exception or an object representing the rejection reason.\n   * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.\n   */\n  var reject = function(reason) {\n    var result = new Deferred();\n    result.reject(reason);\n    return result.promise;\n  };\n\n  var makePromise = function makePromise(value, resolved) {\n    var result = new Deferred();\n    if (resolved) {\n      result.resolve(value);\n    } else {\n      result.reject(value);\n    }\n    return result.promise;\n  };\n\n  var handleCallback = function handleCallback(value, isResolved, callback) {\n    var callbackOutput = null;\n    try {\n      if (isFunction(callback)) callbackOutput = callback();\n    } catch (e) {\n      return makePromise(e, false);\n    }\n    if (isPromiseLike(callbackOutput)) {\n      return callbackOutput.then(function() {\n        return makePromise(value, isResolved);\n      }, function(error) {\n        return makePromise(error, false);\n      });\n    } else {\n      return makePromise(value, isResolved);\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#when\n   * @kind function\n   *\n   * @description\n   * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.\n   * This is useful when you are dealing with an object that might or might not be a promise, or if\n   * the promise comes from a source that can't be trusted.\n   *\n   * @param {*} value Value or a promise\n   * @param {Function=} successCallback\n   * @param {Function=} errorCallback\n   * @param {Function=} progressCallback\n   * @returns {Promise} Returns a promise of the passed value or promise\n   */\n\n\n  var when = function(value, callback, errback, progressBack) {\n    var result = new Deferred();\n    result.resolve(value);\n    return result.promise.then(callback, errback, progressBack);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#resolve\n   * @kind function\n   *\n   * @description\n   * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.\n   *\n   * @param {*} value Value or a promise\n   * @param {Function=} successCallback\n   * @param {Function=} errorCallback\n   * @param {Function=} progressCallback\n   * @returns {Promise} Returns a promise of the passed value or promise\n   */\n  var resolve = when;\n\n  /**\n   * @ngdoc method\n   * @name $q#all\n   * @kind function\n   *\n   * @description\n   * Combines multiple promises into a single promise that is resolved when all of the input\n   * promises are resolved.\n   *\n   * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.\n   * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,\n   *   each value corresponding to the promise at the same index/key in the `promises` array/hash.\n   *   If any of the promises is resolved with a rejection, this resulting promise will be rejected\n   *   with the same rejection value.\n   */\n\n  function all(promises) {\n    var deferred = new Deferred(),\n        counter = 0,\n        results = isArray(promises) ? [] : {};\n\n    forEach(promises, function(promise, key) {\n      counter++;\n      when(promise).then(function(value) {\n        if (results.hasOwnProperty(key)) return;\n        results[key] = value;\n        if (!(--counter)) deferred.resolve(results);\n      }, function(reason) {\n        if (results.hasOwnProperty(key)) return;\n        deferred.reject(reason);\n      });\n    });\n\n    if (counter === 0) {\n      deferred.resolve(results);\n    }\n\n    return deferred.promise;\n  }\n\n  var $Q = function Q(resolver) {\n    if (!isFunction(resolver)) {\n      throw $qMinErr('norslvr', \"Expected resolverFn, got '{0}'\", resolver);\n    }\n\n    if (!(this instanceof Q)) {\n      // More useful when $Q is the Promise itself.\n      return new Q(resolver);\n    }\n\n    var deferred = new Deferred();\n\n    function resolveFn(value) {\n      deferred.resolve(value);\n    }\n\n    function rejectFn(reason) {\n      deferred.reject(reason);\n    }\n\n    resolver(resolveFn, rejectFn);\n\n    return deferred.promise;\n  };\n\n  $Q.defer = defer;\n  $Q.reject = reject;\n  $Q.when = when;\n  $Q.resolve = resolve;\n  $Q.all = all;\n\n  return $Q;\n}\n\nfunction $$RAFProvider() { //rAF\n  this.$get = ['$window', '$timeout', function($window, $timeout) {\n    var requestAnimationFrame = $window.requestAnimationFrame ||\n                                $window.webkitRequestAnimationFrame;\n\n    var cancelAnimationFrame = $window.cancelAnimationFrame ||\n                               $window.webkitCancelAnimationFrame ||\n                               $window.webkitCancelRequestAnimationFrame;\n\n    var rafSupported = !!requestAnimationFrame;\n    var rafFn = rafSupported\n      ? function(fn) {\n          var id = requestAnimationFrame(fn);\n          return function() {\n            cancelAnimationFrame(id);\n          };\n        }\n      : function(fn) {\n          var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666\n          return function() {\n            $timeout.cancel(timer);\n          };\n        };\n\n    queueFn.supported = rafSupported;\n\n    var cancelLastRAF;\n    var taskCount = 0;\n    var taskQueue = [];\n    return queueFn;\n\n    function flush() {\n      for (var i = 0; i < taskQueue.length; i++) {\n        var task = taskQueue[i];\n        if (task) {\n          taskQueue[i] = null;\n          task();\n        }\n      }\n      taskCount = taskQueue.length = 0;\n    }\n\n    function queueFn(asyncFn) {\n      var index = taskQueue.length;\n\n      taskCount++;\n      taskQueue.push(asyncFn);\n\n      if (index === 0) {\n        cancelLastRAF = rafFn(flush);\n      }\n\n      return function cancelQueueFn() {\n        if (index >= 0) {\n          taskQueue[index] = null;\n          index = null;\n\n          if (--taskCount === 0 && cancelLastRAF) {\n            cancelLastRAF();\n            cancelLastRAF = null;\n            taskQueue.length = 0;\n          }\n        }\n      };\n    }\n  }];\n}\n\n/**\n * DESIGN NOTES\n *\n * The design decisions behind the scope are heavily favored for speed and memory consumption.\n *\n * The typical use of scope is to watch the expressions, which most of the time return the same\n * value as last time so we optimize the operation.\n *\n * Closures construction is expensive in terms of speed as well as memory:\n *   - No closures, instead use prototypical inheritance for API\n *   - Internal state needs to be stored on scope directly, which means that private state is\n *     exposed as $$____ properties\n *\n * Loop operations are optimized by using while(count--) { ... }\n *   - this means that in order to keep the same order of execution as addition we have to add\n *     items to the array at the beginning (unshift) instead of at the end (push)\n *\n * Child scopes are created and removed often\n *   - Using an array would be slow since inserts in middle are expensive so we use linked list\n *\n * There are few watches then a lot of observers. This is why you don't want the observer to be\n * implemented in the same way as watch. Watch requires return of initialization function which\n * are expensive to construct.\n */\n\n\n/**\n * @ngdoc provider\n * @name $rootScopeProvider\n * @description\n *\n * Provider for the $rootScope service.\n */\n\n/**\n * @ngdoc method\n * @name $rootScopeProvider#digestTtl\n * @description\n *\n * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that the dependencies between `$watch`s will result in\n * several digest iterations. However if an application needs more than the default 10 digest\n * iterations for its model to stabilize then you should investigate what is causing the model to\n * continuously change during the digest.\n *\n * Increasing the TTL could have performance implications, so you should not change it without\n * proper justification.\n *\n * @param {number} limit The number of digest iterations.\n */\n\n\n/**\n * @ngdoc service\n * @name $rootScope\n * @description\n *\n * Every application has a single root {@link ng.$rootScope.Scope scope}.\n * All other scopes are descendant scopes of the root scope. Scopes provide separation\n * between the model and the view, via a mechanism for watching the model for changes.\n * They also provide an event emission/broadcast and subscription facility. See the\n * {@link guide/scope developer guide on scopes}.\n */\nfunction $RootScopeProvider() {\n  var TTL = 10;\n  var $rootScopeMinErr = minErr('$rootScope');\n  var lastDirtyWatch = null;\n  var applyAsyncId = null;\n\n  this.digestTtl = function(value) {\n    if (arguments.length) {\n      TTL = value;\n    }\n    return TTL;\n  };\n\n  function createChildScopeClass(parent) {\n    function ChildScope() {\n      this.$$watchers = this.$$nextSibling =\n          this.$$childHead = this.$$childTail = null;\n      this.$$listeners = {};\n      this.$$listenerCount = {};\n      this.$$watchersCount = 0;\n      this.$id = nextUid();\n      this.$$ChildScope = null;\n    }\n    ChildScope.prototype = parent;\n    return ChildScope;\n  }\n\n  this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',\n      function($injector, $exceptionHandler, $parse, $browser) {\n\n    function destroyChildScope($event) {\n        $event.currentScope.$$destroyed = true;\n    }\n\n    /**\n     * @ngdoc type\n     * @name $rootScope.Scope\n     *\n     * @description\n     * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the\n     * {@link auto.$injector $injector}. Child scopes are created using the\n     * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when\n     * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for\n     * an in-depth introduction and usage examples.\n     *\n     *\n     * # Inheritance\n     * A scope can inherit from a parent scope, as in this example:\n     * ```js\n         var parent = $rootScope;\n         var child = parent.$new();\n\n         parent.salutation = \"Hello\";\n         expect(child.salutation).toEqual('Hello');\n\n         child.salutation = \"Welcome\";\n         expect(child.salutation).toEqual('Welcome');\n         expect(parent.salutation).toEqual('Hello');\n     * ```\n     *\n     * When interacting with `Scope` in tests, additional helper methods are available on the\n     * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional\n     * details.\n     *\n     *\n     * @param {Object.<string, function()>=} providers Map of service factory which need to be\n     *                                       provided for the current scope. Defaults to {@link ng}.\n     * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should\n     *                              append/override services provided by `providers`. This is handy\n     *                              when unit-testing and having the need to override a default\n     *                              service.\n     * @returns {Object} Newly created scope.\n     *\n     */\n    function Scope() {\n      this.$id = nextUid();\n      this.$$phase = this.$parent = this.$$watchers =\n                     this.$$nextSibling = this.$$prevSibling =\n                     this.$$childHead = this.$$childTail = null;\n      this.$root = this;\n      this.$$destroyed = false;\n      this.$$listeners = {};\n      this.$$listenerCount = {};\n      this.$$watchersCount = 0;\n      this.$$isolateBindings = null;\n    }\n\n    /**\n     * @ngdoc property\n     * @name $rootScope.Scope#$id\n     *\n     * @description\n     * Unique scope ID (monotonically increasing) useful for debugging.\n     */\n\n     /**\n      * @ngdoc property\n      * @name $rootScope.Scope#$parent\n      *\n      * @description\n      * Reference to the parent scope.\n      */\n\n      /**\n       * @ngdoc property\n       * @name $rootScope.Scope#$root\n       *\n       * @description\n       * Reference to the root scope.\n       */\n\n    Scope.prototype = {\n      constructor: Scope,\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$new\n       * @kind function\n       *\n       * @description\n       * Creates a new child {@link ng.$rootScope.Scope scope}.\n       *\n       * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.\n       * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.\n       *\n       * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is\n       * desired for the scope and its child scopes to be permanently detached from the parent and\n       * thus stop participating in model change detection and listener notification by invoking.\n       *\n       * @param {boolean} isolate If true, then the scope does not prototypically inherit from the\n       *         parent scope. The scope is isolated, as it can not see parent scope properties.\n       *         When creating widgets, it is useful for the widget to not accidentally read parent\n       *         state.\n       *\n       * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`\n       *                              of the newly created scope. Defaults to `this` scope if not provided.\n       *                              This is used when creating a transclude scope to correctly place it\n       *                              in the scope hierarchy while maintaining the correct prototypical\n       *                              inheritance.\n       *\n       * @returns {Object} The newly created child scope.\n       *\n       */\n      $new: function(isolate, parent) {\n        var child;\n\n        parent = parent || this;\n\n        if (isolate) {\n          child = new Scope();\n          child.$root = this.$root;\n        } else {\n          // Only create a child scope class if somebody asks for one,\n          // but cache it to allow the VM to optimize lookups.\n          if (!this.$$ChildScope) {\n            this.$$ChildScope = createChildScopeClass(this);\n          }\n          child = new this.$$ChildScope();\n        }\n        child.$parent = parent;\n        child.$$prevSibling = parent.$$childTail;\n        if (parent.$$childHead) {\n          parent.$$childTail.$$nextSibling = child;\n          parent.$$childTail = child;\n        } else {\n          parent.$$childHead = parent.$$childTail = child;\n        }\n\n        // When the new scope is not isolated or we inherit from `this`, and\n        // the parent scope is destroyed, the property `$$destroyed` is inherited\n        // prototypically. In all other cases, this property needs to be set\n        // when the parent scope is destroyed.\n        // The listener needs to be added after the parent is set\n        if (isolate || parent != this) child.$on('$destroy', destroyChildScope);\n\n        return child;\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watch\n       * @kind function\n       *\n       * @description\n       * Registers a `listener` callback to be executed whenever the `watchExpression` changes.\n       *\n       * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest\n       *   $digest()} and should return the value that will be watched. (Since\n       *   {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the\n       *   `watchExpression` can execute multiple times per\n       *   {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)\n       * - The `listener` is called only when the value from the current `watchExpression` and the\n       *   previous call to `watchExpression` are not equal (with the exception of the initial run,\n       *   see below). Inequality is determined according to reference inequality,\n       *   [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)\n       *    via the `!==` Javascript operator, unless `objectEquality == true`\n       *   (see next point)\n       * - When `objectEquality == true`, inequality of the `watchExpression` is determined\n       *   according to the {@link angular.equals} function. To save the value of the object for\n       *   later comparison, the {@link angular.copy} function is used. This therefore means that\n       *   watching complex objects will have adverse memory and performance implications.\n       * - The watch `listener` may change the model, which may trigger other `listener`s to fire.\n       *   This is achieved by rerunning the watchers until no changes are detected. The rerun\n       *   iteration limit is 10 to prevent an infinite loop deadlock.\n       *\n       *\n       * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,\n       * you can register a `watchExpression` function with no `listener`. (Be prepared for\n       * multiple calls to your `watchExpression` because it will execute multiple times in a\n       * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)\n       *\n       * After a watcher is registered with the scope, the `listener` fn is called asynchronously\n       * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the\n       * watcher. In rare cases, this is undesirable because the listener is called when the result\n       * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you\n       * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the\n       * listener was called due to initialization.\n       *\n       *\n       *\n       * # Example\n       * ```js\n           // let's assume that scope was dependency injected as the $rootScope\n           var scope = $rootScope;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n\n\n\n           // Using a function as a watchExpression\n           var food;\n           scope.foodCounter = 0;\n           expect(scope.foodCounter).toEqual(0);\n           scope.$watch(\n             // This function returns the value being watched. It is called for each turn of the $digest loop\n             function() { return food; },\n             // This is the change listener, called when the value returned from the above function changes\n             function(newValue, oldValue) {\n               if ( newValue !== oldValue ) {\n                 // Only increment the counter if the value changed\n                 scope.foodCounter = scope.foodCounter + 1;\n               }\n             }\n           );\n           // No digest has been run so the counter will be zero\n           expect(scope.foodCounter).toEqual(0);\n\n           // Run the digest but since food has not changed count will still be zero\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(0);\n\n           // Update food and run digest.  Now the counter will increment\n           food = 'cheeseburger';\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(1);\n\n       * ```\n       *\n       *\n       *\n       * @param {(function()|string)} watchExpression Expression that is evaluated on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers\n       *    a call to the `listener`.\n       *\n       *    - `string`: Evaluated as {@link guide/expression expression}\n       *    - `function(scope)`: called with current `scope` as a parameter.\n       * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value\n       *    of `watchExpression` changes.\n       *\n       *    - `newVal` contains the current value of the `watchExpression`\n       *    - `oldVal` contains the previous value of the `watchExpression`\n       *    - `scope` refers to the current scope\n       * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of\n       *     comparing for reference equality.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {\n        var get = $parse(watchExp);\n\n        if (get.$$watchDelegate) {\n          return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);\n        }\n        var scope = this,\n            array = scope.$$watchers,\n            watcher = {\n              fn: listener,\n              last: initWatchVal,\n              get: get,\n              exp: prettyPrintExpression || watchExp,\n              eq: !!objectEquality\n            };\n\n        lastDirtyWatch = null;\n\n        if (!isFunction(listener)) {\n          watcher.fn = noop;\n        }\n\n        if (!array) {\n          array = scope.$$watchers = [];\n        }\n        // we use unshift since we use a while loop in $digest for speed.\n        // the while loop reads in reverse order.\n        array.unshift(watcher);\n        incrementWatchersCount(this, 1);\n\n        return function deregisterWatch() {\n          if (arrayRemove(array, watcher) >= 0) {\n            incrementWatchersCount(scope, -1);\n          }\n          lastDirtyWatch = null;\n        };\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchGroup\n       * @kind function\n       *\n       * @description\n       * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.\n       * If any one expression in the collection changes the `listener` is executed.\n       *\n       * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every\n       *   call to $digest() to see if any items changes.\n       * - The `listener` is called whenever any expression in the `watchExpressions` array changes.\n       *\n       * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually\n       * watched using {@link ng.$rootScope.Scope#$watch $watch()}\n       *\n       * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any\n       *    expression in `watchExpressions` changes\n       *    The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    The `scope` refers to the current scope.\n       * @returns {function()} Returns a de-registration function for all listeners.\n       */\n      $watchGroup: function(watchExpressions, listener) {\n        var oldValues = new Array(watchExpressions.length);\n        var newValues = new Array(watchExpressions.length);\n        var deregisterFns = [];\n        var self = this;\n        var changeReactionScheduled = false;\n        var firstRun = true;\n\n        if (!watchExpressions.length) {\n          // No expressions means we call the listener ASAP\n          var shouldCall = true;\n          self.$evalAsync(function() {\n            if (shouldCall) listener(newValues, newValues, self);\n          });\n          return function deregisterWatchGroup() {\n            shouldCall = false;\n          };\n        }\n\n        if (watchExpressions.length === 1) {\n          // Special case size of one\n          return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {\n            newValues[0] = value;\n            oldValues[0] = oldValue;\n            listener(newValues, (value === oldValue) ? newValues : oldValues, scope);\n          });\n        }\n\n        forEach(watchExpressions, function(expr, i) {\n          var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {\n            newValues[i] = value;\n            oldValues[i] = oldValue;\n            if (!changeReactionScheduled) {\n              changeReactionScheduled = true;\n              self.$evalAsync(watchGroupAction);\n            }\n          });\n          deregisterFns.push(unwatchFn);\n        });\n\n        function watchGroupAction() {\n          changeReactionScheduled = false;\n\n          if (firstRun) {\n            firstRun = false;\n            listener(newValues, newValues, self);\n          } else {\n            listener(newValues, oldValues, self);\n          }\n        }\n\n        return function deregisterWatchGroup() {\n          while (deregisterFns.length) {\n            deregisterFns.shift()();\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchCollection\n       * @kind function\n       *\n       * @description\n       * Shallow watches the properties of an object and fires whenever any of the properties change\n       * (for arrays, this implies watching the array items; for object maps, this implies watching\n       * the properties). If a change is detected, the `listener` callback is fired.\n       *\n       * - The `obj` collection is observed via standard $watch operation and is examined on every\n       *   call to $digest() to see if any items have been added, removed, or moved.\n       * - The `listener` is called whenever anything within the `obj` has changed. Examples include\n       *   adding, removing, and moving items belonging to an object or array.\n       *\n       *\n       * # Example\n       * ```js\n          $scope.names = ['igor', 'matias', 'misko', 'james'];\n          $scope.dataCount = 4;\n\n          $scope.$watchCollection('names', function(newNames, oldNames) {\n            $scope.dataCount = newNames.length;\n          });\n\n          expect($scope.dataCount).toEqual(4);\n          $scope.$digest();\n\n          //still at 4 ... no changes\n          expect($scope.dataCount).toEqual(4);\n\n          $scope.names.pop();\n          $scope.$digest();\n\n          //now there's been a change\n          expect($scope.dataCount).toEqual(3);\n       * ```\n       *\n       *\n       * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The\n       *    expression value should evaluate to an object or an array which is observed on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the\n       *    collection will trigger a call to the `listener`.\n       *\n       * @param {function(newCollection, oldCollection, scope)} listener a callback function called\n       *    when a change is detected.\n       *    - The `newCollection` object is the newly modified data obtained from the `obj` expression\n       *    - The `oldCollection` object is a copy of the former collection data.\n       *      Due to performance considerations, the`oldCollection` value is computed only if the\n       *      `listener` function declares two or more arguments.\n       *    - The `scope` argument refers to the current scope.\n       *\n       * @returns {function()} Returns a de-registration function for this listener. When the\n       *    de-registration function is executed, the internal watch operation is terminated.\n       */\n      $watchCollection: function(obj, listener) {\n        $watchCollectionInterceptor.$stateful = true;\n\n        var self = this;\n        // the current value, updated on each dirty-check run\n        var newValue;\n        // a shallow copy of the newValue from the last dirty-check run,\n        // updated to match newValue during dirty-check run\n        var oldValue;\n        // a shallow copy of the newValue from when the last change happened\n        var veryOldValue;\n        // only track veryOldValue if the listener is asking for it\n        var trackVeryOldValue = (listener.length > 1);\n        var changeDetected = 0;\n        var changeDetector = $parse(obj, $watchCollectionInterceptor);\n        var internalArray = [];\n        var internalObject = {};\n        var initRun = true;\n        var oldLength = 0;\n\n        function $watchCollectionInterceptor(_value) {\n          newValue = _value;\n          var newLength, key, bothNaN, newItem, oldItem;\n\n          // If the new value is undefined, then return undefined as the watch may be a one-time watch\n          if (isUndefined(newValue)) return;\n\n          if (!isObject(newValue)) { // if primitive\n            if (oldValue !== newValue) {\n              oldValue = newValue;\n              changeDetected++;\n            }\n          } else if (isArrayLike(newValue)) {\n            if (oldValue !== internalArray) {\n              // we are transitioning from something which was not an array into array.\n              oldValue = internalArray;\n              oldLength = oldValue.length = 0;\n              changeDetected++;\n            }\n\n            newLength = newValue.length;\n\n            if (oldLength !== newLength) {\n              // if lengths do not match we need to trigger change notification\n              changeDetected++;\n              oldValue.length = oldLength = newLength;\n            }\n            // copy the items to oldValue and look for changes.\n            for (var i = 0; i < newLength; i++) {\n              oldItem = oldValue[i];\n              newItem = newValue[i];\n\n              bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n              if (!bothNaN && (oldItem !== newItem)) {\n                changeDetected++;\n                oldValue[i] = newItem;\n              }\n            }\n          } else {\n            if (oldValue !== internalObject) {\n              // we are transitioning from something which was not an object into object.\n              oldValue = internalObject = {};\n              oldLength = 0;\n              changeDetected++;\n            }\n            // copy the items to oldValue and look for changes.\n            newLength = 0;\n            for (key in newValue) {\n              if (newValue.hasOwnProperty(key)) {\n                newLength++;\n                newItem = newValue[key];\n                oldItem = oldValue[key];\n\n                if (key in oldValue) {\n                  bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n                  if (!bothNaN && (oldItem !== newItem)) {\n                    changeDetected++;\n                    oldValue[key] = newItem;\n                  }\n                } else {\n                  oldLength++;\n                  oldValue[key] = newItem;\n                  changeDetected++;\n                }\n              }\n            }\n            if (oldLength > newLength) {\n              // we used to have more keys, need to find them and destroy them.\n              changeDetected++;\n              for (key in oldValue) {\n                if (!newValue.hasOwnProperty(key)) {\n                  oldLength--;\n                  delete oldValue[key];\n                }\n              }\n            }\n          }\n          return changeDetected;\n        }\n\n        function $watchCollectionAction() {\n          if (initRun) {\n            initRun = false;\n            listener(newValue, newValue, self);\n          } else {\n            listener(newValue, veryOldValue, self);\n          }\n\n          // make a copy for the next time a collection is changed\n          if (trackVeryOldValue) {\n            if (!isObject(newValue)) {\n              //primitive\n              veryOldValue = newValue;\n            } else if (isArrayLike(newValue)) {\n              veryOldValue = new Array(newValue.length);\n              for (var i = 0; i < newValue.length; i++) {\n                veryOldValue[i] = newValue[i];\n              }\n            } else { // if object\n              veryOldValue = {};\n              for (var key in newValue) {\n                if (hasOwnProperty.call(newValue, key)) {\n                  veryOldValue[key] = newValue[key];\n                }\n              }\n            }\n          }\n        }\n\n        return this.$watch(changeDetector, $watchCollectionAction);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$digest\n       * @kind function\n       *\n       * @description\n       * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and\n       * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change\n       * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}\n       * until no more listeners are firing. This means that it is possible to get into an infinite\n       * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of\n       * iterations exceeds 10.\n       *\n       * Usually, you don't call `$digest()` directly in\n       * {@link ng.directive:ngController controllers} or in\n       * {@link ng.$compileProvider#directive directives}.\n       * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within\n       * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.\n       *\n       * If you want to be notified whenever `$digest()` is called,\n       * you can register a `watchExpression` function with\n       * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.\n       *\n       * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.\n       *\n       * # Example\n       * ```js\n           var scope = ...;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n       * ```\n       *\n       */\n      $digest: function() {\n        var watch, value, last,\n            watchers,\n            length,\n            dirty, ttl = TTL,\n            next, current, target = this,\n            watchLog = [],\n            logIdx, logMsg, asyncTask;\n\n        beginPhase('$digest');\n        // Check for changes to browser url that happened in sync before the call to $digest\n        $browser.$$checkUrlChange();\n\n        if (this === $rootScope && applyAsyncId !== null) {\n          // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then\n          // cancel the scheduled $apply and flush the queue of expressions to be evaluated.\n          $browser.defer.cancel(applyAsyncId);\n          flushApplyAsync();\n        }\n\n        lastDirtyWatch = null;\n\n        do { // \"while dirty\" loop\n          dirty = false;\n          current = target;\n\n          while (asyncQueue.length) {\n            try {\n              asyncTask = asyncQueue.shift();\n              asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n            lastDirtyWatch = null;\n          }\n\n          traverseScopesLoop:\n          do { // \"traverse the scopes\" loop\n            if ((watchers = current.$$watchers)) {\n              // process our watches\n              length = watchers.length;\n              while (length--) {\n                try {\n                  watch = watchers[length];\n                  // Most common watches are on primitives, in which case we can short\n                  // circuit it with === operator, only when === fails do we use .equals\n                  if (watch) {\n                    if ((value = watch.get(current)) !== (last = watch.last) &&\n                        !(watch.eq\n                            ? equals(value, last)\n                            : (typeof value === 'number' && typeof last === 'number'\n                               && isNaN(value) && isNaN(last)))) {\n                      dirty = true;\n                      lastDirtyWatch = watch;\n                      watch.last = watch.eq ? copy(value, null) : value;\n                      watch.fn(value, ((last === initWatchVal) ? value : last), current);\n                      if (ttl < 5) {\n                        logIdx = 4 - ttl;\n                        if (!watchLog[logIdx]) watchLog[logIdx] = [];\n                        watchLog[logIdx].push({\n                          msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,\n                          newVal: value,\n                          oldVal: last\n                        });\n                      }\n                    } else if (watch === lastDirtyWatch) {\n                      // If the most recently dirty watcher is now clean, short circuit since the remaining watchers\n                      // have already been tested.\n                      dirty = false;\n                      break traverseScopesLoop;\n                    }\n                  }\n                } catch (e) {\n                  $exceptionHandler(e);\n                }\n              }\n            }\n\n            // Insanity Warning: scope depth-first traversal\n            // yes, this code is a bit crazy, but it works and we have tests to prove it!\n            // this piece should be kept in sync with the traversal in $broadcast\n            if (!(next = ((current.$$watchersCount && current.$$childHead) ||\n                (current !== target && current.$$nextSibling)))) {\n              while (current !== target && !(next = current.$$nextSibling)) {\n                current = current.$parent;\n              }\n            }\n          } while ((current = next));\n\n          // `break traverseScopesLoop;` takes us to here\n\n          if ((dirty || asyncQueue.length) && !(ttl--)) {\n            clearPhase();\n            throw $rootScopeMinErr('infdig',\n                '{0} $digest() iterations reached. Aborting!\\n' +\n                'Watchers fired in the last 5 iterations: {1}',\n                TTL, watchLog);\n          }\n\n        } while (dirty || asyncQueue.length);\n\n        clearPhase();\n\n        while (postDigestQueue.length) {\n          try {\n            postDigestQueue.shift()();\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        }\n      },\n\n\n      /**\n       * @ngdoc event\n       * @name $rootScope.Scope#$destroy\n       * @eventType broadcast on scope being destroyed\n       *\n       * @description\n       * Broadcasted when a scope and its children are being destroyed.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$destroy\n       * @kind function\n       *\n       * @description\n       * Removes the current scope (and all of its children) from the parent scope. Removal implies\n       * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer\n       * propagate to the current scope and its children. Removal also implies that the current\n       * scope is eligible for garbage collection.\n       *\n       * The `$destroy()` is usually used by directives such as\n       * {@link ng.directive:ngRepeat ngRepeat} for managing the\n       * unrolling of the loop.\n       *\n       * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.\n       * Application code can register a `$destroy` event handler that will give it a chance to\n       * perform any necessary cleanup.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n      $destroy: function() {\n        // We can't destroy a scope that has been already destroyed.\n        if (this.$$destroyed) return;\n        var parent = this.$parent;\n\n        this.$broadcast('$destroy');\n        this.$$destroyed = true;\n\n        if (this === $rootScope) {\n          //Remove handlers attached to window when $rootScope is removed\n          $browser.$$applicationDestroyed();\n        }\n\n        incrementWatchersCount(this, -this.$$watchersCount);\n        for (var eventName in this.$$listenerCount) {\n          decrementListenerCount(this, this.$$listenerCount[eventName], eventName);\n        }\n\n        // sever all the references to parent scopes (after this cleanup, the current scope should\n        // not be retained by any of our references and should be eligible for garbage collection)\n        if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;\n        if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;\n        if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;\n        if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;\n\n        // Disable listeners, watchers and apply/digest methods\n        this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;\n        this.$on = this.$watch = this.$watchGroup = function() { return noop; };\n        this.$$listeners = {};\n\n        // All of the code below is bogus code that works around V8's memory leak via optimized code\n        // and inline caches.\n        //\n        // see:\n        // - https://code.google.com/p/v8/issues/detail?id=2073#c26\n        // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909\n        // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451\n\n        this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =\n            this.$$childTail = this.$root = this.$$watchers = null;\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$eval\n       * @kind function\n       *\n       * @description\n       * Executes the `expression` on the current scope and returns the result. Any exceptions in\n       * the expression are propagated (uncaught). This is useful when evaluating Angular\n       * expressions.\n       *\n       * # Example\n       * ```js\n           var scope = ng.$rootScope.Scope();\n           scope.a = 1;\n           scope.b = 2;\n\n           expect(scope.$eval('a+b')).toEqual(3);\n           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);\n       * ```\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       * @returns {*} The result of evaluating the expression.\n       */\n      $eval: function(expr, locals) {\n        return $parse(expr)(this, locals);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$evalAsync\n       * @kind function\n       *\n       * @description\n       * Executes the expression on the current scope at a later point in time.\n       *\n       * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only\n       * that:\n       *\n       *   - it will execute after the function that scheduled the evaluation (preferably before DOM\n       *     rendering).\n       *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after\n       *     `expression` execution.\n       *\n       * Any exceptions from the execution of the expression are forwarded to the\n       * {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle\n       * will be scheduled. However, it is encouraged to always call code that changes the model\n       * from within an `$apply` call. That includes code evaluated via `$evalAsync`.\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       */\n      $evalAsync: function(expr, locals) {\n        // if we are outside of an $digest loop and this is the first time we are scheduling async\n        // task also schedule async auto-flush\n        if (!$rootScope.$$phase && !asyncQueue.length) {\n          $browser.defer(function() {\n            if (asyncQueue.length) {\n              $rootScope.$digest();\n            }\n          });\n        }\n\n        asyncQueue.push({scope: this, expression: expr, locals: locals});\n      },\n\n      $$postDigest: function(fn) {\n        postDigestQueue.push(fn);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$apply\n       * @kind function\n       *\n       * @description\n       * `$apply()` is used to execute an expression in angular from outside of the angular\n       * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).\n       * Because we are calling into the angular framework we need to perform proper scope life\n       * cycle of {@link ng.$exceptionHandler exception handling},\n       * {@link ng.$rootScope.Scope#$digest executing watches}.\n       *\n       * ## Life cycle\n       *\n       * # Pseudo-Code of `$apply()`\n       * ```js\n           function $apply(expr) {\n             try {\n               return $eval(expr);\n             } catch (e) {\n               $exceptionHandler(e);\n             } finally {\n               $root.$digest();\n             }\n           }\n       * ```\n       *\n       *\n       * Scope's `$apply()` method transitions through the following stages:\n       *\n       * 1. The {@link guide/expression expression} is executed using the\n       *    {@link ng.$rootScope.Scope#$eval $eval()} method.\n       * 2. Any exceptions from the execution of the expression are forwarded to the\n       *    {@link ng.$exceptionHandler $exceptionHandler} service.\n       * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the\n       *    expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.\n       *\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       *\n       * @returns {*} The result of evaluating the expression.\n       */\n      $apply: function(expr) {\n        try {\n          beginPhase('$apply');\n          try {\n            return this.$eval(expr);\n          } finally {\n            clearPhase();\n          }\n        } catch (e) {\n          $exceptionHandler(e);\n        } finally {\n          try {\n            $rootScope.$digest();\n          } catch (e) {\n            $exceptionHandler(e);\n            throw e;\n          }\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$applyAsync\n       * @kind function\n       *\n       * @description\n       * Schedule the invocation of $apply to occur at a later time. The actual time difference\n       * varies across browsers, but is typically around ~10 milliseconds.\n       *\n       * This can be used to queue up multiple expressions which need to be evaluated in the same\n       * digest.\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       */\n      $applyAsync: function(expr) {\n        var scope = this;\n        expr && applyAsyncQueue.push($applyAsyncExpression);\n        scheduleApplyAsync();\n\n        function $applyAsyncExpression() {\n          scope.$eval(expr);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$on\n       * @kind function\n       *\n       * @description\n       * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for\n       * discussion of event life cycle.\n       *\n       * The event listener function format is: `function(event, args...)`. The `event` object\n       * passed into the listener has the following attributes:\n       *\n       *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or\n       *     `$broadcast`-ed.\n       *   - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the\n       *     event propagates through the scope hierarchy, this property is set to null.\n       *   - `name` - `{string}`: name of the event.\n       *   - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel\n       *     further event propagation (available only for events that were `$emit`-ed).\n       *   - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag\n       *     to true.\n       *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.\n       *\n       * @param {string} name Event name to listen on.\n       * @param {function(event, ...args)} listener Function to call when the event is emitted.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $on: function(name, listener) {\n        var namedListeners = this.$$listeners[name];\n        if (!namedListeners) {\n          this.$$listeners[name] = namedListeners = [];\n        }\n        namedListeners.push(listener);\n\n        var current = this;\n        do {\n          if (!current.$$listenerCount[name]) {\n            current.$$listenerCount[name] = 0;\n          }\n          current.$$listenerCount[name]++;\n        } while ((current = current.$parent));\n\n        var self = this;\n        return function() {\n          var indexOfListener = namedListeners.indexOf(listener);\n          if (indexOfListener !== -1) {\n            namedListeners[indexOfListener] = null;\n            decrementListenerCount(self, 1, name);\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$emit\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` upwards through the scope hierarchy notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$emit` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event traverses upwards toward the root scope and calls all\n       * registered listeners along the way. The event will stop propagating if one of the listeners\n       * cancels it.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to emit.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).\n       */\n      $emit: function(name, args) {\n        var empty = [],\n            namedListeners,\n            scope = this,\n            stopPropagation = false,\n            event = {\n              name: name,\n              targetScope: scope,\n              stopPropagation: function() {stopPropagation = true;},\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            },\n            listenerArgs = concat([event], arguments, 1),\n            i, length;\n\n        do {\n          namedListeners = scope.$$listeners[name] || empty;\n          event.currentScope = scope;\n          for (i = 0, length = namedListeners.length; i < length; i++) {\n\n            // if listeners were deregistered, defragment the array\n            if (!namedListeners[i]) {\n              namedListeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n            try {\n              //allow all listeners attached to the current scope to run\n              namedListeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n          //if any listener on the current scope stops propagation, prevent bubbling\n          if (stopPropagation) {\n            event.currentScope = null;\n            return event;\n          }\n          //traverse upwards\n          scope = scope.$parent;\n        } while (scope);\n\n        event.currentScope = null;\n\n        return event;\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$broadcast\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` downwards to all child scopes (and their children) notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$broadcast` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event propagates to all direct and indirect scopes of the current\n       * scope and calls all registered listeners along the way. The event cannot be canceled.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to broadcast.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}\n       */\n      $broadcast: function(name, args) {\n        var target = this,\n            current = target,\n            next = target,\n            event = {\n              name: name,\n              targetScope: target,\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            };\n\n        if (!target.$$listenerCount[name]) return event;\n\n        var listenerArgs = concat([event], arguments, 1),\n            listeners, i, length;\n\n        //down while you can, then up and next sibling or up and next sibling until back at root\n        while ((current = next)) {\n          event.currentScope = current;\n          listeners = current.$$listeners[name] || [];\n          for (i = 0, length = listeners.length; i < length; i++) {\n            // if listeners were deregistered, defragment the array\n            if (!listeners[i]) {\n              listeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n\n            try {\n              listeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n\n          // Insanity Warning: scope depth-first traversal\n          // yes, this code is a bit crazy, but it works and we have tests to prove it!\n          // this piece should be kept in sync with the traversal in $digest\n          // (though it differs due to having the extra check for $$listenerCount)\n          if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||\n              (current !== target && current.$$nextSibling)))) {\n            while (current !== target && !(next = current.$$nextSibling)) {\n              current = current.$parent;\n            }\n          }\n        }\n\n        event.currentScope = null;\n        return event;\n      }\n    };\n\n    var $rootScope = new Scope();\n\n    //The internal queues. Expose them on the $rootScope for debugging/testing purposes.\n    var asyncQueue = $rootScope.$$asyncQueue = [];\n    var postDigestQueue = $rootScope.$$postDigestQueue = [];\n    var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];\n\n    return $rootScope;\n\n\n    function beginPhase(phase) {\n      if ($rootScope.$$phase) {\n        throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);\n      }\n\n      $rootScope.$$phase = phase;\n    }\n\n    function clearPhase() {\n      $rootScope.$$phase = null;\n    }\n\n    function incrementWatchersCount(current, count) {\n      do {\n        current.$$watchersCount += count;\n      } while ((current = current.$parent));\n    }\n\n    function decrementListenerCount(current, count, name) {\n      do {\n        current.$$listenerCount[name] -= count;\n\n        if (current.$$listenerCount[name] === 0) {\n          delete current.$$listenerCount[name];\n        }\n      } while ((current = current.$parent));\n    }\n\n    /**\n     * function used as an initial value for watchers.\n     * because it's unique we can easily tell it apart from other values\n     */\n    function initWatchVal() {}\n\n    function flushApplyAsync() {\n      while (applyAsyncQueue.length) {\n        try {\n          applyAsyncQueue.shift()();\n        } catch (e) {\n          $exceptionHandler(e);\n        }\n      }\n      applyAsyncId = null;\n    }\n\n    function scheduleApplyAsync() {\n      if (applyAsyncId === null) {\n        applyAsyncId = $browser.defer(function() {\n          $rootScope.$apply(flushApplyAsync);\n        });\n      }\n    }\n  }];\n}\n\n/**\n * @description\n * Private service to sanitize uris for links and images. Used by $compile and $sanitize.\n */\nfunction $$SanitizeUriProvider() {\n  var aHrefSanitizationWhitelist = /^\\s*(https?|ftp|mailto|tel|file):/,\n    imgSrcSanitizationWhitelist = /^\\s*((https?|ftp|file|blob):|data:image\\/)/;\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      aHrefSanitizationWhitelist = regexp;\n      return this;\n    }\n    return aHrefSanitizationWhitelist;\n  };\n\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      imgSrcSanitizationWhitelist = regexp;\n      return this;\n    }\n    return imgSrcSanitizationWhitelist;\n  };\n\n  this.$get = function() {\n    return function sanitizeUri(uri, isImage) {\n      var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;\n      var normalizedVal;\n      normalizedVal = urlResolve(uri).href;\n      if (normalizedVal !== '' && !normalizedVal.match(regex)) {\n        return 'unsafe:' + normalizedVal;\n      }\n      return uri;\n    };\n  };\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $sceMinErr = minErr('$sce');\n\nvar SCE_CONTEXTS = {\n  HTML: 'html',\n  CSS: 'css',\n  URL: 'url',\n  // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a\n  // url.  (e.g. ng-include, script src, templateUrl)\n  RESOURCE_URL: 'resourceUrl',\n  JS: 'js'\n};\n\n// Helper functions follow.\n\nfunction adjustMatcher(matcher) {\n  if (matcher === 'self') {\n    return matcher;\n  } else if (isString(matcher)) {\n    // Strings match exactly except for 2 wildcards - '*' and '**'.\n    // '*' matches any character except those from the set ':/.?&'.\n    // '**' matches any character (like .* in a RegExp).\n    // More than 2 *'s raises an error as it's ill defined.\n    if (matcher.indexOf('***') > -1) {\n      throw $sceMinErr('iwcard',\n          'Illegal sequence *** in string matcher.  String: {0}', matcher);\n    }\n    matcher = escapeForRegexp(matcher).\n                  replace('\\\\*\\\\*', '.*').\n                  replace('\\\\*', '[^:/.?&;]*');\n    return new RegExp('^' + matcher + '$');\n  } else if (isRegExp(matcher)) {\n    // The only other type of matcher allowed is a Regexp.\n    // Match entire URL / disallow partial matches.\n    // Flags are reset (i.e. no global, ignoreCase or multiline)\n    return new RegExp('^' + matcher.source + '$');\n  } else {\n    throw $sceMinErr('imatcher',\n        'Matchers may only be \"self\", string patterns or RegExp objects');\n  }\n}\n\n\nfunction adjustMatchers(matchers) {\n  var adjustedMatchers = [];\n  if (isDefined(matchers)) {\n    forEach(matchers, function(matcher) {\n      adjustedMatchers.push(adjustMatcher(matcher));\n    });\n  }\n  return adjustedMatchers;\n}\n\n\n/**\n * @ngdoc service\n * @name $sceDelegate\n * @kind function\n *\n * @description\n *\n * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict\n * Contextual Escaping (SCE)} services to AngularJS.\n *\n * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of\n * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS.  This is\n * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to\n * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things\n * work because `$sce` delegates to `$sceDelegate` for these operations.\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.\n *\n * The default instance of `$sceDelegate` should work out of the box with little pain.  While you\n * can override it completely to change the behavior of `$sce`, the common case would\n * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting\n * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as\n * templates.  Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist\n * $sceDelegateProvider.resourceUrlWhitelist} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n */\n\n/**\n * @ngdoc provider\n * @name $sceDelegateProvider\n * @description\n *\n * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate\n * $sceDelegate} service.  This allows one to get/set the whitelists and blacklists used to ensure\n * that the URLs used for sourcing Angular templates are safe.  Refer {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and\n * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n *\n * For the general details about this service in Angular, read the main page for {@link ng.$sce\n * Strict Contextual Escaping (SCE)}.\n *\n * **Example**:  Consider the following case. <a name=\"example\"></a>\n *\n * - your app is hosted at url `http://myapp.example.com/`\n * - but some of your templates are hosted on other domains you control such as\n *   `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.\n * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.\n *\n * Here is what a secure configuration for this scenario might look like:\n *\n * ```\n *  angular.module('myApp', []).config(function($sceDelegateProvider) {\n *    $sceDelegateProvider.resourceUrlWhitelist([\n *      // Allow same origin resource loads.\n *      'self',\n *      // Allow loading from our assets domain.  Notice the difference between * and **.\n *      'http://srv*.assets.example.com/**'\n *    ]);\n *\n *    // The blacklist overrides the whitelist so the open redirect here is blocked.\n *    $sceDelegateProvider.resourceUrlBlacklist([\n *      'http://myapp.example.com/clickThru**'\n *    ]);\n *  });\n * ```\n */\n\nfunction $SceDelegateProvider() {\n  this.SCE_CONTEXTS = SCE_CONTEXTS;\n\n  // Resource URLs can also be trusted by policy.\n  var resourceUrlWhitelist = ['self'],\n      resourceUrlBlacklist = [];\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlWhitelist\n   * @kind function\n   *\n   * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     Note: **an empty whitelist array will block all URLs**!\n   *\n   * @return {Array} the currently set whitelist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is `['self']` allowing only\n   * same origin resource requests.\n   *\n   * @description\n   * Sets/Gets the whitelist of trusted resource URLs.\n   */\n  this.resourceUrlWhitelist = function(value) {\n    if (arguments.length) {\n      resourceUrlWhitelist = adjustMatchers(value);\n    }\n    return resourceUrlWhitelist;\n  };\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlBlacklist\n   * @kind function\n   *\n   * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     The typical usage for the blacklist is to **block\n   *     [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as\n   *     these would otherwise be trusted but actually return content from the redirected domain.\n   *\n   *     Finally, **the blacklist overrides the whitelist** and has the final say.\n   *\n   * @return {Array} the currently set blacklist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there\n   * is no blacklist.)\n   *\n   * @description\n   * Sets/Gets the blacklist of trusted resource URLs.\n   */\n\n  this.resourceUrlBlacklist = function(value) {\n    if (arguments.length) {\n      resourceUrlBlacklist = adjustMatchers(value);\n    }\n    return resourceUrlBlacklist;\n  };\n\n  this.$get = ['$injector', function($injector) {\n\n    var htmlSanitizer = function htmlSanitizer(html) {\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    };\n\n    if ($injector.has('$sanitize')) {\n      htmlSanitizer = $injector.get('$sanitize');\n    }\n\n\n    function matchUrl(matcher, parsedUrl) {\n      if (matcher === 'self') {\n        return urlIsSameOrigin(parsedUrl);\n      } else {\n        // definitely a regex.  See adjustMatchers()\n        return !!matcher.exec(parsedUrl.href);\n      }\n    }\n\n    function isResourceUrlAllowedByPolicy(url) {\n      var parsedUrl = urlResolve(url.toString());\n      var i, n, allowed = false;\n      // Ensure that at least one item from the whitelist allows this url.\n      for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {\n        if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {\n          allowed = true;\n          break;\n        }\n      }\n      if (allowed) {\n        // Ensure that no item from the blacklist blocked this url.\n        for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {\n          if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {\n            allowed = false;\n            break;\n          }\n        }\n      }\n      return allowed;\n    }\n\n    function generateHolderType(Base) {\n      var holderType = function TrustedValueHolderType(trustedValue) {\n        this.$$unwrapTrustedValue = function() {\n          return trustedValue;\n        };\n      };\n      if (Base) {\n        holderType.prototype = new Base();\n      }\n      holderType.prototype.valueOf = function sceValueOf() {\n        return this.$$unwrapTrustedValue();\n      };\n      holderType.prototype.toString = function sceToString() {\n        return this.$$unwrapTrustedValue().toString();\n      };\n      return holderType;\n    }\n\n    var trustedValueHolderBase = generateHolderType(),\n        byType = {};\n\n    byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#trustAs\n     *\n     * @description\n     * Returns an object that is trusted by angular for use in specified strict\n     * contextual escaping contexts (such as ng-bind-html, ng-include, any src\n     * attribute interpolation, any dom event binding attribute interpolation\n     * such as for onclick,  etc.) that uses the provided value.\n     * See {@link ng.$sce $sce} for enabling strict contextual escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resourceUrl, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n    function trustAs(type, trustedValue) {\n      var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (!Constructor) {\n        throw $sceMinErr('icontext',\n            'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',\n            type, trustedValue);\n      }\n      if (trustedValue === null || trustedValue === undefined || trustedValue === '') {\n        return trustedValue;\n      }\n      // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting\n      // mutable objects, we ensure here that the value passed in is actually a string.\n      if (typeof trustedValue !== 'string') {\n        throw $sceMinErr('itype',\n            'Attempted to trust a non-string value in a content requiring a string: Context: {0}',\n            type);\n      }\n      return new Constructor(trustedValue);\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#valueOf\n     *\n     * @description\n     * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs\n     * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.\n     *\n     * If the passed parameter is not a value that had been returned by {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.\n     *\n     * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}\n     *      call or anything else.\n     * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if `value` is the result of such a call.  Otherwise, returns\n     *     `value` unchanged.\n     */\n    function valueOf(maybeTrusted) {\n      if (maybeTrusted instanceof trustedValueHolderBase) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      } else {\n        return maybeTrusted;\n      }\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#getTrusted\n     *\n     * @description\n     * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and\n     * returns the originally supplied value if the queried context type is a supertype of the\n     * created type.  If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} call.\n     * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if valid in this context.  Otherwise, throws an exception.\n     */\n    function getTrusted(type, maybeTrusted) {\n      if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {\n        return maybeTrusted;\n      }\n      var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (constructor && maybeTrusted instanceof constructor) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      }\n      // If we get here, then we may only take one of two actions.\n      // 1. sanitize the value for the requested type, or\n      // 2. throw an exception.\n      if (type === SCE_CONTEXTS.RESOURCE_URL) {\n        if (isResourceUrlAllowedByPolicy(maybeTrusted)) {\n          return maybeTrusted;\n        } else {\n          throw $sceMinErr('insecurl',\n              'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',\n              maybeTrusted.toString());\n        }\n      } else if (type === SCE_CONTEXTS.HTML) {\n        return htmlSanitizer(maybeTrusted);\n      }\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    }\n\n    return { trustAs: trustAs,\n             getTrusted: getTrusted,\n             valueOf: valueOf };\n  }];\n}\n\n\n/**\n * @ngdoc provider\n * @name $sceProvider\n * @description\n *\n * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.\n * -   enable/disable Strict Contextual Escaping (SCE) in a module\n * -   override the default implementation with a custom delegate\n *\n * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.\n */\n\n/* jshint maxlen: false*/\n\n/**\n * @ngdoc service\n * @name $sce\n * @kind function\n *\n * @description\n *\n * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.\n *\n * # Strict Contextual Escaping\n *\n * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain\n * contexts to result in a value that is marked as safe to use for that context.  One example of\n * such a context is binding arbitrary html controlled by the user via `ng-bind-html`.  We refer\n * to these contexts as privileged or SCE contexts.\n *\n * As of version 1.2, Angular ships with SCE enabled by default.\n *\n * Note:  When enabled (the default), IE<11 in quirks mode is not supported.  In this mode, IE<11 allow\n * one to execute arbitrary javascript by the use of the expression() syntax.  Refer\n * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.\n * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`\n * to the top of your HTML document.\n *\n * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for\n * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.\n *\n * Here's an example of a binding in a privileged context:\n *\n * ```\n * <input ng-model=\"userHtml\" aria-label=\"User input\">\n * <div ng-bind-html=\"userHtml\"></div>\n * ```\n *\n * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user.  With SCE\n * disabled, this application allows the user to render arbitrary HTML into the DIV.\n * In a more realistic example, one may be rendering user comments, blog articles, etc. via\n * bindings.  (HTML is just one example of a context where rendering user controlled input creates\n * security vulnerabilities.)\n *\n * For the case of HTML, you might use a library, either on the client side, or on the server side,\n * to sanitize unsafe HTML before binding to the value and rendering it in the document.\n *\n * How would you ensure that every place that used these types of bindings was bound to a value that\n * was sanitized by your library (or returned as safe for rendering by your server?)  How can you\n * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some\n * properties/fields and forgot to update the binding to the sanitized value?\n *\n * To be secure by default, you want to ensure that any such bindings are disallowed unless you can\n * determine that something explicitly says it's safe to use a value for binding in that\n * context.  You can then audit your code (a simple grep would do) to ensure that this is only done\n * for those values that you can easily tell are safe - because they were received from your server,\n * sanitized by your library, etc.  You can organize your codebase to help with this - perhaps\n * allowing only the files in a specific directory to do this.  Ensuring that the internal API\n * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.\n *\n * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}\n * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to\n * obtain values that will be accepted by SCE / privileged contexts.\n *\n *\n * ## How does it work?\n *\n * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted\n * $sce.getTrusted(context, value)} rather than to the value directly.  Directives use {@link\n * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the\n * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.\n *\n * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link\n * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}.  Here's the actual code (slightly\n * simplified):\n *\n * ```\n * var ngBindHtmlDirective = ['$sce', function($sce) {\n *   return function(scope, element, attr) {\n *     scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {\n *       element.html(value || '');\n *     });\n *   };\n * }];\n * ```\n *\n * ## Impact on loading templates\n *\n * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as\n * `templateUrl`'s specified by {@link guide/directive directives}.\n *\n * By default, Angular only loads templates from the same domain and protocol as the application\n * document.  This is done by calling {@link ng.$sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on the template URL.  To load templates from other domains and/or\n * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist\n * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.\n *\n * *Please note*:\n * The browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy apply in addition to this and may further restrict whether the template is successfully\n * loaded.  This means that without the right CORS policy, loading templates from a different domain\n * won't work on all browsers.  Also, loading templates from `file://` URL does not work on some\n * browsers.\n *\n * ## This feels like too much overhead\n *\n * It's important to remember that SCE only applies to interpolation expressions.\n *\n * If your expressions are constant literals, they're automatically trusted and you don't need to\n * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.\n * `<div ng-bind-html=\"'<b>implicitly trusted</b>'\"></div>`) just works.\n *\n * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them\n * through {@link ng.$sce#getTrusted $sce.getTrusted}.  SCE doesn't play a role here.\n *\n * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load\n * templates in `ng-include` from your application's domain without having to even know about SCE.\n * It blocks loading templates from other domains or loading templates over http from an https\n * served document.  You can change these by setting your own custom {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.\n *\n * This significantly reduces the overhead.  It is far easier to pay the small overhead and have an\n * application that's secure and can be audited to verify that with much more ease than bolting\n * security onto an application later.\n *\n * <a name=\"contexts\"></a>\n * ## What trusted context types are supported?\n *\n * | Context             | Notes          |\n * |---------------------|----------------|\n * | `$sce.HTML`         | For HTML that's safe to source into the application.  The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |\n * | `$sce.CSS`          | For CSS that's safe to source into the application.  Currently unused.  Feel free to use it in your own directives. |\n * | `$sce.URL`          | For URLs that are safe to follow as links.  Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |\n * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application.  Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.)  <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |\n * | `$sce.JS`           | For JavaScript that is safe to execute in your application's context.  Currently unused.  Feel free to use it in your own directives. |\n *\n * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name=\"resourceUrlPatternItem\"></a>\n *\n *  Each element in these arrays must be one of the following:\n *\n *  - **'self'**\n *    - The special **string**, `'self'`, can be used to match against all URLs of the **same\n *      domain** as the application document using the **same protocol**.\n *  - **String** (except the special value `'self'`)\n *    - The string is matched against the full *normalized / absolute URL* of the resource\n *      being tested (substring matches are not good enough.)\n *    - There are exactly **two wildcard sequences** - `*` and `**`.  All other characters\n *      match themselves.\n *    - `*`: matches zero or more occurrences of any character other than one of the following 6\n *      characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'.  It's a useful wildcard for use\n *      in a whitelist.\n *    - `**`: matches zero or more occurrences of *any* character.  As such, it's not\n *      appropriate for use in a scheme, domain, etc. as it would match too much.  (e.g.\n *      http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might\n *      not have been the intention.)  Its usage at the very end of the path is ok.  (e.g.\n *      http://foo.example.com/templates/**).\n *  - **RegExp** (*see caveat below*)\n *    - *Caveat*:  While regular expressions are powerful and offer great flexibility,  their syntax\n *      (and all the inevitable escaping) makes them *harder to maintain*.  It's easy to\n *      accidentally introduce a bug when one updates a complex expression (imho, all regexes should\n *      have good test coverage).  For instance, the use of `.` in the regex is correct only in a\n *      small number of cases.  A `.` character in the regex used when matching the scheme or a\n *      subdomain could be matched against a `:` or literal `.` that was likely not intended.   It\n *      is highly recommended to use the string patterns and only fall back to regular expressions\n *      as a last resort.\n *    - The regular expression must be an instance of RegExp (i.e. not a string.)  It is\n *      matched against the **entire** *normalized / absolute URL* of the resource being tested\n *      (even when the RegExp did not have the `^` and `$` codes.)  In addition, any flags\n *      present on the RegExp (such as multiline, global, ignoreCase) are ignored.\n *    - If you are generating your JavaScript from some other templating engine (not\n *      recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),\n *      remember to escape your regular expression (and be aware that you might need more than\n *      one level of escaping depending on your templating engine and the way you interpolated\n *      the value.)  Do make use of your platform's escaping mechanism as it might be good\n *      enough before coding your own.  E.g. Ruby has\n *      [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)\n *      and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).\n *      Javascript lacks a similar built in function for escaping.  Take a look at Google\n *      Closure library's [goog.string.regExpEscape(s)](\n *      http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.\n *\n * ## Show me an example using SCE.\n *\n * <example module=\"mySceApp\" deps=\"angular-sanitize.js\">\n * <file name=\"index.html\">\n *   <div ng-controller=\"AppController as myCtrl\">\n *     <i ng-bind-html=\"myCtrl.explicitlyTrustedHtml\" id=\"explicitlyTrustedHtml\"></i><br><br>\n *     <b>User comments</b><br>\n *     By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when\n *     $sanitize is available.  If $sanitize isn't available, this results in an error instead of an\n *     exploit.\n *     <div class=\"well\">\n *       <div ng-repeat=\"userComment in myCtrl.userComments\">\n *         <b>{{userComment.name}}</b>:\n *         <span ng-bind-html=\"userComment.htmlComment\" class=\"htmlComment\"></span>\n *         <br>\n *       </div>\n *     </div>\n *   </div>\n * </file>\n *\n * <file name=\"script.js\">\n *   angular.module('mySceApp', ['ngSanitize'])\n *     .controller('AppController', ['$http', '$templateCache', '$sce',\n *       function($http, $templateCache, $sce) {\n *         var self = this;\n *         $http.get(\"test_data.json\", {cache: $templateCache}).success(function(userComments) {\n *           self.userComments = userComments;\n *         });\n *         self.explicitlyTrustedHtml = $sce.trustAsHtml(\n *             '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *             'sanitization.&quot;\">Hover over this text.</span>');\n *       }]);\n * </file>\n *\n * <file name=\"test_data.json\">\n * [\n *   { \"name\": \"Alice\",\n *     \"htmlComment\":\n *         \"<span onmouseover='this.textContent=\\\"PWN3D!\\\"'>Is <i>anyone</i> reading this?</span>\"\n *   },\n *   { \"name\": \"Bob\",\n *     \"htmlComment\": \"<i>Yes!</i>  Am I the only other one?\"\n *   }\n * ]\n * </file>\n *\n * <file name=\"protractor.js\" type=\"protractor\">\n *   describe('SCE doc demo', function() {\n *     it('should sanitize untrusted values', function() {\n *       expect(element.all(by.css('.htmlComment')).first().getInnerHtml())\n *           .toBe('<span>Is <i>anyone</i> reading this?</span>');\n *     });\n *\n *     it('should NOT sanitize explicitly trusted values', function() {\n *       expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(\n *           '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *           'sanitization.&quot;\">Hover over this text.</span>');\n *     });\n *   });\n * </file>\n * </example>\n *\n *\n *\n * ## Can I disable SCE completely?\n *\n * Yes, you can.  However, this is strongly discouraged.  SCE gives you a lot of security benefits\n * for little coding overhead.  It will be much harder to take an SCE disabled application and\n * either secure it on your own or enable SCE at a later stage.  It might make sense to disable SCE\n * for cases where you have a lot of existing code that was written before SCE was introduced and\n * you're migrating them a module at a time.\n *\n * That said, here's how you can completely disable SCE:\n *\n * ```\n * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {\n *   // Completely disable SCE.  For demonstration purposes only!\n *   // Do not use in new projects.\n *   $sceProvider.enabled(false);\n * });\n * ```\n *\n */\n/* jshint maxlen: 100 */\n\nfunction $SceProvider() {\n  var enabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $sceProvider#enabled\n   * @kind function\n   *\n   * @param {boolean=} value If provided, then enables/disables SCE.\n   * @return {boolean} true if SCE is enabled, false otherwise.\n   *\n   * @description\n   * Enables/disables SCE and returns the current value.\n   */\n  this.enabled = function(value) {\n    if (arguments.length) {\n      enabled = !!value;\n    }\n    return enabled;\n  };\n\n\n  /* Design notes on the default implementation for SCE.\n   *\n   * The API contract for the SCE delegate\n   * -------------------------------------\n   * The SCE delegate object must provide the following 3 methods:\n   *\n   * - trustAs(contextEnum, value)\n   *     This method is used to tell the SCE service that the provided value is OK to use in the\n   *     contexts specified by contextEnum.  It must return an object that will be accepted by\n   *     getTrusted() for a compatible contextEnum and return this value.\n   *\n   * - valueOf(value)\n   *     For values that were not produced by trustAs(), return them as is.  For values that were\n   *     produced by trustAs(), return the corresponding input value to trustAs.  Basically, if\n   *     trustAs is wrapping the given values into some type, this operation unwraps it when given\n   *     such a value.\n   *\n   * - getTrusted(contextEnum, value)\n   *     This function should return the a value that is safe to use in the context specified by\n   *     contextEnum or throw and exception otherwise.\n   *\n   * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be\n   * opaque or wrapped in some holder object.  That happens to be an implementation detail.  For\n   * instance, an implementation could maintain a registry of all trusted objects by context.  In\n   * such a case, trustAs() would return the same object that was passed in.  getTrusted() would\n   * return the same object passed in if it was found in the registry under a compatible context or\n   * throw an exception otherwise.  An implementation might only wrap values some of the time based\n   * on some criteria.  getTrusted() might return a value and not throw an exception for special\n   * constants or objects even if not wrapped.  All such implementations fulfill this contract.\n   *\n   *\n   * A note on the inheritance model for SCE contexts\n   * ------------------------------------------------\n   * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types.  This\n   * is purely an implementation details.\n   *\n   * The contract is simply this:\n   *\n   *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)\n   *     will also succeed.\n   *\n   * Inheritance happens to capture this in a natural way.  In some future, we\n   * may not use inheritance anymore.  That is OK because no code outside of\n   * sce.js and sceSpecs.js would need to be aware of this detail.\n   */\n\n  this.$get = ['$parse', '$sceDelegate', function(\n                $parse,   $sceDelegate) {\n    // Prereq: Ensure that we're not running in IE<11 quirks mode.  In that mode, IE < 11 allow\n    // the \"expression(javascript expression)\" syntax which is insecure.\n    if (enabled && msie < 8) {\n      throw $sceMinErr('iequirks',\n        'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +\n        'mode.  You can fix this by adding the text <!doctype html> to the top of your HTML ' +\n        'document.  See http://docs.angularjs.org/api/ng.$sce for more information.');\n    }\n\n    var sce = shallowCopy(SCE_CONTEXTS);\n\n    /**\n     * @ngdoc method\n     * @name $sce#isEnabled\n     * @kind function\n     *\n     * @return {Boolean} true if SCE is enabled, false otherwise.  If you want to set the value, you\n     * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.\n     *\n     * @description\n     * Returns a boolean indicating if SCE is enabled.\n     */\n    sce.isEnabled = function() {\n      return enabled;\n    };\n    sce.trustAs = $sceDelegate.trustAs;\n    sce.getTrusted = $sceDelegate.getTrusted;\n    sce.valueOf = $sceDelegate.valueOf;\n\n    if (!enabled) {\n      sce.trustAs = sce.getTrusted = function(type, value) { return value; };\n      sce.valueOf = identity;\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAs\n     *\n     * @description\n     * Converts Angular {@link guide/expression expression} into a function.  This is like {@link\n     * ng.$parse $parse} and is identical when the expression is a literal constant.  Otherwise, it\n     * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,\n     * *result*)}\n     *\n     * @param {string} type The kind of SCE context in which this result will be used.\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n    sce.parseAs = function sceParseAs(type, expr) {\n      var parsed = $parse(expr);\n      if (parsed.literal && parsed.constant) {\n        return parsed;\n      } else {\n        return $parse(expr, function(value) {\n          return sce.getTrusted(type, value);\n        });\n      }\n    };\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAs\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.  As such,\n     * returns an object that is trusted by angular for use in specified strict contextual\n     * escaping contexts (such as ng-bind-html, ng-include, any src attribute\n     * interpolation, any dom event binding attribute interpolation such as for onclick,  etc.)\n     * that uses the provided value.  See * {@link ng.$sce $sce} for enabling strict contextual\n     * escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resourceUrl, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsHtml(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml\n     *     $sce.getTrustedHtml(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl\n     *     $sce.getTrustedUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl\n     *     $sce.getTrustedResourceUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the return\n     *     value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsJs(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs\n     *     $sce.getTrustedJs(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrusted\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}.  As such,\n     * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the\n     * originally supplied value if the queried context type is a supertype of the created type.\n     * If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}\n     *                         call.\n     * @returns {*} The value the was originally provided to\n     *              {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.\n     *              Otherwise, throws an exception.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedHtml(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedCss\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedCss(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sceDelegate.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedJs\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedJs(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsHtml(expression string)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsCss\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsCss(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsResourceUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsJs(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    // Shorthand delegations.\n    var parse = sce.parseAs,\n        getTrusted = sce.getTrusted,\n        trustAs = sce.trustAs;\n\n    forEach(SCE_CONTEXTS, function(enumValue, name) {\n      var lName = lowercase(name);\n      sce[camelCase(\"parse_as_\" + lName)] = function(expr) {\n        return parse(enumValue, expr);\n      };\n      sce[camelCase(\"get_trusted_\" + lName)] = function(value) {\n        return getTrusted(enumValue, value);\n      };\n      sce[camelCase(\"trust_as_\" + lName)] = function(value) {\n        return trustAs(enumValue, value);\n      };\n    });\n\n    return sce;\n  }];\n}\n\n/**\n * !!! This is an undocumented \"private\" service !!!\n *\n * @name $sniffer\n * @requires $window\n * @requires $document\n *\n * @property {boolean} history Does the browser support html5 history api ?\n * @property {boolean} transitions Does the browser support CSS transition events ?\n * @property {boolean} animations Does the browser support CSS animation events ?\n *\n * @description\n * This is very simple implementation of testing browser's features.\n */\nfunction $SnifferProvider() {\n  this.$get = ['$window', '$document', function($window, $document) {\n    var eventSupport = {},\n        android =\n          toInt((/android (\\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),\n        boxee = /Boxee/i.test(($window.navigator || {}).userAgent),\n        document = $document[0] || {},\n        vendorPrefix,\n        vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,\n        bodyStyle = document.body && document.body.style,\n        transitions = false,\n        animations = false,\n        match;\n\n    if (bodyStyle) {\n      for (var prop in bodyStyle) {\n        if (match = vendorRegex.exec(prop)) {\n          vendorPrefix = match[0];\n          vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);\n          break;\n        }\n      }\n\n      if (!vendorPrefix) {\n        vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';\n      }\n\n      transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));\n      animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));\n\n      if (android && (!transitions ||  !animations)) {\n        transitions = isString(bodyStyle.webkitTransition);\n        animations = isString(bodyStyle.webkitAnimation);\n      }\n    }\n\n\n    return {\n      // Android has history.pushState, but it does not update location correctly\n      // so let's not use the history API at all.\n      // http://code.google.com/p/android/issues/detail?id=17471\n      // https://github.com/angular/angular.js/issues/904\n\n      // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has\n      // so let's not use the history API also\n      // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined\n      // jshint -W018\n      history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),\n      // jshint +W018\n      hasEvent: function(event) {\n        // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have\n        // it. In particular the event is not fired when backspace or delete key are pressed or\n        // when cut operation is performed.\n        // IE10+ implements 'input' event but it erroneously fires under various situations,\n        // e.g. when placeholder changes, or a form is focused.\n        if (event === 'input' && msie <= 11) return false;\n\n        if (isUndefined(eventSupport[event])) {\n          var divElm = document.createElement('div');\n          eventSupport[event] = 'on' + event in divElm;\n        }\n\n        return eventSupport[event];\n      },\n      csp: csp(),\n      vendorPrefix: vendorPrefix,\n      transitions: transitions,\n      animations: animations,\n      android: android\n    };\n  }];\n}\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc service\n * @name $templateRequest\n *\n * @description\n * The `$templateRequest` service runs security checks then downloads the provided template using\n * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request\n * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the\n * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the\n * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted\n * when `tpl` is of type string and `$templateCache` has the matching entry.\n *\n * @param {string|TrustedResourceUrl} tpl The HTTP request template URL\n * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty\n *\n * @return {Promise} a promise for the HTTP response data of the given URL.\n *\n * @property {number} totalPendingRequests total amount of pending template requests being downloaded.\n */\nfunction $TemplateRequestProvider() {\n  this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {\n    function handleRequestFn(tpl, ignoreRequestError) {\n      handleRequestFn.totalPendingRequests++;\n\n      // We consider the template cache holds only trusted templates, so\n      // there's no need to go through whitelisting again for keys that already\n      // are included in there. This also makes Angular accept any script\n      // directive, no matter its name. However, we still need to unwrap trusted\n      // types.\n      if (!isString(tpl) || !$templateCache.get(tpl)) {\n        tpl = $sce.getTrustedResourceUrl(tpl);\n      }\n\n      var transformResponse = $http.defaults && $http.defaults.transformResponse;\n\n      if (isArray(transformResponse)) {\n        transformResponse = transformResponse.filter(function(transformer) {\n          return transformer !== defaultHttpResponseTransform;\n        });\n      } else if (transformResponse === defaultHttpResponseTransform) {\n        transformResponse = null;\n      }\n\n      var httpOptions = {\n        cache: $templateCache,\n        transformResponse: transformResponse\n      };\n\n      return $http.get(tpl, httpOptions)\n        ['finally'](function() {\n          handleRequestFn.totalPendingRequests--;\n        })\n        .then(function(response) {\n          $templateCache.put(tpl, response.data);\n          return response.data;\n        }, handleError);\n\n      function handleError(resp) {\n        if (!ignoreRequestError) {\n          throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',\n            tpl, resp.status, resp.statusText);\n        }\n        return $q.reject(resp);\n      }\n    }\n\n    handleRequestFn.totalPendingRequests = 0;\n\n    return handleRequestFn;\n  }];\n}\n\nfunction $$TestabilityProvider() {\n  this.$get = ['$rootScope', '$browser', '$location',\n       function($rootScope,   $browser,   $location) {\n\n    /**\n     * @name $testability\n     *\n     * @description\n     * The private $$testability service provides a collection of methods for use when debugging\n     * or by automated test and debugging tools.\n     */\n    var testability = {};\n\n    /**\n     * @name $$testability#findBindings\n     *\n     * @description\n     * Returns an array of elements that are bound (via ng-bind or {{}})\n     * to expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The binding expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression. Filters and whitespace are ignored.\n     */\n    testability.findBindings = function(element, expression, opt_exactMatch) {\n      var bindings = element.getElementsByClassName('ng-binding');\n      var matches = [];\n      forEach(bindings, function(binding) {\n        var dataBinding = angular.element(binding).data('$binding');\n        if (dataBinding) {\n          forEach(dataBinding, function(bindingName) {\n            if (opt_exactMatch) {\n              var matcher = new RegExp('(^|\\\\s)' + escapeForRegexp(expression) + '(\\\\s|\\\\||$)');\n              if (matcher.test(bindingName)) {\n                matches.push(binding);\n              }\n            } else {\n              if (bindingName.indexOf(expression) != -1) {\n                matches.push(binding);\n              }\n            }\n          });\n        }\n      });\n      return matches;\n    };\n\n    /**\n     * @name $$testability#findModels\n     *\n     * @description\n     * Returns an array of elements that are two-way found via ng-model to\n     * expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The model expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression.\n     */\n    testability.findModels = function(element, expression, opt_exactMatch) {\n      var prefixes = ['ng-', 'data-ng-', 'ng\\\\:'];\n      for (var p = 0; p < prefixes.length; ++p) {\n        var attributeEquals = opt_exactMatch ? '=' : '*=';\n        var selector = '[' + prefixes[p] + 'model' + attributeEquals + '\"' + expression + '\"]';\n        var elements = element.querySelectorAll(selector);\n        if (elements.length) {\n          return elements;\n        }\n      }\n    };\n\n    /**\n     * @name $$testability#getLocation\n     *\n     * @description\n     * Shortcut for getting the location in a browser agnostic way. Returns\n     *     the path, search, and hash. (e.g. /path?a=b#hash)\n     */\n    testability.getLocation = function() {\n      return $location.url();\n    };\n\n    /**\n     * @name $$testability#setLocation\n     *\n     * @description\n     * Shortcut for navigating to a location without doing a full page reload.\n     *\n     * @param {string} url The location url (path, search and hash,\n     *     e.g. /path?a=b#hash) to go to.\n     */\n    testability.setLocation = function(url) {\n      if (url !== $location.url()) {\n        $location.url(url);\n        $rootScope.$digest();\n      }\n    };\n\n    /**\n     * @name $$testability#whenStable\n     *\n     * @description\n     * Calls the callback when $timeout and $http requests are completed.\n     *\n     * @param {function} callback\n     */\n    testability.whenStable = function(callback) {\n      $browser.notifyWhenNoOutstandingRequests(callback);\n    };\n\n    return testability;\n  }];\n}\n\nfunction $TimeoutProvider() {\n  this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',\n       function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {\n\n    var deferreds = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $timeout\n      *\n      * @description\n      * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch\n      * block and delegates any exceptions to\n      * {@link ng.$exceptionHandler $exceptionHandler} service.\n      *\n      * The return value of calling `$timeout` is a promise, which will be resolved when\n      * the delay has passed and the timeout function, if provided, is executed.\n      *\n      * To cancel a timeout request, call `$timeout.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to\n      * synchronously flush the queue of deferred functions.\n      *\n      * If you only want a promise that will be resolved after some specified delay\n      * then you can call `$timeout` without the `fn` function.\n      *\n      * @param {function()=} fn A function, whose execution should be delayed.\n      * @param {number=} [delay=0] Delay in milliseconds.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @param {...*=} Pass additional parameters to the executed function.\n      * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this\n      *   promise will be resolved with is the return value of the `fn` function.\n      *\n      */\n    function timeout(fn, delay, invokeApply) {\n      if (!isFunction(fn)) {\n        invokeApply = delay;\n        delay = fn;\n        fn = noop;\n      }\n\n      var args = sliceArgs(arguments, 3),\n          skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise,\n          timeoutId;\n\n      timeoutId = $browser.defer(function() {\n        try {\n          deferred.resolve(fn.apply(null, args));\n        } catch (e) {\n          deferred.reject(e);\n          $exceptionHandler(e);\n        }\n        finally {\n          delete deferreds[promise.$$timeoutId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n      }, delay);\n\n      promise.$$timeoutId = timeoutId;\n      deferreds[timeoutId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $timeout#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`. As a result of this, the promise will be\n      * resolved with a rejection.\n      *\n      * @param {Promise=} promise Promise returned by the `$timeout` function.\n      * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n      *   canceled.\n      */\n    timeout.cancel = function(promise) {\n      if (promise && promise.$$timeoutId in deferreds) {\n        deferreds[promise.$$timeoutId].reject('canceled');\n        delete deferreds[promise.$$timeoutId];\n        return $browser.defer.cancel(promise.$$timeoutId);\n      }\n      return false;\n    };\n\n    return timeout;\n  }];\n}\n\n// NOTE:  The usage of window and document instead of $window and $document here is\n// deliberate.  This service depends on the specific behavior of anchor nodes created by the\n// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and\n// cause us to break tests.  In addition, when the browser resolves a URL for XHR, it\n// doesn't know about mocked locations and resolves URLs to the real document - which is\n// exactly the behavior needed here.  There is little value is mocking these out for this\n// service.\nvar urlParsingNode = document.createElement(\"a\");\nvar originUrl = urlResolve(window.location.href);\n\n\n/**\n *\n * Implementation Notes for non-IE browsers\n * ----------------------------------------\n * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,\n * results both in the normalizing and parsing of the URL.  Normalizing means that a relative\n * URL will be resolved into an absolute URL in the context of the application document.\n * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related\n * properties are all populated to reflect the normalized URL.  This approach has wide\n * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc.  See\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *\n * Implementation Notes for IE\n * ---------------------------\n * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other\n * browsers.  However, the parsed components will not be set if the URL assigned did not specify\n * them.  (e.g. if you assign a.href = \"foo\", then a.protocol, a.host, etc. will be empty.)  We\n * work around that by performing the parsing in a 2nd step by taking a previously normalized\n * URL (e.g. by assigning to a.href) and assigning it a.href again.  This correctly populates the\n * properties such as protocol, hostname, port, etc.\n *\n * References:\n *   http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement\n *   http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *   http://url.spec.whatwg.org/#urlutils\n *   https://github.com/angular/angular.js/pull/2902\n *   http://james.padolsey.com/javascript/parsing-urls-with-the-dom/\n *\n * @kind function\n * @param {string} url The URL to be parsed.\n * @description Normalizes and parses a URL.\n * @returns {object} Returns the normalized URL as a dictionary.\n *\n *   | member name   | Description    |\n *   |---------------|----------------|\n *   | href          | A normalized version of the provided URL if it was not an absolute URL |\n *   | protocol      | The protocol including the trailing colon                              |\n *   | host          | The host and port (if the port is non-default) of the normalizedUrl    |\n *   | search        | The search params, minus the question mark                             |\n *   | hash          | The hash string, minus the hash symbol\n *   | hostname      | The hostname\n *   | port          | The port, without \":\"\n *   | pathname      | The pathname, beginning with \"/\"\n *\n */\nfunction urlResolve(url) {\n  var href = url;\n\n  if (msie) {\n    // Normalize before parse.  Refer Implementation Notes on why this is\n    // done in two steps on IE.\n    urlParsingNode.setAttribute(\"href\", href);\n    href = urlParsingNode.href;\n  }\n\n  urlParsingNode.setAttribute('href', href);\n\n  // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n  return {\n    href: urlParsingNode.href,\n    protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n    host: urlParsingNode.host,\n    search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n    hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n    hostname: urlParsingNode.hostname,\n    port: urlParsingNode.port,\n    pathname: (urlParsingNode.pathname.charAt(0) === '/')\n      ? urlParsingNode.pathname\n      : '/' + urlParsingNode.pathname\n  };\n}\n\n/**\n * Parse a request URL and determine whether this is a same-origin request as the application document.\n *\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\n * or a parsed URL object.\n * @returns {boolean} Whether the request is for the same origin as the application document.\n */\nfunction urlIsSameOrigin(requestUrl) {\n  var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;\n  return (parsed.protocol === originUrl.protocol &&\n          parsed.host === originUrl.host);\n}\n\n/**\n * @ngdoc service\n * @name $window\n *\n * @description\n * A reference to the browser's `window` object. While `window`\n * is globally available in JavaScript, it causes testability problems, because\n * it is a global variable. In angular we always refer to it through the\n * `$window` service, so it may be overridden, removed or mocked for testing.\n *\n * Expressions, like the one defined for the `ngClick` directive in the example\n * below, are evaluated with respect to the current scope.  Therefore, there is\n * no risk of inadvertently coding in a dependency on a global value in such an\n * expression.\n *\n * @example\n   <example module=\"windowExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('windowExample', [])\n           .controller('ExampleController', ['$scope', '$window', function($scope, $window) {\n             $scope.greeting = 'Hello, World!';\n             $scope.doGreeting = function(greeting) {\n               $window.alert(greeting);\n             };\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"text\" ng-model=\"greeting\" aria-label=\"greeting\" />\n         <button ng-click=\"doGreeting(greeting)\">ALERT</button>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n      it('should display the greeting in the input box', function() {\n       element(by.model('greeting')).sendKeys('Hello, E2E Tests');\n       // If we click the button it will block the test runner\n       // element(':button').click();\n      });\n     </file>\n   </example>\n */\nfunction $WindowProvider() {\n  this.$get = valueFn(window);\n}\n\n/**\n * @name $$cookieReader\n * @requires $document\n *\n * @description\n * This is a private service for reading cookies used by $http and ngCookies\n *\n * @return {Object} a key/value map of the current cookies\n */\nfunction $$CookieReader($document) {\n  var rawDocument = $document[0] || {};\n  var lastCookies = {};\n  var lastCookieString = '';\n\n  function safeDecodeURIComponent(str) {\n    try {\n      return decodeURIComponent(str);\n    } catch (e) {\n      return str;\n    }\n  }\n\n  return function() {\n    var cookieArray, cookie, i, index, name;\n    var currentCookieString = rawDocument.cookie || '';\n\n    if (currentCookieString !== lastCookieString) {\n      lastCookieString = currentCookieString;\n      cookieArray = lastCookieString.split('; ');\n      lastCookies = {};\n\n      for (i = 0; i < cookieArray.length; i++) {\n        cookie = cookieArray[i];\n        index = cookie.indexOf('=');\n        if (index > 0) { //ignore nameless cookies\n          name = safeDecodeURIComponent(cookie.substring(0, index));\n          // the first value that is seen for a cookie is the most\n          // specific one.  values for the same cookie name that\n          // follow are for less specific paths.\n          if (lastCookies[name] === undefined) {\n            lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));\n          }\n        }\n      }\n    }\n    return lastCookies;\n  };\n}\n\n$$CookieReader.$inject = ['$document'];\n\nfunction $$CookieReaderProvider() {\n  this.$get = $$CookieReader;\n}\n\n/* global currencyFilter: true,\n dateFilter: true,\n filterFilter: true,\n jsonFilter: true,\n limitToFilter: true,\n lowercaseFilter: true,\n numberFilter: true,\n orderByFilter: true,\n uppercaseFilter: true,\n */\n\n/**\n * @ngdoc provider\n * @name $filterProvider\n * @description\n *\n * Filters are just functions which transform input to an output. However filters need to be\n * Dependency Injected. To achieve this a filter definition consists of a factory function which is\n * annotated with dependencies and is responsible for creating a filter function.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n * </div>\n *\n * ```js\n *   // Filter registration\n *   function MyModule($provide, $filterProvider) {\n *     // create a service to demonstrate injection (not always needed)\n *     $provide.value('greet', function(name){\n *       return 'Hello ' + name + '!';\n *     });\n *\n *     // register a filter factory which uses the\n *     // greet service to demonstrate DI.\n *     $filterProvider.register('greet', function(greet){\n *       // return the filter function which uses the greet service\n *       // to generate salutation\n *       return function(text) {\n *         // filters need to be forgiving so check input validity\n *         return text && greet(text) || text;\n *       };\n *     });\n *   }\n * ```\n *\n * The filter function is registered with the `$injector` under the filter name suffix with\n * `Filter`.\n *\n * ```js\n *   it('should be the same instance', inject(\n *     function($filterProvider) {\n *       $filterProvider.register('reverse', function(){\n *         return ...;\n *       });\n *     },\n *     function($filter, reverseFilter) {\n *       expect($filter('reverse')).toBe(reverseFilter);\n *     });\n * ```\n *\n *\n * For more information about how angular filters work, and how to create your own filters, see\n * {@link guide/filter Filters} in the Angular Developer Guide.\n */\n\n/**\n * @ngdoc service\n * @name $filter\n * @kind function\n * @description\n * Filters are used for formatting data displayed to the user.\n *\n * The general syntax in templates is as follows:\n *\n *         {{ expression [| filter_name[:parameter_value] ... ] }}\n *\n * @param {String} name Name of the filter function to retrieve\n * @return {Function} the filter function\n * @example\n   <example name=\"$filter\" module=\"filterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"MainCtrl\">\n        <h3>{{ originalText }}</h3>\n        <h3>{{ filteredText }}</h3>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n      angular.module('filterExample', [])\n      .controller('MainCtrl', function($scope, $filter) {\n        $scope.originalText = 'hello';\n        $scope.filteredText = $filter('uppercase')($scope.originalText);\n      });\n     </file>\n   </example>\n  */\n$FilterProvider.$inject = ['$provide'];\nfunction $FilterProvider($provide) {\n  var suffix = 'Filter';\n\n  /**\n   * @ngdoc method\n   * @name $filterProvider#register\n   * @param {string|Object} name Name of the filter function, or an object map of filters where\n   *    the keys are the filter names and the values are the filter factories.\n   *\n   *    <div class=\"alert alert-warning\">\n   *    **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n   *    Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n   *    your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n   *    (`myapp_subsection_filterx`).\n   *    </div>\n    * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.\n   * @returns {Object} Registered filter instance, or if a map of filters was provided then a map\n   *    of the registered filter instances.\n   */\n  function register(name, factory) {\n    if (isObject(name)) {\n      var filters = {};\n      forEach(name, function(filter, key) {\n        filters[key] = register(key, filter);\n      });\n      return filters;\n    } else {\n      return $provide.factory(name + suffix, factory);\n    }\n  }\n  this.register = register;\n\n  this.$get = ['$injector', function($injector) {\n    return function(name) {\n      return $injector.get(name + suffix);\n    };\n  }];\n\n  ////////////////////////////////////////\n\n  /* global\n    currencyFilter: false,\n    dateFilter: false,\n    filterFilter: false,\n    jsonFilter: false,\n    limitToFilter: false,\n    lowercaseFilter: false,\n    numberFilter: false,\n    orderByFilter: false,\n    uppercaseFilter: false,\n  */\n\n  register('currency', currencyFilter);\n  register('date', dateFilter);\n  register('filter', filterFilter);\n  register('json', jsonFilter);\n  register('limitTo', limitToFilter);\n  register('lowercase', lowercaseFilter);\n  register('number', numberFilter);\n  register('orderBy', orderByFilter);\n  register('uppercase', uppercaseFilter);\n}\n\n/**\n * @ngdoc filter\n * @name filter\n * @kind function\n *\n * @description\n * Selects a subset of items from `array` and returns it as a new array.\n *\n * @param {Array} array The source array.\n * @param {string|Object|function()} expression The predicate to be used for selecting items from\n *   `array`.\n *\n *   Can be one of:\n *\n *   - `string`: The string is used for matching against the contents of the `array`. All strings or\n *     objects with string properties in `array` that match this string will be returned. This also\n *     applies to nested object properties.\n *     The predicate can be negated by prefixing the string with `!`.\n *\n *   - `Object`: A pattern object can be used to filter specific properties on objects contained\n *     by `array`. For example `{name:\"M\", phone:\"1\"}` predicate will return an array of items\n *     which have property `name` containing \"M\" and property `phone` containing \"1\". A special\n *     property name `$` can be used (as in `{$:\"text\"}`) to accept a match against any\n *     property of the object or its nested object properties. That's equivalent to the simple\n *     substring match with a `string` as described above. The predicate can be negated by prefixing\n *     the string with `!`.\n *     For example `{name: \"!M\"}` predicate will return an array of items which have property `name`\n *     not containing \"M\".\n *\n *     Note that a named property will match properties on the same level only, while the special\n *     `$` property will match properties on the same level or deeper. E.g. an array item like\n *     `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but\n *     **will** be matched by `{$: 'John'}`.\n *\n *   - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.\n *     The function is called for each element of the array, with the element, its index, and\n *     the entire array itself as arguments.\n *\n *     The final result is an array of those elements that the predicate returned true for.\n *\n * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in\n *     determining if the expected value (from the filter expression) and actual value (from\n *     the object in the array) should be considered a match.\n *\n *   Can be one of:\n *\n *   - `function(actual, expected)`:\n *     The function will be given the object value and the predicate value to compare and\n *     should return true if both values should be considered equal.\n *\n *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.\n *     This is essentially strict comparison of expected and actual.\n *\n *   - `false|undefined`: A short hand for a function which will look for a substring match in case\n *     insensitive way.\n *\n *     Primitive values are converted to strings. Objects are not compared against primitives,\n *     unless they have a custom `toString` method (e.g. `Date` objects).\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <div ng-init=\"friends = [{name:'John', phone:'555-1276'},\n                                {name:'Mary', phone:'800-BIG-MARY'},\n                                {name:'Mike', phone:'555-4321'},\n                                {name:'Adam', phone:'555-5678'},\n                                {name:'Julie', phone:'555-8765'},\n                                {name:'Juliette', phone:'555-5678'}]\"></div>\n\n       <label>Search: <input ng-model=\"searchText\"></label>\n       <table id=\"searchTextResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friend in friends | filter:searchText\">\n           <td>{{friend.name}}</td>\n           <td>{{friend.phone}}</td>\n         </tr>\n       </table>\n       <hr>\n       <label>Any: <input ng-model=\"search.$\"></label> <br>\n       <label>Name only <input ng-model=\"search.name\"></label><br>\n       <label>Phone only <input ng-model=\"search.phone\"></label><br>\n       <label>Equality <input type=\"checkbox\" ng-model=\"strict\"></label><br>\n       <table id=\"searchObjResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friendObj in friends | filter:search:strict\">\n           <td>{{friendObj.name}}</td>\n           <td>{{friendObj.phone}}</td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var expectFriendNames = function(expectedNames, key) {\n         element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {\n           arr.forEach(function(wd, i) {\n             expect(wd.getText()).toMatch(expectedNames[i]);\n           });\n         });\n       };\n\n       it('should search across all fields when filtering with a string', function() {\n         var searchText = element(by.model('searchText'));\n         searchText.clear();\n         searchText.sendKeys('m');\n         expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');\n\n         searchText.clear();\n         searchText.sendKeys('76');\n         expectFriendNames(['John', 'Julie'], 'friend');\n       });\n\n       it('should search in specific fields when filtering with a predicate object', function() {\n         var searchAny = element(by.model('search.$'));\n         searchAny.clear();\n         searchAny.sendKeys('i');\n         expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');\n       });\n       it('should use a equal comparison when comparator is true', function() {\n         var searchName = element(by.model('search.name'));\n         var strict = element(by.model('strict'));\n         searchName.clear();\n         searchName.sendKeys('Julie');\n         strict.click();\n         expectFriendNames(['Julie'], 'friendObj');\n       });\n     </file>\n   </example>\n */\nfunction filterFilter() {\n  return function(array, expression, comparator) {\n    if (!isArrayLike(array)) {\n      if (array == null) {\n        return array;\n      } else {\n        throw minErr('filter')('notarray', 'Expected array but received: {0}', array);\n      }\n    }\n\n    var expressionType = getTypeForFilter(expression);\n    var predicateFn;\n    var matchAgainstAnyProp;\n\n    switch (expressionType) {\n      case 'function':\n        predicateFn = expression;\n        break;\n      case 'boolean':\n      case 'null':\n      case 'number':\n      case 'string':\n        matchAgainstAnyProp = true;\n        //jshint -W086\n      case 'object':\n        //jshint +W086\n        predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);\n        break;\n      default:\n        return array;\n    }\n\n    return Array.prototype.filter.call(array, predicateFn);\n  };\n}\n\n// Helper functions for `filterFilter`\nfunction createPredicateFn(expression, comparator, matchAgainstAnyProp) {\n  var shouldMatchPrimitives = isObject(expression) && ('$' in expression);\n  var predicateFn;\n\n  if (comparator === true) {\n    comparator = equals;\n  } else if (!isFunction(comparator)) {\n    comparator = function(actual, expected) {\n      if (isUndefined(actual)) {\n        // No substring matching against `undefined`\n        return false;\n      }\n      if ((actual === null) || (expected === null)) {\n        // No substring matching against `null`; only match against `null`\n        return actual === expected;\n      }\n      if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {\n        // Should not compare primitives against objects, unless they have custom `toString` method\n        return false;\n      }\n\n      actual = lowercase('' + actual);\n      expected = lowercase('' + expected);\n      return actual.indexOf(expected) !== -1;\n    };\n  }\n\n  predicateFn = function(item) {\n    if (shouldMatchPrimitives && !isObject(item)) {\n      return deepCompare(item, expression.$, comparator, false);\n    }\n    return deepCompare(item, expression, comparator, matchAgainstAnyProp);\n  };\n\n  return predicateFn;\n}\n\nfunction deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {\n  var actualType = getTypeForFilter(actual);\n  var expectedType = getTypeForFilter(expected);\n\n  if ((expectedType === 'string') && (expected.charAt(0) === '!')) {\n    return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);\n  } else if (isArray(actual)) {\n    // In case `actual` is an array, consider it a match\n    // if ANY of it's items matches `expected`\n    return actual.some(function(item) {\n      return deepCompare(item, expected, comparator, matchAgainstAnyProp);\n    });\n  }\n\n  switch (actualType) {\n    case 'object':\n      var key;\n      if (matchAgainstAnyProp) {\n        for (key in actual) {\n          if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {\n            return true;\n          }\n        }\n        return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);\n      } else if (expectedType === 'object') {\n        for (key in expected) {\n          var expectedVal = expected[key];\n          if (isFunction(expectedVal) || isUndefined(expectedVal)) {\n            continue;\n          }\n\n          var matchAnyProperty = key === '$';\n          var actualVal = matchAnyProperty ? actual : actual[key];\n          if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {\n            return false;\n          }\n        }\n        return true;\n      } else {\n        return comparator(actual, expected);\n      }\n      break;\n    case 'function':\n      return false;\n    default:\n      return comparator(actual, expected);\n  }\n}\n\n// Used for easily differentiating between `null` and actual `object`\nfunction getTypeForFilter(val) {\n  return (val === null) ? 'null' : typeof val;\n}\n\n/**\n * @ngdoc filter\n * @name currency\n * @kind function\n *\n * @description\n * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default\n * symbol for current locale is used.\n *\n * @param {number} amount Input to filter.\n * @param {string=} symbol Currency symbol or identifier to be displayed.\n * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\n * @returns {string} Formatted number.\n *\n *\n * @example\n   <example module=\"currencyExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('currencyExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.amount = 1234.56;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"number\" ng-model=\"amount\" aria-label=\"amount\"> <br>\n         default currency symbol ($): <span id=\"currency-default\">{{amount | currency}}</span><br>\n         custom currency identifier (USD$): <span id=\"currency-custom\">{{amount | currency:\"USD$\"}}</span>\n         no fractions (0): <span id=\"currency-no-fractions\">{{amount | currency:\"USD$\":0}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should init with 1234.56', function() {\n         expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');\n         expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');\n       });\n       it('should update', function() {\n         if (browser.params.browser == 'safari') {\n           // Safari does not understand the minus key. See\n           // https://github.com/angular/protractor/issues/481\n           return;\n         }\n         element(by.model('amount')).clear();\n         element(by.model('amount')).sendKeys('-1234');\n         expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');\n         expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');\n       });\n     </file>\n   </example>\n */\ncurrencyFilter.$inject = ['$locale'];\nfunction currencyFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(amount, currencySymbol, fractionSize) {\n    if (isUndefined(currencySymbol)) {\n      currencySymbol = formats.CURRENCY_SYM;\n    }\n\n    if (isUndefined(fractionSize)) {\n      fractionSize = formats.PATTERNS[1].maxFrac;\n    }\n\n    // if null or undefined pass it through\n    return (amount == null)\n        ? amount\n        : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).\n            replace(/\\u00A4/g, currencySymbol);\n  };\n}\n\n/**\n * @ngdoc filter\n * @name number\n * @kind function\n *\n * @description\n * Formats a number as text.\n *\n * If the input is null or undefined, it will just be returned.\n * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.\n * If the input is not a number an empty string is returned.\n *\n *\n * @param {number|string} number Number to format.\n * @param {(number|string)=} fractionSize Number of decimal places to round the number to.\n * If this is not provided then the fraction size is computed from the current locale's number\n * formatting pattern. In the case of the default locale, it will be 3.\n * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.\n *\n * @example\n   <example module=\"numberFilterExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('numberFilterExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.val = 1234.56789;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <label>Enter number: <input ng-model='val'></label><br>\n         Default formatting: <span id='number-default'>{{val | number}}</span><br>\n         No fractions: <span>{{val | number:0}}</span><br>\n         Negative number: <span>{{-val | number:4}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format numbers', function() {\n         expect(element(by.id('number-default')).getText()).toBe('1,234.568');\n         expect(element(by.binding('val | number:0')).getText()).toBe('1,235');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');\n       });\n\n       it('should update', function() {\n         element(by.model('val')).clear();\n         element(by.model('val')).sendKeys('3374.333');\n         expect(element(by.id('number-default')).getText()).toBe('3,374.333');\n         expect(element(by.binding('val | number:0')).getText()).toBe('3,374');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');\n      });\n     </file>\n   </example>\n */\n\n\nnumberFilter.$inject = ['$locale'];\nfunction numberFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(number, fractionSize) {\n\n    // if null or undefined pass it through\n    return (number == null)\n        ? number\n        : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,\n                       fractionSize);\n  };\n}\n\nvar DECIMAL_SEP = '.';\nfunction formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {\n  if (isObject(number)) return '';\n\n  var isNegative = number < 0;\n  number = Math.abs(number);\n\n  var isInfinity = number === Infinity;\n  if (!isInfinity && !isFinite(number)) return '';\n\n  var numStr = number + '',\n      formatedText = '',\n      hasExponent = false,\n      parts = [];\n\n  if (isInfinity) formatedText = '\\u221e';\n\n  if (!isInfinity && numStr.indexOf('e') !== -1) {\n    var match = numStr.match(/([\\d\\.]+)e(-?)(\\d+)/);\n    if (match && match[2] == '-' && match[3] > fractionSize + 1) {\n      number = 0;\n    } else {\n      formatedText = numStr;\n      hasExponent = true;\n    }\n  }\n\n  if (!isInfinity && !hasExponent) {\n    var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;\n\n    // determine fractionSize if it is not specified\n    if (isUndefined(fractionSize)) {\n      fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);\n    }\n\n    // safely round numbers in JS without hitting imprecisions of floating-point arithmetics\n    // inspired by:\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\n    number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);\n\n    var fraction = ('' + number).split(DECIMAL_SEP);\n    var whole = fraction[0];\n    fraction = fraction[1] || '';\n\n    var i, pos = 0,\n        lgroup = pattern.lgSize,\n        group = pattern.gSize;\n\n    if (whole.length >= (lgroup + group)) {\n      pos = whole.length - lgroup;\n      for (i = 0; i < pos; i++) {\n        if ((pos - i) % group === 0 && i !== 0) {\n          formatedText += groupSep;\n        }\n        formatedText += whole.charAt(i);\n      }\n    }\n\n    for (i = pos; i < whole.length; i++) {\n      if ((whole.length - i) % lgroup === 0 && i !== 0) {\n        formatedText += groupSep;\n      }\n      formatedText += whole.charAt(i);\n    }\n\n    // format fraction part.\n    while (fraction.length < fractionSize) {\n      fraction += '0';\n    }\n\n    if (fractionSize && fractionSize !== \"0\") formatedText += decimalSep + fraction.substr(0, fractionSize);\n  } else {\n    if (fractionSize > 0 && number < 1) {\n      formatedText = number.toFixed(fractionSize);\n      number = parseFloat(formatedText);\n    }\n  }\n\n  if (number === 0) {\n    isNegative = false;\n  }\n\n  parts.push(isNegative ? pattern.negPre : pattern.posPre,\n             formatedText,\n             isNegative ? pattern.negSuf : pattern.posSuf);\n  return parts.join('');\n}\n\nfunction padNumber(num, digits, trim) {\n  var neg = '';\n  if (num < 0) {\n    neg =  '-';\n    num = -num;\n  }\n  num = '' + num;\n  while (num.length < digits) num = '0' + num;\n  if (trim) {\n    num = num.substr(num.length - digits);\n  }\n  return neg + num;\n}\n\n\nfunction dateGetter(name, size, offset, trim) {\n  offset = offset || 0;\n  return function(date) {\n    var value = date['get' + name]();\n    if (offset > 0 || value > -offset) {\n      value += offset;\n    }\n    if (value === 0 && offset == -12) value = 12;\n    return padNumber(value, size, trim);\n  };\n}\n\nfunction dateStrGetter(name, shortForm) {\n  return function(date, formats) {\n    var value = date['get' + name]();\n    var get = uppercase(shortForm ? ('SHORT' + name) : name);\n\n    return formats[get][value];\n  };\n}\n\nfunction timeZoneGetter(date, formats, offset) {\n  var zone = -1 * offset;\n  var paddedZone = (zone >= 0) ? \"+\" : \"\";\n\n  paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +\n                padNumber(Math.abs(zone % 60), 2);\n\n  return paddedZone;\n}\n\nfunction getFirstThursdayOfYear(year) {\n    // 0 = index of January\n    var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();\n    // 4 = index of Thursday (+1 to account for 1st = 5)\n    // 11 = index of *next* Thursday (+1 account for 1st = 12)\n    return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);\n}\n\nfunction getThursdayThisWeek(datetime) {\n    return new Date(datetime.getFullYear(), datetime.getMonth(),\n      // 4 = index of Thursday\n      datetime.getDate() + (4 - datetime.getDay()));\n}\n\nfunction weekGetter(size) {\n   return function(date) {\n      var firstThurs = getFirstThursdayOfYear(date.getFullYear()),\n         thisThurs = getThursdayThisWeek(date);\n\n      var diff = +thisThurs - +firstThurs,\n         result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week\n\n      return padNumber(result, size);\n   };\n}\n\nfunction ampmGetter(date, formats) {\n  return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];\n}\n\nfunction eraGetter(date, formats) {\n  return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];\n}\n\nfunction longEraGetter(date, formats) {\n  return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];\n}\n\nvar DATE_FORMATS = {\n  yyyy: dateGetter('FullYear', 4),\n    yy: dateGetter('FullYear', 2, 0, true),\n     y: dateGetter('FullYear', 1),\n  MMMM: dateStrGetter('Month'),\n   MMM: dateStrGetter('Month', true),\n    MM: dateGetter('Month', 2, 1),\n     M: dateGetter('Month', 1, 1),\n    dd: dateGetter('Date', 2),\n     d: dateGetter('Date', 1),\n    HH: dateGetter('Hours', 2),\n     H: dateGetter('Hours', 1),\n    hh: dateGetter('Hours', 2, -12),\n     h: dateGetter('Hours', 1, -12),\n    mm: dateGetter('Minutes', 2),\n     m: dateGetter('Minutes', 1),\n    ss: dateGetter('Seconds', 2),\n     s: dateGetter('Seconds', 1),\n     // while ISO 8601 requires fractions to be prefixed with `.` or `,`\n     // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions\n   sss: dateGetter('Milliseconds', 3),\n  EEEE: dateStrGetter('Day'),\n   EEE: dateStrGetter('Day', true),\n     a: ampmGetter,\n     Z: timeZoneGetter,\n    ww: weekGetter(2),\n     w: weekGetter(1),\n     G: eraGetter,\n     GG: eraGetter,\n     GGG: eraGetter,\n     GGGG: longEraGetter\n};\n\nvar DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,\n    NUMBER_STRING = /^\\-?\\d+$/;\n\n/**\n * @ngdoc filter\n * @name date\n * @kind function\n *\n * @description\n *   Formats `date` to a string based on the requested `format`.\n *\n *   `format` string can be composed of the following elements:\n *\n *   * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)\n *   * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)\n *   * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)\n *   * `'MMMM'`: Month in year (January-December)\n *   * `'MMM'`: Month in year (Jan-Dec)\n *   * `'MM'`: Month in year, padded (01-12)\n *   * `'M'`: Month in year (1-12)\n *   * `'dd'`: Day in month, padded (01-31)\n *   * `'d'`: Day in month (1-31)\n *   * `'EEEE'`: Day in Week,(Sunday-Saturday)\n *   * `'EEE'`: Day in Week, (Sun-Sat)\n *   * `'HH'`: Hour in day, padded (00-23)\n *   * `'H'`: Hour in day (0-23)\n *   * `'hh'`: Hour in AM/PM, padded (01-12)\n *   * `'h'`: Hour in AM/PM, (1-12)\n *   * `'mm'`: Minute in hour, padded (00-59)\n *   * `'m'`: Minute in hour (0-59)\n *   * `'ss'`: Second in minute, padded (00-59)\n *   * `'s'`: Second in minute (0-59)\n *   * `'sss'`: Millisecond in second, padded (000-999)\n *   * `'a'`: AM/PM marker\n *   * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)\n *   * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year\n *   * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year\n *   * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')\n *   * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')\n *\n *   `format` string can also be one of the following predefined\n *   {@link guide/i18n localizable formats}:\n *\n *   * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale\n *     (e.g. Sep 3, 2010 12:05:08 PM)\n *   * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US  locale (e.g. 9/3/10 12:05 PM)\n *   * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US  locale\n *     (e.g. Friday, September 3, 2010)\n *   * `'longDate'`: equivalent to `'MMMM d, y'` for en_US  locale (e.g. September 3, 2010)\n *   * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US  locale (e.g. Sep 3, 2010)\n *   * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)\n *   * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)\n *   * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)\n *\n *   `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.\n *   `\"h 'in the morning'\"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence\n *   (e.g. `\"h 'o''clock'\"`).\n *\n * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or\n *    number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its\n *    shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is\n *    specified in the string input, the time is considered to be in the local timezone.\n * @param {string=} format Formatting rules (see Description). If not specified,\n *    `mediumDate` is used.\n * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the\n *    continental US time zone abbreviations, but for general use, use a time zone offset, for\n *    example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n *    If not specified, the timezone of the browser will be used.\n * @returns {string} Formatted string or the input if input is not recognized as date/millis.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:\n           <span>{{1288323623006 | date:'medium'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:\n          <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:\n          <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:\"MM/dd/yyyy 'at' h:mma\"}}</span>:\n          <span>{{'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"}}</span><br>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format date', function() {\n         expect(element(by.binding(\"1288323623006 | date:'medium'\")).getText()).\n            toMatch(/Oct 2\\d, 2010 \\d{1,2}:\\d{2}:\\d{2} (AM|PM)/);\n         expect(element(by.binding(\"1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'\")).getText()).\n            toMatch(/2010\\-10\\-2\\d \\d{2}:\\d{2}:\\d{2} (\\-|\\+)?\\d{4}/);\n         expect(element(by.binding(\"'1288323623006' | date:'MM/dd/yyyy @ h:mma'\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 @ \\d{1,2}:\\d{2}(AM|PM)/);\n         expect(element(by.binding(\"'1288323623006' | date:\\\"MM/dd/yyyy 'at' h:mma\\\"\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 at \\d{1,2}:\\d{2}(AM|PM)/);\n       });\n     </file>\n   </example>\n */\ndateFilter.$inject = ['$locale'];\nfunction dateFilter($locale) {\n\n\n  var R_ISO8601_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:\\.(\\d+))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d))?)?$/;\n                     // 1        2       3         4          5          6          7          8  9     10      11\n  function jsonStringToDate(string) {\n    var match;\n    if (match = string.match(R_ISO8601_STR)) {\n      var date = new Date(0),\n          tzHour = 0,\n          tzMin  = 0,\n          dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,\n          timeSetter = match[8] ? date.setUTCHours : date.setHours;\n\n      if (match[9]) {\n        tzHour = toInt(match[9] + match[10]);\n        tzMin = toInt(match[9] + match[11]);\n      }\n      dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));\n      var h = toInt(match[4] || 0) - tzHour;\n      var m = toInt(match[5] || 0) - tzMin;\n      var s = toInt(match[6] || 0);\n      var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);\n      timeSetter.call(date, h, m, s, ms);\n      return date;\n    }\n    return string;\n  }\n\n\n  return function(date, format, timezone) {\n    var text = '',\n        parts = [],\n        fn, match;\n\n    format = format || 'mediumDate';\n    format = $locale.DATETIME_FORMATS[format] || format;\n    if (isString(date)) {\n      date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);\n    }\n\n    if (isNumber(date)) {\n      date = new Date(date);\n    }\n\n    if (!isDate(date) || !isFinite(date.getTime())) {\n      return date;\n    }\n\n    while (format) {\n      match = DATE_FORMATS_SPLIT.exec(format);\n      if (match) {\n        parts = concat(parts, match, 1);\n        format = parts.pop();\n      } else {\n        parts.push(format);\n        format = null;\n      }\n    }\n\n    var dateTimezoneOffset = date.getTimezoneOffset();\n    if (timezone) {\n      dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());\n      date = convertTimezoneToLocal(date, timezone, true);\n    }\n    forEach(parts, function(value) {\n      fn = DATE_FORMATS[value];\n      text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)\n                 : value.replace(/(^'|'$)/g, '').replace(/''/g, \"'\");\n    });\n\n    return text;\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name json\n * @kind function\n *\n * @description\n *   Allows you to convert a JavaScript object into JSON string.\n *\n *   This filter is mostly useful for debugging. When using the double curly {{value}} notation\n *   the binding is automatically converted to JSON.\n *\n * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.\n * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.\n * @returns {string} JSON string.\n *\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <pre id=\"default-spacing\">{{ {'name':'value'} | json }}</pre>\n       <pre id=\"custom-spacing\">{{ {'name':'value'} | json:4 }}</pre>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should jsonify filtered objects', function() {\n         expect(element(by.id('default-spacing')).getText()).toMatch(/\\{\\n  \"name\": ?\"value\"\\n}/);\n         expect(element(by.id('custom-spacing')).getText()).toMatch(/\\{\\n    \"name\": ?\"value\"\\n}/);\n       });\n     </file>\n   </example>\n *\n */\nfunction jsonFilter() {\n  return function(object, spacing) {\n    if (isUndefined(spacing)) {\n        spacing = 2;\n    }\n    return toJson(object, spacing);\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name lowercase\n * @kind function\n * @description\n * Converts string to lowercase.\n * @see angular.lowercase\n */\nvar lowercaseFilter = valueFn(lowercase);\n\n\n/**\n * @ngdoc filter\n * @name uppercase\n * @kind function\n * @description\n * Converts string to uppercase.\n * @see angular.uppercase\n */\nvar uppercaseFilter = valueFn(uppercase);\n\n/**\n * @ngdoc filter\n * @name limitTo\n * @kind function\n *\n * @description\n * Creates a new array or string containing only a specified number of elements. The elements\n * are taken from either the beginning or the end of the source array, string or number, as specified by\n * the value and sign (positive or negative) of `limit`. If a number is used as input, it is\n * converted to a string.\n *\n * @param {Array|string|number} input Source array, string or number to be limited.\n * @param {string|number} limit The length of the returned array or string. If the `limit` number\n *     is positive, `limit` number of items from the beginning of the source array/string are copied.\n *     If the number is negative, `limit` number  of items from the end of the source array/string\n *     are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,\n *     the input will be returned unchanged.\n * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`\n *     indicates an offset from the end of `input`. Defaults to `0`.\n * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array\n *     had less than `limit` elements.\n *\n * @example\n   <example module=\"limitToExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('limitToExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.numbers = [1,2,3,4,5,6,7,8,9];\n             $scope.letters = \"abcdefghi\";\n             $scope.longNumber = 2345432342;\n             $scope.numLimit = 3;\n             $scope.letterLimit = 3;\n             $scope.longNumberLimit = 3;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <label>\n            Limit {{numbers}} to:\n            <input type=\"number\" step=\"1\" ng-model=\"numLimit\">\n         </label>\n         <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>\n         <label>\n            Limit {{letters}} to:\n            <input type=\"number\" step=\"1\" ng-model=\"letterLimit\">\n         </label>\n         <p>Output letters: {{ letters | limitTo:letterLimit }}</p>\n         <label>\n            Limit {{longNumber}} to:\n            <input type=\"number\" step=\"1\" ng-model=\"longNumberLimit\">\n         </label>\n         <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var numLimitInput = element(by.model('numLimit'));\n       var letterLimitInput = element(by.model('letterLimit'));\n       var longNumberLimitInput = element(by.model('longNumberLimit'));\n       var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));\n       var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));\n       var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));\n\n       it('should limit the number array to first three items', function() {\n         expect(numLimitInput.getAttribute('value')).toBe('3');\n         expect(letterLimitInput.getAttribute('value')).toBe('3');\n         expect(longNumberLimitInput.getAttribute('value')).toBe('3');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abc');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 234');\n       });\n\n       // There is a bug in safari and protractor that doesn't like the minus key\n       // it('should update the output when -3 is entered', function() {\n       //   numLimitInput.clear();\n       //   numLimitInput.sendKeys('-3');\n       //   letterLimitInput.clear();\n       //   letterLimitInput.sendKeys('-3');\n       //   longNumberLimitInput.clear();\n       //   longNumberLimitInput.sendKeys('-3');\n       //   expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');\n       //   expect(limitedLetters.getText()).toEqual('Output letters: ghi');\n       //   expect(limitedLongNumber.getText()).toEqual('Output long number: 342');\n       // });\n\n       it('should not exceed the maximum size of input array', function() {\n         numLimitInput.clear();\n         numLimitInput.sendKeys('100');\n         letterLimitInput.clear();\n         letterLimitInput.sendKeys('100');\n         longNumberLimitInput.clear();\n         longNumberLimitInput.sendKeys('100');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');\n       });\n     </file>\n   </example>\n*/\nfunction limitToFilter() {\n  return function(input, limit, begin) {\n    if (Math.abs(Number(limit)) === Infinity) {\n      limit = Number(limit);\n    } else {\n      limit = toInt(limit);\n    }\n    if (isNaN(limit)) return input;\n\n    if (isNumber(input)) input = input.toString();\n    if (!isArray(input) && !isString(input)) return input;\n\n    begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);\n    begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;\n\n    if (limit >= 0) {\n      return input.slice(begin, begin + limit);\n    } else {\n      if (begin === 0) {\n        return input.slice(limit, input.length);\n      } else {\n        return input.slice(Math.max(0, begin + limit), begin);\n      }\n    }\n  };\n}\n\n/**\n * @ngdoc filter\n * @name orderBy\n * @kind function\n *\n * @description\n * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically\n * for strings and numerically for numbers. Note: if you notice numbers are not being sorted\n * as expected, make sure they are actually being saved as numbers and not strings.\n *\n * @param {Array} array The array to sort.\n * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be\n *    used by the comparator to determine the order of elements.\n *\n *    Can be one of:\n *\n *    - `function`: Getter function. The result of this function will be sorted using the\n *      `<`, `===`, `>` operator.\n *    - `string`: An Angular expression. The result of this expression is used to compare elements\n *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by\n *      3 first characters of a property called `name`). The result of a constant expression\n *      is interpreted as a property name to be used in comparisons (for example `\"special name\"`\n *      to sort object by the value of their `special name` property). An expression can be\n *      optionally prefixed with `+` or `-` to control ascending or descending sort order\n *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array\n *      element itself is used to compare where sorting.\n *    - `Array`: An array of function or string predicates. The first predicate in the array\n *      is used for sorting, but when two items are equivalent, the next predicate is used.\n *\n *    If the predicate is missing or empty then it defaults to `'+'`.\n *\n * @param {boolean=} reverse Reverse the order of the array.\n * @returns {Array} Sorted copy of the source array.\n *\n *\n * @example\n * The example below demonstrates a simple ngRepeat, where the data is sorted\n * by age in descending order (predicate is set to `'-age'`).\n * `reverse` is not set, which means it defaults to `false`.\n   <example module=\"orderByExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('orderByExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.friends =\n                 [{name:'John', phone:'555-1212', age:10},\n                  {name:'Mary', phone:'555-9876', age:19},\n                  {name:'Mike', phone:'555-4321', age:21},\n                  {name:'Adam', phone:'555-5678', age:35},\n                  {name:'Julie', phone:'555-8765', age:29}];\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <table class=\"friend\">\n           <tr>\n             <th>Name</th>\n             <th>Phone Number</th>\n             <th>Age</th>\n           </tr>\n           <tr ng-repeat=\"friend in friends | orderBy:'-age'\">\n             <td>{{friend.name}}</td>\n             <td>{{friend.phone}}</td>\n             <td>{{friend.age}}</td>\n           </tr>\n         </table>\n       </div>\n     </file>\n   </example>\n *\n * The predicate and reverse parameters can be controlled dynamically through scope properties,\n * as shown in the next example.\n * @example\n   <example module=\"orderByExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('orderByExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.friends =\n                 [{name:'John', phone:'555-1212', age:10},\n                  {name:'Mary', phone:'555-9876', age:19},\n                  {name:'Mike', phone:'555-4321', age:21},\n                  {name:'Adam', phone:'555-5678', age:35},\n                  {name:'Julie', phone:'555-8765', age:29}];\n             $scope.predicate = 'age';\n             $scope.reverse = true;\n             $scope.order = function(predicate) {\n               $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;\n               $scope.predicate = predicate;\n             };\n           }]);\n       </script>\n       <style type=\"text/css\">\n         .sortorder:after {\n           content: '\\25b2';\n         }\n         .sortorder.reverse:after {\n           content: '\\25bc';\n         }\n       </style>\n       <div ng-controller=\"ExampleController\">\n         <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>\n         <hr/>\n         [ <a href=\"\" ng-click=\"predicate=''\">unsorted</a> ]\n         <table class=\"friend\">\n           <tr>\n             <th>\n               <a href=\"\" ng-click=\"order('name')\">Name</a>\n               <span class=\"sortorder\" ng-show=\"predicate === 'name'\" ng-class=\"{reverse:reverse}\"></span>\n             </th>\n             <th>\n               <a href=\"\" ng-click=\"order('phone')\">Phone Number</a>\n               <span class=\"sortorder\" ng-show=\"predicate === 'phone'\" ng-class=\"{reverse:reverse}\"></span>\n             </th>\n             <th>\n               <a href=\"\" ng-click=\"order('age')\">Age</a>\n               <span class=\"sortorder\" ng-show=\"predicate === 'age'\" ng-class=\"{reverse:reverse}\"></span>\n             </th>\n           </tr>\n           <tr ng-repeat=\"friend in friends | orderBy:predicate:reverse\">\n             <td>{{friend.name}}</td>\n             <td>{{friend.phone}}</td>\n             <td>{{friend.age}}</td>\n           </tr>\n         </table>\n       </div>\n     </file>\n   </example>\n *\n * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the\n * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the\n * desired parameters.\n *\n * Example:\n *\n * @example\n  <example module=\"orderByExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <table class=\"friend\">\n          <tr>\n            <th><a href=\"\" ng-click=\"reverse=false;order('name', false)\">Name</a>\n              (<a href=\"\" ng-click=\"order('-name',false)\">^</a>)</th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('phone', reverse)\">Phone Number</a></th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('age',reverse)\">Age</a></th>\n          </tr>\n          <tr ng-repeat=\"friend in friends\">\n            <td>{{friend.name}}</td>\n            <td>{{friend.phone}}</td>\n            <td>{{friend.age}}</td>\n          </tr>\n        </table>\n      </div>\n    </file>\n\n    <file name=\"script.js\">\n      angular.module('orderByExample', [])\n        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {\n          var orderBy = $filter('orderBy');\n          $scope.friends = [\n            { name: 'John',    phone: '555-1212',    age: 10 },\n            { name: 'Mary',    phone: '555-9876',    age: 19 },\n            { name: 'Mike',    phone: '555-4321',    age: 21 },\n            { name: 'Adam',    phone: '555-5678',    age: 35 },\n            { name: 'Julie',   phone: '555-8765',    age: 29 }\n          ];\n          $scope.order = function(predicate, reverse) {\n            $scope.friends = orderBy($scope.friends, predicate, reverse);\n          };\n          $scope.order('-age',false);\n        }]);\n    </file>\n</example>\n */\norderByFilter.$inject = ['$parse'];\nfunction orderByFilter($parse) {\n  return function(array, sortPredicate, reverseOrder) {\n\n    if (!(isArrayLike(array))) return array;\n\n    if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }\n    if (sortPredicate.length === 0) { sortPredicate = ['+']; }\n\n    var predicates = processPredicates(sortPredicate, reverseOrder);\n    // Add a predicate at the end that evaluates to the element index. This makes the\n    // sort stable as it works as a tie-breaker when all the input predicates cannot\n    // distinguish between two elements.\n    predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});\n\n    // The next three lines are a version of a Swartzian Transform idiom from Perl\n    // (sometimes called the Decorate-Sort-Undecorate idiom)\n    // See https://en.wikipedia.org/wiki/Schwartzian_transform\n    var compareValues = Array.prototype.map.call(array, getComparisonObject);\n    compareValues.sort(doComparison);\n    array = compareValues.map(function(item) { return item.value; });\n\n    return array;\n\n    function getComparisonObject(value, index) {\n      return {\n        value: value,\n        predicateValues: predicates.map(function(predicate) {\n          return getPredicateValue(predicate.get(value), index);\n        })\n      };\n    }\n\n    function doComparison(v1, v2) {\n      var result = 0;\n      for (var index=0, length = predicates.length; index < length; ++index) {\n        result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;\n        if (result) break;\n      }\n      return result;\n    }\n  };\n\n  function processPredicates(sortPredicate, reverseOrder) {\n    reverseOrder = reverseOrder ? -1 : 1;\n    return sortPredicate.map(function(predicate) {\n      var descending = 1, get = identity;\n\n      if (isFunction(predicate)) {\n        get = predicate;\n      } else if (isString(predicate)) {\n        if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {\n          descending = predicate.charAt(0) == '-' ? -1 : 1;\n          predicate = predicate.substring(1);\n        }\n        if (predicate !== '') {\n          get = $parse(predicate);\n          if (get.constant) {\n            var key = get();\n            get = function(value) { return value[key]; };\n          }\n        }\n      }\n      return { get: get, descending: descending * reverseOrder };\n    });\n  }\n\n  function isPrimitive(value) {\n    switch (typeof value) {\n      case 'number': /* falls through */\n      case 'boolean': /* falls through */\n      case 'string':\n        return true;\n      default:\n        return false;\n    }\n  }\n\n  function objectValue(value, index) {\n    // If `valueOf` is a valid function use that\n    if (typeof value.valueOf === 'function') {\n      value = value.valueOf();\n      if (isPrimitive(value)) return value;\n    }\n    // If `toString` is a valid function and not the one from `Object.prototype` use that\n    if (hasCustomToString(value)) {\n      value = value.toString();\n      if (isPrimitive(value)) return value;\n    }\n    // We have a basic object so we use the position of the object in the collection\n    return index;\n  }\n\n  function getPredicateValue(value, index) {\n    var type = typeof value;\n    if (value === null) {\n      type = 'string';\n      value = 'null';\n    } else if (type === 'string') {\n      value = value.toLowerCase();\n    } else if (type === 'object') {\n      value = objectValue(value, index);\n    }\n    return { value: value, type: type };\n  }\n\n  function compare(v1, v2) {\n    var result = 0;\n    if (v1.type === v2.type) {\n      if (v1.value !== v2.value) {\n        result = v1.value < v2.value ? -1 : 1;\n      }\n    } else {\n      result = v1.type < v2.type ? -1 : 1;\n    }\n    return result;\n  }\n}\n\nfunction ngDirective(directive) {\n  if (isFunction(directive)) {\n    directive = {\n      link: directive\n    };\n  }\n  directive.restrict = directive.restrict || 'AC';\n  return valueFn(directive);\n}\n\n/**\n * @ngdoc directive\n * @name a\n * @restrict E\n *\n * @description\n * Modifies the default behavior of the html A tag so that the default action is prevented when\n * the href attribute is empty.\n *\n * This change permits the easy creation of action links with the `ngClick` directive\n * without changing the location or causing page reloads, e.g.:\n * `<a href=\"\" ng-click=\"list.addItem()\">Add Item</a>`\n */\nvar htmlAnchorDirective = valueFn({\n  restrict: 'E',\n  compile: function(element, attr) {\n    if (!attr.href && !attr.xlinkHref) {\n      return function(scope, element) {\n        // If the linked element is not an anchor tag anymore, do nothing\n        if (element[0].nodeName.toLowerCase() !== 'a') return;\n\n        // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n        var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n                   'xlink:href' : 'href';\n        element.on('click', function(event) {\n          // if we have no href url, then don't navigate anywhere.\n          if (!element.attr(href)) {\n            event.preventDefault();\n          }\n        });\n      };\n    }\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngHref\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in an href attribute will\n * make the link go to the wrong URL if the user clicks it before\n * Angular has a chance to replace the `{{hash}}` markup with its\n * value. Until Angular replaces the markup the link will be broken\n * and will most likely return a 404 error. The `ngHref` directive\n * solves this problem.\n *\n * The wrong way to write it:\n * ```html\n * <a href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <a ng-href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * @element A\n * @param {template} ngHref any string which can contain `{{}}` markup.\n *\n * @example\n * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes\n * in links and their different behaviors:\n    <example>\n      <file name=\"index.html\">\n        <input ng-model=\"value\" /><br />\n        <a id=\"link-1\" href ng-click=\"value = 1\">link 1</a> (link, don't reload)<br />\n        <a id=\"link-2\" href=\"\" ng-click=\"value = 2\">link 2</a> (link, don't reload)<br />\n        <a id=\"link-3\" ng-href=\"/{{'123'}}\">link 3</a> (link, reload!)<br />\n        <a id=\"link-4\" href=\"\" name=\"xx\" ng-click=\"value = 4\">anchor</a> (link, don't reload)<br />\n        <a id=\"link-5\" name=\"xxx\" ng-click=\"value = 5\">anchor</a> (no link)<br />\n        <a id=\"link-6\" ng-href=\"{{value}}\">link</a> (link, change location)\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should execute ng-click but not reload when href without value', function() {\n          element(by.id('link-1')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('1');\n          expect(element(by.id('link-1')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when href empty string', function() {\n          element(by.id('link-2')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('2');\n          expect(element(by.id('link-2')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click and change url when ng-href specified', function() {\n          expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\\/123$/);\n\n          element(by.id('link-3')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/123$/);\n            });\n          }, 5000, 'page should navigate to /123');\n        });\n\n        it('should execute ng-click but not reload when href empty string and name specified', function() {\n          element(by.id('link-4')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('4');\n          expect(element(by.id('link-4')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when no href but name specified', function() {\n          element(by.id('link-5')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('5');\n          expect(element(by.id('link-5')).getAttribute('href')).toBe(null);\n        });\n\n        it('should only change url when only ng-href', function() {\n          element(by.model('value')).clear();\n          element(by.model('value')).sendKeys('6');\n          expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\\/6$/);\n\n          element(by.id('link-6')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/6$/);\n            });\n          }, 5000, 'page should navigate to /6');\n        });\n      </file>\n    </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngSrc\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `src` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrc` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img src=\"http://www.gravatar.com/avatar/{{hash}}\" alt=\"Description\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-src=\"http://www.gravatar.com/avatar/{{hash}}\" alt=\"Description\" />\n * ```\n *\n * @element IMG\n * @param {template} ngSrc any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngSrcset\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrcset` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\" alt=\"Description\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\" alt=\"Description\" />\n * ```\n *\n * @element IMG\n * @param {template} ngSrcset any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngDisabled\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * This directive sets the `disabled` attribute on the element if the\n * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `disabled`\n * attribute.  The following example would make the button enabled on Chrome/Firefox\n * but not on older IEs:\n *\n * ```html\n * <!-- See below for an example of ng-disabled being used correctly -->\n * <div ng-init=\"isDisabled = false\">\n *  <button disabled=\"{{isDisabled}}\">Disabled</button>\n * </div>\n * ```\n *\n * This is because the HTML specification does not require browsers to preserve the values of\n * boolean attributes such as `disabled` (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Click me to toggle: <input type=\"checkbox\" ng-model=\"checked\"></label><br/>\n        <button ng-model=\"button\" ng-disabled=\"checked\">Button</button>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle button', function() {\n          expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,\n *     then the `disabled` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngChecked\n * @restrict A\n * @priority 100\n *\n * @description\n * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.\n *\n * Note that this directive should not be used together with {@link ngModel `ngModel`},\n * as this can lead to unexpected behavior.\n *\n * ### Why do we need `ngChecked`?\n *\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as checked. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngChecked` directive solves this problem for the `checked` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Check me to check both: <input type=\"checkbox\" ng-model=\"master\"></label><br/>\n        <input id=\"checkSlave\" type=\"checkbox\" ng-checked=\"master\" aria-label=\"Slave input\">\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should check both checkBoxes', function() {\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();\n          element(by.model('master')).click();\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,\n *     then the `checked` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngReadonly\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as readonly. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngReadonly` directive solves this problem for the `readonly` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Check me to make text readonly: <input type=\"checkbox\" ng-model=\"checked\"></label><br/>\n        <input type=\"text\" ng-readonly=\"checked\" value=\"I'm Angular\" aria-label=\"Readonly field\" />\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle readonly attr', function() {\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,\n *     then special attribute \"readonly\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSelected\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as selected. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngSelected` directive solves this problem for the `selected` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Check me to select: <input type=\"checkbox\" ng-model=\"selected\"></label><br/>\n        <select aria-label=\"ngSelected demo\">\n          <option>Hello!</option>\n          <option id=\"greet\" ng-selected=\"selected\">Greetings!</option>\n        </select>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should select Greetings!', function() {\n          expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();\n          element(by.model('selected')).click();\n          expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element OPTION\n * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,\n *     then special attribute \"selected\" will be set on the element\n */\n\n/**\n * @ngdoc directive\n * @name ngOpen\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as open. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngOpen` directive solves this problem for the `open` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n     <example>\n       <file name=\"index.html\">\n         <label>Check me check multiple: <input type=\"checkbox\" ng-model=\"open\"></label><br/>\n         <details id=\"details\" ng-open=\"open\">\n            <summary>Show/Hide me</summary>\n         </details>\n       </file>\n       <file name=\"protractor.js\" type=\"protractor\">\n         it('should toggle open', function() {\n           expect(element(by.id('details')).getAttribute('open')).toBeFalsy();\n           element(by.model('open')).click();\n           expect(element(by.id('details')).getAttribute('open')).toBeTruthy();\n         });\n       </file>\n     </example>\n *\n * @element DETAILS\n * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,\n *     then special attribute \"open\" will be set on the element\n */\n\nvar ngAttributeAliasDirectives = {};\n\n// boolean attrs are evaluated\nforEach(BOOLEAN_ATTR, function(propName, attrName) {\n  // binding to multiple is not supported\n  if (propName == \"multiple\") return;\n\n  function defaultLinkFn(scope, element, attr) {\n    scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {\n      attr.$set(attrName, !!value);\n    });\n  }\n\n  var normalized = directiveNormalize('ng-' + attrName);\n  var linkFn = defaultLinkFn;\n\n  if (propName === 'checked') {\n    linkFn = function(scope, element, attr) {\n      // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input\n      if (attr.ngModel !== attr[normalized]) {\n        defaultLinkFn(scope, element, attr);\n      }\n    };\n  }\n\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      restrict: 'A',\n      priority: 100,\n      link: linkFn\n    };\n  };\n});\n\n// aliased input attrs are evaluated\nforEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {\n  ngAttributeAliasDirectives[ngAttr] = function() {\n    return {\n      priority: 100,\n      link: function(scope, element, attr) {\n        //special case ngPattern when a literal regular expression value\n        //is used as the expression (this way we don't have to watch anything).\n        if (ngAttr === \"ngPattern\" && attr.ngPattern.charAt(0) == \"/\") {\n          var match = attr.ngPattern.match(REGEX_STRING_REGEXP);\n          if (match) {\n            attr.$set(\"ngPattern\", new RegExp(match[1], match[2]));\n            return;\n          }\n        }\n\n        scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {\n          attr.$set(ngAttr, value);\n        });\n      }\n    };\n  };\n});\n\n// ng-src, ng-srcset, ng-href are interpolated\nforEach(['src', 'srcset', 'href'], function(attrName) {\n  var normalized = directiveNormalize('ng-' + attrName);\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      priority: 99, // it needs to run after the attributes are interpolated\n      link: function(scope, element, attr) {\n        var propName = attrName,\n            name = attrName;\n\n        if (attrName === 'href' &&\n            toString.call(element.prop('href')) === '[object SVGAnimatedString]') {\n          name = 'xlinkHref';\n          attr.$attr[name] = 'xlink:href';\n          propName = null;\n        }\n\n        attr.$observe(normalized, function(value) {\n          if (!value) {\n            if (attrName === 'href') {\n              attr.$set(name, null);\n            }\n            return;\n          }\n\n          attr.$set(name, value);\n\n          // on IE, if \"ng:src\" directive declaration is used and \"src\" attribute doesn't exist\n          // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need\n          // to set the property as well to achieve the desired effect.\n          // we use attr[attrName] value since $set can sanitize the url.\n          if (msie && propName) element.prop(propName, attr[name]);\n        });\n      }\n    };\n  };\n});\n\n/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true\n */\nvar nullFormCtrl = {\n  $addControl: noop,\n  $$renameControl: nullFormRenameControl,\n  $removeControl: noop,\n  $setValidity: noop,\n  $setDirty: noop,\n  $setPristine: noop,\n  $setSubmitted: noop\n},\nSUBMITTED_CLASS = 'ng-submitted';\n\nfunction nullFormRenameControl(control, name) {\n  control.$name = name;\n}\n\n/**\n * @ngdoc type\n * @name form.FormController\n *\n * @property {boolean} $pristine True if user has not interacted with the form yet.\n * @property {boolean} $dirty True if user has already interacted with the form.\n * @property {boolean} $valid True if all of the containing forms and controls are valid.\n * @property {boolean} $invalid True if at least one containing control or form is invalid.\n * @property {boolean} $submitted True if user has submitted the form even if its invalid.\n *\n * @property {Object} $error Is an object hash, containing references to controls or\n *  forms with failing validators, where:\n *\n *  - keys are validation tokens (error names),\n *  - values are arrays of controls or forms that have a failing validator for given error name.\n *\n *  Built-in validation tokens:\n *\n *  - `email`\n *  - `max`\n *  - `maxlength`\n *  - `min`\n *  - `minlength`\n *  - `number`\n *  - `pattern`\n *  - `required`\n *  - `url`\n *  - `date`\n *  - `datetimelocal`\n *  - `time`\n *  - `week`\n *  - `month`\n *\n * @description\n * `FormController` keeps track of all its controls and nested forms as well as the state of them,\n * such as being valid/invalid or dirty/pristine.\n *\n * Each {@link ng.directive:form form} directive creates an instance\n * of `FormController`.\n *\n */\n//asks for $scope to fool the BC controller module\nFormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];\nfunction FormController(element, attrs, $scope, $animate, $interpolate) {\n  var form = this,\n      controls = [];\n\n  var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;\n\n  // init state\n  form.$error = {};\n  form.$$success = {};\n  form.$pending = undefined;\n  form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);\n  form.$dirty = false;\n  form.$pristine = true;\n  form.$valid = true;\n  form.$invalid = false;\n  form.$submitted = false;\n\n  parentForm.$addControl(form);\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$rollbackViewValue\n   *\n   * @description\n   * Rollback all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is typically needed by the reset button of\n   * a form that uses `ng-model-options` to pend updates.\n   */\n  form.$rollbackViewValue = function() {\n    forEach(controls, function(control) {\n      control.$rollbackViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$commitViewValue\n   *\n   * @description\n   * Commit all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  form.$commitViewValue = function() {\n    forEach(controls, function(control) {\n      control.$commitViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$addControl\n   *\n   * @description\n   * Register a control with the form.\n   *\n   * Input elements using ngModelController do this automatically when they are linked.\n   */\n  form.$addControl = function(control) {\n    // Breaking change - before, inputs whose name was \"hasOwnProperty\" were quietly ignored\n    // and not added to the scope.  Now we throw an error.\n    assertNotHasOwnProperty(control.$name, 'input');\n    controls.push(control);\n\n    if (control.$name) {\n      form[control.$name] = control;\n    }\n  };\n\n  // Private API: rename a form control\n  form.$$renameControl = function(control, newName) {\n    var oldName = control.$name;\n\n    if (form[oldName] === control) {\n      delete form[oldName];\n    }\n    form[newName] = control;\n    control.$name = newName;\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$removeControl\n   *\n   * @description\n   * Deregister a control from the form.\n   *\n   * Input elements using ngModelController do this automatically when they are destroyed.\n   */\n  form.$removeControl = function(control) {\n    if (control.$name && form[control.$name] === control) {\n      delete form[control.$name];\n    }\n    forEach(form.$pending, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$error, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$$success, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n\n    arrayRemove(controls, control);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setValidity\n   *\n   * @description\n   * Sets the validity of a form control.\n   *\n   * This method will also propagate to parent forms.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: element,\n    set: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        object[property] = [controller];\n      } else {\n        var index = list.indexOf(controller);\n        if (index === -1) {\n          list.push(controller);\n        }\n      }\n    },\n    unset: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        return;\n      }\n      arrayRemove(list, controller);\n      if (list.length === 0) {\n        delete object[property];\n      }\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setDirty\n   *\n   * @description\n   * Sets the form to a dirty state.\n   *\n   * This method can be called to add the 'ng-dirty' class and set the form to a dirty\n   * state (ng-dirty class). This method will also propagate to parent forms.\n   */\n  form.$setDirty = function() {\n    $animate.removeClass(element, PRISTINE_CLASS);\n    $animate.addClass(element, DIRTY_CLASS);\n    form.$dirty = true;\n    form.$pristine = false;\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setPristine\n   *\n   * @description\n   * Sets the form to its pristine state.\n   *\n   * This method can be called to remove the 'ng-dirty' class and set the form to its pristine\n   * state (ng-pristine class). This method will also propagate to all the controls contained\n   * in this form.\n   *\n   * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after\n   * saving or resetting it.\n   */\n  form.$setPristine = function() {\n    $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);\n    form.$dirty = false;\n    form.$pristine = true;\n    form.$submitted = false;\n    forEach(controls, function(control) {\n      control.$setPristine();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setUntouched\n   *\n   * @description\n   * Sets the form to its untouched state.\n   *\n   * This method can be called to remove the 'ng-touched' class and set the form controls to their\n   * untouched state (ng-untouched class).\n   *\n   * Setting a form controls back to their untouched state is often useful when setting the form\n   * back to its pristine state.\n   */\n  form.$setUntouched = function() {\n    forEach(controls, function(control) {\n      control.$setUntouched();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setSubmitted\n   *\n   * @description\n   * Sets the form to its submitted state.\n   */\n  form.$setSubmitted = function() {\n    $animate.addClass(element, SUBMITTED_CLASS);\n    form.$submitted = true;\n    parentForm.$setSubmitted();\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ngForm\n * @restrict EAC\n *\n * @description\n * Nestable alias of {@link ng.directive:form `form`} directive. HTML\n * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a\n * sub-group of controls needs to be determined.\n *\n * Note: the purpose of `ngForm` is to group controls,\n * but not to be a replacement for the `<form>` tag with all of its capabilities\n * (e.g. posting to the server, ...).\n *\n * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n *\n */\n\n /**\n * @ngdoc directive\n * @name form\n * @restrict E\n *\n * @description\n * Directive that instantiates\n * {@link form.FormController FormController}.\n *\n * If the `name` attribute is specified, the form controller is published onto the current scope under\n * this name.\n *\n * # Alias: {@link ng.directive:ngForm `ngForm`}\n *\n * In Angular, forms can be nested. This means that the outer form is valid when all of the child\n * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so\n * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to\n * `<form>` but can be nested.  This allows you to have nested forms, which is very useful when\n * using Angular validation directives in forms that are dynamically generated using the\n * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`\n * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an\n * `ngForm` directive and nest these in an outer `form` element.\n *\n *\n * # CSS classes\n *  - `ng-valid` is set if the form is valid.\n *  - `ng-invalid` is set if the form is invalid.\n *  - `ng-pristine` is set if the form is pristine.\n *  - `ng-dirty` is set if the form is dirty.\n *  - `ng-submitted` is set if the form was submitted.\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n *\n * # Submitting a form and preventing the default action\n *\n * Since the role of forms in client-side Angular applications is different than in classical\n * roundtrip apps, it is desirable for the browser not to translate the form submission into a full\n * page reload that sends the data to the server. Instead some javascript logic should be triggered\n * to handle the form submission in an application-specific way.\n *\n * For this reason, Angular prevents the default action (form submission to the server) unless the\n * `<form>` element has an `action` attribute specified.\n *\n * You can use one of the following two ways to specify what javascript method should be called when\n * a form is submitted:\n *\n * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element\n * - {@link ng.directive:ngClick ngClick} directive on the first\n  *  button or input field of type submit (input[type=submit])\n *\n * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}\n * or {@link ng.directive:ngClick ngClick} directives.\n * This is because of the following form submission rules in the HTML specification:\n *\n * - If a form has only one input field then hitting enter in this field triggers form submit\n * (`ngSubmit`)\n * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter\n * doesn't trigger submit\n * - if a form has one or more input fields and one or more buttons or input[type=submit] then\n * hitting enter in any of the input fields will trigger the click handler on the *first* button or\n * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)\n *\n * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is\n * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * ## Animation Hooks\n *\n * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.\n * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any\n * other validations that are performed within the form. Animations in ngForm are similar to how\n * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well\n * as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style a form element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-form {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-form.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n    <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"formExample\">\n      <file name=\"index.html\">\n       <script>\n         angular.module('formExample', [])\n           .controller('FormController', ['$scope', function($scope) {\n             $scope.userType = 'guest';\n           }]);\n       </script>\n       <style>\n        .my-form {\n          -webkit-transition:all linear 0.5s;\n          transition:all linear 0.5s;\n          background: transparent;\n        }\n        .my-form.ng-invalid {\n          background: red;\n        }\n       </style>\n       <form name=\"myForm\" ng-controller=\"FormController\" class=\"my-form\">\n         userType: <input name=\"input\" ng-model=\"userType\" required>\n         <span class=\"error\" ng-show=\"myForm.input.$error.required\">Required!</span><br>\n         <code>userType = {{userType}}</code><br>\n         <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>\n         <code>myForm.input.$error = {{myForm.input.$error}}</code><br>\n         <code>myForm.$valid = {{myForm.$valid}}</code><br>\n         <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should initialize to model', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n\n          expect(userType.getText()).toContain('guest');\n          expect(valid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var userInput = element(by.model('userType'));\n\n          userInput.clear();\n          userInput.sendKeys('');\n\n          expect(userType.getText()).toEqual('userType =');\n          expect(valid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n *\n * @param {string=} name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n */\nvar formDirectiveFactory = function(isNgForm) {\n  return ['$timeout', '$parse', function($timeout, $parse) {\n    var formDirective = {\n      name: 'form',\n      restrict: isNgForm ? 'EAC' : 'E',\n      controller: FormController,\n      compile: function ngFormCompile(formElement, attr) {\n        // Setup initial state of the control\n        formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);\n\n        var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);\n\n        return {\n          pre: function ngFormPreLink(scope, formElement, attr, controller) {\n            // if `action` attr is not present on the form, prevent the default action (submission)\n            if (!('action' in attr)) {\n              // we can't use jq events because if a form is destroyed during submission the default\n              // action is not prevented. see #1238\n              //\n              // IE 9 is not affected because it doesn't fire a submit event and try to do a full\n              // page reload if the form was destroyed by submission of the form via a click handler\n              // on a button in the form. Looks like an IE9 specific bug.\n              var handleFormSubmission = function(event) {\n                scope.$apply(function() {\n                  controller.$commitViewValue();\n                  controller.$setSubmitted();\n                });\n\n                event.preventDefault();\n              };\n\n              addEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n\n              // unregister the preventDefault listener so that we don't not leak memory but in a\n              // way that will achieve the prevention of the default action.\n              formElement.on('$destroy', function() {\n                $timeout(function() {\n                  removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n                }, 0, false);\n              });\n            }\n\n            var parentFormCtrl = controller.$$parentForm;\n            var setter = nameAttr ? getSetter(controller.$name) : noop;\n\n            if (nameAttr) {\n              setter(scope, controller);\n              attr.$observe(nameAttr, function(newValue) {\n                if (controller.$name === newValue) return;\n                setter(scope, undefined);\n                parentFormCtrl.$$renameControl(controller, newValue);\n                setter = getSetter(controller.$name);\n                setter(scope, controller);\n              });\n            }\n            formElement.on('$destroy', function() {\n              parentFormCtrl.$removeControl(controller);\n              setter(scope, undefined);\n              extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards\n            });\n          }\n        };\n      }\n    };\n\n    return formDirective;\n\n    function getSetter(expression) {\n      if (expression === '') {\n        //create an assignable expression, so forms with an empty name can be renamed later\n        return $parse('this[\"\"]').assign;\n      }\n      return $parse(expression).assign || noop;\n    }\n  }];\n};\n\nvar formDirective = formDirectiveFactory();\nvar ngFormDirective = formDirectiveFactory(true);\n\n/* global VALID_CLASS: false,\n  INVALID_CLASS: false,\n  PRISTINE_CLASS: false,\n  DIRTY_CLASS: false,\n  UNTOUCHED_CLASS: false,\n  TOUCHED_CLASS: false,\n  ngModelMinErr: false,\n*/\n\n// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231\nvar ISO_DATE_REGEXP = /\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)/;\nvar URL_REGEXP = /^(ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?$/;\nvar EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;\nvar NUMBER_REGEXP = /^\\s*(\\-|\\+)?(\\d+|(\\d*(\\.\\d*)))([eE][+-]?\\d+)?\\s*$/;\nvar DATE_REGEXP = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nvar DATETIMELOCAL_REGEXP = /^(\\d{4})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\nvar WEEK_REGEXP = /^(\\d{4})-W(\\d\\d)$/;\nvar MONTH_REGEXP = /^(\\d{4})-(\\d\\d)$/;\nvar TIME_REGEXP = /^(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\n\nvar inputType = {\n\n  /**\n   * @ngdoc input\n   * @name input[text]\n   *\n   * @description\n   * Standard HTML text input with angular data binding, inherited by most of the `input` elements.\n   *\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Adds `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n   *    This parameter is ignored for input[type=password] controls, which will never trim the\n   *    input.\n   *\n   * @example\n      <example name=\"text-input-directive\" module=\"textInputExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('textInputExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 text: 'guest',\n                 word: /^\\s*\\w*\\s*$/\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>Single word:\n             <input type=\"text\" name=\"input\" ng-model=\"example.text\"\n                    ng-pattern=\"example.word\" required ng-trim=\"false\">\n           </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.pattern\">\n               Single word only!</span>\n           </div>\n           <tt>text = {{example.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('example.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('guest');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if multi word', function() {\n            input.clear();\n            input.sendKeys('hello world');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'text': textInputType,\n\n    /**\n     * @ngdoc input\n     * @name input[date]\n     *\n     * @description\n     * Input with date validation and transformation. In browsers that do not yet support\n     * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601\n     * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many\n     * modern browsers do not yet support this input type, it is important to provide cues to users on the\n     * expected input format via a placeholder or label.\n     *\n     * The model must always be a Date object, otherwise Angular will throw an error.\n     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n     *\n     * The timezone to be used to read/write the `Date` instance in the model can be defined using\n     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n     *\n     * @param {string} ngModel Assignable angular expression to data-bind to.\n     * @param {string=} name Property name of the form under which the control is published.\n     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n     * valid ISO date string (yyyy-MM-dd).\n     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n     * a valid ISO date string (yyyy-MM-dd).\n     * @param {string=} required Sets `required` validation error key if the value is not entered.\n     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n     *    `required` when you want to data-bind to the `required` attribute.\n     * @param {string=} ngChange Angular expression to be executed when input changes due to user\n     *    interaction with the input element.\n     *\n     * @example\n     <example name=\"date-input-directive\" module=\"dateInputExample\">\n     <file name=\"index.html\">\n       <script>\n          angular.module('dateInputExample', [])\n            .controller('DateController', ['$scope', function($scope) {\n              $scope.example = {\n                value: new Date(2013, 9, 22)\n              };\n            }]);\n       </script>\n       <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n          <label for=\"exampleInput\">Pick a date in 2013:</label>\n          <input type=\"date\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n              placeholder=\"yyyy-MM-dd\" min=\"2013-01-01\" max=\"2013-12-31\" required />\n          <div role=\"alert\">\n            <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n                Required!</span>\n            <span class=\"error\" ng-show=\"myForm.input.$error.date\">\n                Not a valid date!</span>\n           </div>\n           <tt>value = {{example.value | date: \"yyyy-MM-dd\"}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n       </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        var value = element(by.binding('example.value | date: \"yyyy-MM-dd\"'));\n        var valid = element(by.binding('myForm.input.$valid'));\n        var input = element(by.model('example.value'));\n\n        // currently protractor/webdriver does not support\n        // sending keys to all known HTML5 input controls\n        // for various browsers (see https://github.com/angular/protractor/issues/562).\n        function setInput(val) {\n          // set the value of the element and force validation.\n          var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n          \"ipt.value = '\" + val + \"';\" +\n          \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n          browser.executeScript(scr);\n        }\n\n        it('should initialize to model', function() {\n          expect(value.getText()).toContain('2013-10-22');\n          expect(valid.getText()).toContain('myForm.input.$valid = true');\n        });\n\n        it('should be invalid if empty', function() {\n          setInput('');\n          expect(value.getText()).toEqual('value =');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n\n        it('should be invalid if over max', function() {\n          setInput('2015-01-01');\n          expect(value.getText()).toContain('');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n     </file>\n     </example>\n     */\n  'date': createDateInputType('date', DATE_REGEXP,\n         createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),\n         'yyyy-MM-dd'),\n\n   /**\n    * @ngdoc input\n    * @name input[datetime-local]\n    *\n    * @description\n    * Input with datetime validation and transformation. In browsers that do not yet support\n    * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"datetimelocal-input-directive\" module=\"dateExample\">\n    <file name=\"index.html\">\n      <script>\n        angular.module('dateExample', [])\n          .controller('DateController', ['$scope', function($scope) {\n            $scope.example = {\n              value: new Date(2010, 11, 28, 14, 57)\n            };\n          }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        <label for=\"exampleInput\">Pick a date between in 2013:</label>\n        <input type=\"datetime-local\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"yyyy-MM-ddTHH:mm:ss\" min=\"2001-01-01T00:00:00\" max=\"2013-12-31T00:00:00\" required />\n        <div role=\"alert\">\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.datetimelocal\">\n              Not a valid date!</span>\n        </div>\n        <tt>value = {{example.value | date: \"yyyy-MM-ddTHH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM-ddTHH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2010-12-28T14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01-01T23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,\n      createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),\n      'yyyy-MM-ddTHH:mm:ss.sss'),\n\n  /**\n   * @ngdoc input\n   * @name input[time]\n   *\n   * @description\n   * Input with time validation and transformation. In browsers that do not yet support\n   * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a\n   * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"time-input-directive\" module=\"timeExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('timeExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(1970, 0, 1, 14, 57, 0)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        <label for=\"exampleInput\">Pick a between 8am and 5pm:</label>\n        <input type=\"time\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"HH:mm:ss\" min=\"08:00:00\" max=\"17:00:00\" required />\n        <div role=\"alert\">\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.time\">\n              Not a valid date!</span>\n        </div>\n        <tt>value = {{example.value | date: \"HH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"HH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'time': createDateInputType('time', TIME_REGEXP,\n      createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),\n     'HH:mm:ss.sss'),\n\n   /**\n    * @ngdoc input\n    * @name input[week]\n    *\n    * @description\n    * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support\n    * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * week format (yyyy-W##), for example: `2013-W02`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO week format (yyyy-W##).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO week format (yyyy-W##).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"week-input-directive\" module=\"weekExample\">\n    <file name=\"index.html\">\n      <script>\n      angular.module('weekExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 0, 3)\n          };\n        }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        <label>Pick a date between in 2013:\n          <input id=\"exampleInput\" type=\"week\" name=\"input\" ng-model=\"example.value\"\n                 placeholder=\"YYYY-W##\" min=\"2012-W32\"\n                 max=\"2013-W52\" required />\n        </label>\n        <div role=\"alert\">\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.week\">\n              Not a valid date!</span>\n        </div>\n        <tt>value = {{example.value | date: \"yyyy-Www\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-Www\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-W01');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-W01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),\n\n  /**\n   * @ngdoc input\n   * @name input[month]\n   *\n   * @description\n   * Input with month validation and transformation. In browsers that do not yet support\n   * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * month format (yyyy-MM), for example: `2009-01`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   * If the model is not set to the first of the month, the next view to model update will set it\n   * to the first of the month.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be\n   * a valid ISO month format (yyyy-MM).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must\n   * be a valid ISO month format (yyyy-MM).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"month-input-directive\" module=\"monthExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('monthExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 9, 1)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n       <label for=\"exampleInput\">Pick a month in 2013:</label>\n       <input id=\"exampleInput\" type=\"month\" name=\"input\" ng-model=\"example.value\"\n          placeholder=\"yyyy-MM\" min=\"2013-01\" max=\"2013-12\" required />\n       <div role=\"alert\">\n         <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n         <span class=\"error\" ng-show=\"myForm.input.$error.month\">\n            Not a valid month!</span>\n       </div>\n       <tt>value = {{example.value | date: \"yyyy-MM\"}}</tt><br/>\n       <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n       <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n       <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n       <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-10');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'month': createDateInputType('month', MONTH_REGEXP,\n     createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),\n     'yyyy-MM'),\n\n  /**\n   * @ngdoc input\n   * @name input[number]\n   *\n   * @description\n   * Text input with number validation and transformation. Sets the `number` validation\n   * error if not a valid number.\n   *\n   * <div class=\"alert alert-warning\">\n   * The model must always be of type `number` otherwise Angular will throw an error.\n   * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}\n   * error docs for more information and an example of how to convert your model if necessary.\n   * </div>\n   *\n   * ## Issues with HTML5 constraint validation\n   *\n   * In browsers that follow the\n   * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),\n   * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.\n   * If a non-number is entered in the input, the browser will report the value as an empty string,\n   * which means the view / model values in `ngModel` and subsequently the scope value\n   * will also be an empty string.\n   *\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"number-input-directive\" module=\"numberExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('numberExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 value: 12\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>Number:\n             <input type=\"number\" name=\"input\" ng-model=\"example.value\"\n                    min=\"0\" max=\"99\" required>\n          </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.number\">\n               Not valid number!</span>\n           </div>\n           <tt>value = {{example.value}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var value = element(by.binding('example.value'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.value'));\n\n          it('should initialize to model', function() {\n            expect(value.getText()).toContain('12');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if over max', function() {\n            input.clear();\n            input.sendKeys('123');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'number': numberInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[url]\n   *\n   * @description\n   * Text input with URL validation. Sets the `url` validation error key if the content is not a\n   * valid URL.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex\n   * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify\n   * the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"url-input-directive\" module=\"urlExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('urlExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.url = {\n                 text: 'http://google.com'\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>URL:\n             <input type=\"url\" name=\"input\" ng-model=\"url.text\" required>\n           <label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.url\">\n               Not valid url!</span>\n           </div>\n           <tt>text = {{url.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n           <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('url.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('url.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('http://google.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not url', function() {\n            input.clear();\n            input.sendKeys('box');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'url': urlInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[email]\n   *\n   * @description\n   * Text input with email validation. Sets the `email` validation error key if not a valid email\n   * address.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex\n   * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can\n   * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"email-input-directive\" module=\"emailExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('emailExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.email = {\n                 text: 'me@example.com'\n               };\n             }]);\n         </script>\n           <form name=\"myForm\" ng-controller=\"ExampleController\">\n             <label>Email:\n               <input type=\"email\" name=\"input\" ng-model=\"email.text\" required>\n             </label>\n             <div role=\"alert\">\n               <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n                 Required!</span>\n               <span class=\"error\" ng-show=\"myForm.input.$error.email\">\n                 Not valid email!</span>\n             </div>\n             <tt>text = {{email.text}}</tt><br/>\n             <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n             <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n             <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n             <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n             <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>\n           </form>\n         </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('email.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('email.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('me@example.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not email', function() {\n            input.clear();\n            input.sendKeys('xxx');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'email': emailInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[radio]\n   *\n   * @description\n   * HTML radio button.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string} value The value to which the `ngModel` expression should be set when selected.\n   *    Note that `value` only supports `string` values, i.e. the scope model needs to be a string,\n   *    too. Use `ngValue` if you need complex models (`number`, `object`, ...).\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio\n   *    is selected. Should be used instead of the `value` attribute if you need\n   *    a non-string `ngModel` (`boolean`, `array`, ...).\n   *\n   * @example\n      <example name=\"radio-input-directive\" module=\"radioExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('radioExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.color = {\n                 name: 'blue'\n               };\n               $scope.specialValue = {\n                 \"id\": \"12345\",\n                 \"value\": \"green\"\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>\n             <input type=\"radio\" ng-model=\"color.name\" value=\"red\">\n             Red\n           </label><br/>\n           <label>\n             <input type=\"radio\" ng-model=\"color.name\" ng-value=\"specialValue\">\n             Green\n           </label><br/>\n           <label>\n             <input type=\"radio\" ng-model=\"color.name\" value=\"blue\">\n             Blue\n           </label><br/>\n           <tt>color = {{color.name | json}}</tt><br/>\n          </form>\n          Note that `ng-value=\"specialValue\"` sets radio item's value to be the value of `$scope.specialValue`.\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var color = element(by.binding('color.name'));\n\n            expect(color.getText()).toContain('blue');\n\n            element.all(by.model('color.name')).get(0).click();\n\n            expect(color.getText()).toContain('red');\n          });\n        </file>\n      </example>\n   */\n  'radio': radioInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[checkbox]\n   *\n   * @description\n   * HTML checkbox.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {expression=} ngTrueValue The value to which the expression should be set when selected.\n   * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"checkbox-input-directive\" module=\"checkboxExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('checkboxExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.checkboxModel = {\n                value1 : true,\n                value2 : 'YES'\n              };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>Value1:\n             <input type=\"checkbox\" ng-model=\"checkboxModel.value1\">\n           </label><br/>\n           <label>Value2:\n             <input type=\"checkbox\" ng-model=\"checkboxModel.value2\"\n                    ng-true-value=\"'YES'\" ng-false-value=\"'NO'\">\n            </label><br/>\n           <tt>value1 = {{checkboxModel.value1}}</tt><br/>\n           <tt>value2 = {{checkboxModel.value2}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var value1 = element(by.binding('checkboxModel.value1'));\n            var value2 = element(by.binding('checkboxModel.value2'));\n\n            expect(value1.getText()).toContain('true');\n            expect(value2.getText()).toContain('YES');\n\n            element(by.model('checkboxModel.value1')).click();\n            element(by.model('checkboxModel.value2')).click();\n\n            expect(value1.getText()).toContain('false');\n            expect(value2.getText()).toContain('NO');\n          });\n        </file>\n      </example>\n   */\n  'checkbox': checkboxInputType,\n\n  'hidden': noop,\n  'button': noop,\n  'submit': noop,\n  'reset': noop,\n  'file': noop\n};\n\nfunction stringBasedInputType(ctrl) {\n  ctrl.$formatters.push(function(value) {\n    return ctrl.$isEmpty(value) ? value : value.toString();\n  });\n}\n\nfunction textInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n}\n\nfunction baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  var type = lowercase(element[0].type);\n\n  // In composition mode, users are still inputing intermediate text buffer,\n  // hold the listener until composition is done.\n  // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent\n  if (!$sniffer.android) {\n    var composing = false;\n\n    element.on('compositionstart', function(data) {\n      composing = true;\n    });\n\n    element.on('compositionend', function() {\n      composing = false;\n      listener();\n    });\n  }\n\n  var listener = function(ev) {\n    if (timeout) {\n      $browser.defer.cancel(timeout);\n      timeout = null;\n    }\n    if (composing) return;\n    var value = element.val(),\n        event = ev && ev.type;\n\n    // By default we will trim the value\n    // If the attribute ng-trim exists we will avoid trimming\n    // If input type is 'password', the value is never trimmed\n    if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {\n      value = trim(value);\n    }\n\n    // If a control is suffering from bad input (due to native validators), browsers discard its\n    // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the\n    // control's value is the same empty value twice in a row.\n    if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {\n      ctrl.$setViewValue(value, event);\n    }\n  };\n\n  // if the browser does support \"input\" event, we are fine - except on IE9 which doesn't fire the\n  // input event on backspace, delete or cut\n  if ($sniffer.hasEvent('input')) {\n    element.on('input', listener);\n  } else {\n    var timeout;\n\n    var deferListener = function(ev, input, origValue) {\n      if (!timeout) {\n        timeout = $browser.defer(function() {\n          timeout = null;\n          if (!input || input.value !== origValue) {\n            listener(ev);\n          }\n        });\n      }\n    };\n\n    element.on('keydown', function(event) {\n      var key = event.keyCode;\n\n      // ignore\n      //    command            modifiers                   arrows\n      if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;\n\n      deferListener(event, this, this.value);\n    });\n\n    // if user modifies input value using context menu in IE, we need \"paste\" and \"cut\" events to catch it\n    if ($sniffer.hasEvent('paste')) {\n      element.on('paste cut', deferListener);\n    }\n  }\n\n  // if user paste into input using mouse on older browser\n  // or form autocomplete on newer browser, we need \"change\" event to catch it\n  element.on('change', listener);\n\n  ctrl.$render = function() {\n    // Workaround for Firefox validation #12102.\n    var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;\n    if (element.val() !== value) {\n      element.val(value);\n    }\n  };\n}\n\nfunction weekParser(isoWeek, existingDate) {\n  if (isDate(isoWeek)) {\n    return isoWeek;\n  }\n\n  if (isString(isoWeek)) {\n    WEEK_REGEXP.lastIndex = 0;\n    var parts = WEEK_REGEXP.exec(isoWeek);\n    if (parts) {\n      var year = +parts[1],\n          week = +parts[2],\n          hours = 0,\n          minutes = 0,\n          seconds = 0,\n          milliseconds = 0,\n          firstThurs = getFirstThursdayOfYear(year),\n          addDays = (week - 1) * 7;\n\n      if (existingDate) {\n        hours = existingDate.getHours();\n        minutes = existingDate.getMinutes();\n        seconds = existingDate.getSeconds();\n        milliseconds = existingDate.getMilliseconds();\n      }\n\n      return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);\n    }\n  }\n\n  return NaN;\n}\n\nfunction createDateParser(regexp, mapping) {\n  return function(iso, date) {\n    var parts, map;\n\n    if (isDate(iso)) {\n      return iso;\n    }\n\n    if (isString(iso)) {\n      // When a date is JSON'ified to wraps itself inside of an extra\n      // set of double quotes. This makes the date parsing code unable\n      // to match the date string and parse it as a date.\n      if (iso.charAt(0) == '\"' && iso.charAt(iso.length - 1) == '\"') {\n        iso = iso.substring(1, iso.length - 1);\n      }\n      if (ISO_DATE_REGEXP.test(iso)) {\n        return new Date(iso);\n      }\n      regexp.lastIndex = 0;\n      parts = regexp.exec(iso);\n\n      if (parts) {\n        parts.shift();\n        if (date) {\n          map = {\n            yyyy: date.getFullYear(),\n            MM: date.getMonth() + 1,\n            dd: date.getDate(),\n            HH: date.getHours(),\n            mm: date.getMinutes(),\n            ss: date.getSeconds(),\n            sss: date.getMilliseconds() / 1000\n          };\n        } else {\n          map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };\n        }\n\n        forEach(parts, function(part, index) {\n          if (index < mapping.length) {\n            map[mapping[index]] = +part;\n          }\n        });\n        return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);\n      }\n    }\n\n    return NaN;\n  };\n}\n\nfunction createDateInputType(type, regexp, parseDate, format) {\n  return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {\n    badInputChecker(scope, element, attr, ctrl);\n    baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n    var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;\n    var previousDate;\n\n    ctrl.$$parserName = type;\n    ctrl.$parsers.push(function(value) {\n      if (ctrl.$isEmpty(value)) return null;\n      if (regexp.test(value)) {\n        // Note: We cannot read ctrl.$modelValue, as there might be a different\n        // parser/formatter in the processing chain so that the model\n        // contains some different data format!\n        var parsedDate = parseDate(value, previousDate);\n        if (timezone) {\n          parsedDate = convertTimezoneToLocal(parsedDate, timezone);\n        }\n        return parsedDate;\n      }\n      return undefined;\n    });\n\n    ctrl.$formatters.push(function(value) {\n      if (value && !isDate(value)) {\n        throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);\n      }\n      if (isValidDate(value)) {\n        previousDate = value;\n        if (previousDate && timezone) {\n          previousDate = convertTimezoneToLocal(previousDate, timezone, true);\n        }\n        return $filter('date')(value, format, timezone);\n      } else {\n        previousDate = null;\n        return '';\n      }\n    });\n\n    if (isDefined(attr.min) || attr.ngMin) {\n      var minVal;\n      ctrl.$validators.min = function(value) {\n        return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;\n      };\n      attr.$observe('min', function(val) {\n        minVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    if (isDefined(attr.max) || attr.ngMax) {\n      var maxVal;\n      ctrl.$validators.max = function(value) {\n        return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;\n      };\n      attr.$observe('max', function(val) {\n        maxVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    function isValidDate(value) {\n      // Invalid Date: getTime() returns NaN\n      return value && !(value.getTime && value.getTime() !== value.getTime());\n    }\n\n    function parseObservedDateValue(val) {\n      return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;\n    }\n  };\n}\n\nfunction badInputChecker(scope, element, attr, ctrl) {\n  var node = element[0];\n  var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);\n  if (nativeValidation) {\n    ctrl.$parsers.push(function(value) {\n      var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};\n      // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):\n      // - also sets validity.badInput (should only be validity.typeMismatch).\n      // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)\n      // - can ignore this case as we can still read out the erroneous email...\n      return validity.badInput && !validity.typeMismatch ? undefined : value;\n    });\n  }\n}\n\nfunction numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  badInputChecker(scope, element, attr, ctrl);\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n  ctrl.$$parserName = 'number';\n  ctrl.$parsers.push(function(value) {\n    if (ctrl.$isEmpty(value))      return null;\n    if (NUMBER_REGEXP.test(value)) return parseFloat(value);\n    return undefined;\n  });\n\n  ctrl.$formatters.push(function(value) {\n    if (!ctrl.$isEmpty(value)) {\n      if (!isNumber(value)) {\n        throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);\n      }\n      value = value.toString();\n    }\n    return value;\n  });\n\n  if (isDefined(attr.min) || attr.ngMin) {\n    var minVal;\n    ctrl.$validators.min = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;\n    };\n\n    attr.$observe('min', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      minVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n\n  if (isDefined(attr.max) || attr.ngMax) {\n    var maxVal;\n    ctrl.$validators.max = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;\n    };\n\n    attr.$observe('max', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      maxVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n}\n\nfunction urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'url';\n  ctrl.$validators.url = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || URL_REGEXP.test(value);\n  };\n}\n\nfunction emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'email';\n  ctrl.$validators.email = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);\n  };\n}\n\nfunction radioInputType(scope, element, attr, ctrl) {\n  // make the name unique, if not defined\n  if (isUndefined(attr.name)) {\n    element.attr('name', nextUid());\n  }\n\n  var listener = function(ev) {\n    if (element[0].checked) {\n      ctrl.$setViewValue(attr.value, ev && ev.type);\n    }\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    var value = attr.value;\n    element[0].checked = (value == ctrl.$viewValue);\n  };\n\n  attr.$observe('value', ctrl.$render);\n}\n\nfunction parseConstantExpr($parse, context, name, expression, fallback) {\n  var parseFn;\n  if (isDefined(expression)) {\n    parseFn = $parse(expression);\n    if (!parseFn.constant) {\n      throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +\n                                   '`{1}`.', name, expression);\n    }\n    return parseFn(context);\n  }\n  return fallback;\n}\n\nfunction checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n  var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);\n  var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);\n\n  var listener = function(ev) {\n    ctrl.$setViewValue(element[0].checked, ev && ev.type);\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    element[0].checked = ctrl.$viewValue;\n  };\n\n  // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`\n  // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert\n  // it to a boolean.\n  ctrl.$isEmpty = function(value) {\n    return value === false;\n  };\n\n  ctrl.$formatters.push(function(value) {\n    return equals(value, trueValue);\n  });\n\n  ctrl.$parsers.push(function(value) {\n    return value ? trueValue : falseValue;\n  });\n}\n\n\n/**\n * @ngdoc directive\n * @name textarea\n * @restrict E\n *\n * @description\n * HTML textarea element control with angular data-binding. The data-binding and validation\n * properties of this element are exactly the same as those of the\n * {@link ng.directive:input input element}.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n *    a RegExp found by evaluating the Angular expression given in the attribute value.\n *    If the expression evaluates to a RegExp object, then this is used directly.\n *    If the expression evaluates to a string, then it will be converted to a RegExp\n *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n *    `new RegExp('^abc$')`.<br />\n *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n *    start at the index of the last search's match, thus not taking the whole input value into\n *    account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n */\n\n\n/**\n * @ngdoc directive\n * @name input\n * @restrict E\n *\n * @description\n * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,\n * input state control, and validation.\n * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Not every feature offered is available for all input types.\n * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.\n * </div>\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {boolean=} ngRequired Sets `required` attribute if set to true\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n *    a RegExp found by evaluating the Angular expression given in the attribute value.\n *    If the expression evaluates to a RegExp object, then this is used directly.\n *    If the expression evaluates to a string, then it will be converted to a RegExp\n *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n *    `new RegExp('^abc$')`.<br />\n *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n *    start at the index of the last search's match, thus not taking the whole input value into\n *    account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n *    This parameter is ignored for input[type=password] controls, which will never trim the\n *    input.\n *\n * @example\n    <example name=\"input-directive\" module=\"inputExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('inputExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.user = {name: 'guest', last: 'visitor'};\n            }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <form name=\"myForm\">\n           <label>\n              User name:\n              <input type=\"text\" name=\"userName\" ng-model=\"user.name\" required>\n           </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.userName.$error.required\">\n              Required!</span>\n           </div>\n           <label>\n              Last name:\n              <input type=\"text\" name=\"lastName\" ng-model=\"user.last\"\n              ng-minlength=\"3\" ng-maxlength=\"10\">\n           </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.lastName.$error.minlength\">\n               Too short!</span>\n             <span class=\"error\" ng-show=\"myForm.lastName.$error.maxlength\">\n               Too long!</span>\n           </div>\n         </form>\n         <hr>\n         <tt>user = {{user}}</tt><br/>\n         <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>\n         <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>\n         <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>\n         <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>\n         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n         <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>\n         <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>\n       </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var user = element(by.exactBinding('user'));\n        var userNameValid = element(by.binding('myForm.userName.$valid'));\n        var lastNameValid = element(by.binding('myForm.lastName.$valid'));\n        var lastNameError = element(by.binding('myForm.lastName.$error'));\n        var formValid = element(by.binding('myForm.$valid'));\n        var userNameInput = element(by.model('user.name'));\n        var userLastInput = element(by.model('user.last'));\n\n        it('should initialize to model', function() {\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty when required', function() {\n          userNameInput.clear();\n          userNameInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('false');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be valid if empty when min length is set', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"\"}');\n          expect(lastNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if less than required min length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('xx');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('minlength');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be invalid if longer than max length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('some ridiculously long name');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('maxlength');\n          expect(formValid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n */\nvar inputDirective = ['$browser', '$sniffer', '$filter', '$parse',\n    function($browser, $sniffer, $filter, $parse) {\n  return {\n    restrict: 'E',\n    require: ['?ngModel'],\n    link: {\n      pre: function(scope, element, attr, ctrls) {\n        if (ctrls[0]) {\n          (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,\n                                                              $browser, $filter, $parse);\n        }\n      }\n    }\n  };\n}];\n\n\n\nvar CONSTANT_VALUE_REGEXP = /^(true|false|\\d+)$/;\n/**\n * @ngdoc directive\n * @name ngValue\n *\n * @description\n * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},\n * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to\n * the bound value.\n *\n * `ngValue` is useful when dynamically generating lists of radio buttons using\n * {@link ngRepeat `ngRepeat`}, as shown below.\n *\n * Likewise, `ngValue` can be used to generate `<option>` elements for\n * the {@link select `select`} element. In that case however, only strings are supported\n * for the `value `attribute, so the resulting `ngModel` will always be a string.\n * Support for `select` models with non-string values is available via `ngOptions`.\n *\n * @element input\n * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute\n *   of the `input` element\n *\n * @example\n    <example name=\"ngValue-directive\" module=\"valueExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('valueExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.names = ['pizza', 'unicorns', 'robots'];\n              $scope.my = { favorite: 'unicorns' };\n            }]);\n       </script>\n        <form ng-controller=\"ExampleController\">\n          <h2>Which is your favorite?</h2>\n            <label ng-repeat=\"name in names\" for=\"{{name}}\">\n              {{name}}\n              <input type=\"radio\"\n                     ng-model=\"my.favorite\"\n                     ng-value=\"name\"\n                     id=\"{{name}}\"\n                     name=\"favorite\">\n            </label>\n          <div>You chose {{my.favorite}}</div>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var favorite = element(by.binding('my.favorite'));\n\n        it('should initialize to model', function() {\n          expect(favorite.getText()).toContain('unicorns');\n        });\n        it('should bind the values to the inputs', function() {\n          element.all(by.model('my.favorite')).get(0).click();\n          expect(favorite.getText()).toContain('pizza');\n        });\n      </file>\n    </example>\n */\nvar ngValueDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    compile: function(tpl, tplAttr) {\n      if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {\n        return function ngValueConstantLink(scope, elm, attr) {\n          attr.$set('value', scope.$eval(attr.ngValue));\n        };\n      } else {\n        return function ngValueLink(scope, elm, attr) {\n          scope.$watch(attr.ngValue, function valueWatchAction(value) {\n            attr.$set('value', value);\n          });\n        };\n      }\n    }\n  };\n};\n\n/**\n * @ngdoc directive\n * @name ngBind\n * @restrict AC\n *\n * @description\n * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element\n * with the value of a given expression, and to update the text content when the value of that\n * expression changes.\n *\n * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like\n * `{{ expression }}` which is similar but less verbose.\n *\n * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily\n * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an\n * element attribute, it makes the bindings invisible to the user while the page is loading.\n *\n * An alternative solution to this problem would be using the\n * {@link ng.directive:ngCloak ngCloak} directive.\n *\n *\n * @element ANY\n * @param {expression} ngBind {@link guide/expression Expression} to evaluate.\n *\n * @example\n * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.name = 'Whirled';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <label>Enter name: <input type=\"text\" ng-model=\"name\"></label><br>\n         Hello <span ng-bind=\"name\"></span>!\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var nameInput = element(by.model('name'));\n\n         expect(element(by.binding('name')).getText()).toBe('Whirled');\n         nameInput.clear();\n         nameInput.sendKeys('world');\n         expect(element(by.binding('name')).getText()).toBe('world');\n       });\n     </file>\n   </example>\n */\nvar ngBindDirective = ['$compile', function($compile) {\n  return {\n    restrict: 'AC',\n    compile: function ngBindCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBind);\n        element = element[0];\n        scope.$watch(attr.ngBind, function ngBindWatchAction(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindTemplate\n *\n * @description\n * The `ngBindTemplate` directive specifies that the element\n * text content should be replaced with the interpolation of the template\n * in the `ngBindTemplate` attribute.\n * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`\n * expressions. This directive is needed since some HTML elements\n * (such as TITLE and OPTION) cannot contain SPAN elements.\n *\n * @element ANY\n * @param {string} ngBindTemplate template of form\n *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.\n *\n * @example\n * Try it here: enter text in text box and watch the greeting change.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.salutation = 'Hello';\n             $scope.name = 'World';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n        <label>Salutation: <input type=\"text\" ng-model=\"salutation\"></label><br>\n        <label>Name: <input type=\"text\" ng-model=\"name\"></label><br>\n        <pre ng-bind-template=\"{{salutation}} {{name}}!\"></pre>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var salutationElem = element(by.binding('salutation'));\n         var salutationInput = element(by.model('salutation'));\n         var nameInput = element(by.model('name'));\n\n         expect(salutationElem.getText()).toBe('Hello World!');\n\n         salutationInput.clear();\n         salutationInput.sendKeys('Greetings');\n         nameInput.clear();\n         nameInput.sendKeys('user');\n\n         expect(salutationElem.getText()).toBe('Greetings user!');\n       });\n     </file>\n   </example>\n */\nvar ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {\n  return {\n    compile: function ngBindTemplateCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindTemplateLink(scope, element, attr) {\n        var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));\n        $compile.$$addBindingInfo(element, interpolateFn.expressions);\n        element = element[0];\n        attr.$observe('ngBindTemplate', function(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindHtml\n *\n * @description\n * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,\n * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.\n * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link\n * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}\n * in your module's dependencies, you need to include \"angular-sanitize.js\" in your application.\n *\n * You may also bypass sanitization for values you know are safe. To do so, bind to\n * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}.  See the example\n * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.\n *\n * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you\n * will have an exception (instead of an exploit.)\n *\n * @element ANY\n * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.\n *\n * @example\n\n   <example module=\"bindHtmlExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n        <p ng-bind-html=\"myHTML\"></p>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n       angular.module('bindHtmlExample', ['ngSanitize'])\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.myHTML =\n              'I am an <code>HTML</code>string with ' +\n              '<a href=\"#\">links!</a> and other <em>stuff</em>';\n         }]);\n     </file>\n\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind-html', function() {\n         expect(element(by.binding('myHTML')).getText()).toBe(\n             'I am an HTMLstring with links! and other stuff');\n       });\n     </file>\n   </example>\n */\nvar ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {\n  return {\n    restrict: 'A',\n    compile: function ngBindHtmlCompile(tElement, tAttrs) {\n      var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);\n      var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {\n        return (value || '').toString();\n      });\n      $compile.$$addBindingClass(tElement);\n\n      return function ngBindHtmlLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBindHtml);\n\n        scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {\n          // we re-evaluate the expr because we want a TrustedValueHolderType\n          // for $sce, not a string\n          element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');\n        });\n      };\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngChange\n *\n * @description\n * Evaluate the given expression when the user changes the input.\n * The expression is evaluated immediately, unlike the JavaScript onchange event\n * which only triggers at the end of a change (usually, when the user leaves the\n * form element or presses the return key).\n *\n * The `ngChange` expression is only evaluated when a change in the input value causes\n * a new value to be committed to the model.\n *\n * It will not be evaluated:\n * * if the value returned from the `$parsers` transformation pipeline has not changed\n * * if the input has continued to be invalid since the model will stay `null`\n * * if the model is changed programmatically and not by a change to the input value\n *\n *\n * Note, this directive requires `ngModel` to be present.\n *\n * @element input\n * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change\n * in input value.\n *\n * @example\n * <example name=\"ngChange-directive\" module=\"changeExample\">\n *   <file name=\"index.html\">\n *     <script>\n *       angular.module('changeExample', [])\n *         .controller('ExampleController', ['$scope', function($scope) {\n *           $scope.counter = 0;\n *           $scope.change = function() {\n *             $scope.counter++;\n *           };\n *         }]);\n *     </script>\n *     <div ng-controller=\"ExampleController\">\n *       <input type=\"checkbox\" ng-model=\"confirmed\" ng-change=\"change()\" id=\"ng-change-example1\" />\n *       <input type=\"checkbox\" ng-model=\"confirmed\" id=\"ng-change-example2\" />\n *       <label for=\"ng-change-example2\">Confirmed</label><br />\n *       <tt>debug = {{confirmed}}</tt><br/>\n *       <tt>counter = {{counter}}</tt><br/>\n *     </div>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var counter = element(by.binding('counter'));\n *     var debug = element(by.binding('confirmed'));\n *\n *     it('should evaluate the expression if changing from view', function() {\n *       expect(counter.getText()).toContain('0');\n *\n *       element(by.id('ng-change-example1')).click();\n *\n *       expect(counter.getText()).toContain('1');\n *       expect(debug.getText()).toContain('true');\n *     });\n *\n *     it('should not evaluate the expression if changing from model', function() {\n *       element(by.id('ng-change-example2')).click();\n\n *       expect(counter.getText()).toContain('0');\n *       expect(debug.getText()).toContain('true');\n *     });\n *   </file>\n * </example>\n */\nvar ngChangeDirective = valueFn({\n  restrict: 'A',\n  require: 'ngModel',\n  link: function(scope, element, attr, ctrl) {\n    ctrl.$viewChangeListeners.push(function() {\n      scope.$eval(attr.ngChange);\n    });\n  }\n});\n\nfunction classDirective(name, selector) {\n  name = 'ngClass' + name;\n  return ['$animate', function($animate) {\n    return {\n      restrict: 'AC',\n      link: function(scope, element, attr) {\n        var oldVal;\n\n        scope.$watch(attr[name], ngClassWatchAction, true);\n\n        attr.$observe('class', function(value) {\n          ngClassWatchAction(scope.$eval(attr[name]));\n        });\n\n\n        if (name !== 'ngClass') {\n          scope.$watch('$index', function($index, old$index) {\n            // jshint bitwise: false\n            var mod = $index & 1;\n            if (mod !== (old$index & 1)) {\n              var classes = arrayClasses(scope.$eval(attr[name]));\n              mod === selector ?\n                addClasses(classes) :\n                removeClasses(classes);\n            }\n          });\n        }\n\n        function addClasses(classes) {\n          var newClasses = digestClassCounts(classes, 1);\n          attr.$addClass(newClasses);\n        }\n\n        function removeClasses(classes) {\n          var newClasses = digestClassCounts(classes, -1);\n          attr.$removeClass(newClasses);\n        }\n\n        function digestClassCounts(classes, count) {\n          // Use createMap() to prevent class assumptions involving property\n          // names in Object.prototype\n          var classCounts = element.data('$classCounts') || createMap();\n          var classesToUpdate = [];\n          forEach(classes, function(className) {\n            if (count > 0 || classCounts[className]) {\n              classCounts[className] = (classCounts[className] || 0) + count;\n              if (classCounts[className] === +(count > 0)) {\n                classesToUpdate.push(className);\n              }\n            }\n          });\n          element.data('$classCounts', classCounts);\n          return classesToUpdate.join(' ');\n        }\n\n        function updateClasses(oldClasses, newClasses) {\n          var toAdd = arrayDifference(newClasses, oldClasses);\n          var toRemove = arrayDifference(oldClasses, newClasses);\n          toAdd = digestClassCounts(toAdd, 1);\n          toRemove = digestClassCounts(toRemove, -1);\n          if (toAdd && toAdd.length) {\n            $animate.addClass(element, toAdd);\n          }\n          if (toRemove && toRemove.length) {\n            $animate.removeClass(element, toRemove);\n          }\n        }\n\n        function ngClassWatchAction(newVal) {\n          if (selector === true || scope.$index % 2 === selector) {\n            var newClasses = arrayClasses(newVal || []);\n            if (!oldVal) {\n              addClasses(newClasses);\n            } else if (!equals(newVal,oldVal)) {\n              var oldClasses = arrayClasses(oldVal);\n              updateClasses(oldClasses, newClasses);\n            }\n          }\n          oldVal = shallowCopy(newVal);\n        }\n      }\n    };\n\n    function arrayDifference(tokens1, tokens2) {\n      var values = [];\n\n      outer:\n      for (var i = 0; i < tokens1.length; i++) {\n        var token = tokens1[i];\n        for (var j = 0; j < tokens2.length; j++) {\n          if (token == tokens2[j]) continue outer;\n        }\n        values.push(token);\n      }\n      return values;\n    }\n\n    function arrayClasses(classVal) {\n      var classes = [];\n      if (isArray(classVal)) {\n        forEach(classVal, function(v) {\n          classes = classes.concat(arrayClasses(v));\n        });\n        return classes;\n      } else if (isString(classVal)) {\n        return classVal.split(' ');\n      } else if (isObject(classVal)) {\n        forEach(classVal, function(v, k) {\n          if (v) {\n            classes = classes.concat(k.split(' '));\n          }\n        });\n        return classes;\n      }\n      return classVal;\n    }\n  }];\n}\n\n/**\n * @ngdoc directive\n * @name ngClass\n * @restrict AC\n *\n * @description\n * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding\n * an expression that represents all classes to be added.\n *\n * The directive operates in three different ways, depending on which of three types the expression\n * evaluates to:\n *\n * 1. If the expression evaluates to a string, the string should be one or more space-delimited class\n * names.\n *\n * 2. If the expression evaluates to an object, then for each key-value pair of the\n * object with a truthy value the corresponding key is used as a class name.\n *\n * 3. If the expression evaluates to an array, each element of the array should either be a string as in\n * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array\n * to give you more control over what CSS classes appear. See the code below for an example of this.\n *\n *\n * The directive won't add duplicate classes if a particular class was already set.\n *\n * When the expression changes, the previously added classes are removed and only then are the\n * new classes added.\n *\n * @animations\n * **add** - happens just before the class is applied to the elements\n *\n * **remove** - happens just before the class is removed from the element\n *\n * @element ANY\n * @param {expression} ngClass {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class\n *   names, an array, or a map of class names to boolean values. In the case of a map, the\n *   names of the properties whose values are truthy will be added as css classes to the\n *   element.\n *\n * @example Example that demonstrates basic bindings via ngClass directive.\n   <example>\n     <file name=\"index.html\">\n       <p ng-class=\"{strike: deleted, bold: important, 'has-error': error}\">Map Syntax Example</p>\n       <label>\n          <input type=\"checkbox\" ng-model=\"deleted\">\n          deleted (apply \"strike\" class)\n       </label><br>\n       <label>\n          <input type=\"checkbox\" ng-model=\"important\">\n          important (apply \"bold\" class)\n       </label><br>\n       <label>\n          <input type=\"checkbox\" ng-model=\"error\">\n          error (apply \"has-error\" class)\n       </label>\n       <hr>\n       <p ng-class=\"style\">Using String Syntax</p>\n       <input type=\"text\" ng-model=\"style\"\n              placeholder=\"Type: bold strike red\" aria-label=\"Type: bold strike red\">\n       <hr>\n       <p ng-class=\"[style1, style2, style3]\">Using Array Syntax</p>\n       <input ng-model=\"style1\"\n              placeholder=\"Type: bold, strike or red\" aria-label=\"Type: bold, strike or red\"><br>\n       <input ng-model=\"style2\"\n              placeholder=\"Type: bold, strike or red\" aria-label=\"Type: bold, strike or red 2\"><br>\n       <input ng-model=\"style3\"\n              placeholder=\"Type: bold, strike or red\" aria-label=\"Type: bold, strike or red 3\"><br>\n       <hr>\n       <p ng-class=\"[style4, {orange: warning}]\">Using Array and Map Syntax</p>\n       <input ng-model=\"style4\" placeholder=\"Type: bold, strike\" aria-label=\"Type: bold, strike\"><br>\n       <label><input type=\"checkbox\" ng-model=\"warning\"> warning (apply \"orange\" class)</label>\n     </file>\n     <file name=\"style.css\">\n       .strike {\n           text-decoration: line-through;\n       }\n       .bold {\n           font-weight: bold;\n       }\n       .red {\n           color: red;\n       }\n       .has-error {\n           color: red;\n           background-color: yellow;\n       }\n       .orange {\n           color: orange;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var ps = element.all(by.css('p'));\n\n       it('should let you toggle the class', function() {\n\n         expect(ps.first().getAttribute('class')).not.toMatch(/bold/);\n         expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);\n\n         element(by.model('important')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/bold/);\n\n         element(by.model('error')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/has-error/);\n       });\n\n       it('should let you toggle string example', function() {\n         expect(ps.get(1).getAttribute('class')).toBe('');\n         element(by.model('style')).clear();\n         element(by.model('style')).sendKeys('red');\n         expect(ps.get(1).getAttribute('class')).toBe('red');\n       });\n\n       it('array example should have 3 classes', function() {\n         expect(ps.get(2).getAttribute('class')).toBe('');\n         element(by.model('style1')).sendKeys('bold');\n         element(by.model('style2')).sendKeys('strike');\n         element(by.model('style3')).sendKeys('red');\n         expect(ps.get(2).getAttribute('class')).toBe('bold strike red');\n       });\n\n       it('array with map example should have 2 classes', function() {\n         expect(ps.last().getAttribute('class')).toBe('');\n         element(by.model('style4')).sendKeys('bold');\n         element(by.model('warning')).click();\n         expect(ps.last().getAttribute('class')).toBe('bold orange');\n       });\n     </file>\n   </example>\n\n   ## Animations\n\n   The example below demonstrates how to perform animations using ngClass.\n\n   <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n     <file name=\"index.html\">\n      <input id=\"setbtn\" type=\"button\" value=\"set\" ng-click=\"myVar='my-class'\">\n      <input id=\"clearbtn\" type=\"button\" value=\"clear\" ng-click=\"myVar=''\">\n      <br>\n      <span class=\"base-class\" ng-class=\"myVar\">Sample Text</span>\n     </file>\n     <file name=\"style.css\">\n       .base-class {\n         -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n       }\n\n       .base-class.my-class {\n         color: red;\n         font-size:3em;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class', function() {\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n\n         element(by.id('setbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).\n           toMatch(/my-class/);\n\n         element(by.id('clearbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n       });\n     </file>\n   </example>\n\n\n   ## ngClass and pre-existing CSS3 Transitions/Animations\n   The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.\n   Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder\n   any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure\n   to view the step by step details of {@link $animate#addClass $animate.addClass} and\n   {@link $animate#removeClass $animate.removeClass}.\n */\nvar ngClassDirective = classDirective('', true);\n\n/**\n * @ngdoc directive\n * @name ngClassOdd\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}}\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassOddDirective = classDirective('Odd', 0);\n\n/**\n * @ngdoc directive\n * @name ngClassEven\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The\n *   result of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}} &nbsp; &nbsp; &nbsp;\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassEvenDirective = classDirective('Even', 1);\n\n/**\n * @ngdoc directive\n * @name ngCloak\n * @restrict AC\n *\n * @description\n * The `ngCloak` directive is used to prevent the Angular html template from being briefly\n * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this\n * directive to avoid the undesirable flicker effect caused by the html template display.\n *\n * The directive can be applied to the `<body>` element, but the preferred usage is to apply\n * multiple `ngCloak` directives to small portions of the page to permit progressive rendering\n * of the browser view.\n *\n * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and\n * `angular.min.js`.\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```css\n * [ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {\n *   display: none !important;\n * }\n * ```\n *\n * When this css rule is loaded by the browser, all html elements (including their children) that\n * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive\n * during the compilation of the template it deletes the `ngCloak` element attribute, making\n * the compiled element visible.\n *\n * For the best result, the `angular.js` script must be loaded in the head section of the html\n * document; alternatively, the css rule above must be included in the external stylesheet of the\n * application.\n *\n * @element ANY\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <div id=\"template1\" ng-cloak>{{ 'hello' }}</div>\n        <div id=\"template2\" class=\"ng-cloak\">{{ 'world' }}</div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should remove the template directive and css class', function() {\n         expect($('#template1').getAttribute('ng-cloak')).\n           toBeNull();\n         expect($('#template2').getAttribute('ng-cloak')).\n           toBeNull();\n       });\n     </file>\n   </example>\n *\n */\nvar ngCloakDirective = ngDirective({\n  compile: function(element, attr) {\n    attr.$set('ngCloak', undefined);\n    element.removeClass('ng-cloak');\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngController\n *\n * @description\n * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular\n * supports the principles behind the Model-View-Controller design pattern.\n *\n * MVC components in angular:\n *\n * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties\n *   are accessed through bindings.\n * * View — The template (HTML with data bindings) that is rendered into the View.\n * * Controller — The `ngController` directive specifies a Controller class; the class contains business\n *   logic behind the application to decorate the scope with functions and values\n *\n * Note that you can also attach controllers to the DOM by declaring it in a route definition\n * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller\n * again using `ng-controller` in the template itself.  This will cause the controller to be attached\n * and executed twice.\n *\n * @element ANY\n * @scope\n * @priority 500\n * @param {expression} ngController Name of a constructor function registered with the current\n * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}\n * that on the current scope evaluates to a constructor function.\n *\n * The controller instance can be published into a scope property by specifying\n * `ng-controller=\"as propertyName\"`.\n *\n * If the current `$controllerProvider` is configured to use globals (via\n * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may\n * also be the name of a globally accessible constructor function (not recommended).\n *\n * @example\n * Here is a simple form for editing user contact information. Adding, removing, clearing, and\n * greeting are methods declared on the controller (see source tab). These methods can\n * easily be called from the angular markup. Any changes to the data are automatically reflected\n * in the View without the need for a manual update.\n *\n * Two different declaration styles are included below:\n *\n * * one binds methods and properties directly onto the controller using `this`:\n * `ng-controller=\"SettingsController1 as settings\"`\n * * one injects `$scope` into the controller:\n * `ng-controller=\"SettingsController2\"`\n *\n * The second option is more common in the Angular community, and is generally used in boilerplates\n * and in this guide. However, there are advantages to binding properties directly to the controller\n * and avoiding scope.\n *\n * * Using `controller as` makes it obvious which controller you are accessing in the template when\n * multiple controllers apply to an element.\n * * If you are writing your controllers as classes you have easier access to the properties and\n * methods, which will appear on the scope, from inside the controller code.\n * * Since there is always a `.` in the bindings, you don't have to worry about prototypal\n * inheritance masking primitives.\n *\n * This example demonstrates the `controller as` syntax.\n *\n * <example name=\"ngControllerAs\" module=\"controllerAsExample\">\n *   <file name=\"index.html\">\n *    <div id=\"ctrl-as-exmpl\" ng-controller=\"SettingsController1 as settings\">\n *      <label>Name: <input type=\"text\" ng-model=\"settings.name\"/></label>\n *      <button ng-click=\"settings.greet()\">greet</button><br/>\n *      Contact:\n *      <ul>\n *        <li ng-repeat=\"contact in settings.contacts\">\n *          <select ng-model=\"contact.type\" aria-label=\"Contact method\" id=\"select_{{$index}}\">\n *             <option>phone</option>\n *             <option>email</option>\n *          </select>\n *          <input type=\"text\" ng-model=\"contact.value\" aria-labelledby=\"select_{{$index}}\" />\n *          <button ng-click=\"settings.clearContact(contact)\">clear</button>\n *          <button ng-click=\"settings.removeContact(contact)\" aria-label=\"Remove\">X</button>\n *        </li>\n *        <li><button ng-click=\"settings.addContact()\">add</button></li>\n *     </ul>\n *    </div>\n *   </file>\n *   <file name=\"app.js\">\n *    angular.module('controllerAsExample', [])\n *      .controller('SettingsController1', SettingsController1);\n *\n *    function SettingsController1() {\n *      this.name = \"John Smith\";\n *      this.contacts = [\n *        {type: 'phone', value: '408 555 1212'},\n *        {type: 'email', value: 'john.smith@example.org'} ];\n *    }\n *\n *    SettingsController1.prototype.greet = function() {\n *      alert(this.name);\n *    };\n *\n *    SettingsController1.prototype.addContact = function() {\n *      this.contacts.push({type: 'email', value: 'yourname@example.org'});\n *    };\n *\n *    SettingsController1.prototype.removeContact = function(contactToRemove) {\n *     var index = this.contacts.indexOf(contactToRemove);\n *      this.contacts.splice(index, 1);\n *    };\n *\n *    SettingsController1.prototype.clearContact = function(contact) {\n *      contact.type = 'phone';\n *      contact.value = '';\n *    };\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it('should check controller as', function() {\n *       var container = element(by.id('ctrl-as-exmpl'));\n *         expect(container.element(by.model('settings.name'))\n *           .getAttribute('value')).toBe('John Smith');\n *\n *       var firstRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(0));\n *       var secondRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(1));\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('408 555 1212');\n *\n *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('john.smith@example.org');\n *\n *       firstRepeat.element(by.buttonText('clear')).click();\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('');\n *\n *       container.element(by.buttonText('add')).click();\n *\n *       expect(container.element(by.repeater('contact in settings.contacts').row(2))\n *           .element(by.model('contact.value'))\n *           .getAttribute('value'))\n *           .toBe('yourname@example.org');\n *     });\n *   </file>\n * </example>\n *\n * This example demonstrates the \"attach to `$scope`\" style of controller.\n *\n * <example name=\"ngController\" module=\"controllerExample\">\n *  <file name=\"index.html\">\n *   <div id=\"ctrl-exmpl\" ng-controller=\"SettingsController2\">\n *     <label>Name: <input type=\"text\" ng-model=\"name\"/></label>\n *     <button ng-click=\"greet()\">greet</button><br/>\n *     Contact:\n *     <ul>\n *       <li ng-repeat=\"contact in contacts\">\n *         <select ng-model=\"contact.type\" id=\"select_{{$index}}\">\n *            <option>phone</option>\n *            <option>email</option>\n *         </select>\n *         <input type=\"text\" ng-model=\"contact.value\" aria-labelledby=\"select_{{$index}}\" />\n *         <button ng-click=\"clearContact(contact)\">clear</button>\n *         <button ng-click=\"removeContact(contact)\">X</button>\n *       </li>\n *       <li>[ <button ng-click=\"addContact()\">add</button> ]</li>\n *    </ul>\n *   </div>\n *  </file>\n *  <file name=\"app.js\">\n *   angular.module('controllerExample', [])\n *     .controller('SettingsController2', ['$scope', SettingsController2]);\n *\n *   function SettingsController2($scope) {\n *     $scope.name = \"John Smith\";\n *     $scope.contacts = [\n *       {type:'phone', value:'408 555 1212'},\n *       {type:'email', value:'john.smith@example.org'} ];\n *\n *     $scope.greet = function() {\n *       alert($scope.name);\n *     };\n *\n *     $scope.addContact = function() {\n *       $scope.contacts.push({type:'email', value:'yourname@example.org'});\n *     };\n *\n *     $scope.removeContact = function(contactToRemove) {\n *       var index = $scope.contacts.indexOf(contactToRemove);\n *       $scope.contacts.splice(index, 1);\n *     };\n *\n *     $scope.clearContact = function(contact) {\n *       contact.type = 'phone';\n *       contact.value = '';\n *     };\n *   }\n *  </file>\n *  <file name=\"protractor.js\" type=\"protractor\">\n *    it('should check controller', function() {\n *      var container = element(by.id('ctrl-exmpl'));\n *\n *      expect(container.element(by.model('name'))\n *          .getAttribute('value')).toBe('John Smith');\n *\n *      var firstRepeat =\n *          container.element(by.repeater('contact in contacts').row(0));\n *      var secondRepeat =\n *          container.element(by.repeater('contact in contacts').row(1));\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('408 555 1212');\n *      expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('john.smith@example.org');\n *\n *      firstRepeat.element(by.buttonText('clear')).click();\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('');\n *\n *      container.element(by.buttonText('add')).click();\n *\n *      expect(container.element(by.repeater('contact in contacts').row(2))\n *          .element(by.model('contact.value'))\n *          .getAttribute('value'))\n *          .toBe('yourname@example.org');\n *    });\n *  </file>\n *</example>\n\n */\nvar ngControllerDirective = [function() {\n  return {\n    restrict: 'A',\n    scope: true,\n    controller: '@',\n    priority: 500\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngCsp\n *\n * @element html\n * @description\n *\n * Angular has some features that can break certain\n * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.\n *\n * If you intend to implement these rules then you must tell Angular not to use these features.\n *\n * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.\n *\n *\n * The following rules affect Angular:\n *\n * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions\n * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%\n * increase in the speed of evaluating Angular expressions.\n *\n * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular\n * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).\n * To make these directives work when a CSP rule is blocking inline styles, you must link to the\n * `angular-csp.css` in your HTML manually.\n *\n * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval\n * and automatically deactivates this feature in the {@link $parse} service. This autodetection,\n * however, triggers a CSP error to be logged in the console:\n *\n * ```\n * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of\n * script in the following Content Security Policy directive: \"default-src 'self'\". Note that\n * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.\n * ```\n *\n * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`\n * directive on an element of the HTML document that appears before the `<script>` tag that loads\n * the `angular.js` file.\n *\n * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*\n *\n * You can specify which of the CSP related Angular features should be deactivated by providing\n * a value for the `ng-csp` attribute. The options are as follows:\n *\n * * no-inline-style: this stops Angular from injecting CSS styles into the DOM\n *\n * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings\n *\n * You can use these values in the following combinations:\n *\n *\n * * No declaration means that Angular will assume that you can do inline styles, but it will do\n * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions\n * of Angular.\n *\n * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline\n * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions\n * of Angular.\n *\n * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject\n * inline styles. E.g. `<body ng-csp=\"no-unsafe-eval\">`.\n *\n * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can\n * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp=\"no-inline-style\">`\n *\n * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject\n * styles nor use eval, which is the same as an empty: ng-csp.\n * E.g.`<body ng-csp=\"no-inline-style;no-unsafe-eval\">`\n *\n * @example\n * This example shows how to apply the `ngCsp` directive to the `html` tag.\n   ```html\n     <!doctype html>\n     <html ng-app ng-csp>\n     ...\n     ...\n     </html>\n   ```\n  * @example\n      // Note: the suffix `.csp` in the example name triggers\n      // csp mode in our http server!\n      <example name=\"example.csp\" module=\"cspExample\" ng-csp=\"true\">\n        <file name=\"index.html\">\n          <div ng-controller=\"MainController as ctrl\">\n            <div>\n              <button ng-click=\"ctrl.inc()\" id=\"inc\">Increment</button>\n              <span id=\"counter\">\n                {{ctrl.counter}}\n              </span>\n            </div>\n\n            <div>\n              <button ng-click=\"ctrl.evil()\" id=\"evil\">Evil</button>\n              <span id=\"evilError\">\n                {{ctrl.evilError}}\n              </span>\n            </div>\n          </div>\n        </file>\n        <file name=\"script.js\">\n           angular.module('cspExample', [])\n             .controller('MainController', function() {\n                this.counter = 0;\n                this.inc = function() {\n                  this.counter++;\n                };\n                this.evil = function() {\n                  // jshint evil:true\n                  try {\n                    eval('1+2');\n                  } catch (e) {\n                    this.evilError = e.message;\n                  }\n                };\n              });\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var util, webdriver;\n\n          var incBtn = element(by.id('inc'));\n          var counter = element(by.id('counter'));\n          var evilBtn = element(by.id('evil'));\n          var evilError = element(by.id('evilError'));\n\n          function getAndClearSevereErrors() {\n            return browser.manage().logs().get('browser').then(function(browserLog) {\n              return browserLog.filter(function(logEntry) {\n                return logEntry.level.value > webdriver.logging.Level.WARNING.value;\n              });\n            });\n          }\n\n          function clearErrors() {\n            getAndClearSevereErrors();\n          }\n\n          function expectNoErrors() {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              expect(filteredLog.length).toEqual(0);\n              if (filteredLog.length) {\n                console.log('browser console errors: ' + util.inspect(filteredLog));\n              }\n            });\n          }\n\n          function expectError(regex) {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              var found = false;\n              filteredLog.forEach(function(log) {\n                if (log.message.match(regex)) {\n                  found = true;\n                }\n              });\n              if (!found) {\n                throw new Error('expected an error that matches ' + regex);\n              }\n            });\n          }\n\n          beforeEach(function() {\n            util = require('util');\n            webdriver = require('protractor/node_modules/selenium-webdriver');\n          });\n\n          // For now, we only test on Chrome,\n          // as Safari does not load the page with Protractor's injected scripts,\n          // and Firefox webdriver always disables content security policy (#6358)\n          if (browser.params.browser !== 'chrome') {\n            return;\n          }\n\n          it('should not report errors when the page is loaded', function() {\n            // clear errors so we are not dependent on previous tests\n            clearErrors();\n            // Need to reload the page as the page is already loaded when\n            // we come here\n            browser.driver.getCurrentUrl().then(function(url) {\n              browser.get(url);\n            });\n            expectNoErrors();\n          });\n\n          it('should evaluate expressions', function() {\n            expect(counter.getText()).toEqual('0');\n            incBtn.click();\n            expect(counter.getText()).toEqual('1');\n            expectNoErrors();\n          });\n\n          it('should throw and report an error when using \"eval\"', function() {\n            evilBtn.click();\n            expect(evilError.getText()).toMatch(/Content Security Policy/);\n            expectError(/Content Security Policy/);\n          });\n        </file>\n      </example>\n  */\n\n// ngCsp is not implemented as a proper directive any more, because we need it be processed while we\n// bootstrap the system (before $parse is instantiated), for this reason we just have\n// the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc\n\n/**\n * @ngdoc directive\n * @name ngClick\n *\n * @description\n * The ngClick directive allows you to specify custom behavior when\n * an element is clicked.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon\n * click. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-click=\"count = count + 1\" ng-init=\"count=0\">\n        Increment\n      </button>\n      <span>\n        count: {{count}}\n      </span>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-click', function() {\n         expect(element(by.binding('count')).getText()).toMatch('0');\n         element(by.css('button')).click();\n         expect(element(by.binding('count')).getText()).toMatch('1');\n       });\n     </file>\n   </example>\n */\n/*\n * A collection of directives that allows creation of custom event handlers that are defined as\n * angular expressions and are compiled and executed within the current scope.\n */\nvar ngEventDirectives = {};\n\n// For events that might fire synchronously during DOM manipulation\n// we need to execute their event handlers asynchronously using $evalAsync,\n// so that they are not executed in an inconsistent state.\nvar forceAsyncEvents = {\n  'blur': true,\n  'focus': true\n};\nforEach(\n  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),\n  function(eventName) {\n    var directiveName = directiveNormalize('ng-' + eventName);\n    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {\n      return {\n        restrict: 'A',\n        compile: function($element, attr) {\n          // We expose the powerful $event object on the scope that provides access to the Window,\n          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better\n          // checks at the cost of speed since event handler expressions are not executed as\n          // frequently as regular change detection.\n          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);\n          return function ngEventHandler(scope, element) {\n            element.on(eventName, function(event) {\n              var callback = function() {\n                fn(scope, {$event:event});\n              };\n              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {\n                scope.$evalAsync(callback);\n              } else {\n                scope.$apply(callback);\n              }\n            });\n          };\n        }\n      };\n    }];\n  }\n);\n\n/**\n * @ngdoc directive\n * @name ngDblclick\n *\n * @description\n * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon\n * a dblclick. (The Event object is available as `$event`)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-dblclick=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on double click)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousedown\n *\n * @description\n * The ngMousedown directive allows you to specify custom behavior on mousedown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon\n * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousedown=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse down)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseup\n *\n * @description\n * Specify custom behavior on mouseup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon\n * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseup=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse up)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngMouseover\n *\n * @description\n * Specify custom behavior on mouseover event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon\n * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseover=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse is over)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseenter\n *\n * @description\n * Specify custom behavior on mouseenter event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon\n * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseenter=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse enters)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseleave\n *\n * @description\n * Specify custom behavior on mouseleave event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon\n * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseleave=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse leaves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousemove\n *\n * @description\n * Specify custom behavior on mousemove event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon\n * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousemove=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse moves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeydown\n *\n * @description\n * Specify custom behavior on keydown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon\n * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keydown=\"count = count + 1\" ng-init=\"count=0\">\n      key down count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeyup\n *\n * @description\n * Specify custom behavior on keyup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon\n * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <p>Typing in the input box below updates the key count</p>\n       <input ng-keyup=\"count = count + 1\" ng-init=\"count=0\"> key up count: {{count}}\n\n       <p>Typing in the input box below updates the keycode</p>\n       <input ng-keyup=\"event=$event\">\n       <p>event keyCode: {{ event.keyCode }}</p>\n       <p>event altKey: {{ event.altKey }}</p>\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeypress\n *\n * @description\n * Specify custom behavior on keypress event.\n *\n * @element ANY\n * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon\n * keypress. ({@link guide/expression#-event- Event object is available as `$event`}\n * and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keypress=\"count = count + 1\" ng-init=\"count=0\">\n      key press count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSubmit\n *\n * @description\n * Enables binding angular expressions to onsubmit events.\n *\n * Additionally it prevents the default action (which for form means sending the request to the\n * server and reloading the current page), but only if the form does not contain `action`,\n * `data-action`, or `x-action` attributes.\n *\n * <div class=\"alert alert-warning\">\n * **Warning:** Be careful not to cause \"double-submission\" by using both the `ngClick` and\n * `ngSubmit` handlers together. See the\n * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}\n * for a detailed discussion of when `ngSubmit` may be triggered.\n * </div>\n *\n * @element form\n * @priority 0\n * @param {expression} ngSubmit {@link guide/expression Expression} to eval.\n * ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example module=\"submitExample\">\n     <file name=\"index.html\">\n      <script>\n        angular.module('submitExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.list = [];\n            $scope.text = 'hello';\n            $scope.submit = function() {\n              if ($scope.text) {\n                $scope.list.push(this.text);\n                $scope.text = '';\n              }\n            };\n          }]);\n      </script>\n      <form ng-submit=\"submit()\" ng-controller=\"ExampleController\">\n        Enter text and hit enter:\n        <input type=\"text\" ng-model=\"text\" name=\"text\" />\n        <input type=\"submit\" id=\"submit\" value=\"Submit\" />\n        <pre>list={{list}}</pre>\n      </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-submit', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n         expect(element(by.model('text')).getAttribute('value')).toBe('');\n       });\n       it('should ignore empty strings', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n        });\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngFocus\n *\n * @description\n * Specify custom behavior on focus event.\n *\n * Note: As the `focus` event is executed synchronously when calling `input.focus()`\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon\n * focus. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngBlur\n *\n * @description\n * Specify custom behavior on blur event.\n *\n * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when\n * an element has lost focus.\n *\n * Note: As the `blur` event is executed synchronously also during DOM manipulations\n * (e.g. removing a focussed input),\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon\n * blur. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngCopy\n *\n * @description\n * Specify custom behavior on copy event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon\n * copy. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-copy=\"copied=true\" ng-init=\"copied=false; value='copy me'\" ng-model=\"value\">\n      copied: {{copied}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngCut\n *\n * @description\n * Specify custom behavior on cut event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon\n * cut. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-cut=\"cut=true\" ng-init=\"cut=false; value='cut me'\" ng-model=\"value\">\n      cut: {{cut}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngPaste\n *\n * @description\n * Specify custom behavior on paste event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon\n * paste. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-paste=\"paste=true\" ng-init=\"paste=false\" placeholder='paste here'>\n      pasted: {{paste}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngIf\n * @restrict A\n * @multiElement\n *\n * @description\n * The `ngIf` directive removes or recreates a portion of the DOM tree based on an\n * {expression}. If the expression assigned to `ngIf` evaluates to a false\n * value then the element is removed from the DOM, otherwise a clone of the\n * element is reinserted into the DOM.\n *\n * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the\n * element in the DOM rather than changing its visibility via the `display` css property.  A common\n * case when this difference is significant is when using css selectors that rely on an element's\n * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.\n *\n * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope\n * is created when the element is restored.  The scope created within `ngIf` inherits from\n * its parent scope using\n * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).\n * An important implication of this is if `ngModel` is used within `ngIf` to bind to\n * a javascript primitive defined in the parent scope. In this case any modifications made to the\n * variable within the child scope will override (hide) the value in the parent scope.\n *\n * Also, `ngIf` recreates elements using their compiled state. An example of this behavior\n * is if an element's class attribute is directly modified after it's compiled, using something like\n * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element\n * the added class will be lost because the original compiled state is used to regenerate the element.\n *\n * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`\n * and `leave` effects.\n *\n * @animations\n * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container\n * leave - happens just before the `ngIf` contents are removed from the DOM\n *\n * @element ANY\n * @scope\n * @priority 600\n * @param {expression} ngIf If the {@link guide/expression expression} is falsy then\n *     the element is removed from the DOM tree. If it is truthy a copy of the compiled\n *     element is added to the DOM tree.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <label>Click me: <input type=\"checkbox\" ng-model=\"checked\" ng-init=\"checked=true\" /></label><br/>\n      Show when checked:\n      <span ng-if=\"checked\" class=\"animate-if\">\n        This is removed when the checkbox is unchecked.\n      </span>\n    </file>\n    <file name=\"animations.css\">\n      .animate-if {\n        background:white;\n        border:1px solid black;\n        padding:10px;\n      }\n\n      .animate-if.ng-enter, .animate-if.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n      }\n\n      .animate-if.ng-enter,\n      .animate-if.ng-leave.ng-leave-active {\n        opacity:0;\n      }\n\n      .animate-if.ng-leave,\n      .animate-if.ng-enter.ng-enter-active {\n        opacity:1;\n      }\n    </file>\n  </example>\n */\nvar ngIfDirective = ['$animate', function($animate) {\n  return {\n    multiElement: true,\n    transclude: 'element',\n    priority: 600,\n    terminal: true,\n    restrict: 'A',\n    $$tlb: true,\n    link: function($scope, $element, $attr, ctrl, $transclude) {\n        var block, childScope, previousElements;\n        $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {\n\n          if (value) {\n            if (!childScope) {\n              $transclude(function(clone, newScope) {\n                childScope = newScope;\n                clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block = {\n                  clone: clone\n                };\n                $animate.enter(clone, $element.parent(), $element);\n              });\n            }\n          } else {\n            if (previousElements) {\n              previousElements.remove();\n              previousElements = null;\n            }\n            if (childScope) {\n              childScope.$destroy();\n              childScope = null;\n            }\n            if (block) {\n              previousElements = getBlockNodes(block.clone);\n              $animate.leave(previousElements).then(function() {\n                previousElements = null;\n              });\n              block = null;\n            }\n          }\n        });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngInclude\n * @restrict ECA\n *\n * @description\n * Fetches, compiles and includes an external HTML fragment.\n *\n * By default, the template URL is restricted to the same domain and protocol as the\n * application document. This is done by calling {@link $sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols\n * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or\n * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link\n * ng.$sce Strict Contextual Escaping}.\n *\n * In addition, the browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy may further restrict whether the template is successfully loaded.\n * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`\n * access on some browsers.\n *\n * @animations\n * enter - animation is used to bring new content into the browser.\n * leave - animation is used to animate existing content away.\n *\n * The enter and leave animation occur concurrently.\n *\n * @scope\n * @priority 400\n *\n * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,\n *                 make sure you wrap it in **single** quotes, e.g. `src=\"'myPartialTemplate.html'\"`.\n * @param {string=} onload Expression to evaluate when a new partial is loaded.\n *\n * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll\n *                  $anchorScroll} to scroll the viewport after the content is loaded.\n *\n *                  - If the attribute is not set, disable scrolling.\n *                  - If the attribute is set without value, enable scrolling.\n *                  - Otherwise enable scrolling only if the expression evaluates to truthy value.\n *\n * @example\n  <example module=\"includeExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n     <div ng-controller=\"ExampleController\">\n       <select ng-model=\"template\" ng-options=\"t.name for t in templates\">\n        <option value=\"\">(blank)</option>\n       </select>\n       url of the template: <code>{{template.url}}</code>\n       <hr/>\n       <div class=\"slide-animate-container\">\n         <div class=\"slide-animate\" ng-include=\"template.url\"></div>\n       </div>\n     </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('includeExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.templates =\n            [ { name: 'template1.html', url: 'template1.html'},\n              { name: 'template2.html', url: 'template2.html'} ];\n          $scope.template = $scope.templates[0];\n        }]);\n     </file>\n    <file name=\"template1.html\">\n      Content of template1.html\n    </file>\n    <file name=\"template2.html\">\n      Content of template2.html\n    </file>\n    <file name=\"animations.css\">\n      .slide-animate-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .slide-animate {\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter, .slide-animate.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n        display:block;\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter {\n        top:-50px;\n      }\n      .slide-animate.ng-enter.ng-enter-active {\n        top:0;\n      }\n\n      .slide-animate.ng-leave {\n        top:0;\n      }\n      .slide-animate.ng-leave.ng-leave-active {\n        top:50px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var templateSelect = element(by.model('template'));\n      var includeElem = element(by.css('[ng-include]'));\n\n      it('should load template1.html', function() {\n        expect(includeElem.getText()).toMatch(/Content of template1.html/);\n      });\n\n      it('should load template2.html', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          // See https://github.com/angular/protractor/issues/480\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(2).click();\n        expect(includeElem.getText()).toMatch(/Content of template2.html/);\n      });\n\n      it('should change to blank', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(0).click();\n        expect(includeElem.isPresent()).toBe(false);\n      });\n    </file>\n  </example>\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentRequested\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted every time the ngInclude content is requested.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentLoaded\n * @eventType emit on the current ngInclude scope\n * @description\n * Emitted every time the ngInclude content is reloaded.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentError\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\nvar ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',\n                  function($templateRequest,   $anchorScroll,   $animate) {\n  return {\n    restrict: 'ECA',\n    priority: 400,\n    terminal: true,\n    transclude: 'element',\n    controller: angular.noop,\n    compile: function(element, attr) {\n      var srcExp = attr.ngInclude || attr.src,\n          onloadExp = attr.onload || '',\n          autoScrollExp = attr.autoscroll;\n\n      return function(scope, $element, $attr, ctrl, $transclude) {\n        var changeCounter = 0,\n            currentScope,\n            previousElement,\n            currentElement;\n\n        var cleanupLastIncludeContent = function() {\n          if (previousElement) {\n            previousElement.remove();\n            previousElement = null;\n          }\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n          if (currentElement) {\n            $animate.leave(currentElement).then(function() {\n              previousElement = null;\n            });\n            previousElement = currentElement;\n            currentElement = null;\n          }\n        };\n\n        scope.$watch(srcExp, function ngIncludeWatchAction(src) {\n          var afterAnimation = function() {\n            if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {\n              $anchorScroll();\n            }\n          };\n          var thisChangeId = ++changeCounter;\n\n          if (src) {\n            //set the 2nd param to true to ignore the template request error so that the inner\n            //contents and scope can be cleaned up.\n            $templateRequest(src, true).then(function(response) {\n              if (thisChangeId !== changeCounter) return;\n              var newScope = scope.$new();\n              ctrl.template = response;\n\n              // Note: This will also link all children of ng-include that were contained in the original\n              // html. If that content contains controllers, ... they could pollute/change the scope.\n              // However, using ng-include on an element with additional content does not make sense...\n              // Note: We can't remove them in the cloneAttchFn of $transclude as that\n              // function is called before linking the content, which would apply child\n              // directives to non existing elements.\n              var clone = $transclude(newScope, function(clone) {\n                cleanupLastIncludeContent();\n                $animate.enter(clone, null, $element).then(afterAnimation);\n              });\n\n              currentScope = newScope;\n              currentElement = clone;\n\n              currentScope.$emit('$includeContentLoaded', src);\n              scope.$eval(onloadExp);\n            }, function() {\n              if (thisChangeId === changeCounter) {\n                cleanupLastIncludeContent();\n                scope.$emit('$includeContentError', src);\n              }\n            });\n            scope.$emit('$includeContentRequested', src);\n          } else {\n            cleanupLastIncludeContent();\n            ctrl.template = null;\n          }\n        });\n      };\n    }\n  };\n}];\n\n// This directive is called during the $transclude call of the first `ngInclude` directive.\n// It will replace and compile the content of the element with the loaded template.\n// We need this directive so that the element content is already filled when\n// the link function of another directive on the same element as ngInclude\n// is called.\nvar ngIncludeFillContentDirective = ['$compile',\n  function($compile) {\n    return {\n      restrict: 'ECA',\n      priority: -400,\n      require: 'ngInclude',\n      link: function(scope, $element, $attr, ctrl) {\n        if (/SVG/.test($element[0].toString())) {\n          // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not\n          // support innerHTML, so detect this here and try to generate the contents\n          // specially.\n          $element.empty();\n          $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,\n              function namespaceAdaptedClone(clone) {\n            $element.append(clone);\n          }, {futureParentElement: $element});\n          return;\n        }\n\n        $element.html(ctrl.template);\n        $compile($element.contents())(scope);\n      }\n    };\n  }];\n\n/**\n * @ngdoc directive\n * @name ngInit\n * @restrict AC\n *\n * @description\n * The `ngInit` directive allows you to evaluate an expression in the\n * current scope.\n *\n * <div class=\"alert alert-danger\">\n * The only appropriate use of `ngInit` is for aliasing special properties of\n * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you\n * should use {@link guide/controller controllers} rather than `ngInit`\n * to initialize values on a scope.\n * </div>\n * <div class=\"alert alert-warning\">\n * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make\n * sure you have parenthesis for correct precedence:\n * <pre class=\"prettyprint\">\n * `<div ng-init=\"test1 = (data | orderBy:'name')\"></div>`\n * </pre>\n * </div>\n *\n * @priority 450\n *\n * @element ANY\n * @param {expression} ngInit {@link guide/expression Expression} to eval.\n *\n * @example\n   <example module=\"initExample\">\n     <file name=\"index.html\">\n   <script>\n     angular.module('initExample', [])\n       .controller('ExampleController', ['$scope', function($scope) {\n         $scope.list = [['a', 'b'], ['c', 'd']];\n       }]);\n   </script>\n   <div ng-controller=\"ExampleController\">\n     <div ng-repeat=\"innerList in list\" ng-init=\"outerIndex = $index\">\n       <div ng-repeat=\"value in innerList\" ng-init=\"innerIndex = $index\">\n          <span class=\"example-init\">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>\n       </div>\n     </div>\n   </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should alias index positions', function() {\n         var elements = element.all(by.css('.example-init'));\n         expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');\n         expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');\n         expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');\n         expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');\n       });\n     </file>\n   </example>\n */\nvar ngInitDirective = ngDirective({\n  priority: 450,\n  compile: function() {\n    return {\n      pre: function(scope, element, attrs) {\n        scope.$eval(attrs.ngInit);\n      }\n    };\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngList\n *\n * @description\n * Text input that converts between a delimited string and an array of strings. The default\n * delimiter is a comma followed by a space - equivalent to `ng-list=\", \"`. You can specify a custom\n * delimiter as the value of the `ngList` attribute - for example, `ng-list=\" | \"`.\n *\n * The behaviour of the directive is affected by the use of the `ngTrim` attribute.\n * * If `ngTrim` is set to `\"false\"` then whitespace around both the separator and each\n *   list item is respected. This implies that the user of the directive is responsible for\n *   dealing with whitespace but also allows you to use whitespace as a delimiter, such as a\n *   tab or newline character.\n * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected\n *   when joining the list items back together) and whitespace around each list item is stripped\n *   before it is added to the model.\n *\n * ### Example with Validation\n *\n * <example name=\"ngList-directive\" module=\"listExample\">\n *   <file name=\"app.js\">\n *      angular.module('listExample', [])\n *        .controller('ExampleController', ['$scope', function($scope) {\n *          $scope.names = ['morpheus', 'neo', 'trinity'];\n *        }]);\n *   </file>\n *   <file name=\"index.html\">\n *    <form name=\"myForm\" ng-controller=\"ExampleController\">\n *      <label>List: <input name=\"namesInput\" ng-model=\"names\" ng-list required></label>\n *      <span role=\"alert\">\n *        <span class=\"error\" ng-show=\"myForm.namesInput.$error.required\">\n *        Required!</span>\n *      </span>\n *      <br>\n *      <tt>names = {{names}}</tt><br/>\n *      <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>\n *      <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>\n *      <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n *      <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n *     </form>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var listInput = element(by.model('names'));\n *     var names = element(by.exactBinding('names'));\n *     var valid = element(by.binding('myForm.namesInput.$valid'));\n *     var error = element(by.css('span.error'));\n *\n *     it('should initialize to model', function() {\n *       expect(names.getText()).toContain('[\"morpheus\",\"neo\",\"trinity\"]');\n *       expect(valid.getText()).toContain('true');\n *       expect(error.getCssValue('display')).toBe('none');\n *     });\n *\n *     it('should be invalid if empty', function() {\n *       listInput.clear();\n *       listInput.sendKeys('');\n *\n *       expect(names.getText()).toContain('');\n *       expect(valid.getText()).toContain('false');\n *       expect(error.getCssValue('display')).not.toBe('none');\n *     });\n *   </file>\n * </example>\n *\n * ### Example - splitting on whitespace\n * <example name=\"ngList-directive-newlines\">\n *   <file name=\"index.html\">\n *    <textarea ng-model=\"list\" ng-list=\"&#10;\" ng-trim=\"false\"></textarea>\n *    <pre>{{ list | json }}</pre>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it(\"should split the text by newlines\", function() {\n *       var listInput = element(by.model('list'));\n *       var output = element(by.binding('list | json'));\n *       listInput.sendKeys('abc\\ndef\\nghi');\n *       expect(output.getText()).toContain('[\\n  \"abc\",\\n  \"def\",\\n  \"ghi\"\\n]');\n *     });\n *   </file>\n * </example>\n *\n * @element input\n * @param {string=} ngList optional delimiter that should be used to split the value.\n */\nvar ngListDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    require: 'ngModel',\n    link: function(scope, element, attr, ctrl) {\n      // We want to control whitespace trimming so we use this convoluted approach\n      // to access the ngList attribute, which doesn't pre-trim the attribute\n      var ngList = element.attr(attr.$attr.ngList) || ', ';\n      var trimValues = attr.ngTrim !== 'false';\n      var separator = trimValues ? trim(ngList) : ngList;\n\n      var parse = function(viewValue) {\n        // If the viewValue is invalid (say required but empty) it will be `undefined`\n        if (isUndefined(viewValue)) return;\n\n        var list = [];\n\n        if (viewValue) {\n          forEach(viewValue.split(separator), function(value) {\n            if (value) list.push(trimValues ? trim(value) : value);\n          });\n        }\n\n        return list;\n      };\n\n      ctrl.$parsers.push(parse);\n      ctrl.$formatters.push(function(value) {\n        if (isArray(value)) {\n          return value.join(ngList);\n        }\n\n        return undefined;\n      });\n\n      // Override the standard $isEmpty because an empty array means the input is empty.\n      ctrl.$isEmpty = function(value) {\n        return !value || !value.length;\n      };\n    }\n  };\n};\n\n/* global VALID_CLASS: true,\n  INVALID_CLASS: true,\n  PRISTINE_CLASS: true,\n  DIRTY_CLASS: true,\n  UNTOUCHED_CLASS: true,\n  TOUCHED_CLASS: true,\n*/\n\nvar VALID_CLASS = 'ng-valid',\n    INVALID_CLASS = 'ng-invalid',\n    PRISTINE_CLASS = 'ng-pristine',\n    DIRTY_CLASS = 'ng-dirty',\n    UNTOUCHED_CLASS = 'ng-untouched',\n    TOUCHED_CLASS = 'ng-touched',\n    PENDING_CLASS = 'ng-pending';\n\nvar ngModelMinErr = minErr('ngModel');\n\n/**\n * @ngdoc type\n * @name ngModel.NgModelController\n *\n * @property {string} $viewValue Actual string value in the view.\n * @property {*} $modelValue The value in the model that the control is bound to.\n * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever\n       the control reads value from the DOM. The functions are called in array order, each passing\n       its return value through to the next. The last return value is forwarded to the\n       {@link ngModel.NgModelController#$validators `$validators`} collection.\n\nParsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue\n`$viewValue`}.\n\nReturning `undefined` from a parser means a parse error occurred. In that case,\nno {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`\nwill be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}\nis set to `true`. The parse error is stored in `ngModel.$error.parse`.\n\n *\n * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever\n       the model value changes. The functions are called in reverse array order, each passing the value through to the\n       next. The last return value is used as the actual DOM value.\n       Used to format / convert values for display in the control.\n * ```js\n * function formatter(value) {\n *   if (value) {\n *     return value.toUpperCase();\n *   }\n * }\n * ngModel.$formatters.push(formatter);\n * ```\n *\n * @property {Object.<string, function>} $validators A collection of validators that are applied\n *      whenever the model value changes. The key value within the object refers to the name of the\n *      validator while the function refers to the validation operation. The validation operation is\n *      provided with the model value as an argument and must return a true or false value depending\n *      on the response of that validation.\n *\n * ```js\n * ngModel.$validators.validCharacters = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *   return /[0-9]+/.test(value) &&\n *          /[a-z]+/.test(value) &&\n *          /[A-Z]+/.test(value) &&\n *          /\\W+/.test(value);\n * };\n * ```\n *\n * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to\n *      perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided\n *      is expected to return a promise when it is run during the model validation process. Once the promise\n *      is delivered then the validation status will be set to true when fulfilled and false when rejected.\n *      When the asynchronous validators are triggered, each of the validators will run in parallel and the model\n *      value will only be updated once all validators have been fulfilled. As long as an asynchronous validator\n *      is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators\n *      will only run once all synchronous validators have passed.\n *\n * Please note that if $http is used then it is important that the server returns a success HTTP response code\n * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.\n *\n * ```js\n * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *\n *   // Lookup user by username\n *   return $http.get('/api/users/' + value).\n *      then(function resolved() {\n *        //username exists, this means validation fails\n *        return $q.reject('exists');\n *      }, function rejected() {\n *        //username does not exist, therefore this validation passes\n *        return true;\n *      });\n * };\n * ```\n *\n * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the\n *     view value has changed. It is called with no arguments, and its return value is ignored.\n *     This can be used in place of additional $watches against the model value.\n *\n * @property {Object} $error An object hash with all failing validator ids as keys.\n * @property {Object} $pending An object hash with all pending validator ids as keys.\n *\n * @property {boolean} $untouched True if control has not lost focus yet.\n * @property {boolean} $touched True if control has lost focus.\n * @property {boolean} $pristine True if user has not interacted with the control yet.\n * @property {boolean} $dirty True if user has already interacted with the control.\n * @property {boolean} $valid True if there is no error.\n * @property {boolean} $invalid True if at least one error on the control.\n * @property {string} $name The name attribute of the control.\n *\n * @description\n *\n * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.\n * The controller contains services for data-binding, validation, CSS updates, and value formatting\n * and parsing. It purposefully does not contain any logic which deals with DOM rendering or\n * listening to DOM events.\n * Such DOM related logic should be provided by other directives which make use of\n * `NgModelController` for data-binding to control elements.\n * Angular provides this DOM logic for most {@link input `input`} elements.\n * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example\n * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.\n *\n * @example\n * ### Custom Control Example\n * This example shows how to use `NgModelController` with a custom control to achieve\n * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)\n * collaborate together to achieve the desired result.\n *\n * `contenteditable` is an HTML5 attribute, which tells the browser to let the element\n * contents be edited in place by the user.\n *\n * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}\n * module to automatically remove \"bad\" content like inline event listener (e.g. `<span onclick=\"...\">`).\n * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks\n * that content using the `$sce` service.\n *\n * <example name=\"NgModelController\" module=\"customControl\" deps=\"angular-sanitize.js\">\n    <file name=\"style.css\">\n      [contenteditable] {\n        border: 1px solid black;\n        background-color: white;\n        min-height: 20px;\n      }\n\n      .ng-invalid {\n        border: 1px solid red;\n      }\n\n    </file>\n    <file name=\"script.js\">\n      angular.module('customControl', ['ngSanitize']).\n        directive('contenteditable', ['$sce', function($sce) {\n          return {\n            restrict: 'A', // only activate on element attribute\n            require: '?ngModel', // get a hold of NgModelController\n            link: function(scope, element, attrs, ngModel) {\n              if (!ngModel) return; // do nothing if no ng-model\n\n              // Specify how UI should be updated\n              ngModel.$render = function() {\n                element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));\n              };\n\n              // Listen for change events to enable binding\n              element.on('blur keyup change', function() {\n                scope.$evalAsync(read);\n              });\n              read(); // initialize\n\n              // Write data to the model\n              function read() {\n                var html = element.html();\n                // When we clear the content editable the browser leaves a <br> behind\n                // If strip-br attribute is provided then we strip this out\n                if ( attrs.stripBr && html == '<br>' ) {\n                  html = '';\n                }\n                ngModel.$setViewValue(html);\n              }\n            }\n          };\n        }]);\n    </file>\n    <file name=\"index.html\">\n      <form name=\"myForm\">\n       <div contenteditable\n            name=\"myWidget\" ng-model=\"userContent\"\n            strip-br=\"true\"\n            required>Change me!</div>\n        <span ng-show=\"myForm.myWidget.$error.required\">Required!</span>\n       <hr>\n       <textarea ng-model=\"userContent\" aria-label=\"Dynamic textarea\"></textarea>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n    it('should data-bind and become invalid', function() {\n      if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {\n        // SafariDriver can't handle contenteditable\n        // and Firefox driver can't clear contenteditables very well\n        return;\n      }\n      var contentEditable = element(by.css('[contenteditable]'));\n      var content = 'Change me!';\n\n      expect(contentEditable.getText()).toEqual(content);\n\n      contentEditable.clear();\n      contentEditable.sendKeys(protractor.Key.BACK_SPACE);\n      expect(contentEditable.getText()).toEqual('');\n      expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);\n    });\n    </file>\n * </example>\n *\n *\n */\nvar NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',\n    function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {\n  this.$viewValue = Number.NaN;\n  this.$modelValue = Number.NaN;\n  this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.\n  this.$validators = {};\n  this.$asyncValidators = {};\n  this.$parsers = [];\n  this.$formatters = [];\n  this.$viewChangeListeners = [];\n  this.$untouched = true;\n  this.$touched = false;\n  this.$pristine = true;\n  this.$dirty = false;\n  this.$valid = true;\n  this.$invalid = false;\n  this.$error = {}; // keep invalid keys here\n  this.$$success = {}; // keep valid keys here\n  this.$pending = undefined; // keep pending keys here\n  this.$name = $interpolate($attr.name || '', false)($scope);\n\n\n  var parsedNgModel = $parse($attr.ngModel),\n      parsedNgModelAssign = parsedNgModel.assign,\n      ngModelGet = parsedNgModel,\n      ngModelSet = parsedNgModelAssign,\n      pendingDebounce = null,\n      parserValid,\n      ctrl = this;\n\n  this.$$setOptions = function(options) {\n    ctrl.$options = options;\n    if (options && options.getterSetter) {\n      var invokeModelGetter = $parse($attr.ngModel + '()'),\n          invokeModelSetter = $parse($attr.ngModel + '($$$p)');\n\n      ngModelGet = function($scope) {\n        var modelValue = parsedNgModel($scope);\n        if (isFunction(modelValue)) {\n          modelValue = invokeModelGetter($scope);\n        }\n        return modelValue;\n      };\n      ngModelSet = function($scope, newValue) {\n        if (isFunction(parsedNgModel($scope))) {\n          invokeModelSetter($scope, {$$$p: ctrl.$modelValue});\n        } else {\n          parsedNgModelAssign($scope, ctrl.$modelValue);\n        }\n      };\n    } else if (!parsedNgModel.assign) {\n      throw ngModelMinErr('nonassign', \"Expression '{0}' is non-assignable. Element: {1}\",\n          $attr.ngModel, startingTag($element));\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$render\n   *\n   * @description\n   * Called when the view needs to be updated. It is expected that the user of the ng-model\n   * directive will implement this method.\n   *\n   * The `$render()` method is invoked in the following situations:\n   *\n   * * `$rollbackViewValue()` is called.  If we are rolling back the view value to the last\n   *   committed value then `$render()` is called to update the input control.\n   * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and\n   *   the `$viewValue` are different from last time.\n   *\n   * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of\n   * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`\n   * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be\n   * invoked if you only change a property on the objects.\n   */\n  this.$render = noop;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$isEmpty\n   *\n   * @description\n   * This is called when we need to determine if the value of an input is empty.\n   *\n   * For instance, the required directive does this to work out if the input has data or not.\n   *\n   * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.\n   *\n   * You can override this for input directives whose concept of being empty is different from the\n   * default. The `checkboxInputType` directive does this because in its case a value of `false`\n   * implies empty.\n   *\n   * @param {*} value The value of the input to check for emptiness.\n   * @returns {boolean} True if `value` is \"empty\".\n   */\n  this.$isEmpty = function(value) {\n    return isUndefined(value) || value === '' || value === null || value !== value;\n  };\n\n  var parentForm = $element.inheritedData('$formController') || nullFormCtrl,\n      currentValidationRunId = 0;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setValidity\n   *\n   * @description\n   * Change the validity state, and notify the form.\n   *\n   * This method can be called within $parsers/$formatters or a custom validation implementation.\n   * However, in most cases it should be sufficient to use the `ngModel.$validators` and\n   * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.\n   *\n   * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned\n   *        to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`\n   *        (for unfulfilled `$asyncValidators`), so that it is available for data-binding.\n   *        The `validationErrorKey` should be in camelCase and will get converted into dash-case\n   *        for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`\n   *        class and can be bound to as  `{{someForm.someControl.$error.myError}}` .\n   * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),\n   *                          or skipped (null). Pending is used for unfulfilled `$asyncValidators`.\n   *                          Skipped is used by Angular when validators do not run because of parse errors and\n   *                          when `$asyncValidators` do not run because any of the `$validators` failed.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: $element,\n    set: function(object, property) {\n      object[property] = true;\n    },\n    unset: function(object, property) {\n      delete object[property];\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setPristine\n   *\n   * @description\n   * Sets the control to its pristine state.\n   *\n   * This method can be called to remove the `ng-dirty` class and set the control to its pristine\n   * state (`ng-pristine` class). A model is considered to be pristine when the control\n   * has not been changed from when first compiled.\n   */\n  this.$setPristine = function() {\n    ctrl.$dirty = false;\n    ctrl.$pristine = true;\n    $animate.removeClass($element, DIRTY_CLASS);\n    $animate.addClass($element, PRISTINE_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setDirty\n   *\n   * @description\n   * Sets the control to its dirty state.\n   *\n   * This method can be called to remove the `ng-pristine` class and set the control to its dirty\n   * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed\n   * from when first compiled.\n   */\n  this.$setDirty = function() {\n    ctrl.$dirty = true;\n    ctrl.$pristine = false;\n    $animate.removeClass($element, PRISTINE_CLASS);\n    $animate.addClass($element, DIRTY_CLASS);\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setUntouched\n   *\n   * @description\n   * Sets the control to its untouched state.\n   *\n   * This method can be called to remove the `ng-touched` class and set the control to its\n   * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched\n   * by default, however this function can be used to restore that state if the model has\n   * already been touched by the user.\n   */\n  this.$setUntouched = function() {\n    ctrl.$touched = false;\n    ctrl.$untouched = true;\n    $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setTouched\n   *\n   * @description\n   * Sets the control to its touched state.\n   *\n   * This method can be called to remove the `ng-untouched` class and set the control to its\n   * touched state (`ng-touched` class). A model is considered to be touched when the user has\n   * first focused the control element and then shifted focus away from the control (blur event).\n   */\n  this.$setTouched = function() {\n    ctrl.$touched = true;\n    ctrl.$untouched = false;\n    $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$rollbackViewValue\n   *\n   * @description\n   * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,\n   * which may be caused by a pending debounced event or because the input is waiting for a some\n   * future event.\n   *\n   * If you have an input that uses `ng-model-options` to set up debounced events or events such\n   * as blur you can have a situation where there is a period when the `$viewValue`\n   * is out of synch with the ngModel's `$modelValue`.\n   *\n   * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`\n   * programmatically before these debounced/future events have resolved/occurred, because Angular's\n   * dirty checking mechanism is not able to tell whether the model has actually changed or not.\n   *\n   * The `$rollbackViewValue()` method should be called before programmatically changing the model of an\n   * input which may have such events pending. This is important in order to make sure that the\n   * input field will be updated with the new model value and any pending operations are cancelled.\n   *\n   * <example name=\"ng-model-cancel-update\" module=\"cancel-update-example\">\n   *   <file name=\"app.js\">\n   *     angular.module('cancel-update-example', [])\n   *\n   *     .controller('CancelUpdateController', ['$scope', function($scope) {\n   *       $scope.resetWithCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myForm.myInput1.$rollbackViewValue();\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *       $scope.resetWithoutCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *     }]);\n   *   </file>\n   *   <file name=\"index.html\">\n   *     <div ng-controller=\"CancelUpdateController\">\n   *       <p>Try typing something in each input.  See that the model only updates when you\n   *          blur off the input.\n   *        </p>\n   *        <p>Now see what happens if you start typing then press the Escape key</p>\n   *\n   *       <form name=\"myForm\" ng-model-options=\"{ updateOn: 'blur' }\">\n   *         <p id=\"inputDescription1\">With $rollbackViewValue()</p>\n   *         <input name=\"myInput1\" aria-describedby=\"inputDescription1\" ng-model=\"myValue\"\n   *                ng-keydown=\"resetWithCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *\n   *         <p id=\"inputDescription2\">Without $rollbackViewValue()</p>\n   *         <input name=\"myInput2\" aria-describedby=\"inputDescription2\" ng-model=\"myValue\"\n   *                ng-keydown=\"resetWithoutCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *       </form>\n   *     </div>\n   *   </file>\n   * </example>\n   */\n  this.$rollbackViewValue = function() {\n    $timeout.cancel(pendingDebounce);\n    ctrl.$viewValue = ctrl.$$lastCommittedViewValue;\n    ctrl.$render();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$validate\n   *\n   * @description\n   * Runs each of the registered validators (first synchronous validators and then\n   * asynchronous validators).\n   * If the validity changes to invalid, the model will be set to `undefined`,\n   * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.\n   * If the validity changes to valid, it will set the model to the last available valid\n   * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.\n   */\n  this.$validate = function() {\n    // ignore $validate before model is initialized\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      return;\n    }\n\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    // Note: we use the $$rawModelValue as $modelValue might have been\n    // set to undefined during a view -> model update that found validation\n    // errors. We can't parse the view here, since that could change\n    // the model although neither viewValue nor the model on the scope changed\n    var modelValue = ctrl.$$rawModelValue;\n\n    var prevValid = ctrl.$valid;\n    var prevModelValue = ctrl.$modelValue;\n\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n\n    ctrl.$$runValidators(modelValue, viewValue, function(allValid) {\n      // If there was no change in validity, don't update the model\n      // This prevents changing an invalid modelValue to undefined\n      if (!allowInvalid && prevValid !== allValid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n\n        if (ctrl.$modelValue !== prevModelValue) {\n          ctrl.$$writeModelToScope();\n        }\n      }\n    });\n\n  };\n\n  this.$$runValidators = function(modelValue, viewValue, doneCallback) {\n    currentValidationRunId++;\n    var localValidationRunId = currentValidationRunId;\n\n    // check parser error\n    if (!processParseErrors()) {\n      validationDone(false);\n      return;\n    }\n    if (!processSyncValidators()) {\n      validationDone(false);\n      return;\n    }\n    processAsyncValidators();\n\n    function processParseErrors() {\n      var errorKey = ctrl.$$parserName || 'parse';\n      if (parserValid === undefined) {\n        setValidity(errorKey, null);\n      } else {\n        if (!parserValid) {\n          forEach(ctrl.$validators, function(v, name) {\n            setValidity(name, null);\n          });\n          forEach(ctrl.$asyncValidators, function(v, name) {\n            setValidity(name, null);\n          });\n        }\n        // Set the parse error last, to prevent unsetting it, should a $validators key == parserName\n        setValidity(errorKey, parserValid);\n        return parserValid;\n      }\n      return true;\n    }\n\n    function processSyncValidators() {\n      var syncValidatorsValid = true;\n      forEach(ctrl.$validators, function(validator, name) {\n        var result = validator(modelValue, viewValue);\n        syncValidatorsValid = syncValidatorsValid && result;\n        setValidity(name, result);\n      });\n      if (!syncValidatorsValid) {\n        forEach(ctrl.$asyncValidators, function(v, name) {\n          setValidity(name, null);\n        });\n        return false;\n      }\n      return true;\n    }\n\n    function processAsyncValidators() {\n      var validatorPromises = [];\n      var allValid = true;\n      forEach(ctrl.$asyncValidators, function(validator, name) {\n        var promise = validator(modelValue, viewValue);\n        if (!isPromiseLike(promise)) {\n          throw ngModelMinErr(\"$asyncValidators\",\n            \"Expected asynchronous validator to return a promise but got '{0}' instead.\", promise);\n        }\n        setValidity(name, undefined);\n        validatorPromises.push(promise.then(function() {\n          setValidity(name, true);\n        }, function(error) {\n          allValid = false;\n          setValidity(name, false);\n        }));\n      });\n      if (!validatorPromises.length) {\n        validationDone(true);\n      } else {\n        $q.all(validatorPromises).then(function() {\n          validationDone(allValid);\n        }, noop);\n      }\n    }\n\n    function setValidity(name, isValid) {\n      if (localValidationRunId === currentValidationRunId) {\n        ctrl.$setValidity(name, isValid);\n      }\n    }\n\n    function validationDone(allValid) {\n      if (localValidationRunId === currentValidationRunId) {\n\n        doneCallback(allValid);\n      }\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$commitViewValue\n   *\n   * @description\n   * Commit a pending update to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  this.$commitViewValue = function() {\n    var viewValue = ctrl.$viewValue;\n\n    $timeout.cancel(pendingDebounce);\n\n    // If the view value has not changed then we should just exit, except in the case where there is\n    // a native validator on the element. In this case the validation state may have changed even though\n    // the viewValue has stayed empty.\n    if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {\n      return;\n    }\n    ctrl.$$lastCommittedViewValue = viewValue;\n\n    // change to dirty\n    if (ctrl.$pristine) {\n      this.$setDirty();\n    }\n    this.$$parseAndValidate();\n  };\n\n  this.$$parseAndValidate = function() {\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    var modelValue = viewValue;\n    parserValid = isUndefined(modelValue) ? undefined : true;\n\n    if (parserValid) {\n      for (var i = 0; i < ctrl.$parsers.length; i++) {\n        modelValue = ctrl.$parsers[i](modelValue);\n        if (isUndefined(modelValue)) {\n          parserValid = false;\n          break;\n        }\n      }\n    }\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      // ctrl.$modelValue has not been touched yet...\n      ctrl.$modelValue = ngModelGet($scope);\n    }\n    var prevModelValue = ctrl.$modelValue;\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n    ctrl.$$rawModelValue = modelValue;\n\n    if (allowInvalid) {\n      ctrl.$modelValue = modelValue;\n      writeToModelIfNeeded();\n    }\n\n    // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.\n    // This can happen if e.g. $setViewValue is called from inside a parser\n    ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {\n      if (!allowInvalid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n        writeToModelIfNeeded();\n      }\n    });\n\n    function writeToModelIfNeeded() {\n      if (ctrl.$modelValue !== prevModelValue) {\n        ctrl.$$writeModelToScope();\n      }\n    }\n  };\n\n  this.$$writeModelToScope = function() {\n    ngModelSet($scope, ctrl.$modelValue);\n    forEach(ctrl.$viewChangeListeners, function(listener) {\n      try {\n        listener();\n      } catch (e) {\n        $exceptionHandler(e);\n      }\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setViewValue\n   *\n   * @description\n   * Update the view value.\n   *\n   * This method should be called when an input directive want to change the view value; typically,\n   * this is done from within a DOM event handler.\n   *\n   * For example {@link ng.directive:input input} calls it when the value of the input changes and\n   * {@link ng.directive:select select} calls it when an option is selected.\n   *\n   * If the new `value` is an object (rather than a string or a number), we should make a copy of the\n   * object before passing it to `$setViewValue`.  This is because `ngModel` does not perform a deep\n   * watch of objects, it only looks for a change of identity. If you only change the property of\n   * the object then ngModel will not realise that the object has changed and will not invoke the\n   * `$parsers` and `$validators` pipelines.\n   *\n   * For this reason, you should not change properties of the copy once it has been passed to\n   * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.\n   *\n   * When this method is called, the new `value` will be staged for committing through the `$parsers`\n   * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged\n   * value sent directly for processing, finally to be applied to `$modelValue` and then the\n   * **expression** specified in the `ng-model` attribute.\n   *\n   * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.\n   *\n   * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`\n   * and the `default` trigger is not listed, all those actions will remain pending until one of the\n   * `updateOn` events is triggered on the DOM element.\n   * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}\n   * directive is used with a custom debounce for this particular event.\n   *\n   * Note that calling this function does not trigger a `$digest`.\n   *\n   * @param {string} value Value from the view.\n   * @param {string} trigger Event that triggered the update.\n   */\n  this.$setViewValue = function(value, trigger) {\n    ctrl.$viewValue = value;\n    if (!ctrl.$options || ctrl.$options.updateOnDefault) {\n      ctrl.$$debounceViewValueCommit(trigger);\n    }\n  };\n\n  this.$$debounceViewValueCommit = function(trigger) {\n    var debounceDelay = 0,\n        options = ctrl.$options,\n        debounce;\n\n    if (options && isDefined(options.debounce)) {\n      debounce = options.debounce;\n      if (isNumber(debounce)) {\n        debounceDelay = debounce;\n      } else if (isNumber(debounce[trigger])) {\n        debounceDelay = debounce[trigger];\n      } else if (isNumber(debounce['default'])) {\n        debounceDelay = debounce['default'];\n      }\n    }\n\n    $timeout.cancel(pendingDebounce);\n    if (debounceDelay) {\n      pendingDebounce = $timeout(function() {\n        ctrl.$commitViewValue();\n      }, debounceDelay);\n    } else if ($rootScope.$$phase) {\n      ctrl.$commitViewValue();\n    } else {\n      $scope.$apply(function() {\n        ctrl.$commitViewValue();\n      });\n    }\n  };\n\n  // model -> value\n  // Note: we cannot use a normal scope.$watch as we want to detect the following:\n  // 1. scope value is 'a'\n  // 2. user enters 'b'\n  // 3. ng-change kicks in and reverts scope value to 'a'\n  //    -> scope value did not change since the last digest as\n  //       ng-change executes in apply phase\n  // 4. view should be changed back to 'a'\n  $scope.$watch(function ngModelWatch() {\n    var modelValue = ngModelGet($scope);\n\n    // if scope model value and ngModel value are out of sync\n    // TODO(perf): why not move this to the action fn?\n    if (modelValue !== ctrl.$modelValue &&\n       // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator\n       (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)\n    ) {\n      ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;\n      parserValid = undefined;\n\n      var formatters = ctrl.$formatters,\n          idx = formatters.length;\n\n      var viewValue = modelValue;\n      while (idx--) {\n        viewValue = formatters[idx](viewValue);\n      }\n      if (ctrl.$viewValue !== viewValue) {\n        ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;\n        ctrl.$render();\n\n        ctrl.$$runValidators(modelValue, viewValue, noop);\n      }\n    }\n\n    return modelValue;\n  });\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngModel\n *\n * @element input\n * @priority 1\n *\n * @description\n * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a\n * property on the scope using {@link ngModel.NgModelController NgModelController},\n * which is created and exposed by this directive.\n *\n * `ngModel` is responsible for:\n *\n * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`\n *   require.\n * - Providing validation behavior (i.e. required, number, email, url).\n * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).\n * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.\n * - Registering the control with its parent {@link ng.directive:form form}.\n *\n * Note: `ngModel` will try to bind to the property given by evaluating the expression on the\n * current scope. If the property doesn't already exist on this scope, it will be created\n * implicitly and added to the scope.\n *\n * For best practices on using `ngModel`, see:\n *\n *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)\n *\n * For basic examples, how to use `ngModel`, see:\n *\n *  - {@link ng.directive:input input}\n *    - {@link input[text] text}\n *    - {@link input[checkbox] checkbox}\n *    - {@link input[radio] radio}\n *    - {@link input[number] number}\n *    - {@link input[email] email}\n *    - {@link input[url] url}\n *    - {@link input[date] date}\n *    - {@link input[datetime-local] datetime-local}\n *    - {@link input[time] time}\n *    - {@link input[month] month}\n *    - {@link input[week] week}\n *  - {@link ng.directive:select select}\n *  - {@link ng.directive:textarea textarea}\n *\n * # CSS classes\n * The following CSS classes are added and removed on the associated input/select/textarea element\n * depending on the validity of the model.\n *\n *  - `ng-valid`: the model is valid\n *  - `ng-invalid`: the model is invalid\n *  - `ng-valid-[key]`: for each valid key added by `$setValidity`\n *  - `ng-invalid-[key]`: for each invalid key added by `$setValidity`\n *  - `ng-pristine`: the control hasn't been interacted with yet\n *  - `ng-dirty`: the control has been interacted with\n *  - `ng-touched`: the control has been blurred\n *  - `ng-untouched`: the control hasn't been blurred\n *  - `ng-pending`: any `$asyncValidators` are unfulfilled\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n * ## Animation Hooks\n *\n * Animations within models are triggered when any of the associated CSS classes are added and removed\n * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,\n * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.\n * The animations that are triggered within ngModel are similar to how they work in ngClass and\n * animations can be hooked into using CSS transitions, keyframes as well as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style an input element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-input {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-input.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n * <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"inputExample\">\n     <file name=\"index.html\">\n       <script>\n        angular.module('inputExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.val = '1';\n          }]);\n       </script>\n       <style>\n         .my-input {\n           -webkit-transition:all linear 0.5s;\n           transition:all linear 0.5s;\n           background: transparent;\n         }\n         .my-input.ng-invalid {\n           color:white;\n           background: red;\n         }\n       </style>\n       <p id=\"inputDescription\">\n        Update input to see transitions when valid/invalid.\n        Integer is a valid value.\n       </p>\n       <form name=\"testForm\" ng-controller=\"ExampleController\">\n         <input ng-model=\"val\" ng-pattern=\"/^\\d+$/\" name=\"anim\" class=\"my-input\"\n                aria-describedby=\"inputDescription\" />\n       </form>\n     </file>\n * </example>\n *\n * ## Binding to a getter/setter\n *\n * Sometimes it's helpful to bind `ngModel` to a getter/setter function.  A getter/setter is a\n * function that returns a representation of the model when called with zero arguments, and sets\n * the internal state of a model when called with an argument. It's sometimes useful to use this\n * for models that have an internal representation that's different from what the model exposes\n * to the view.\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more\n * frequently than other parts of your code.\n * </div>\n *\n * You use this behavior by adding `ng-model-options=\"{ getterSetter: true }\"` to an element that\n * has `ng-model` attached to it. You can also add `ng-model-options=\"{ getterSetter: true }\"` to\n * a `<form>`, which will enable this behavior for all `<input>`s within it. See\n * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.\n *\n * The following example shows how to use `ngModel` with a getter/setter:\n *\n * @example\n * <example name=\"ngModel-getter-setter\" module=\"getterSetterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <form name=\"userForm\">\n           <label>Name:\n             <input type=\"text\" name=\"userName\"\n                    ng-model=\"user.name\"\n                    ng-model-options=\"{ getterSetter: true }\" />\n           </label>\n         </form>\n         <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n       </div>\n     </file>\n     <file name=\"app.js\">\n       angular.module('getterSetterExample', [])\n         .controller('ExampleController', ['$scope', function($scope) {\n           var _name = 'Brian';\n           $scope.user = {\n             name: function(newName) {\n              // Note that newName can be undefined for two reasons:\n              // 1. Because it is called as a getter and thus called with no arguments\n              // 2. Because the property should actually be set to undefined. This happens e.g. if the\n              //    input is invalid\n              return arguments.length ? (_name = newName) : _name;\n             }\n           };\n         }]);\n     </file>\n * </example>\n */\nvar ngModelDirective = ['$rootScope', function($rootScope) {\n  return {\n    restrict: 'A',\n    require: ['ngModel', '^?form', '^?ngModelOptions'],\n    controller: NgModelController,\n    // Prelink needs to run before any input directive\n    // so that we can set the NgModelOptions in NgModelController\n    // before anyone else uses it.\n    priority: 1,\n    compile: function ngModelCompile(element) {\n      // Setup initial state of the control\n      element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);\n\n      return {\n        pre: function ngModelPreLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0],\n              formCtrl = ctrls[1] || nullFormCtrl;\n\n          modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);\n\n          // notify others, especially parent forms\n          formCtrl.$addControl(modelCtrl);\n\n          attr.$observe('name', function(newValue) {\n            if (modelCtrl.$name !== newValue) {\n              formCtrl.$$renameControl(modelCtrl, newValue);\n            }\n          });\n\n          scope.$on('$destroy', function() {\n            formCtrl.$removeControl(modelCtrl);\n          });\n        },\n        post: function ngModelPostLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0];\n          if (modelCtrl.$options && modelCtrl.$options.updateOn) {\n            element.on(modelCtrl.$options.updateOn, function(ev) {\n              modelCtrl.$$debounceViewValueCommit(ev && ev.type);\n            });\n          }\n\n          element.on('blur', function(ev) {\n            if (modelCtrl.$touched) return;\n\n            if ($rootScope.$$phase) {\n              scope.$evalAsync(modelCtrl.$setTouched);\n            } else {\n              scope.$apply(modelCtrl.$setTouched);\n            }\n          });\n        }\n      };\n    }\n  };\n}];\n\nvar DEFAULT_REGEXP = /(\\s+|^)default(\\s+|$)/;\n\n/**\n * @ngdoc directive\n * @name ngModelOptions\n *\n * @description\n * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of\n * events that will trigger a model update and/or a debouncing delay so that the actual update only\n * takes place when a timer expires; this timer will be reset after another change takes place.\n *\n * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might\n * be different from the value in the actual model. This means that if you update the model you\n * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in\n * order to make sure it is synchronized with the model and that any debounced action is canceled.\n *\n * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}\n * method is by making sure the input is placed inside a form that has a `name` attribute. This is\n * important because `form` controllers are published to the related scope under the name in their\n * `name` attribute.\n *\n * Any pending changes will take place immediately when an enclosing form is submitted via the\n * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * `ngModelOptions` has an effect on the element it's declared on and its descendants.\n *\n * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:\n *   - `updateOn`: string specifying which event should the input be bound to. You can set several\n *     events using an space delimited list. There is a special event called `default` that\n *     matches the default events belonging of the control.\n *   - `debounce`: integer value which contains the debounce model update value in milliseconds. A\n *     value of 0 triggers an immediate update. If an object is supplied instead, you can specify a\n *     custom value for each event. For example:\n *     `ng-model-options=\"{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }\"`\n *   - `allowInvalid`: boolean value which indicates that the model can be set with values that did\n *     not validate correctly instead of the default behavior of setting the model to undefined.\n *   - `getterSetter`: boolean value which determines whether or not to treat functions bound to\n       `ngModel` as getters/setters.\n *   - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for\n *     `<input type=\"date\">`, `<input type=\"time\">`, ... . It understands UTC/GMT and the\n *     continental US time zone abbreviations, but for general use, use a time zone offset, for\n *     example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n *     If not specified, the timezone of the browser will be used.\n *\n * @example\n\n  The following example shows how to override immediate updates. Changes on the inputs within the\n  form will update the model only when the control loses focus (blur event). If `escape` key is\n  pressed while the input field is focused, the value is reset to the value in the current model.\n\n  <example name=\"ngModelOptions-directive-blur\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          <label>Name:\n            <input type=\"text\" name=\"userName\"\n                   ng-model=\"user.name\"\n                   ng-model-options=\"{ updateOn: 'blur' }\"\n                   ng-keyup=\"cancel($event)\" />\n          </label><br />\n          <label>Other data:\n            <input type=\"text\" ng-model=\"user.data\" />\n          </label><br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say', data: '' };\n\n          $scope.cancel = function(e) {\n            if (e.keyCode == 27) {\n              $scope.userForm.userName.$rollbackViewValue();\n            }\n          };\n        }]);\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var model = element(by.binding('user.name'));\n      var input = element(by.model('user.name'));\n      var other = element(by.model('user.data'));\n\n      it('should allow custom events', function() {\n        input.sendKeys(' hello');\n        input.click();\n        expect(model.getText()).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say hello');\n      });\n\n      it('should $rollbackViewValue when model changes', function() {\n        input.sendKeys(' hello');\n        expect(input.getAttribute('value')).toEqual('say hello');\n        input.sendKeys(protractor.Key.ESCAPE);\n        expect(input.getAttribute('value')).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say');\n      });\n    </file>\n  </example>\n\n  This one shows how to debounce model changes. Model will be updated only 1 sec after last change.\n  If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.\n\n  <example name=\"ngModelOptions-directive-debounce\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          <label>Name:\n            <input type=\"text\" name=\"userName\"\n                   ng-model=\"user.name\"\n                   ng-model-options=\"{ debounce: 1000 }\" />\n          </label>\n          <button ng-click=\"userForm.userName.$rollbackViewValue(); user.name=''\">Clear</button>\n          <br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say' };\n        }]);\n    </file>\n  </example>\n\n  This one shows how to bind to getter/setters:\n\n  <example name=\"ngModelOptions-directive-getter-setter\" module=\"getterSetterExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          <label>Name:\n            <input type=\"text\" name=\"userName\"\n                   ng-model=\"user.name\"\n                   ng-model-options=\"{ getterSetter: true }\" />\n          </label>\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('getterSetterExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          var _name = 'Brian';\n          $scope.user = {\n            name: function(newName) {\n              // Note that newName can be undefined for two reasons:\n              // 1. Because it is called as a getter and thus called with no arguments\n              // 2. Because the property should actually be set to undefined. This happens e.g. if the\n              //    input is invalid\n              return arguments.length ? (_name = newName) : _name;\n            }\n          };\n        }]);\n    </file>\n  </example>\n */\nvar ngModelOptionsDirective = function() {\n  return {\n    restrict: 'A',\n    controller: ['$scope', '$attrs', function($scope, $attrs) {\n      var that = this;\n      this.$options = copy($scope.$eval($attrs.ngModelOptions));\n      // Allow adding/overriding bound events\n      if (this.$options.updateOn !== undefined) {\n        this.$options.updateOnDefault = false;\n        // extract \"default\" pseudo-event from list of events that can trigger a model update\n        this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {\n          that.$options.updateOnDefault = true;\n          return ' ';\n        }));\n      } else {\n        this.$options.updateOnDefault = true;\n      }\n    }]\n  };\n};\n\n\n\n// helper methods\nfunction addSetValidityMethod(context) {\n  var ctrl = context.ctrl,\n      $element = context.$element,\n      classCache = {},\n      set = context.set,\n      unset = context.unset,\n      parentForm = context.parentForm,\n      $animate = context.$animate;\n\n  classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));\n\n  ctrl.$setValidity = setValidity;\n\n  function setValidity(validationErrorKey, state, controller) {\n    if (state === undefined) {\n      createAndSet('$pending', validationErrorKey, controller);\n    } else {\n      unsetAndCleanup('$pending', validationErrorKey, controller);\n    }\n    if (!isBoolean(state)) {\n      unset(ctrl.$error, validationErrorKey, controller);\n      unset(ctrl.$$success, validationErrorKey, controller);\n    } else {\n      if (state) {\n        unset(ctrl.$error, validationErrorKey, controller);\n        set(ctrl.$$success, validationErrorKey, controller);\n      } else {\n        set(ctrl.$error, validationErrorKey, controller);\n        unset(ctrl.$$success, validationErrorKey, controller);\n      }\n    }\n    if (ctrl.$pending) {\n      cachedToggleClass(PENDING_CLASS, true);\n      ctrl.$valid = ctrl.$invalid = undefined;\n      toggleValidationCss('', null);\n    } else {\n      cachedToggleClass(PENDING_CLASS, false);\n      ctrl.$valid = isObjectEmpty(ctrl.$error);\n      ctrl.$invalid = !ctrl.$valid;\n      toggleValidationCss('', ctrl.$valid);\n    }\n\n    // re-read the state as the set/unset methods could have\n    // combined state in ctrl.$error[validationError] (used for forms),\n    // where setting/unsetting only increments/decrements the value,\n    // and does not replace it.\n    var combinedState;\n    if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {\n      combinedState = undefined;\n    } else if (ctrl.$error[validationErrorKey]) {\n      combinedState = false;\n    } else if (ctrl.$$success[validationErrorKey]) {\n      combinedState = true;\n    } else {\n      combinedState = null;\n    }\n\n    toggleValidationCss(validationErrorKey, combinedState);\n    parentForm.$setValidity(validationErrorKey, combinedState, ctrl);\n  }\n\n  function createAndSet(name, value, controller) {\n    if (!ctrl[name]) {\n      ctrl[name] = {};\n    }\n    set(ctrl[name], value, controller);\n  }\n\n  function unsetAndCleanup(name, value, controller) {\n    if (ctrl[name]) {\n      unset(ctrl[name], value, controller);\n    }\n    if (isObjectEmpty(ctrl[name])) {\n      ctrl[name] = undefined;\n    }\n  }\n\n  function cachedToggleClass(className, switchValue) {\n    if (switchValue && !classCache[className]) {\n      $animate.addClass($element, className);\n      classCache[className] = true;\n    } else if (!switchValue && classCache[className]) {\n      $animate.removeClass($element, className);\n      classCache[className] = false;\n    }\n  }\n\n  function toggleValidationCss(validationErrorKey, isValid) {\n    validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';\n\n    cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);\n    cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);\n  }\n}\n\nfunction isObjectEmpty(obj) {\n  if (obj) {\n    for (var prop in obj) {\n      if (obj.hasOwnProperty(prop)) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n/**\n * @ngdoc directive\n * @name ngNonBindable\n * @restrict AC\n * @priority 1000\n *\n * @description\n * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current\n * DOM element. This is useful if the element contains what appears to be Angular directives and\n * bindings but which should be ignored by Angular. This could be the case if you have a site that\n * displays snippets of code, for instance.\n *\n * @element ANY\n *\n * @example\n * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,\n * but the one wrapped in `ngNonBindable` is left alone.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <div>Normal: {{1 + 2}}</div>\n        <div ng-non-bindable>Ignored: {{1 + 2}}</div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-non-bindable', function() {\n         expect(element(by.binding('1 + 2')).getText()).toContain('3');\n         expect(element.all(by.css('div')).last().getText()).toMatch(/1 \\+ 2/);\n       });\n      </file>\n    </example>\n */\nvar ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });\n\n/* global jqLiteRemove */\n\nvar ngOptionsMinErr = minErr('ngOptions');\n\n/**\n * @ngdoc directive\n * @name ngOptions\n * @restrict A\n *\n * @description\n *\n * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`\n * elements for the `<select>` element using the array or object obtained by evaluating the\n * `ngOptions` comprehension expression.\n *\n * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a\n * similar result. However, `ngOptions` provides some benefits such as reducing memory and\n * increasing speed by not creating a new scope for each repeated instance, as well as providing\n * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the\n * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound\n *  to a non-string value. This is because an option element can only be bound to string values at\n * present.\n *\n * When an item in the `<select>` menu is selected, the array element or object property\n * represented by the selected option will be bound to the model identified by the `ngModel`\n * directive.\n *\n * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can\n * be nested into the `<select>` element. This element will then represent the `null` or \"not selected\"\n * option. See example below for demonstration.\n *\n * ## Complex Models (objects or collections)\n *\n * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when\n * binding any input directive to a model that is an object or a collection.\n *\n * Since this is a common situation for `ngOptions` the directive additionally watches the model using\n * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in\n * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual\n * object/collection has not changed identity but only a property on the object or an item in the collection\n * changes.\n *\n * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection\n * if the model is an array). This means that changing a property deeper inside the object/collection that the\n * first level will not trigger a re-rendering.\n *\n *\n * ## `select` **`as`**\n *\n * Using `select` **`as`** will bind the result of the `select` expression to the model, but\n * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)\n * or property name (for object data sources) of the value within the collection. If a **`track by`** expression\n * is used, the result of that expression will be set as the value of the `option` and `select` elements.\n *\n *\n * ### `select` **`as`** and **`track by`**\n *\n * <div class=\"alert alert-warning\">\n * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.\n * </div>\n *\n * Consider the following example:\n *\n * ```html\n * <select ng-options=\"item.subItem as item.label for item in values track by item.id\" ng-model=\"selected\"></select>\n * ```\n *\n * ```js\n * $scope.values = [{\n *   id: 1,\n *   label: 'aLabel',\n *   subItem: { name: 'aSubItem' }\n * }, {\n *   id: 2,\n *   label: 'bLabel',\n *   subItem: { name: 'bSubItem' }\n * }];\n *\n * $scope.selected = { name: 'aSubItem' };\n * ```\n *\n * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element\n * of the data source (to `item` in this example). To calculate whether an element is selected, we do the\n * following:\n *\n * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`\n * 2. Apply **`track by`** to the already selected value in `ngModel`.\n *    In the example: this is not possible as **`track by`** refers to `item.id`, but the selected\n *    value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to\n *    a wrong object, the selected element can't be found, `<select>` is always reset to the \"not\n *    selected\" option.\n *\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required The control is considered valid only if value is entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {comprehension_expression=} ngOptions in one of the following forms:\n *\n *   * for array data sources:\n *     * `label` **`for`** `value` **`in`** `array`\n *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array`\n *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`\n *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`\n *     * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`\n *        (for including a filter with `track by`)\n *   * for object data sources:\n *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`\n *     * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`group by`** `group`\n *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`disable when`** `disable`\n *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`\n *\n * Where:\n *\n *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.\n *   * `value`: local variable which will refer to each item in the `array` or each property value\n *      of `object` during iteration.\n *   * `key`: local variable which will refer to a property name in `object` during iteration.\n *   * `label`: The result of this expression will be the label for `<option>` element. The\n *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).\n *   * `select`: The result of this expression will be bound to the model of the parent `<select>`\n *      element. If not specified, `select` expression will default to `value`.\n *   * `group`: The result of this expression will be used to group options using the `<optgroup>`\n *      DOM element.\n *   * `disable`: The result of this expression will be used to disable the rendered `<option>`\n *      element. Return `true` to disable.\n *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be\n *      used to identify the objects in the array. The `trackexpr` will most likely refer to the\n *     `value` variable (e.g. `value.propertyName`). With this the selection is preserved\n *      even when the options are recreated (e.g. reloaded from the server).\n *\n * @example\n    <example module=\"selectExample\">\n      <file name=\"index.html\">\n        <script>\n        angular.module('selectExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.colors = [\n              {name:'black', shade:'dark'},\n              {name:'white', shade:'light', notAnOption: true},\n              {name:'red', shade:'dark'},\n              {name:'blue', shade:'dark', notAnOption: true},\n              {name:'yellow', shade:'light', notAnOption: false}\n            ];\n            $scope.myColor = $scope.colors[2]; // red\n          }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          <ul>\n            <li ng-repeat=\"color in colors\">\n              <label>Name: <input ng-model=\"color.name\"></label>\n              <label><input type=\"checkbox\" ng-model=\"color.notAnOption\"> Disabled?</label>\n              <button ng-click=\"colors.splice($index, 1)\" aria-label=\"Remove\">X</button>\n            </li>\n            <li>\n              <button ng-click=\"colors.push({})\">add</button>\n            </li>\n          </ul>\n          <hr/>\n          <label>Color (null not allowed):\n            <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\"></select>\n          </label><br/>\n          <label>Color (null allowed):\n          <span  class=\"nullable\">\n            <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\">\n              <option value=\"\">-- choose color --</option>\n            </select>\n          </span></label><br/>\n\n          <label>Color grouped by shade:\n            <select ng-model=\"myColor\" ng-options=\"color.name group by color.shade for color in colors\">\n            </select>\n          </label><br/>\n\n          <label>Color grouped by shade, with some disabled:\n            <select ng-model=\"myColor\"\n                  ng-options=\"color.name group by color.shade disable when color.notAnOption for color in colors\">\n            </select>\n          </label><br/>\n\n\n\n          Select <button ng-click=\"myColor = { name:'not in list', shade: 'other' }\">bogus</button>.\n          <br/>\n          <hr/>\n          Currently selected: {{ {selected_color:myColor} }}\n          <div style=\"border:solid 1px black; height:20px\"\n               ng-style=\"{'background-color':myColor.name}\">\n          </div>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n         it('should check ng-options', function() {\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');\n           element.all(by.model('myColor')).first().click();\n           element.all(by.css('select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');\n           element(by.css('.nullable select[ng-model=\"myColor\"]')).click();\n           element.all(by.css('.nullable select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');\n         });\n      </file>\n    </example>\n */\n\n// jshint maxlen: false\n//                     //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999\nvar NG_OPTIONS_REGEXP = /^\\s*([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+group\\s+by\\s+([\\s\\S]+?))?(?:\\s+disable\\s+when\\s+([\\s\\S]+?))?\\s+for\\s+(?:([\\$\\w][\\$\\w]*)|(?:\\(\\s*([\\$\\w][\\$\\w]*)\\s*,\\s*([\\$\\w][\\$\\w]*)\\s*\\)))\\s+in\\s+([\\s\\S]+?)(?:\\s+track\\s+by\\s+([\\s\\S]+?))?$/;\n                        // 1: value expression (valueFn)\n                        // 2: label expression (displayFn)\n                        // 3: group by expression (groupByFn)\n                        // 4: disable when expression (disableWhenFn)\n                        // 5: array item variable name\n                        // 6: object item key variable name\n                        // 7: object item value variable name\n                        // 8: collection expression\n                        // 9: track by expression\n// jshint maxlen: 100\n\n\nvar ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {\n\n  function parseOptionsExpression(optionsExp, selectElement, scope) {\n\n    var match = optionsExp.match(NG_OPTIONS_REGEXP);\n    if (!(match)) {\n      throw ngOptionsMinErr('iexp',\n        \"Expected expression in form of \" +\n        \"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'\" +\n        \" but got '{0}'. Element: {1}\",\n        optionsExp, startingTag(selectElement));\n    }\n\n    // Extract the parts from the ngOptions expression\n\n    // The variable name for the value of the item in the collection\n    var valueName = match[5] || match[7];\n    // The variable name for the key of the item in the collection\n    var keyName = match[6];\n\n    // An expression that generates the viewValue for an option if there is a label expression\n    var selectAs = / as /.test(match[0]) && match[1];\n    // An expression that is used to track the id of each object in the options collection\n    var trackBy = match[9];\n    // An expression that generates the viewValue for an option if there is no label expression\n    var valueFn = $parse(match[2] ? match[1] : valueName);\n    var selectAsFn = selectAs && $parse(selectAs);\n    var viewValueFn = selectAsFn || valueFn;\n    var trackByFn = trackBy && $parse(trackBy);\n\n    // Get the value by which we are going to track the option\n    // if we have a trackFn then use that (passing scope and locals)\n    // otherwise just hash the given viewValue\n    var getTrackByValueFn = trackBy ?\n                              function(value, locals) { return trackByFn(scope, locals); } :\n                              function getHashOfValue(value) { return hashKey(value); };\n    var getTrackByValue = function(value, key) {\n      return getTrackByValueFn(value, getLocals(value, key));\n    };\n\n    var displayFn = $parse(match[2] || match[1]);\n    var groupByFn = $parse(match[3] || '');\n    var disableWhenFn = $parse(match[4] || '');\n    var valuesFn = $parse(match[8]);\n\n    var locals = {};\n    var getLocals = keyName ? function(value, key) {\n      locals[keyName] = key;\n      locals[valueName] = value;\n      return locals;\n    } : function(value) {\n      locals[valueName] = value;\n      return locals;\n    };\n\n\n    function Option(selectValue, viewValue, label, group, disabled) {\n      this.selectValue = selectValue;\n      this.viewValue = viewValue;\n      this.label = label;\n      this.group = group;\n      this.disabled = disabled;\n    }\n\n    function getOptionValuesKeys(optionValues) {\n      var optionValuesKeys;\n\n      if (!keyName && isArrayLike(optionValues)) {\n        optionValuesKeys = optionValues;\n      } else {\n        // if object, extract keys, in enumeration order, unsorted\n        optionValuesKeys = [];\n        for (var itemKey in optionValues) {\n          if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {\n            optionValuesKeys.push(itemKey);\n          }\n        }\n      }\n      return optionValuesKeys;\n    }\n\n    return {\n      trackBy: trackBy,\n      getTrackByValue: getTrackByValue,\n      getWatchables: $parse(valuesFn, function(optionValues) {\n        // Create a collection of things that we would like to watch (watchedArray)\n        // so that they can all be watched using a single $watchCollection\n        // that only runs the handler once if anything changes\n        var watchedArray = [];\n        optionValues = optionValues || [];\n\n        var optionValuesKeys = getOptionValuesKeys(optionValues);\n        var optionValuesLength = optionValuesKeys.length;\n        for (var index = 0; index < optionValuesLength; index++) {\n          var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];\n          var value = optionValues[key];\n\n          var locals = getLocals(optionValues[key], key);\n          var selectValue = getTrackByValueFn(optionValues[key], locals);\n          watchedArray.push(selectValue);\n\n          // Only need to watch the displayFn if there is a specific label expression\n          if (match[2] || match[1]) {\n            var label = displayFn(scope, locals);\n            watchedArray.push(label);\n          }\n\n          // Only need to watch the disableWhenFn if there is a specific disable expression\n          if (match[4]) {\n            var disableWhen = disableWhenFn(scope, locals);\n            watchedArray.push(disableWhen);\n          }\n        }\n        return watchedArray;\n      }),\n\n      getOptions: function() {\n\n        var optionItems = [];\n        var selectValueMap = {};\n\n        // The option values were already computed in the `getWatchables` fn,\n        // which must have been called to trigger `getOptions`\n        var optionValues = valuesFn(scope) || [];\n        var optionValuesKeys = getOptionValuesKeys(optionValues);\n        var optionValuesLength = optionValuesKeys.length;\n\n        for (var index = 0; index < optionValuesLength; index++) {\n          var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];\n          var value = optionValues[key];\n          var locals = getLocals(value, key);\n          var viewValue = viewValueFn(scope, locals);\n          var selectValue = getTrackByValueFn(viewValue, locals);\n          var label = displayFn(scope, locals);\n          var group = groupByFn(scope, locals);\n          var disabled = disableWhenFn(scope, locals);\n          var optionItem = new Option(selectValue, viewValue, label, group, disabled);\n\n          optionItems.push(optionItem);\n          selectValueMap[selectValue] = optionItem;\n        }\n\n        return {\n          items: optionItems,\n          selectValueMap: selectValueMap,\n          getOptionFromViewValue: function(value) {\n            return selectValueMap[getTrackByValue(value)];\n          },\n          getViewValueFromOption: function(option) {\n            // If the viewValue could be an object that may be mutated by the application,\n            // we need to make a copy and not return the reference to the value on the option.\n            return trackBy ? angular.copy(option.viewValue) : option.viewValue;\n          }\n        };\n      }\n    };\n  }\n\n\n  // we can't just jqLite('<option>') since jqLite is not smart enough\n  // to create it in <select> and IE barfs otherwise.\n  var optionTemplate = document.createElement('option'),\n      optGroupTemplate = document.createElement('optgroup');\n\n  return {\n    restrict: 'A',\n    terminal: true,\n    require: ['select', '?ngModel'],\n    link: function(scope, selectElement, attr, ctrls) {\n\n      // if ngModel is not defined, we don't need to do anything\n      var ngModelCtrl = ctrls[1];\n      if (!ngModelCtrl) return;\n\n      var selectCtrl = ctrls[0];\n      var multiple = attr.multiple;\n\n      // The emptyOption allows the application developer to provide their own custom \"empty\"\n      // option when the viewValue does not match any of the option values.\n      var emptyOption;\n      for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {\n        if (children[i].value === '') {\n          emptyOption = children.eq(i);\n          break;\n        }\n      }\n\n      var providedEmptyOption = !!emptyOption;\n\n      var unknownOption = jqLite(optionTemplate.cloneNode(false));\n      unknownOption.val('?');\n\n      var options;\n      var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);\n\n\n      var renderEmptyOption = function() {\n        if (!providedEmptyOption) {\n          selectElement.prepend(emptyOption);\n        }\n        selectElement.val('');\n        emptyOption.prop('selected', true); // needed for IE\n        emptyOption.attr('selected', true);\n      };\n\n      var removeEmptyOption = function() {\n        if (!providedEmptyOption) {\n          emptyOption.remove();\n        }\n      };\n\n\n      var renderUnknownOption = function() {\n        selectElement.prepend(unknownOption);\n        selectElement.val('?');\n        unknownOption.prop('selected', true); // needed for IE\n        unknownOption.attr('selected', true);\n      };\n\n      var removeUnknownOption = function() {\n        unknownOption.remove();\n      };\n\n\n      // Update the controller methods for multiple selectable options\n      if (!multiple) {\n\n        selectCtrl.writeValue = function writeNgOptionsValue(value) {\n          var option = options.getOptionFromViewValue(value);\n\n          if (option && !option.disabled) {\n            if (selectElement[0].value !== option.selectValue) {\n              removeUnknownOption();\n              removeEmptyOption();\n\n              selectElement[0].value = option.selectValue;\n              option.element.selected = true;\n              option.element.setAttribute('selected', 'selected');\n            }\n          } else {\n            if (value === null || providedEmptyOption) {\n              removeUnknownOption();\n              renderEmptyOption();\n            } else {\n              removeEmptyOption();\n              renderUnknownOption();\n            }\n          }\n        };\n\n        selectCtrl.readValue = function readNgOptionsValue() {\n\n          var selectedOption = options.selectValueMap[selectElement.val()];\n\n          if (selectedOption && !selectedOption.disabled) {\n            removeEmptyOption();\n            removeUnknownOption();\n            return options.getViewValueFromOption(selectedOption);\n          }\n          return null;\n        };\n\n        // If we are using `track by` then we must watch the tracked value on the model\n        // since ngModel only watches for object identity change\n        if (ngOptions.trackBy) {\n          scope.$watch(\n            function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },\n            function() { ngModelCtrl.$render(); }\n          );\n        }\n\n      } else {\n\n        ngModelCtrl.$isEmpty = function(value) {\n          return !value || value.length === 0;\n        };\n\n\n        selectCtrl.writeValue = function writeNgOptionsMultiple(value) {\n          options.items.forEach(function(option) {\n            option.element.selected = false;\n          });\n\n          if (value) {\n            value.forEach(function(item) {\n              var option = options.getOptionFromViewValue(item);\n              if (option && !option.disabled) option.element.selected = true;\n            });\n          }\n        };\n\n\n        selectCtrl.readValue = function readNgOptionsMultiple() {\n          var selectedValues = selectElement.val() || [],\n              selections = [];\n\n          forEach(selectedValues, function(value) {\n            var option = options.selectValueMap[value];\n            if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));\n          });\n\n          return selections;\n        };\n\n        // If we are using `track by` then we must watch these tracked values on the model\n        // since ngModel only watches for object identity change\n        if (ngOptions.trackBy) {\n\n          scope.$watchCollection(function() {\n            if (isArray(ngModelCtrl.$viewValue)) {\n              return ngModelCtrl.$viewValue.map(function(value) {\n                return ngOptions.getTrackByValue(value);\n              });\n            }\n          }, function() {\n            ngModelCtrl.$render();\n          });\n\n        }\n      }\n\n\n      if (providedEmptyOption) {\n\n        // we need to remove it before calling selectElement.empty() because otherwise IE will\n        // remove the label from the element. wtf?\n        emptyOption.remove();\n\n        // compile the element since there might be bindings in it\n        $compile(emptyOption)(scope);\n\n        // remove the class, which is added automatically because we recompile the element and it\n        // becomes the compilation root\n        emptyOption.removeClass('ng-scope');\n      } else {\n        emptyOption = jqLite(optionTemplate.cloneNode(false));\n      }\n\n      // We need to do this here to ensure that the options object is defined\n      // when we first hit it in writeNgOptionsValue\n      updateOptions();\n\n      // We will re-render the option elements if the option values or labels change\n      scope.$watchCollection(ngOptions.getWatchables, updateOptions);\n\n      // ------------------------------------------------------------------ //\n\n\n      function updateOptionElement(option, element) {\n        option.element = element;\n        element.disabled = option.disabled;\n        if (option.value !== element.value) element.value = option.selectValue;\n        if (option.label !== element.label) {\n          element.label = option.label;\n          element.textContent = option.label;\n        }\n      }\n\n      function addOrReuseElement(parent, current, type, templateElement) {\n        var element;\n        // Check whether we can reuse the next element\n        if (current && lowercase(current.nodeName) === type) {\n          // The next element is the right type so reuse it\n          element = current;\n        } else {\n          // The next element is not the right type so create a new one\n          element = templateElement.cloneNode(false);\n          if (!current) {\n            // There are no more elements so just append it to the select\n            parent.appendChild(element);\n          } else {\n            // The next element is not a group so insert the new one\n            parent.insertBefore(element, current);\n          }\n        }\n        return element;\n      }\n\n\n      function removeExcessElements(current) {\n        var next;\n        while (current) {\n          next = current.nextSibling;\n          jqLiteRemove(current);\n          current = next;\n        }\n      }\n\n\n      function skipEmptyAndUnknownOptions(current) {\n        var emptyOption_ = emptyOption && emptyOption[0];\n        var unknownOption_ = unknownOption && unknownOption[0];\n\n        if (emptyOption_ || unknownOption_) {\n          while (current &&\n                (current === emptyOption_ ||\n                current === unknownOption_)) {\n            current = current.nextSibling;\n          }\n        }\n        return current;\n      }\n\n\n      function updateOptions() {\n\n        var previousValue = options && selectCtrl.readValue();\n\n        options = ngOptions.getOptions();\n\n        var groupMap = {};\n        var currentElement = selectElement[0].firstChild;\n\n        // Ensure that the empty option is always there if it was explicitly provided\n        if (providedEmptyOption) {\n          selectElement.prepend(emptyOption);\n        }\n\n        currentElement = skipEmptyAndUnknownOptions(currentElement);\n\n        options.items.forEach(function updateOption(option) {\n          var group;\n          var groupElement;\n          var optionElement;\n\n          if (option.group) {\n\n            // This option is to live in a group\n            // See if we have already created this group\n            group = groupMap[option.group];\n\n            if (!group) {\n\n              // We have not already created this group\n              groupElement = addOrReuseElement(selectElement[0],\n                                               currentElement,\n                                               'optgroup',\n                                               optGroupTemplate);\n              // Move to the next element\n              currentElement = groupElement.nextSibling;\n\n              // Update the label on the group element\n              groupElement.label = option.group;\n\n              // Store it for use later\n              group = groupMap[option.group] = {\n                groupElement: groupElement,\n                currentOptionElement: groupElement.firstChild\n              };\n\n            }\n\n            // So now we have a group for this option we add the option to the group\n            optionElement = addOrReuseElement(group.groupElement,\n                                              group.currentOptionElement,\n                                              'option',\n                                              optionTemplate);\n            updateOptionElement(option, optionElement);\n            // Move to the next element\n            group.currentOptionElement = optionElement.nextSibling;\n\n          } else {\n\n            // This option is not in a group\n            optionElement = addOrReuseElement(selectElement[0],\n                                              currentElement,\n                                              'option',\n                                              optionTemplate);\n            updateOptionElement(option, optionElement);\n            // Move to the next element\n            currentElement = optionElement.nextSibling;\n          }\n        });\n\n\n        // Now remove all excess options and group\n        Object.keys(groupMap).forEach(function(key) {\n          removeExcessElements(groupMap[key].currentOptionElement);\n        });\n        removeExcessElements(currentElement);\n\n        ngModelCtrl.$render();\n\n        // Check to see if the value has changed due to the update to the options\n        if (!ngModelCtrl.$isEmpty(previousValue)) {\n          var nextValue = selectCtrl.readValue();\n          if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {\n            ngModelCtrl.$setViewValue(nextValue);\n            ngModelCtrl.$render();\n          }\n        }\n\n      }\n\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngPluralize\n * @restrict EA\n *\n * @description\n * `ngPluralize` is a directive that displays messages according to en-US localization rules.\n * These rules are bundled with angular.js, but can be overridden\n * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive\n * by specifying the mappings between\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * and the strings to be displayed.\n *\n * # Plural categories and explicit number rules\n * There are two\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * in Angular's default en-US locale: \"one\" and \"other\".\n *\n * While a plural category may match many numbers (for example, in en-US locale, \"other\" can match\n * any number that is not 1), an explicit number rule can only match one number. For example, the\n * explicit number rule for \"3\" matches the number 3. There are examples of plural categories\n * and explicit number rules throughout the rest of this documentation.\n *\n * # Configuring ngPluralize\n * You configure ngPluralize by providing 2 attributes: `count` and `when`.\n * You can also provide an optional attribute, `offset`.\n *\n * The value of the `count` attribute can be either a string or an {@link guide/expression\n * Angular expression}; these are evaluated on the current scope for its bound value.\n *\n * The `when` attribute specifies the mappings between plural categories and the actual\n * string to be displayed. The value of the attribute should be a JSON object.\n *\n * The following example shows how to configure ngPluralize:\n *\n * ```html\n * <ng-pluralize count=\"personCount\"\n                 when=\"{'0': 'Nobody is viewing.',\n *                      'one': '1 person is viewing.',\n *                      'other': '{} people are viewing.'}\">\n * </ng-pluralize>\n *```\n *\n * In the example, `\"0: Nobody is viewing.\"` is an explicit number rule. If you did not\n * specify this rule, 0 would be matched to the \"other\" category and \"0 people are viewing\"\n * would be shown instead of \"Nobody is viewing\". You can specify an explicit number rule for\n * other numbers, for example 12, so that instead of showing \"12 people are viewing\", you can\n * show \"a dozen people are viewing\".\n *\n * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted\n * into pluralized strings. In the previous example, Angular will replace `{}` with\n * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder\n * for <span ng-non-bindable>{{numberExpression}}</span>.\n *\n * If no rule is defined for a category, then an empty string is displayed and a warning is generated.\n * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.\n *\n * # Configuring ngPluralize with offset\n * The `offset` attribute allows further customization of pluralized text, which can result in\n * a better user experience. For example, instead of the message \"4 people are viewing this document\",\n * you might display \"John, Kate and 2 others are viewing this document\".\n * The offset attribute allows you to offset a number by any desired value.\n * Let's take a look at an example:\n *\n * ```html\n * <ng-pluralize count=\"personCount\" offset=2\n *               when=\"{'0': 'Nobody is viewing.',\n *                      '1': '{{person1}} is viewing.',\n *                      '2': '{{person1}} and {{person2}} are viewing.',\n *                      'one': '{{person1}}, {{person2}} and one other person are viewing.',\n *                      'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n * </ng-pluralize>\n * ```\n *\n * Notice that we are still using two plural categories(one, other), but we added\n * three explicit number rules 0, 1 and 2.\n * When one person, perhaps John, views the document, \"John is viewing\" will be shown.\n * When three people view the document, no explicit number rule is found, so\n * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.\n * In this case, plural category 'one' is matched and \"John, Mary and one other person are viewing\"\n * is shown.\n *\n * Note that when you specify offsets, you must provide explicit number rules for\n * numbers from 0 up to and including the offset. If you use an offset of 3, for example,\n * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for\n * plural categories \"one\" and \"other\".\n *\n * @param {string|expression} count The variable to be bound to.\n * @param {string} when The mapping between plural category to its corresponding strings.\n * @param {number=} offset Offset to deduct from the total number.\n *\n * @example\n    <example module=\"pluralizeExample\">\n      <file name=\"index.html\">\n        <script>\n          angular.module('pluralizeExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.person1 = 'Igor';\n              $scope.person2 = 'Misko';\n              $scope.personCount = 1;\n            }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          <label>Person 1:<input type=\"text\" ng-model=\"person1\" value=\"Igor\" /></label><br/>\n          <label>Person 2:<input type=\"text\" ng-model=\"person2\" value=\"Misko\" /></label><br/>\n          <label>Number of People:<input type=\"text\" ng-model=\"personCount\" value=\"1\" /></label><br/>\n\n          <!--- Example with simple pluralization rules for en locale --->\n          Without Offset:\n          <ng-pluralize count=\"personCount\"\n                        when=\"{'0': 'Nobody is viewing.',\n                               'one': '1 person is viewing.',\n                               'other': '{} people are viewing.'}\">\n          </ng-pluralize><br>\n\n          <!--- Example with offset --->\n          With Offset(2):\n          <ng-pluralize count=\"personCount\" offset=2\n                        when=\"{'0': 'Nobody is viewing.',\n                               '1': '{{person1}} is viewing.',\n                               '2': '{{person1}} and {{person2}} are viewing.',\n                               'one': '{{person1}}, {{person2}} and one other person are viewing.',\n                               'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n          </ng-pluralize>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should show correct pluralized string', function() {\n          var withoutOffset = element.all(by.css('ng-pluralize')).get(0);\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var countInput = element(by.model('personCount'));\n\n          expect(withoutOffset.getText()).toEqual('1 person is viewing.');\n          expect(withOffset.getText()).toEqual('Igor is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('0');\n\n          expect(withoutOffset.getText()).toEqual('Nobody is viewing.');\n          expect(withOffset.getText()).toEqual('Nobody is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('2');\n\n          expect(withoutOffset.getText()).toEqual('2 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('3');\n\n          expect(withoutOffset.getText()).toEqual('3 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('4');\n\n          expect(withoutOffset.getText()).toEqual('4 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');\n        });\n        it('should show data-bound names', function() {\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var personCount = element(by.model('personCount'));\n          var person1 = element(by.model('person1'));\n          var person2 = element(by.model('person2'));\n          personCount.clear();\n          personCount.sendKeys('4');\n          person1.clear();\n          person1.sendKeys('Di');\n          person2.clear();\n          person2.sendKeys('Vojta');\n          expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');\n        });\n      </file>\n    </example>\n */\nvar ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {\n  var BRACE = /{}/g,\n      IS_WHEN = /^when(Minus)?(.+)$/;\n\n  return {\n    link: function(scope, element, attr) {\n      var numberExp = attr.count,\n          whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs\n          offset = attr.offset || 0,\n          whens = scope.$eval(whenExp) || {},\n          whensExpFns = {},\n          startSymbol = $interpolate.startSymbol(),\n          endSymbol = $interpolate.endSymbol(),\n          braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,\n          watchRemover = angular.noop,\n          lastCount;\n\n      forEach(attr, function(expression, attributeName) {\n        var tmpMatch = IS_WHEN.exec(attributeName);\n        if (tmpMatch) {\n          var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);\n          whens[whenKey] = element.attr(attr.$attr[attributeName]);\n        }\n      });\n      forEach(whens, function(expression, key) {\n        whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));\n\n      });\n\n      scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {\n        var count = parseFloat(newVal);\n        var countIsNaN = isNaN(count);\n\n        if (!countIsNaN && !(count in whens)) {\n          // If an explicit number rule such as 1, 2, 3... is defined, just use it.\n          // Otherwise, check it against pluralization rules in $locale service.\n          count = $locale.pluralCat(count - offset);\n        }\n\n        // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.\n        // In JS `NaN !== NaN`, so we have to exlicitly check.\n        if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {\n          watchRemover();\n          var whenExpFn = whensExpFns[count];\n          if (isUndefined(whenExpFn)) {\n            if (newVal != null) {\n              $log.debug(\"ngPluralize: no rule defined for '\" + count + \"' in \" + whenExp);\n            }\n            watchRemover = noop;\n            updateElementText();\n          } else {\n            watchRemover = scope.$watch(whenExpFn, updateElementText);\n          }\n          lastCount = count;\n        }\n      });\n\n      function updateElementText(newText) {\n        element.text(newText || '');\n      }\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngRepeat\n * @multiElement\n *\n * @description\n * The `ngRepeat` directive instantiates a template once per item from a collection. Each template\n * instance gets its own scope, where the given loop variable is set to the current collection item,\n * and `$index` is set to the item index or key.\n *\n * Special properties are exposed on the local scope of each template instance, including:\n *\n * | Variable  | Type            | Details                                                                     |\n * |-----------|-----------------|-----------------------------------------------------------------------------|\n * | `$index`  | {@type number}  | iterator offset of the repeated element (0..length-1)                       |\n * | `$first`  | {@type boolean} | true if the repeated element is first in the iterator.                      |\n * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |\n * | `$last`   | {@type boolean} | true if the repeated element is last in the iterator.                       |\n * | `$even`   | {@type boolean} | true if the iterator position `$index` is even (otherwise false).           |\n * | `$odd`    | {@type boolean} | true if the iterator position `$index` is odd (otherwise false).            |\n *\n * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.\n * This may be useful when, for instance, nesting ngRepeats.\n *\n *\n * # Iterating over object properties\n *\n * It is possible to get `ngRepeat` to iterate over the properties of an object using the following\n * syntax:\n *\n * ```js\n * <div ng-repeat=\"(key, value) in myObj\"> ... </div>\n * ```\n *\n * You need to be aware that the JavaScript specification does not define the order of keys\n * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive\n * used to sort the keys alphabetically.)\n *\n * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser\n * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing\n * keys in the order in which they were defined, although there are exceptions when keys are deleted\n * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues\n *\n * If this is not desired, the recommended workaround is to convert your object into an array\n * that is sorted into the order that you prefer before providing it to `ngRepeat`.  You could\n * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)\n * or implement a `$watch` on the object yourself.\n *\n *\n * # Tracking and Duplicates\n *\n * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:\n *\n * * When an item is added, a new instance of the template is added to the DOM.\n * * When an item is removed, its template instance is removed from the DOM.\n * * When items are reordered, their respective templates are reordered in the DOM.\n *\n * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when\n * there are duplicates, it is not possible to maintain a one-to-one mapping between collection\n * items and DOM elements.\n *\n * If you do need to repeat duplicate items, you can substitute the default tracking behavior\n * with your own using the `track by` expression.\n *\n * For example, you may track items by the index of each item in the collection, using the\n * special scope property `$index`:\n * ```html\n *    <div ng-repeat=\"n in [42, 42, 43, 43] track by $index\">\n *      {{n}}\n *    </div>\n * ```\n *\n * You may use arbitrary expressions in `track by`, including references to custom functions\n * on the scope:\n * ```html\n *    <div ng-repeat=\"n in [42, 42, 43, 43] track by myTrackingFunction(n)\">\n *      {{n}}\n *    </div>\n * ```\n *\n * If you are working with objects that have an identifier property, you can track\n * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`\n * will not have to rebuild the DOM elements for items it has already rendered, even if the\n * JavaScript objects in the collection have been substituted for new ones:\n * ```html\n *    <div ng-repeat=\"model in collection track by model.id\">\n *      {{model.name}}\n *    </div>\n * ```\n *\n * When no `track by` expression is provided, it is equivalent to tracking by the built-in\n * `$id` function, which tracks items by their identity:\n * ```html\n *    <div ng-repeat=\"obj in collection track by $id(obj)\">\n *      {{obj.prop}}\n *    </div>\n * ```\n *\n * <div class=\"alert alert-warning\">\n * **Note:** `track by` must always be the last expression:\n * </div>\n * ```\n * <div ng-repeat=\"model in collection | orderBy: 'id' as filtered_result track by model.id\">\n *     {{model.name}}\n * </div>\n * ```\n *\n * # Special repeat start and end points\n * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending\n * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.\n * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)\n * up to and including the ending HTML tag where **ng-repeat-end** is placed.\n *\n * The example below makes use of this feature:\n * ```html\n *   <header ng-repeat-start=\"item in items\">\n *     Header {{ item }}\n *   </header>\n *   <div class=\"body\">\n *     Body {{ item }}\n *   </div>\n *   <footer ng-repeat-end>\n *     Footer {{ item }}\n *   </footer>\n * ```\n *\n * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:\n * ```html\n *   <header>\n *     Header A\n *   </header>\n *   <div class=\"body\">\n *     Body A\n *   </div>\n *   <footer>\n *     Footer A\n *   </footer>\n *   <header>\n *     Header B\n *   </header>\n *   <div class=\"body\">\n *     Body B\n *   </div>\n *   <footer>\n *     Footer B\n *   </footer>\n * ```\n *\n * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such\n * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).\n *\n * @animations\n * **.enter** - when a new item is added to the list or when an item is revealed after a filter\n *\n * **.leave** - when an item is removed from the list or when an item is filtered out\n *\n * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered\n *\n * @element ANY\n * @scope\n * @priority 1000\n * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These\n *   formats are currently supported:\n *\n *   * `variable in expression` – where variable is the user defined loop variable and `expression`\n *     is a scope expression giving the collection to enumerate.\n *\n *     For example: `album in artist.albums`.\n *\n *   * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,\n *     and `expression` is the scope expression giving the collection to enumerate.\n *\n *     For example: `(name, age) in {'adam':10, 'amalie':12}`.\n *\n *   * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression\n *     which can be used to associate the objects in the collection with the DOM elements. If no tracking expression\n *     is specified, ng-repeat associates elements by identity. It is an error to have\n *     more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are\n *     mapped to the same DOM element, which is not possible.)\n *\n *     Note that the tracking expression must come last, after any filters, and the alias expression.\n *\n *     For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements\n *     will be associated by item identity in the array.\n *\n *     For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique\n *     `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements\n *     with the corresponding item in the array by identity. Moving the same object in array would move the DOM\n *     element in the same way in the DOM.\n *\n *     For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this\n *     case the object identity does not matter. Two objects are considered equivalent as long as their `id`\n *     property is same.\n *\n *     For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter\n *     to items in conjunction with a tracking expression.\n *\n *   * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the\n *     intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message\n *     when a filter is active on the repeater, but the filtered result set is empty.\n *\n *     For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after\n *     the items have been processed through the filter.\n *\n *     Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end\n *     (and not as operator, inside an expression).\n *\n *     For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .\n *\n * @example\n * This example initializes the scope to a list of names and\n * then uses `ngRepeat` to display every person:\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-init=\"friends = [\n        {name:'John', age:25, gender:'boy'},\n        {name:'Jessie', age:30, gender:'girl'},\n        {name:'Johanna', age:28, gender:'girl'},\n        {name:'Joy', age:15, gender:'girl'},\n        {name:'Mary', age:28, gender:'girl'},\n        {name:'Peter', age:95, gender:'boy'},\n        {name:'Sebastian', age:50, gender:'boy'},\n        {name:'Erika', age:27, gender:'girl'},\n        {name:'Patrick', age:40, gender:'boy'},\n        {name:'Samantha', age:60, gender:'girl'}\n      ]\">\n        I have {{friends.length}} friends. They are:\n        <input type=\"search\" ng-model=\"q\" placeholder=\"filter friends...\" aria-label=\"filter friends\" />\n        <ul class=\"example-animate-container\">\n          <li class=\"animate-repeat\" ng-repeat=\"friend in friends | filter:q as results\">\n            [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.\n          </li>\n          <li class=\"animate-repeat\" ng-if=\"results.length == 0\">\n            <strong>No results found...</strong>\n          </li>\n        </ul>\n      </div>\n    </file>\n    <file name=\"animations.css\">\n      .example-animate-container {\n        background:white;\n        border:1px solid black;\n        list-style:none;\n        margin:0;\n        padding:0 10px;\n      }\n\n      .animate-repeat {\n        line-height:40px;\n        list-style:none;\n        box-sizing:border-box;\n      }\n\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter,\n      .animate-repeat.ng-leave {\n        -webkit-transition:all linear 0.5s;\n        transition:all linear 0.5s;\n      }\n\n      .animate-repeat.ng-leave.ng-leave-active,\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter {\n        opacity:0;\n        max-height:0;\n      }\n\n      .animate-repeat.ng-leave,\n      .animate-repeat.ng-move.ng-move-active,\n      .animate-repeat.ng-enter.ng-enter-active {\n        opacity:1;\n        max-height:40px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var friends = element.all(by.repeater('friend in friends'));\n\n      it('should render initial data set', function() {\n        expect(friends.count()).toBe(10);\n        expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');\n        expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');\n        expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');\n        expect(element(by.binding('friends.length')).getText())\n            .toMatch(\"I have 10 friends. They are:\");\n      });\n\n       it('should update repeater when filter predicate changes', function() {\n         expect(friends.count()).toBe(10);\n\n         element(by.model('q')).sendKeys('ma');\n\n         expect(friends.count()).toBe(2);\n         expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');\n         expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');\n       });\n      </file>\n    </example>\n */\nvar ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {\n  var NG_REMOVED = '$$NG_REMOVED';\n  var ngRepeatMinErr = minErr('ngRepeat');\n\n  var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {\n    // TODO(perf): generate setters to shave off ~40ms or 1-1.5%\n    scope[valueIdentifier] = value;\n    if (keyIdentifier) scope[keyIdentifier] = key;\n    scope.$index = index;\n    scope.$first = (index === 0);\n    scope.$last = (index === (arrayLength - 1));\n    scope.$middle = !(scope.$first || scope.$last);\n    // jshint bitwise: false\n    scope.$odd = !(scope.$even = (index&1) === 0);\n    // jshint bitwise: true\n  };\n\n  var getBlockStart = function(block) {\n    return block.clone[0];\n  };\n\n  var getBlockEnd = function(block) {\n    return block.clone[block.clone.length - 1];\n  };\n\n\n  return {\n    restrict: 'A',\n    multiElement: true,\n    transclude: 'element',\n    priority: 1000,\n    terminal: true,\n    $$tlb: true,\n    compile: function ngRepeatCompile($element, $attr) {\n      var expression = $attr.ngRepeat;\n      var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');\n\n      var match = expression.match(/^\\s*([\\s\\S]+?)\\s+in\\s+([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+track\\s+by\\s+([\\s\\S]+?))?\\s*$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iexp', \"Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.\",\n            expression);\n      }\n\n      var lhs = match[1];\n      var rhs = match[2];\n      var aliasAs = match[3];\n      var trackByExp = match[4];\n\n      match = lhs.match(/^(?:(\\s*[\\$\\w]+)|\\(\\s*([\\$\\w]+)\\s*,\\s*([\\$\\w]+)\\s*\\))$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iidexp', \"'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.\",\n            lhs);\n      }\n      var valueIdentifier = match[3] || match[1];\n      var keyIdentifier = match[2];\n\n      if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||\n          /^(null|undefined|this|\\$index|\\$first|\\$middle|\\$last|\\$even|\\$odd|\\$parent|\\$root|\\$id)$/.test(aliasAs))) {\n        throw ngRepeatMinErr('badident', \"alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.\",\n          aliasAs);\n      }\n\n      var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;\n      var hashFnLocals = {$id: hashKey};\n\n      if (trackByExp) {\n        trackByExpGetter = $parse(trackByExp);\n      } else {\n        trackByIdArrayFn = function(key, value) {\n          return hashKey(value);\n        };\n        trackByIdObjFn = function(key) {\n          return key;\n        };\n      }\n\n      return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {\n\n        if (trackByExpGetter) {\n          trackByIdExpFn = function(key, value, index) {\n            // assign key, value, and $index to the locals so that they can be used in hash functions\n            if (keyIdentifier) hashFnLocals[keyIdentifier] = key;\n            hashFnLocals[valueIdentifier] = value;\n            hashFnLocals.$index = index;\n            return trackByExpGetter($scope, hashFnLocals);\n          };\n        }\n\n        // Store a list of elements from previous run. This is a hash where key is the item from the\n        // iterator, and the value is objects with following properties.\n        //   - scope: bound scope\n        //   - element: previous element.\n        //   - index: position\n        //\n        // We are using no-proto object so that we don't need to guard against inherited props via\n        // hasOwnProperty.\n        var lastBlockMap = createMap();\n\n        //watch props\n        $scope.$watchCollection(rhs, function ngRepeatAction(collection) {\n          var index, length,\n              previousNode = $element[0],     // node that cloned nodes should be inserted after\n                                              // initialized to the comment node anchor\n              nextNode,\n              // Same as lastBlockMap but it has the current state. It will become the\n              // lastBlockMap on the next iteration.\n              nextBlockMap = createMap(),\n              collectionLength,\n              key, value, // key/value of iteration\n              trackById,\n              trackByIdFn,\n              collectionKeys,\n              block,       // last object information {scope, element, id}\n              nextBlockOrder,\n              elementsToRemove;\n\n          if (aliasAs) {\n            $scope[aliasAs] = collection;\n          }\n\n          if (isArrayLike(collection)) {\n            collectionKeys = collection;\n            trackByIdFn = trackByIdExpFn || trackByIdArrayFn;\n          } else {\n            trackByIdFn = trackByIdExpFn || trackByIdObjFn;\n            // if object, extract keys, in enumeration order, unsorted\n            collectionKeys = [];\n            for (var itemKey in collection) {\n              if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {\n                collectionKeys.push(itemKey);\n              }\n            }\n          }\n\n          collectionLength = collectionKeys.length;\n          nextBlockOrder = new Array(collectionLength);\n\n          // locate existing items\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            trackById = trackByIdFn(key, value, index);\n            if (lastBlockMap[trackById]) {\n              // found previously seen block\n              block = lastBlockMap[trackById];\n              delete lastBlockMap[trackById];\n              nextBlockMap[trackById] = block;\n              nextBlockOrder[index] = block;\n            } else if (nextBlockMap[trackById]) {\n              // if collision detected. restore lastBlockMap and throw an error\n              forEach(nextBlockOrder, function(block) {\n                if (block && block.scope) lastBlockMap[block.id] = block;\n              });\n              throw ngRepeatMinErr('dupes',\n                  \"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}\",\n                  expression, trackById, value);\n            } else {\n              // new never before seen block\n              nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};\n              nextBlockMap[trackById] = true;\n            }\n          }\n\n          // remove leftover items\n          for (var blockKey in lastBlockMap) {\n            block = lastBlockMap[blockKey];\n            elementsToRemove = getBlockNodes(block.clone);\n            $animate.leave(elementsToRemove);\n            if (elementsToRemove[0].parentNode) {\n              // if the element was not removed yet because of pending animation, mark it as deleted\n              // so that we can ignore it later\n              for (index = 0, length = elementsToRemove.length; index < length; index++) {\n                elementsToRemove[index][NG_REMOVED] = true;\n              }\n            }\n            block.scope.$destroy();\n          }\n\n          // we are not using forEach for perf reasons (trying to avoid #call)\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            block = nextBlockOrder[index];\n\n            if (block.scope) {\n              // if we have already seen this object, then we need to reuse the\n              // associated scope/element\n\n              nextNode = previousNode;\n\n              // skip nodes that are already pending removal via leave animation\n              do {\n                nextNode = nextNode.nextSibling;\n              } while (nextNode && nextNode[NG_REMOVED]);\n\n              if (getBlockStart(block) != nextNode) {\n                // existing item which got moved\n                $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));\n              }\n              previousNode = getBlockEnd(block);\n              updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n            } else {\n              // new item which we don't know about\n              $transclude(function ngRepeatTransclude(clone, scope) {\n                block.scope = scope;\n                // http://jsperf.com/clone-vs-createcomment\n                var endNode = ngRepeatEndComment.cloneNode(false);\n                clone[clone.length++] = endNode;\n\n                // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?\n                $animate.enter(clone, null, jqLite(previousNode));\n                previousNode = endNode;\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block.clone = clone;\n                nextBlockMap[block.id] = block;\n                updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n              });\n            }\n          }\n          lastBlockMap = nextBlockMap;\n        });\n      };\n    }\n  };\n}];\n\nvar NG_HIDE_CLASS = 'ng-hide';\nvar NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';\n/**\n * @ngdoc directive\n * @name ngShow\n * @multiElement\n *\n * @description\n * The `ngShow` directive shows or hides the given HTML element based on the expression\n * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding\n * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is visible) -->\n * <div ng-show=\"myValue\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is hidden) -->\n * <div ng-show=\"myValue\" class=\"ng-hide\"></div>\n * ```\n *\n * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope\n * with extra animation classes that can be added.\n *\n * ```css\n * .ng-hide:not(.ng-hide-animate) {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngShow`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass except that\n * you must also include the !important flag to override the display property\n * so that you can perform an animation when the element is hidden during the time of the animation.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   /&#42; this is required as of 1.3x to properly\n *      apply all styling in a show/hide animation &#42;/\n *   transition: 0s linear all;\n * }\n *\n * .my-element.ng-hide-add-active,\n * .my-element.ng-hide-remove-active {\n *   /&#42; the transition is defined in the active class &#42;/\n *   transition: 1s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible\n * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden\n *\n * @element ANY\n * @param {expression} ngShow If the {@link guide/expression expression} is truthy\n *     then the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\" aria-label=\"Toggle ngHide\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-show\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-show\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-show {\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-show.ng-hide-add.ng-hide-add-active,\n      .animate-show.ng-hide-remove.ng-hide-remove-active {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n      }\n\n      .animate-show.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngShowDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngShow, function ngShowWatchAction(value) {\n        // we're adding a temporary, animation-specific class for ng-hide since this way\n        // we can control when the element is actually displayed on screen without having\n        // to have a global/greedy CSS selector that breaks when other animations are run.\n        // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845\n        $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngHide\n * @multiElement\n *\n * @description\n * The `ngHide` directive shows or hides the given HTML element based on the expression\n * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding\n * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is hidden) -->\n * <div ng-hide=\"myValue\" class=\"ng-hide\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is visible) -->\n * <div ng-hide=\"myValue\"></div>\n * ```\n *\n * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class in CSS:\n *\n * ```css\n * .ng-hide {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngHide`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`\n * CSS class is added and removed for you instead of your own CSS class.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   transition: 0.5s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden\n * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible\n *\n * @element ANY\n * @param {expression} ngHide If the {@link guide/expression expression} is truthy then\n *     the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\" aria-label=\"Toggle ngShow\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-hide\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-hide\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-hide {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-hide.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngHideDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngHide, function ngHideWatchAction(value) {\n        // The comment inside of the ngShowDirective explains why we add and\n        // remove a temporary class for the show/hide animation\n        $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngStyle\n * @restrict AC\n *\n * @description\n * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.\n *\n * @element ANY\n * @param {expression} ngStyle\n *\n * {@link guide/expression Expression} which evals to an\n * object whose keys are CSS style names and values are corresponding values for those CSS\n * keys.\n *\n * Since some CSS style names are not valid keys for an object, they must be quoted.\n * See the 'background-color' style in the example below.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <input type=\"button\" value=\"set color\" ng-click=\"myStyle={color:'red'}\">\n        <input type=\"button\" value=\"set background\" ng-click=\"myStyle={'background-color':'blue'}\">\n        <input type=\"button\" value=\"clear\" ng-click=\"myStyle={}\">\n        <br/>\n        <span ng-style=\"myStyle\">Sample Text</span>\n        <pre>myStyle={{myStyle}}</pre>\n     </file>\n     <file name=\"style.css\">\n       span {\n         color: black;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var colorSpan = element(by.css('span'));\n\n       it('should check ng-style', function() {\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n         element(by.css('input[value=\\'set color\\']')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');\n         element(by.css('input[value=clear]')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n       });\n     </file>\n   </example>\n */\nvar ngStyleDirective = ngDirective(function(scope, element, attr) {\n  scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {\n    if (oldStyles && (newStyles !== oldStyles)) {\n      forEach(oldStyles, function(val, style) { element.css(style, '');});\n    }\n    if (newStyles) element.css(newStyles);\n  }, true);\n});\n\n/**\n * @ngdoc directive\n * @name ngSwitch\n * @restrict EA\n *\n * @description\n * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.\n * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location\n * as specified in the template.\n *\n * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it\n * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element\n * matches the value obtained from the evaluated expression. In other words, you define a container element\n * (where you place the directive), place an expression on the **`on=\"...\"` attribute**\n * (or the **`ng-switch=\"...\"` attribute**), define any inner elements inside of the directive and place\n * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on\n * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default\n * attribute is displayed.\n *\n * <div class=\"alert alert-info\">\n * Be aware that the attribute values to match against cannot be expressions. They are interpreted\n * as literal string values to match against.\n * For example, **`ng-switch-when=\"someVal\"`** will match against the string `\"someVal\"` not against the\n * value of the expression `$scope.someVal`.\n * </div>\n\n * @animations\n * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container\n * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM\n *\n * @usage\n *\n * ```\n * <ANY ng-switch=\"expression\">\n *   <ANY ng-switch-when=\"matchValue1\">...</ANY>\n *   <ANY ng-switch-when=\"matchValue2\">...</ANY>\n *   <ANY ng-switch-default>...</ANY>\n * </ANY>\n * ```\n *\n *\n * @scope\n * @priority 1200\n * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.\n * On child elements add:\n *\n * * `ngSwitchWhen`: the case statement to match against. If match then this\n *   case will be displayed. If the same match appears multiple times, all the\n *   elements will be displayed.\n * * `ngSwitchDefault`: the default case when no other case match. If there\n *   are multiple default cases, all of them will be displayed when no other\n *   case match.\n *\n *\n * @example\n  <example module=\"switchExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <select ng-model=\"selection\" ng-options=\"item for item in items\">\n        </select>\n        <code>selection={{selection}}</code>\n        <hr/>\n        <div class=\"animate-switch-container\"\n          ng-switch on=\"selection\">\n            <div class=\"animate-switch\" ng-switch-when=\"settings\">Settings Div</div>\n            <div class=\"animate-switch\" ng-switch-when=\"home\">Home Span</div>\n            <div class=\"animate-switch\" ng-switch-default>default</div>\n        </div>\n      </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('switchExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.items = ['settings', 'home', 'other'];\n          $scope.selection = $scope.items[0];\n        }]);\n    </file>\n    <file name=\"animations.css\">\n      .animate-switch-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .animate-switch {\n        padding:10px;\n      }\n\n      .animate-switch.ng-animate {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n      }\n\n      .animate-switch.ng-leave.ng-leave-active,\n      .animate-switch.ng-enter {\n        top:-50px;\n      }\n      .animate-switch.ng-leave,\n      .animate-switch.ng-enter.ng-enter-active {\n        top:0;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var switchElem = element(by.css('[ng-switch]'));\n      var select = element(by.model('selection'));\n\n      it('should start in settings', function() {\n        expect(switchElem.getText()).toMatch(/Settings Div/);\n      });\n      it('should change to home', function() {\n        select.all(by.css('option')).get(1).click();\n        expect(switchElem.getText()).toMatch(/Home Span/);\n      });\n      it('should select default', function() {\n        select.all(by.css('option')).get(2).click();\n        expect(switchElem.getText()).toMatch(/default/);\n      });\n    </file>\n  </example>\n */\nvar ngSwitchDirective = ['$animate', function($animate) {\n  return {\n    require: 'ngSwitch',\n\n    // asks for $scope to fool the BC controller module\n    controller: ['$scope', function ngSwitchController() {\n     this.cases = {};\n    }],\n    link: function(scope, element, attr, ngSwitchController) {\n      var watchExpr = attr.ngSwitch || attr.on,\n          selectedTranscludes = [],\n          selectedElements = [],\n          previousLeaveAnimations = [],\n          selectedScopes = [];\n\n      var spliceFactory = function(array, index) {\n          return function() { array.splice(index, 1); };\n      };\n\n      scope.$watch(watchExpr, function ngSwitchWatchAction(value) {\n        var i, ii;\n        for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {\n          $animate.cancel(previousLeaveAnimations[i]);\n        }\n        previousLeaveAnimations.length = 0;\n\n        for (i = 0, ii = selectedScopes.length; i < ii; ++i) {\n          var selected = getBlockNodes(selectedElements[i].clone);\n          selectedScopes[i].$destroy();\n          var promise = previousLeaveAnimations[i] = $animate.leave(selected);\n          promise.then(spliceFactory(previousLeaveAnimations, i));\n        }\n\n        selectedElements.length = 0;\n        selectedScopes.length = 0;\n\n        if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {\n          forEach(selectedTranscludes, function(selectedTransclude) {\n            selectedTransclude.transclude(function(caseElement, selectedScope) {\n              selectedScopes.push(selectedScope);\n              var anchor = selectedTransclude.element;\n              caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');\n              var block = { clone: caseElement };\n\n              selectedElements.push(block);\n              $animate.enter(caseElement, anchor.parent(), anchor);\n            });\n          });\n        }\n      });\n    }\n  };\n}];\n\nvar ngSwitchWhenDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attrs, ctrl, $transclude) {\n    ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);\n    ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });\n  }\n});\n\nvar ngSwitchDefaultDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attr, ctrl, $transclude) {\n    ctrl.cases['?'] = (ctrl.cases['?'] || []);\n    ctrl.cases['?'].push({ transclude: $transclude, element: element });\n   }\n});\n\n/**\n * @ngdoc directive\n * @name ngTransclude\n * @restrict EAC\n *\n * @description\n * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.\n *\n * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.\n *\n * @element ANY\n *\n * @example\n   <example module=\"transcludeExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('transcludeExample', [])\n          .directive('pane', function(){\n             return {\n               restrict: 'E',\n               transclude: true,\n               scope: { title:'@' },\n               template: '<div style=\"border: 1px solid black;\">' +\n                           '<div style=\"background-color: gray\">{{title}}</div>' +\n                           '<ng-transclude></ng-transclude>' +\n                         '</div>'\n             };\n         })\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.title = 'Lorem Ipsum';\n           $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';\n         }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input ng-model=\"title\" aria-label=\"title\"> <br/>\n         <textarea ng-model=\"text\" aria-label=\"text\"></textarea> <br/>\n         <pane title=\"{{title}}\">{{text}}</pane>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        it('should have transcluded', function() {\n          var titleElement = element(by.model('title'));\n          titleElement.clear();\n          titleElement.sendKeys('TITLE');\n          var textElement = element(by.model('text'));\n          textElement.clear();\n          textElement.sendKeys('TEXT');\n          expect(element(by.binding('title')).getText()).toEqual('TITLE');\n          expect(element(by.binding('text')).getText()).toEqual('TEXT');\n        });\n     </file>\n   </example>\n *\n */\nvar ngTranscludeDirective = ngDirective({\n  restrict: 'EAC',\n  link: function($scope, $element, $attrs, controller, $transclude) {\n    if (!$transclude) {\n      throw minErr('ngTransclude')('orphan',\n       'Illegal use of ngTransclude directive in the template! ' +\n       'No parent directive that requires a transclusion found. ' +\n       'Element: {0}',\n       startingTag($element));\n    }\n\n    $transclude(function(clone) {\n      $element.empty();\n      $element.append(clone);\n    });\n  }\n});\n\n/**\n * @ngdoc directive\n * @name script\n * @restrict E\n *\n * @description\n * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the\n * template can be used by {@link ng.directive:ngInclude `ngInclude`},\n * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the\n * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be\n * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.\n *\n * @param {string} type Must be set to `'text/ng-template'`.\n * @param {string} id Cache name of the template.\n *\n * @example\n  <example>\n    <file name=\"index.html\">\n      <script type=\"text/ng-template\" id=\"/tpl.html\">\n        Content of the template.\n      </script>\n\n      <a ng-click=\"currentTpl='/tpl.html'\" id=\"tpl-link\">Load inlined template</a>\n      <div id=\"tpl-content\" ng-include src=\"currentTpl\"></div>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      it('should load template defined inside script tag', function() {\n        element(by.css('#tpl-link')).click();\n        expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);\n      });\n    </file>\n  </example>\n */\nvar scriptDirective = ['$templateCache', function($templateCache) {\n  return {\n    restrict: 'E',\n    terminal: true,\n    compile: function(element, attr) {\n      if (attr.type == 'text/ng-template') {\n        var templateUrl = attr.id,\n            text = element[0].text;\n\n        $templateCache.put(templateUrl, text);\n      }\n    }\n  };\n}];\n\nvar noopNgModelController = { $setViewValue: noop, $render: noop };\n\n/**\n * @ngdoc type\n * @name  select.SelectController\n * @description\n * The controller for the `<select>` directive. This provides support for reading\n * and writing the selected value(s) of the control and also coordinates dynamically\n * added `<option>` elements, perhaps by an `ngRepeat` directive.\n */\nvar SelectController =\n        ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {\n\n  var self = this,\n      optionsMap = new HashMap();\n\n  // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors\n  self.ngModelCtrl = noopNgModelController;\n\n  // The \"unknown\" option is one that is prepended to the list if the viewValue\n  // does not match any of the options. When it is rendered the value of the unknown\n  // option is '? XXX ?' where XXX is the hashKey of the value that is not known.\n  //\n  // We can't just jqLite('<option>') since jqLite is not smart enough\n  // to create it in <select> and IE barfs otherwise.\n  self.unknownOption = jqLite(document.createElement('option'));\n  self.renderUnknownOption = function(val) {\n    var unknownVal = '? ' + hashKey(val) + ' ?';\n    self.unknownOption.val(unknownVal);\n    $element.prepend(self.unknownOption);\n    $element.val(unknownVal);\n  };\n\n  $scope.$on('$destroy', function() {\n    // disable unknown option so that we don't do work when the whole select is being destroyed\n    self.renderUnknownOption = noop;\n  });\n\n  self.removeUnknownOption = function() {\n    if (self.unknownOption.parent()) self.unknownOption.remove();\n  };\n\n\n  // Read the value of the select control, the implementation of this changes depending\n  // upon whether the select can have multiple values and whether ngOptions is at work.\n  self.readValue = function readSingleValue() {\n    self.removeUnknownOption();\n    return $element.val();\n  };\n\n\n  // Write the value to the select control, the implementation of this changes depending\n  // upon whether the select can have multiple values and whether ngOptions is at work.\n  self.writeValue = function writeSingleValue(value) {\n    if (self.hasOption(value)) {\n      self.removeUnknownOption();\n      $element.val(value);\n      if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy\n    } else {\n      if (value == null && self.emptyOption) {\n        self.removeUnknownOption();\n        $element.val('');\n      } else {\n        self.renderUnknownOption(value);\n      }\n    }\n  };\n\n\n  // Tell the select control that an option, with the given value, has been added\n  self.addOption = function(value, element) {\n    assertNotHasOwnProperty(value, '\"option value\"');\n    if (value === '') {\n      self.emptyOption = element;\n    }\n    var count = optionsMap.get(value) || 0;\n    optionsMap.put(value, count + 1);\n  };\n\n  // Tell the select control that an option, with the given value, has been removed\n  self.removeOption = function(value) {\n    var count = optionsMap.get(value);\n    if (count) {\n      if (count === 1) {\n        optionsMap.remove(value);\n        if (value === '') {\n          self.emptyOption = undefined;\n        }\n      } else {\n        optionsMap.put(value, count - 1);\n      }\n    }\n  };\n\n  // Check whether the select control has an option matching the given value\n  self.hasOption = function(value) {\n    return !!optionsMap.get(value);\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name select\n * @restrict E\n *\n * @description\n * HTML `SELECT` element with angular data-binding.\n *\n * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions\n * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing\n * memory and increasing speed by not creating a new scope for each repeated instance, as well as providing\n * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the\n * comprehension expression.\n *\n * When an item in the `<select>` menu is selected, the array element or object property\n * represented by the selected option will be bound to the model identified by the `ngModel`\n * directive.\n *\n * If the viewValue contains a value that doesn't match any of the options then the control\n * will automatically add an \"unknown\" option, which it then removes when this is resolved.\n *\n * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can\n * be nested into the `<select>` element. This element will then represent the `null` or \"not selected\"\n * option. See example below for demonstration.\n *\n * <div class=\"alert alert-info\">\n * The value of a `select` directive used without `ngOptions` is always a string.\n * When the model needs to be bound to a non-string value, you must either explictly convert it\n * using a directive (see example below) or use `ngOptions` to specify the set of options.\n * This is because an option element can only be bound to string values at present.\n * </div>\n *\n * ### Example (binding `select` to a non-string value)\n *\n * <example name=\"select-with-non-string-options\" module=\"nonStringSelect\">\n *   <file name=\"index.html\">\n *     <select ng-model=\"model.id\" convert-to-number>\n *       <option value=\"0\">Zero</option>\n *       <option value=\"1\">One</option>\n *       <option value=\"2\">Two</option>\n *     </select>\n *     {{ model }}\n *   </file>\n *   <file name=\"app.js\">\n *     angular.module('nonStringSelect', [])\n *       .run(function($rootScope) {\n *         $rootScope.model = { id: 2 };\n *       })\n *       .directive('convertToNumber', function() {\n *         return {\n *           require: 'ngModel',\n *           link: function(scope, element, attrs, ngModel) {\n *             ngModel.$parsers.push(function(val) {\n *               return parseInt(val, 10);\n *             });\n *             ngModel.$formatters.push(function(val) {\n *               return '' + val;\n *             });\n *           }\n *         };\n *       });\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it('should initialize to model', function() {\n *       var select = element(by.css('select'));\n *       expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');\n *     });\n *   </file>\n * </example>\n *\n */\nvar selectDirective = function() {\n\n  return {\n    restrict: 'E',\n    require: ['select', '?ngModel'],\n    controller: SelectController,\n    link: function(scope, element, attr, ctrls) {\n\n      // if ngModel is not defined, we don't need to do anything\n      var ngModelCtrl = ctrls[1];\n      if (!ngModelCtrl) return;\n\n      var selectCtrl = ctrls[0];\n\n      selectCtrl.ngModelCtrl = ngModelCtrl;\n\n      // We delegate rendering to the `writeValue` method, which can be changed\n      // if the select can have multiple selected values or if the options are being\n      // generated by `ngOptions`\n      ngModelCtrl.$render = function() {\n        selectCtrl.writeValue(ngModelCtrl.$viewValue);\n      };\n\n      // When the selected item(s) changes we delegate getting the value of the select control\n      // to the `readValue` method, which can be changed if the select can have multiple\n      // selected values or if the options are being generated by `ngOptions`\n      element.on('change', function() {\n        scope.$apply(function() {\n          ngModelCtrl.$setViewValue(selectCtrl.readValue());\n        });\n      });\n\n      // If the select allows multiple values then we need to modify how we read and write\n      // values from and to the control; also what it means for the value to be empty and\n      // we have to add an extra watch since ngModel doesn't work well with arrays - it\n      // doesn't trigger rendering if only an item in the array changes.\n      if (attr.multiple) {\n\n        // Read value now needs to check each option to see if it is selected\n        selectCtrl.readValue = function readMultipleValue() {\n          var array = [];\n          forEach(element.find('option'), function(option) {\n            if (option.selected) {\n              array.push(option.value);\n            }\n          });\n          return array;\n        };\n\n        // Write value now needs to set the selected property of each matching option\n        selectCtrl.writeValue = function writeMultipleValue(value) {\n          var items = new HashMap(value);\n          forEach(element.find('option'), function(option) {\n            option.selected = isDefined(items.get(option.value));\n          });\n        };\n\n        // we have to do it on each watch since ngModel watches reference, but\n        // we need to work of an array, so we need to see if anything was inserted/removed\n        var lastView, lastViewRef = NaN;\n        scope.$watch(function selectMultipleWatch() {\n          if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {\n            lastView = shallowCopy(ngModelCtrl.$viewValue);\n            ngModelCtrl.$render();\n          }\n          lastViewRef = ngModelCtrl.$viewValue;\n        });\n\n        // If we are a multiple select then value is now a collection\n        // so the meaning of $isEmpty changes\n        ngModelCtrl.$isEmpty = function(value) {\n          return !value || value.length === 0;\n        };\n\n      }\n    }\n  };\n};\n\n\n// The option directive is purely designed to communicate the existence (or lack of)\n// of dynamically created (and destroyed) option elements to their containing select\n// directive via its controller.\nvar optionDirective = ['$interpolate', function($interpolate) {\n\n  function chromeHack(optionElement) {\n    // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459\n    // Adding an <option selected=\"selected\"> element to a <select required=\"required\"> should\n    // automatically select the new element\n    if (optionElement[0].hasAttribute('selected')) {\n      optionElement[0].selected = true;\n    }\n  }\n\n  return {\n    restrict: 'E',\n    priority: 100,\n    compile: function(element, attr) {\n\n      // If the value attribute is not defined then we fall back to the\n      // text content of the option element, which may be interpolated\n      if (isUndefined(attr.value)) {\n        var interpolateFn = $interpolate(element.text(), true);\n        if (!interpolateFn) {\n          attr.$set('value', element.text());\n        }\n      }\n\n      return function(scope, element, attr) {\n\n        // This is an optimization over using ^^ since we don't want to have to search\n        // all the way to the root of the DOM for every single option element\n        var selectCtrlName = '$selectController',\n            parent = element.parent(),\n            selectCtrl = parent.data(selectCtrlName) ||\n              parent.parent().data(selectCtrlName); // in case we are in optgroup\n\n        // Only update trigger option updates if this is an option within a `select`\n        // that also has `ngModel` attached\n        if (selectCtrl && selectCtrl.ngModelCtrl) {\n\n          if (interpolateFn) {\n            scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {\n              attr.$set('value', newVal);\n              if (oldVal !== newVal) {\n                selectCtrl.removeOption(oldVal);\n              }\n              selectCtrl.addOption(newVal, element);\n              selectCtrl.ngModelCtrl.$render();\n              chromeHack(element);\n            });\n          } else {\n            selectCtrl.addOption(attr.value, element);\n            selectCtrl.ngModelCtrl.$render();\n            chromeHack(element);\n          }\n\n          element.on('$destroy', function() {\n            selectCtrl.removeOption(attr.value);\n            selectCtrl.ngModelCtrl.$render();\n          });\n        }\n      };\n    }\n  };\n}];\n\nvar styleDirective = valueFn({\n  restrict: 'E',\n  terminal: false\n});\n\nvar requiredDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n      attr.required = true; // force truthy in case we are on non input element\n\n      ctrl.$validators.required = function(modelValue, viewValue) {\n        return !attr.required || !ctrl.$isEmpty(viewValue);\n      };\n\n      attr.$observe('required', function() {\n        ctrl.$validate();\n      });\n    }\n  };\n};\n\n\nvar patternDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var regexp, patternExp = attr.ngPattern || attr.pattern;\n      attr.$observe('pattern', function(regex) {\n        if (isString(regex) && regex.length > 0) {\n          regex = new RegExp('^' + regex + '$');\n        }\n\n        if (regex && !regex.test) {\n          throw minErr('ngPattern')('noregexp',\n            'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,\n            regex, startingTag(elm));\n        }\n\n        regexp = regex || undefined;\n        ctrl.$validate();\n      });\n\n      ctrl.$validators.pattern = function(value) {\n        return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);\n      };\n    }\n  };\n};\n\n\nvar maxlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var maxlength = -1;\n      attr.$observe('maxlength', function(value) {\n        var intVal = toInt(value);\n        maxlength = isNaN(intVal) ? -1 : intVal;\n        ctrl.$validate();\n      });\n      ctrl.$validators.maxlength = function(modelValue, viewValue) {\n        return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);\n      };\n    }\n  };\n};\n\nvar minlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var minlength = 0;\n      attr.$observe('minlength', function(value) {\n        minlength = toInt(value) || 0;\n        ctrl.$validate();\n      });\n      ctrl.$validators.minlength = function(modelValue, viewValue) {\n        return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;\n      };\n    }\n  };\n};\n\nif (window.angular.bootstrap) {\n  //AngularJS is already loaded, so we can return here...\n  console.log('WARNING: Tried to load angular more than once.');\n  return;\n}\n\n//try to bind to jquery now so that one can write jqLite(document).ready()\n//but we will rebind on bootstrap again.\nbindJQuery();\n\npublishExternalAPI(angular);\n\nangular.module(\"ngLocale\", [], [\"$provide\", function($provide) {\nvar PLURAL_CATEGORY = {ZERO: \"zero\", ONE: \"one\", TWO: \"two\", FEW: \"few\", MANY: \"many\", OTHER: \"other\"};\nfunction getDecimals(n) {\n  n = n + '';\n  var i = n.indexOf('.');\n  return (i == -1) ? 0 : n.length - i - 1;\n}\n\nfunction getVF(n, opt_precision) {\n  var v = opt_precision;\n\n  if (undefined === v) {\n    v = Math.min(getDecimals(n), 3);\n  }\n\n  var base = Math.pow(10, v);\n  var f = ((n * base) | 0) % base;\n  return {v: v, f: f};\n}\n\n$provide.value(\"$locale\", {\n  \"DATETIME_FORMATS\": {\n    \"AMPMS\": [\n      \"AM\",\n      \"PM\"\n    ],\n    \"DAY\": [\n      \"Sunday\",\n      \"Monday\",\n      \"Tuesday\",\n      \"Wednesday\",\n      \"Thursday\",\n      \"Friday\",\n      \"Saturday\"\n    ],\n    \"ERANAMES\": [\n      \"Before Christ\",\n      \"Anno Domini\"\n    ],\n    \"ERAS\": [\n      \"BC\",\n      \"AD\"\n    ],\n    \"FIRSTDAYOFWEEK\": 6,\n    \"MONTH\": [\n      \"January\",\n      \"February\",\n      \"March\",\n      \"April\",\n      \"May\",\n      \"June\",\n      \"July\",\n      \"August\",\n      \"September\",\n      \"October\",\n      \"November\",\n      \"December\"\n    ],\n    \"SHORTDAY\": [\n      \"Sun\",\n      \"Mon\",\n      \"Tue\",\n      \"Wed\",\n      \"Thu\",\n      \"Fri\",\n      \"Sat\"\n    ],\n    \"SHORTMONTH\": [\n      \"Jan\",\n      \"Feb\",\n      \"Mar\",\n      \"Apr\",\n      \"May\",\n      \"Jun\",\n      \"Jul\",\n      \"Aug\",\n      \"Sep\",\n      \"Oct\",\n      \"Nov\",\n      \"Dec\"\n    ],\n    \"WEEKENDRANGE\": [\n      5,\n      6\n    ],\n    \"fullDate\": \"EEEE, MMMM d, y\",\n    \"longDate\": \"MMMM d, y\",\n    \"medium\": \"MMM d, y h:mm:ss a\",\n    \"mediumDate\": \"MMM d, y\",\n    \"mediumTime\": \"h:mm:ss a\",\n    \"short\": \"M/d/yy h:mm a\",\n    \"shortDate\": \"M/d/yy\",\n    \"shortTime\": \"h:mm a\"\n  },\n  \"NUMBER_FORMATS\": {\n    \"CURRENCY_SYM\": \"$\",\n    \"DECIMAL_SEP\": \".\",\n    \"GROUP_SEP\": \",\",\n    \"PATTERNS\": [\n      {\n        \"gSize\": 3,\n        \"lgSize\": 3,\n        \"maxFrac\": 3,\n        \"minFrac\": 0,\n        \"minInt\": 1,\n        \"negPre\": \"-\",\n        \"negSuf\": \"\",\n        \"posPre\": \"\",\n        \"posSuf\": \"\"\n      },\n      {\n        \"gSize\": 3,\n        \"lgSize\": 3,\n        \"maxFrac\": 2,\n        \"minFrac\": 2,\n        \"minInt\": 1,\n        \"negPre\": \"-\\u00a4\",\n        \"negSuf\": \"\",\n        \"posPre\": \"\\u00a4\",\n        \"posSuf\": \"\"\n      }\n    ]\n  },\n  \"id\": \"en-us\",\n  \"pluralCat\": function(n, opt_precision) {  var i = n | 0;  var vf = getVF(n, opt_precision);  if (i == 1 && vf.v == 0) {    return PLURAL_CATEGORY.ONE;  }  return PLURAL_CATEGORY.OTHER;}\n});\n}]);\n\n  jqLite(document).ready(function() {\n    angularInit(document, bootstrap);\n  });\n\n})(window, document);\n\n!window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type=\"text/css\">@charset \"UTF-8\";[ng\\\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');"
  },
  {
    "path": "examples/client/vendor/satellizer.js",
    "content": "/**\n * Satellizer 0.15.5\n * (c) 2016 Sahat Yalkabov \n * License: MIT \n */\n\n(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n    typeof define === 'function' && define.amd ? define(factory) :\n    (global.satellizer = factory());\n}(this, function () { 'use strict';\n\n    var Config = (function () {\n        function Config() {\n            this.baseUrl = '/';\n            this.loginUrl = '/auth/login';\n            this.signupUrl = '/auth/signup';\n            this.unlinkUrl = '/auth/unlink/';\n            this.tokenName = 'token';\n            this.tokenPrefix = 'satellizer';\n            this.tokenHeader = 'Authorization';\n            this.tokenType = 'Bearer';\n            this.storageType = 'localStorage';\n            this.tokenRoot = null;\n            this.withCredentials = false;\n            this.providers = {\n                facebook: {\n                    name: 'facebook',\n                    url: '/auth/facebook',\n                    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ',',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 580, height: 400 }\n                },\n                google: {\n                    name: 'google',\n                    url: '/auth/google',\n                    authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    optionalUrlParams: ['display', 'state'],\n                    scope: ['profile', 'email'],\n                    scopePrefix: 'openid',\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 452, height: 633 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                },\n                github: {\n                    name: 'github',\n                    url: '/auth/github',\n                    authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['scope'],\n                    scope: ['user:email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1020, height: 618 }\n                },\n                instagram: {\n                    name: 'instagram',\n                    url: '/auth/instagram',\n                    authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['basic'],\n                    scopeDelimiter: '+',\n                    oauthType: '2.0'\n                },\n                linkedin: {\n                    name: 'linkedin',\n                    url: '/auth/linkedin',\n                    authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['state'],\n                    scope: ['r_emailaddress'],\n                    scopeDelimiter: ' ',\n                    state: 'STATE',\n                    oauthType: '2.0',\n                    popupOptions: { width: 527, height: 582 }\n                },\n                twitter: {\n                    name: 'twitter',\n                    url: '/auth/twitter',\n                    authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n                    redirectUri: window.location.origin,\n                    oauthType: '1.0',\n                    popupOptions: { width: 495, height: 645 }\n                },\n                twitch: {\n                    name: 'twitch',\n                    url: '/auth/twitch',\n                    authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['user_read'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                live: {\n                    name: 'live',\n                    url: '/auth/live',\n                    authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['wl.emails'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                yahoo: {\n                    name: 'yahoo',\n                    url: '/auth/yahoo',\n                    authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n                    redirectUri: window.location.origin,\n                    scope: [],\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 559, height: 519 }\n                },\n                bitbucket: {\n                    name: 'bitbucket',\n                    url: '/auth/bitbucket',\n                    authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1028, height: 529 }\n                },\n                spotify: {\n                    name: 'spotify',\n                    url: '/auth/spotify',\n                    authorizationEndpoint: 'https://accounts.spotify.com/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['state'],\n                    requiredUrlParams: ['scope'],\n                    scope: ['user-read-email'],\n                    scopePrefix: '',\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 530 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                }\n            };\n            this.httpInterceptor = function () { return true; };\n        }\n        Object.defineProperty(Config, \"getConstant\", {\n            get: function () {\n                return new Config();\n            },\n            enumerable: true,\n            configurable: true\n        });\n        return Config;\n    }());\n    ;\n\n    var AuthProvider = (function () {\n        function AuthProvider(SatellizerConfig) {\n            this.SatellizerConfig = SatellizerConfig;\n        }\n        Object.defineProperty(AuthProvider.prototype, \"baseUrl\", {\n            get: function () { return this.SatellizerConfig.baseUrl; },\n            set: function (value) { this.SatellizerConfig.baseUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"loginUrl\", {\n            get: function () { return this.SatellizerConfig.loginUrl; },\n            set: function (value) { this.SatellizerConfig.loginUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"signupUrl\", {\n            get: function () { return this.SatellizerConfig.signupUrl; },\n            set: function (value) { this.SatellizerConfig.signupUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"unlinkUrl\", {\n            get: function () { return this.SatellizerConfig.unlinkUrl; },\n            set: function (value) { this.SatellizerConfig.unlinkUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenRoot\", {\n            get: function () { return this.SatellizerConfig.tokenRoot; },\n            set: function (value) { this.SatellizerConfig.tokenRoot = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenName\", {\n            get: function () { return this.SatellizerConfig.tokenName; },\n            set: function (value) { this.SatellizerConfig.tokenName = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenPrefix\", {\n            get: function () { return this.SatellizerConfig.tokenPrefix; },\n            set: function (value) { this.SatellizerConfig.tokenPrefix = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenHeader\", {\n            get: function () { return this.SatellizerConfig.tokenHeader; },\n            set: function (value) { this.SatellizerConfig.tokenHeader = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenType\", {\n            get: function () { return this.SatellizerConfig.tokenType; },\n            set: function (value) { this.SatellizerConfig.tokenType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"withCredentials\", {\n            get: function () { return this.SatellizerConfig.withCredentials; },\n            set: function (value) { this.SatellizerConfig.withCredentials = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"storageType\", {\n            get: function () { return this.SatellizerConfig.storageType; },\n            set: function (value) { this.SatellizerConfig.storageType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"httpInterceptor\", {\n            get: function () { return this.SatellizerConfig.httpInterceptor; },\n            set: function (value) {\n                if (typeof value === 'function') {\n                    this.SatellizerConfig.httpInterceptor = value;\n                }\n                else {\n                    this.SatellizerConfig.httpInterceptor = function () { return value; };\n                }\n            },\n            enumerable: true,\n            configurable: true\n        });\n        AuthProvider.prototype.facebook = function (options) {\n            angular.extend(this.SatellizerConfig.providers.facebook, options);\n        };\n        AuthProvider.prototype.google = function (options) {\n            angular.extend(this.SatellizerConfig.providers.google, options);\n        };\n        AuthProvider.prototype.github = function (options) {\n            angular.extend(this.SatellizerConfig.providers.github, options);\n        };\n        AuthProvider.prototype.instagram = function (options) {\n            angular.extend(this.SatellizerConfig.providers.instagram, options);\n        };\n        AuthProvider.prototype.linkedin = function (options) {\n            angular.extend(this.SatellizerConfig.providers.linkedin, options);\n        };\n        AuthProvider.prototype.twitter = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitter, options);\n        };\n        AuthProvider.prototype.twitch = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitch, options);\n        };\n        AuthProvider.prototype.live = function (options) {\n            angular.extend(this.SatellizerConfig.providers.live, options);\n        };\n        AuthProvider.prototype.yahoo = function (options) {\n            angular.extend(this.SatellizerConfig.providers.yahoo, options);\n        };\n        AuthProvider.prototype.bitbucket = function (options) {\n            angular.extend(this.SatellizerConfig.providers.bitbucket, options);\n        };\n        AuthProvider.prototype.spotify = function (options) {\n            angular.extend(this.SatellizerConfig.providers.spotify, options);\n        };\n        AuthProvider.prototype.oauth1 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '1.0'\n            });\n        };\n        AuthProvider.prototype.oauth2 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '2.0'\n            });\n        };\n        AuthProvider.prototype.$get = function (SatellizerShared, SatellizerLocal, SatellizerOAuth) {\n            return {\n                login: function (user, options) { return SatellizerLocal.login(user, options); },\n                signup: function (user, options) { return SatellizerLocal.signup(user, options); },\n                logout: function () { return SatellizerShared.logout(); },\n                authenticate: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                link: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                unlink: function (name, options) { return SatellizerOAuth.unlink(name, options); },\n                isAuthenticated: function () { return SatellizerShared.isAuthenticated(); },\n                getPayload: function () { return SatellizerShared.getPayload(); },\n                getToken: function () { return SatellizerShared.getToken(); },\n                setToken: function (token) { return SatellizerShared.setToken({ access_token: token }); },\n                removeToken: function () { return SatellizerShared.removeToken(); },\n                setStorageType: function (type) { return SatellizerShared.setStorageType(type); }\n            };\n        };\n        AuthProvider.$inject = ['SatellizerConfig'];\n        return AuthProvider;\n    }());\n    AuthProvider.prototype.$get.$inject = ['SatellizerShared', 'SatellizerLocal', 'SatellizerOAuth'];\n\n    function joinUrl(baseUrl, url) {\n        if (/^(?:[a-z]+:)?\\/\\//i.test(url)) {\n            return url;\n        }\n        var joined = [baseUrl, url].join('/');\n        var normalize = function (str) {\n            return str\n                .replace(/[\\/]+/g, '/')\n                .replace(/\\/\\?/g, '?')\n                .replace(/\\/\\#/g, '#')\n                .replace(/\\:\\//g, '://');\n        };\n        return normalize(joined);\n    }\n    function getFullUrlPath(location) {\n        var isHttps = location.protocol === 'https:';\n        return location.protocol + '//' + location.hostname +\n            ':' + (location.port || (isHttps ? '443' : '80')) +\n            (/^\\//.test(location.pathname) ? location.pathname : '/' + location.pathname);\n    }\n    function parseQueryString(str) {\n        var obj = {};\n        var key;\n        var value;\n        angular.forEach((str || '').split('&'), function (keyValue) {\n            if (keyValue) {\n                value = keyValue.split('=');\n                key = decodeURIComponent(value[0]);\n                obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;\n            }\n        });\n        return obj;\n    }\n    function decodeBase64(str) {\n        var buffer;\n        if (typeof module !== 'undefined' && module.exports) {\n            try {\n                buffer = require('buffer').Buffer;\n            }\n            catch (err) {\n            }\n        }\n        var fromCharCode = String.fromCharCode;\n        var re_btou = new RegExp([\n            '[\\xC0-\\xDF][\\x80-\\xBF]',\n            '[\\xE0-\\xEF][\\x80-\\xBF]{2}',\n            '[\\xF0-\\xF7][\\x80-\\xBF]{3}'\n        ].join('|'), 'g');\n        var cb_btou = function (cccc) {\n            switch (cccc.length) {\n                case 4:\n                    var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n                        | ((0x3f & cccc.charCodeAt(1)) << 12)\n                        | ((0x3f & cccc.charCodeAt(2)) << 6)\n                        | (0x3f & cccc.charCodeAt(3));\n                    var offset = cp - 0x10000;\n                    return (fromCharCode((offset >>> 10) + 0xD800)\n                        + fromCharCode((offset & 0x3FF) + 0xDC00));\n                case 3:\n                    return fromCharCode(((0x0f & cccc.charCodeAt(0)) << 12)\n                        | ((0x3f & cccc.charCodeAt(1)) << 6)\n                        | (0x3f & cccc.charCodeAt(2)));\n                default:\n                    return fromCharCode(((0x1f & cccc.charCodeAt(0)) << 6)\n                        | (0x3f & cccc.charCodeAt(1)));\n            }\n        };\n        var btou = function (b) {\n            return b.replace(re_btou, cb_btou);\n        };\n        var _decode = buffer ? function (a) {\n            return (a.constructor === buffer.constructor\n                ? a : new buffer(a, 'base64')).toString();\n        }\n            : function (a) {\n                return btou(atob(a));\n            };\n        return _decode(String(str).replace(/[-_]/g, function (m0) {\n            return m0 === '-' ? '+' : '/';\n        })\n            .replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n    }\n\n    var Shared = (function () {\n        function Shared($q, $window, SatellizerConfig, SatellizerStorage) {\n            this.$q = $q;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerStorage = SatellizerStorage;\n            var _a = this.SatellizerConfig, tokenName = _a.tokenName, tokenPrefix = _a.tokenPrefix;\n            this.prefixedTokenName = tokenPrefix ? [tokenPrefix, tokenName].join('_') : tokenName;\n        }\n        Shared.prototype.getToken = function () {\n            return this.SatellizerStorage.get(this.prefixedTokenName);\n        };\n        Shared.prototype.getPayload = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token && token.split('.').length === 3) {\n                try {\n                    var base64Url = token.split('.')[1];\n                    var base64 = base64Url.replace('-', '+').replace('_', '/');\n                    return JSON.parse(decodeBase64(base64));\n                }\n                catch (e) {\n                }\n            }\n        };\n        Shared.prototype.setToken = function (response) {\n            var tokenRoot = this.SatellizerConfig.tokenRoot;\n            var tokenName = this.SatellizerConfig.tokenName;\n            var accessToken = response && response.access_token;\n            var token;\n            if (accessToken) {\n                if (angular.isObject(accessToken) && angular.isObject(accessToken.data)) {\n                    response = accessToken;\n                }\n                else if (angular.isString(accessToken)) {\n                    token = accessToken;\n                }\n            }\n            if (!token && response) {\n                var tokenRootData = tokenRoot && tokenRoot.split('.').reduce(function (o, x) { return o[x]; }, response.data);\n                token = tokenRootData ? tokenRootData[tokenName] : response.data && response.data[tokenName];\n            }\n            if (token) {\n                this.SatellizerStorage.set(this.prefixedTokenName, token);\n            }\n        };\n        Shared.prototype.removeToken = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n        };\n        Shared.prototype.isAuthenticated = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token) {\n                if (token.split('.').length === 3) {\n                    try {\n                        var base64Url = token.split('.')[1];\n                        var base64 = base64Url.replace('-', '+').replace('_', '/');\n                        var exp = JSON.parse(this.$window.atob(base64)).exp;\n                        if (typeof exp === 'number') {\n                            return Math.round(new Date().getTime() / 1000) < exp;\n                        }\n                    }\n                    catch (e) {\n                        return true; // Pass: Non-JWT token that looks like JWT\n                    }\n                }\n                return true; // Pass: All other tokens\n            }\n            return false; // Fail: No token at all\n        };\n        Shared.prototype.logout = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n            return this.$q.when();\n        };\n        Shared.prototype.setStorageType = function (type) {\n            this.SatellizerConfig.storageType = type;\n        };\n        Shared.$inject = ['$q', '$window', 'SatellizerConfig', 'SatellizerStorage'];\n        return Shared;\n    }());\n\n    var Local = (function () {\n        function Local($http, SatellizerConfig, SatellizerShared) {\n            this.$http = $http;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n        }\n        Local.prototype.login = function (user, options) {\n            var _this = this;\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.loginUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options).then(function (response) {\n                _this.SatellizerShared.setToken(response);\n                return response;\n            });\n        };\n        Local.prototype.signup = function (user, options) {\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.signupUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options);\n        };\n        Local.$inject = ['$http', 'SatellizerConfig', 'SatellizerShared'];\n        return Local;\n    }());\n\n    var Popup = (function () {\n        function Popup($interval, $window, $q) {\n            this.$interval = $interval;\n            this.$window = $window;\n            this.$q = $q;\n            this.popup = null;\n            this.defaults = {\n                redirectUri: null\n            };\n        }\n        Popup.prototype.stringifyOptions = function (options) {\n            var parts = [];\n            angular.forEach(options, function (value, key) {\n                parts.push(key + '=' + value);\n            });\n            return parts.join(',');\n        };\n        Popup.prototype.open = function (url, name, popupOptions, redirectUri, dontPoll) {\n            var width = popupOptions.width || 500;\n            var height = popupOptions.height || 500;\n            var options = this.stringifyOptions({\n                width: width,\n                height: height,\n                top: this.$window.screenY + ((this.$window.outerHeight - height) / 2.5),\n                left: this.$window.screenX + ((this.$window.outerWidth - width) / 2)\n            });\n            var popupName = this.$window['cordova'] || this.$window.navigator.userAgent.indexOf('CriOS') > -1 ? '_blank' : name;\n            this.popup = this.$window.open(url, popupName, options);\n            if (this.popup && this.popup.focus) {\n                this.popup.focus();\n            }\n            if (dontPoll) {\n                return;\n            }\n            if (this.$window['cordova']) {\n                return this.eventListener(redirectUri);\n            }\n            else {\n                if (url === 'about:blank') {\n                    this.popup.location = url;\n                }\n                return this.polling(redirectUri);\n            }\n        };\n        Popup.prototype.polling = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var redirectUriParser = document.createElement('a');\n                redirectUriParser.href = redirectUri;\n                var redirectUriPath = getFullUrlPath(redirectUriParser);\n                var polling = _this.$interval(function () {\n                    if (!_this.popup || _this.popup.closed || _this.popup.closed === undefined) {\n                        _this.$interval.cancel(polling);\n                        reject(new Error('The popup window was closed'));\n                    }\n                    try {\n                        var popupWindowPath = getFullUrlPath(_this.popup.location);\n                        if (popupWindowPath === redirectUriPath) {\n                            if (_this.popup.location.search || _this.popup.location.hash) {\n                                var query = parseQueryString(_this.popup.location.search.substring(1).replace(/\\/$/, ''));\n                                var hash = parseQueryString(_this.popup.location.hash.substring(1).replace(/[\\/$]/, ''));\n                                var params = angular.extend({}, query, hash);\n                                if (params.error) {\n                                    reject(new Error(params.error));\n                                }\n                                else {\n                                    resolve(params);\n                                }\n                            }\n                            else {\n                                reject(new Error('OAuth redirect has occurred but no query or hash parameters were found. ' +\n                                    'They were either not set during the redirect, or were removed—typically by a ' +\n                                    'routing library—before Satellizer could read it.'));\n                            }\n                            _this.$interval.cancel(polling);\n                            _this.popup.close();\n                        }\n                    }\n                    catch (error) {\n                    }\n                }, 500);\n            });\n        };\n        Popup.prototype.eventListener = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                _this.popup.addEventListener('loadstart', function (event) {\n                    if (event.url.indexOf(redirectUri) !== 0) {\n                        return;\n                    }\n                    var parser = document.createElement('a');\n                    parser.href = event.url;\n                    if (parser.search || parser.hash) {\n                        var query = parseQueryString(parser.search.substring(1).replace(/\\/$/, ''));\n                        var hash = parseQueryString(parser.hash.substring(1).replace(/[\\/$]/, ''));\n                        var params = angular.extend({}, query, hash);\n                        if (params.error) {\n                            reject(new Error(params.error));\n                        }\n                        else {\n                            resolve(params);\n                        }\n                        _this.popup.close();\n                    }\n                });\n                _this.popup.addEventListener('loaderror', function () {\n                    reject(new Error('Authorization failed'));\n                });\n                _this.popup.addEventListener('exit', function () {\n                    reject(new Error('The popup window was closed'));\n                });\n            });\n        };\n        Popup.$inject = ['$interval', '$window', '$q'];\n        return Popup;\n    }());\n\n    var OAuth1 = (function () {\n        function OAuth1($http, $window, SatellizerConfig, SatellizerPopup) {\n            this.$http = $http;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.defaults = {\n                name: null,\n                url: null,\n                authorizationEndpoint: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                redirectUri: null,\n                requiredUrlParams: null,\n                defaultUrlParams: null,\n                oauthType: '1.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        ;\n        OAuth1.prototype.init = function (options, userData) {\n            var _this = this;\n            angular.extend(this.defaults, options);\n            var name = options.name, popupOptions = options.popupOptions;\n            var redirectUri = this.defaults.redirectUri;\n            // Should open an empty popup and wait until request token is received\n            if (!this.$window['cordova']) {\n                this.SatellizerPopup.open('about:blank', name, popupOptions, redirectUri, true);\n            }\n            return this.getRequestToken().then(function (response) {\n                return _this.openPopup(options, response).then(function (popupResponse) {\n                    return _this.exchangeForToken(popupResponse, userData);\n                });\n            });\n        };\n        OAuth1.prototype.openPopup = function (options, response) {\n            var url = [options.authorizationEndpoint, this.buildQueryString(response.data)].join('?');\n            var redirectUri = this.defaults.redirectUri;\n            if (this.$window['cordova']) {\n                return this.SatellizerPopup.open(url, options.name, options.popupOptions, redirectUri);\n            }\n            else {\n                this.SatellizerPopup.popup.location = url;\n                return this.SatellizerPopup.polling(redirectUri);\n            }\n        };\n        OAuth1.prototype.getRequestToken = function () {\n            var url = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(url, this.defaults);\n        };\n        OAuth1.prototype.exchangeForToken = function (oauthData, userData) {\n            var payload = angular.extend({}, userData, oauthData);\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth1.prototype.buildQueryString = function (obj) {\n            var str = [];\n            angular.forEach(obj, function (value, key) {\n                str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n            });\n            return str.join('&');\n        };\n        OAuth1.$inject = ['$http', '$window', 'SatellizerConfig', 'SatellizerPopup'];\n        return OAuth1;\n    }());\n\n    var OAuth2 = (function () {\n        function OAuth2($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.defaults = {\n                name: null,\n                url: null,\n                clientId: null,\n                authorizationEndpoint: null,\n                redirectUri: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                state: null,\n                requiredUrlParams: null,\n                defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n                responseType: 'code',\n                responseParams: {\n                    code: 'code',\n                    clientId: 'clientId',\n                    redirectUri: 'redirectUri'\n                },\n                oauthType: '2.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        OAuth2.camelCase = function (name) {\n            return name.replace(/([\\:\\-\\_]+(.))/g, function (_, separator, letter, offset) {\n                return offset ? letter.toUpperCase() : letter;\n            });\n        };\n        OAuth2.prototype.init = function (options, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                angular.extend(_this.defaults, options);\n                var stateName = _this.defaults.name + '_state';\n                var _a = _this.defaults, name = _a.name, state = _a.state, popupOptions = _a.popupOptions, redirectUri = _a.redirectUri, responseType = _a.responseType;\n                if (typeof state === 'function') {\n                    _this.SatellizerStorage.set(stateName, state());\n                }\n                else if (typeof state === 'string') {\n                    _this.SatellizerStorage.set(stateName, state);\n                }\n                var url = [_this.defaults.authorizationEndpoint, _this.buildQueryString()].join('?');\n                _this.SatellizerPopup.open(url, name, popupOptions, redirectUri).then(function (oauth) {\n                    if (responseType === 'token' || !url) {\n                        return resolve(oauth);\n                    }\n                    if (oauth.state && oauth.state !== _this.SatellizerStorage.get(stateName)) {\n                        return reject(new Error('The value returned in the state parameter does not match the state value from your original ' +\n                            'authorization code request.'));\n                    }\n                    resolve(_this.exchangeForToken(oauth, userData));\n                }).catch(function (error) { return reject(error); });\n            });\n        };\n        OAuth2.prototype.exchangeForToken = function (oauthData, userData) {\n            var _this = this;\n            var payload = angular.extend({}, userData);\n            angular.forEach(this.defaults.responseParams, function (value, key) {\n                switch (key) {\n                    case 'code':\n                        payload[value] = oauthData.code;\n                        break;\n                    case 'clientId':\n                        payload[value] = _this.defaults.clientId;\n                        break;\n                    case 'redirectUri':\n                        payload[value] = _this.defaults.redirectUri;\n                        break;\n                    default:\n                        payload[value] = oauthData[key];\n                }\n            });\n            if (oauthData.state) {\n                payload.state = oauthData.state;\n            }\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ?\n                joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) :\n                this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth2.prototype.buildQueryString = function () {\n            var _this = this;\n            var keyValuePairs = [];\n            var urlParamsCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];\n            angular.forEach(urlParamsCategories, function (paramsCategory) {\n                angular.forEach(_this.defaults[paramsCategory], function (paramName) {\n                    var camelizedName = OAuth2.camelCase(paramName);\n                    var paramValue = angular.isFunction(_this.defaults[paramName]) ? _this.defaults[paramName]() : _this.defaults[camelizedName];\n                    if (paramName === 'redirect_uri' && !paramValue) {\n                        return;\n                    }\n                    if (paramName === 'state') {\n                        var stateName = _this.defaults.name + '_state';\n                        paramValue = encodeURIComponent(_this.SatellizerStorage.get(stateName));\n                    }\n                    if (paramName === 'scope' && Array.isArray(paramValue)) {\n                        paramValue = paramValue.join(_this.defaults.scopeDelimiter);\n                        if (_this.defaults.scopePrefix) {\n                            paramValue = [_this.defaults.scopePrefix, paramValue].join(_this.defaults.scopeDelimiter);\n                        }\n                    }\n                    keyValuePairs.push([paramName, paramValue]);\n                });\n            });\n            return keyValuePairs.map(function (pair) { return pair.join('='); }).join('&');\n        };\n        OAuth2.$inject = ['$http', '$window', '$timeout', '$q', 'SatellizerConfig', 'SatellizerPopup', 'SatellizerStorage'];\n        return OAuth2;\n    }());\n\n    var OAuth = (function () {\n        function OAuth($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage, SatellizerShared, SatellizerOAuth1, SatellizerOAuth2) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerOAuth1 = SatellizerOAuth1;\n            this.SatellizerOAuth2 = SatellizerOAuth2;\n        }\n        OAuth.prototype.authenticate = function (name, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var provider = _this.SatellizerConfig.providers[name];\n                var oauth = null;\n                switch (provider.oauthType) {\n                    case '1.0':\n                        oauth = new OAuth1(_this.$http, _this.$window, _this.SatellizerConfig, _this.SatellizerPopup);\n                        break;\n                    case '2.0':\n                        oauth = new OAuth2(_this.$http, _this.$window, _this.$timeout, _this.$q, _this.SatellizerConfig, _this.SatellizerPopup, _this.SatellizerStorage);\n                        break;\n                    default:\n                        return reject(new Error('Invalid OAuth Type'));\n                }\n                return oauth.init(provider, userData).then(function (response) {\n                    if (provider.url) {\n                        _this.SatellizerShared.setToken(response);\n                    }\n                    resolve(response);\n                }).catch(function (error) {\n                    reject(error);\n                });\n            });\n        };\n        OAuth.prototype.unlink = function (provider, httpOptions) {\n            if (httpOptions === void 0) { httpOptions = {}; }\n            httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);\n            httpOptions.data = { provider: provider } || httpOptions.data;\n            httpOptions.method = httpOptions.method || 'POST';\n            httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(httpOptions);\n        };\n        OAuth.$inject = [\n            '$http',\n            '$window',\n            '$timeout',\n            '$q',\n            'SatellizerConfig',\n            'SatellizerPopup',\n            'SatellizerStorage',\n            'SatellizerShared',\n            'SatellizerOAuth1',\n            'SatellizerOAuth2'\n        ];\n        return OAuth;\n    }());\n\n    var Storage = (function () {\n        function Storage($window, SatellizerConfig) {\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.memoryStore = {};\n        }\n        Storage.prototype.get = function (key) {\n            try {\n                return this.$window[this.SatellizerConfig.storageType].getItem(key);\n            }\n            catch (e) {\n                return this.memoryStore[key];\n            }\n        };\n        Storage.prototype.set = function (key, value) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].setItem(key, value);\n            }\n            catch (e) {\n                this.memoryStore[key] = value;\n            }\n        };\n        Storage.prototype.remove = function (key) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].removeItem(key);\n            }\n            catch (e) {\n                delete this.memoryStore[key];\n            }\n        };\n        Storage.$inject = ['$window', 'SatellizerConfig'];\n        return Storage;\n    }());\n\n    var Interceptor = (function () {\n        function Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            var _this = this;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerStorage = SatellizerStorage;\n            this.request = function (config) {\n                if (config['skipAuthorization']) {\n                    return config;\n                }\n                if (_this.SatellizerShared.isAuthenticated() && _this.SatellizerConfig.httpInterceptor()) {\n                    var tokenName = _this.SatellizerConfig.tokenPrefix ?\n                        [_this.SatellizerConfig.tokenPrefix, _this.SatellizerConfig.tokenName].join('_') : _this.SatellizerConfig.tokenName;\n                    var token = _this.SatellizerStorage.get(tokenName);\n                    if (_this.SatellizerConfig.tokenHeader && _this.SatellizerConfig.tokenType) {\n                        token = _this.SatellizerConfig.tokenType + ' ' + token;\n                    }\n                    config.headers[_this.SatellizerConfig.tokenHeader] = token;\n                }\n                return config;\n            };\n        }\n        Interceptor.Factory = function (SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            return new Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage);\n        };\n        Interceptor.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n        return Interceptor;\n    }());\n    Interceptor.Factory.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n\n    var HttpProviderConfig = (function () {\n        function HttpProviderConfig($httpProvider) {\n            this.$httpProvider = $httpProvider;\n            $httpProvider.interceptors.push(Interceptor.Factory);\n        }\n        HttpProviderConfig.$inject = ['$httpProvider'];\n        return HttpProviderConfig;\n    }());\n\n    angular.module('satellizer', [])\n        .provider('$auth', ['SatellizerConfig', function (SatellizerConfig) { return new AuthProvider(SatellizerConfig); }])\n        .constant('SatellizerConfig', Config.getConstant)\n        .service('SatellizerShared', Shared)\n        .service('SatellizerLocal', Local)\n        .service('SatellizerPopup', Popup)\n        .service('SatellizerOAuth', OAuth)\n        .service('SatellizerOAuth2', OAuth2)\n        .service('SatellizerOAuth1', OAuth1)\n        .service('SatellizerStorage', Storage)\n        .service('SatellizerInterceptor', Interceptor)\n        .config(['$httpProvider', function ($httpProvider) { return new HttpProviderConfig($httpProvider); }]);\n    var ng1 = 'satellizer';\n\n    return ng1;\n\n}));\n//# sourceMappingURL=satellizer.js.map\n"
  },
  {
    "path": "examples/ionic/.bowerrc",
    "content": "{\n  \"directory\": \"www/lib\"\n}\n"
  },
  {
    "path": "examples/ionic/.gitignore",
    "content": "# Specifies intentionally untracked files to ignore when using Git\n# http://git-scm.com/docs/gitignore\n\nnode_modules/\nplatforms/\nplugins/\n"
  },
  {
    "path": "examples/ionic/README.md",
    "content": "<img src=\"http://ionicframework.com/img/ionic-logo-blue.svg\">\n\nIonic is the beautiful, open source front-end SDK for developing hybrid mobile apps with web technologies.\n\n## Usage\n\n1. First, install [Node.js](https://nodejs.org/en/). Then, install the latest Cordova and Ionic command-line tools:\n - `sudo npm install -g cordova ionic`\n - **Note**: iOS development requires Mac OS X. iOS simulator through the Ionic CLI requires the `ios-sim` npm package, which can be installed with the command `sudo npm -g install ios-sim`.\n4. Install dependencies with `npm install`.\n5. <img src=\"http://cnet2.cbsistatic.com/hub/i/r/2011/10/05/74df5391-fdc1-11e2-8c7c-d4ae52e62bcc/resize/370xauto/26609a1fcbb66cad8783b098ebf0ed80/apple-logo-2.jpg\" height=\"16\"> **iOS**\n - `ionic build ios`\n - `ionic emulate ios`\n6. <img src=\"http://icons.iconarchive.com/icons/carlosjj/google-jfk/128/android-icon.png\" height=\"17\"> **Android**\n - `ionic platform add android`\n - `ionic build android`\n - `ionic emulate android`\n"
  },
  {
    "path": "examples/ionic/bower.json",
    "content": "{\n  \"name\": \"satellizer-ionic-example\",\n  \"devDependencies\": {\n    \"ionic\": \"^1.3.1\",\n    \"satellizer\": \"latest\"\n  }\n}\n"
  },
  {
    "path": "examples/ionic/config.xml",
    "content": "<?xml version='1.0' encoding='utf-8'?>\n<widget id=\"com.ionicframework.sidemenu268668\" version=\"0.0.1\" xmlns=\"http://www.w3.org/ns/widgets\" xmlns:cdv=\"http://cordova.apache.org/ns/1.0\">\n    <name>satellizer-ionic</name>\n    <description>\n        An Ionic Framework and Cordova project.\n    </description>\n    <author email=\"hi@ionicframework\" href=\"http://ionicframework.com/\">\n      Ionic Framework Team\n    </author>\n    <content src=\"index.html\" />\n    <access origin=\"*\" />\n    <preference name=\"webviewbounce\" value=\"false\" />\n    <preference name=\"UIWebViewBounce\" value=\"false\" />\n    <preference name=\"DisallowOverscroll\" value=\"true\" />\n    <preference name=\"BackupWebStorage\" value=\"none\" />\n    <preference name=\"SplashScreen\" value=\"screen\" />\n    <preference name=\"SplashScreenDelay\" value=\"3000\" />\n    <feature name=\"StatusBar\">\n        <param name=\"ios-package\" onload=\"true\" value=\"CDVStatusBar\" />\n    </feature>\n    <platform name=\"ios\">\n        <icon height=\"57\" src=\"resources/ios/icon/icon.png\" width=\"57\" />\n        <icon height=\"114\" src=\"resources/ios/icon/icon@2x.png\" width=\"114\" />\n        <icon height=\"40\" src=\"resources/ios/icon/icon-40.png\" width=\"40\" />\n        <icon height=\"80\" src=\"resources/ios/icon/icon-40@2x.png\" width=\"80\" />\n        <icon height=\"50\" src=\"resources/ios/icon/icon-50.png\" width=\"50\" />\n        <icon height=\"100\" src=\"resources/ios/icon/icon-50@2x.png\" width=\"100\" />\n        <icon height=\"60\" src=\"resources/ios/icon/icon-60.png\" width=\"60\" />\n        <icon height=\"120\" src=\"resources/ios/icon/icon-60@2x.png\" width=\"120\" />\n        <icon height=\"180\" src=\"resources/ios/icon/icon-60@3x.png\" width=\"180\" />\n        <icon height=\"72\" src=\"resources/ios/icon/icon-72.png\" width=\"72\" />\n        <icon height=\"144\" src=\"resources/ios/icon/icon-72@2x.png\" width=\"144\" />\n        <icon height=\"76\" src=\"resources/ios/icon/icon-76.png\" width=\"76\" />\n        <icon height=\"152\" src=\"resources/ios/icon/icon-76@2x.png\" width=\"152\" />\n        <icon height=\"29\" src=\"resources/ios/icon/icon-small.png\" width=\"29\" />\n        <icon height=\"58\" src=\"resources/ios/icon/icon-small@2x.png\" width=\"58\" />\n        <icon height=\"87\" src=\"resources/ios/icon/icon-small@3x.png\" width=\"87\" />\n        <splash height=\"1136\" src=\"resources/ios/splash/Default-568h@2x~iphone.png\" width=\"640\" />\n        <splash height=\"1334\" src=\"resources/ios/splash/Default-667h.png\" width=\"750\" />\n        <splash height=\"2208\" src=\"resources/ios/splash/Default-736h.png\" width=\"1242\" />\n        <splash height=\"1242\" src=\"resources/ios/splash/Default-Landscape-736h.png\" width=\"2208\" />\n        <splash height=\"1536\" src=\"resources/ios/splash/Default-Landscape@2x~ipad.png\" width=\"2048\" />\n        <splash height=\"768\" src=\"resources/ios/splash/Default-Landscape~ipad.png\" width=\"1024\" />\n        <splash height=\"2048\" src=\"resources/ios/splash/Default-Portrait@2x~ipad.png\" width=\"1536\" />\n        <splash height=\"1024\" src=\"resources/ios/splash/Default-Portrait~ipad.png\" width=\"768\" />\n        <splash height=\"960\" src=\"resources/ios/splash/Default@2x~iphone.png\" width=\"640\" />\n        <splash height=\"480\" src=\"resources/ios/splash/Default~iphone.png\" width=\"320\" />\n    </platform>\n    <platform name=\"android\">\n        <icon density=\"ldpi\" src=\"resources/android/icon/drawable-ldpi-icon.png\" />\n        <icon density=\"mdpi\" src=\"resources/android/icon/drawable-mdpi-icon.png\" />\n        <icon density=\"hdpi\" src=\"resources/android/icon/drawable-hdpi-icon.png\" />\n        <icon density=\"xhdpi\" src=\"resources/android/icon/drawable-xhdpi-icon.png\" />\n        <icon density=\"xxhdpi\" src=\"resources/android/icon/drawable-xxhdpi-icon.png\" />\n        <icon density=\"xxxhdpi\" src=\"resources/android/icon/drawable-xxxhdpi-icon.png\" />\n        <splash density=\"land-ldpi\" src=\"resources/android/splash/drawable-land-ldpi-screen.png\" />\n        <splash density=\"land-mdpi\" src=\"resources/android/splash/drawable-land-mdpi-screen.png\" />\n        <splash density=\"land-hdpi\" src=\"resources/android/splash/drawable-land-hdpi-screen.png\" />\n        <splash density=\"land-xhdpi\" src=\"resources/android/splash/drawable-land-xhdpi-screen.png\" />\n        <splash density=\"land-xxhdpi\" src=\"resources/android/splash/drawable-land-xxhdpi-screen.png\" />\n        <splash density=\"land-xxxhdpi\" src=\"resources/android/splash/drawable-land-xxxhdpi-screen.png\" />\n        <splash density=\"port-ldpi\" src=\"resources/android/splash/drawable-port-ldpi-screen.png\" />\n        <splash density=\"port-mdpi\" src=\"resources/android/splash/drawable-port-mdpi-screen.png\" />\n        <splash density=\"port-hdpi\" src=\"resources/android/splash/drawable-port-hdpi-screen.png\" />\n        <splash density=\"port-xhdpi\" src=\"resources/android/splash/drawable-port-xhdpi-screen.png\" />\n        <splash density=\"port-xxhdpi\" src=\"resources/android/splash/drawable-port-xxhdpi-screen.png\" />\n        <splash density=\"port-xxxhdpi\" src=\"resources/android/splash/drawable-port-xxxhdpi-screen.png\" />\n    </platform>\n    <plugin name=\"cordova-plugin-inappbrowser\" spec=\"~1.3.0\" />\n</widget>\n"
  },
  {
    "path": "examples/ionic/gulpfile.js",
    "content": "var gulp = require('gulp');\nvar gutil = require('gulp-util');\nvar bower = require('bower');\nvar concat = require('gulp-concat');\nvar sass = require('gulp-sass');\nvar minifyCss = require('gulp-minify-css');\nvar rename = require('gulp-rename');\nvar sh = require('shelljs');\n\nvar paths = {\n  sass: ['./scss/**/*.scss']\n};\n\ngulp.task('default', ['sass']);\n\ngulp.task('sass', function(done) {\n  gulp.src('./scss/ionic.app.scss')\n    .pipe(sass())\n    .pipe(gulp.dest('./www/css/'))\n    .pipe(minifyCss({\n      keepSpecialComments: 0\n    }))\n    .pipe(rename({ extname: '.min.css' }))\n    .pipe(gulp.dest('./www/css/'))\n    .on('end', done);\n});\n\ngulp.task('watch', function() {\n  gulp.watch(paths.sass, ['sass']);\n});\n\ngulp.task('install', ['git-check'], function() {\n  return bower.commands.install()\n    .on('log', function(data) {\n      gutil.log('bower', gutil.colors.cyan(data.id), data.message);\n    });\n});\n\ngulp.task('git-check', function(done) {\n  if (!sh.which('git')) {\n    console.log(\n      '  ' + gutil.colors.red('Git is not installed.'),\n      '\\n  Git, the version control system, is required to download Ionic.',\n      '\\n  Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',\n      '\\n  Once git is installed, run \\'' + gutil.colors.cyan('gulp install') + '\\' again.'\n    );\n    process.exit(1);\n  }\n  done();\n});\n"
  },
  {
    "path": "examples/ionic/hooks/README.md",
    "content": "<!--\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n#  KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n-->\n# Cordova Hooks\n\nThis directory may contain scripts used to customize cordova commands. This\ndirectory used to exist at `.cordova/hooks`, but has now been moved to the\nproject root. Any scripts you add to these directories will be executed before\nand after the commands corresponding to the directory name. Useful for\nintegrating your own build systems or integrating with version control systems.\n\n__Remember__: Make your scripts executable.\n\n## Hook Directories\nThe following subdirectories will be used for hooks:\n\n    after_build/\n    after_compile/\n    after_docs/\n    after_emulate/\n    after_platform_add/\n    after_platform_rm/\n    after_platform_ls/\n    after_plugin_add/\n    after_plugin_ls/\n    after_plugin_rm/\n    after_plugin_search/\n    after_prepare/\n    after_run/\n    after_serve/\n    before_build/\n    before_compile/\n    before_docs/\n    before_emulate/\n    before_platform_add/\n    before_platform_rm/\n    before_platform_ls/\n    before_plugin_add/\n    before_plugin_ls/\n    before_plugin_rm/\n    before_plugin_search/\n    before_prepare/\n    before_run/\n    before_serve/\n    pre_package/ <-- Windows 8 and Windows Phone only.\n\n## Script Interface\n\nAll scripts are run from the project's root directory and have the root directory passes as the first argument. All other options are passed to the script using environment variables:\n\n* CORDOVA_VERSION - The version of the Cordova-CLI.\n* CORDOVA_PLATFORMS - Comma separated list of platforms that the command applies to (e.g.: android, ios).\n* CORDOVA_PLUGINS - Comma separated list of plugin IDs that the command applies to (e.g.: org.apache.cordova.file, org.apache.cordova.file-transfer)\n* CORDOVA_HOOK - Path to the hook that is being executed.\n* CORDOVA_CMDLINE - The exact command-line arguments passed to cordova (e.g.: cordova run ios --emulate)\n\nIf a script returns a non-zero exit code, then the parent cordova command will be aborted.\n\n\n## Writing hooks\n\nWe highly recommend writting your hooks using Node.js so that they are\ncross-platform. Some good examples are shown here:\n\n[http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/](http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/)\n\n"
  },
  {
    "path": "examples/ionic/hooks/after_platform_add/010_install_plugins.js",
    "content": "#!/usr/bin/env node\n\n// This hook installs all cordova plugins.\n\n// Add plugins to this list - either the identifier or the URL.\nvar pluginlist = [\n  'org.apache.cordova.device@0.2.12',\n  'org.apache.cordova.console@0.2.11',\n  'cordova-plugin-inappbrowser@1.0.0',\n  'com.ionic.keyboard@1.0.3',\n  'com.pushwoosh.plugins.pushwoosh@3.3.0',\n  'https://bitbucket.org/180vita/cordova-adjust-sdk/',\n  'com.danielcwilson.plugins.googleanalytics@0.6.0',\n  'org.apache.cordova.statusbar@0.1.8'\n];\n\n// No need to configure anything below.\n\nvar fs = require('fs');\nvar path = require('path');\nvar sys = require('sys')\nvar exec = require('child_process').exec;\n\nfunction puts(error, stdout, stderr) {\n    sys.puts(stdout)\n}\n\npluginlist.forEach(function(plugin) {\n    exec(\"cordova plugin add \" + plugin, puts);\n});\n"
  },
  {
    "path": "examples/ionic/hooks/after_prepare/010_add_platform_class.js",
    "content": "#!/usr/bin/env node\n\n// Add Platform Class\n// v1.0\n// Automatically adds the platform class to the body tag\n// after the `prepare` command. By placing the platform CSS classes\n// directly in the HTML built for the platform, it speeds up\n// rendering the correct layout/style for the specific platform\n// instead of waiting for the JS to figure out the correct classes.\n\nvar fs = require('fs');\nvar path = require('path');\n\nvar rootdir = process.argv[2];\n\nfunction addPlatformBodyTag(indexPath, platform) {\n  // add the platform class to the body tag\n  try {\n    var platformClass = 'platform-' + platform;\n    var cordovaClass = 'platform-cordova platform-webview';\n\n    var html = fs.readFileSync(indexPath, 'utf8');\n\n    var bodyTag = findBodyTag(html);\n    if(!bodyTag) return; // no opening body tag, something's wrong\n\n    if(bodyTag.indexOf(platformClass) > -1) return; // already added\n\n    var newBodyTag = bodyTag;\n\n    var classAttr = findClassAttr(bodyTag);\n    if(classAttr) {\n      // body tag has existing class attribute, add the classname\n      var endingQuote = classAttr.substring(classAttr.length-1);\n      var newClassAttr = classAttr.substring(0, classAttr.length-1);\n      newClassAttr += ' ' + platformClass + ' ' + cordovaClass + endingQuote;\n      newBodyTag = bodyTag.replace(classAttr, newClassAttr);\n\n    } else {\n      // add class attribute to the body tag\n      newBodyTag = bodyTag.replace('>', ' class=\"' + platformClass + ' ' + cordovaClass + '\">');\n    }\n\n    html = html.replace(bodyTag, newBodyTag);\n\n    fs.writeFileSync(indexPath, html, 'utf8');\n\n    process.stdout.write('add to body class: ' + platformClass + '\\n');\n  } catch(e) {\n    process.stdout.write(e);\n  }\n}\n\nfunction findBodyTag(html) {\n  // get the body tag\n  try{\n    return html.match(/<body(?=[\\s>])(.*?)>/gi)[0];\n  }catch(e){}\n}\n\nfunction findClassAttr(bodyTag) {\n  // get the body tag's class attribute\n  try{\n    return bodyTag.match(/ class=[\"|'](.*?)[\"|']/gi)[0];\n  }catch(e){}\n}\n\nif (rootdir) {\n\n  // go through each of the platform directories that have been prepared\n  var platforms = (process.env.CORDOVA_PLATFORMS ? process.env.CORDOVA_PLATFORMS.split(',') : []);\n\n  for(var x=0; x<platforms.length; x++) {\n    // open up the index.html file at the www root\n    try {\n      var platform = platforms[x].trim().toLowerCase();\n      var indexPath;\n\n      if(platform == 'android') {\n        indexPath = path.join('platforms', platform, 'assets', 'www', 'index.html');\n      } else {\n        indexPath = path.join('platforms', platform, 'www', 'index.html');\n      }\n\n      if(fs.existsSync(indexPath)) {\n        addPlatformBodyTag(indexPath, platform);\n      }\n\n    } catch(e) {\n      process.stdout.write(e);\n    }\n  }\n\n}\n"
  },
  {
    "path": "examples/ionic/ionic.project",
    "content": "{\n  \"name\": \"satellizer-ionic\",\n  \"app_id\": \"\"\n}"
  },
  {
    "path": "examples/ionic/package.json",
    "content": "{\n  \"name\": \"satellizer-ionic-example\",\n  \"version\": \"1.0.0\",\n  \"dependencies\": {\n    \"gulp\": \"^3.9.1\",\n    \"gulp-sass\": \"^2.3.2\",\n    \"gulp-concat\": \"^2.6.0\",\n    \"gulp-minify-css\": \"^1.2.4\",\n    \"gulp-rename\": \"^1.2.2\"\n  },\n  \"devDependencies\": {\n    \"bower\": \"^1.7.9\",\n    \"gulp-util\": \"^3.0.7\",\n    \"shelljs\": \"^0.7.3\"\n  },\n  \"cordovaPlugins\": [\n    \"cordova-plugin-device\",\n    \"cordova-plugin-console\",\n    \"cordova-plugin-whitelist\",\n    \"cordova-plugin-splashscreen\",\n    \"cordova-plugin-statusbar\"\n  ],\n  \"cordovaPlatforms\": [\n    \"android\",\n    \"ios\"\n  ]\n}\n"
  },
  {
    "path": "examples/ionic/scss/ionic.app.scss",
    "content": "/*\nTo customize the look and feel of Ionic, you can override the variables\nin ionic's _variables.scss file.\n\nFor example, you might change some of the default colors:\n\n$light:                           #fff !default;\n$stable:                          #f8f8f8 !default;\n$positive:                        #387ef5 !default;\n$calm:                            #11c1f3 !default;\n$balanced:                        #33cd5f !default;\n$energized:                       #ffc900 !default;\n$assertive:                       #ef473a !default;\n$royal:                           #886aea !default;\n$dark:                            #444 !default;\n*/\n\n// The path for our ionicons font files, relative to the built CSS in www/css\n$ionicons-font-path: \"../vendor/ionic/fonts\" !default;\n\n// Include all of Ionic\n@import \"www/vendor/ionic/scss/ionic\";\n\n"
  },
  {
    "path": "examples/ionic/www/css/style.css",
    "content": "/* Empty. Add your own CSS if you like */\n"
  },
  {
    "path": "examples/ionic/www/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width\">\n    <title></title>\n\n    <link href=\"lib/ionic/css/ionic.css\" rel=\"stylesheet\">\n    <link href=\"css/style.css\" rel=\"stylesheet\">\n\n    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above\n    <link href=\"css/ionic.app.css\" rel=\"stylesheet\">\n    -->\n\n    <!-- ionic/angularjs js -->\n    <script src=\"lib/ionic/js/ionic.bundle.js\"></script>\n\n    <!-- satellizer -->\n    <script src=\"lib/satellizer/dist/satellizer.js\"></script>\n\n    <!-- cordova script (this will be a 404 during development) -->\n    <script src=\"cordova.js\"></script>\n\n    <!-- your app's js -->\n    <script src=\"js/app.js\"></script>\n    <script src=\"js/controllers.js\"></script>\n  </head>\n\n  <body ng-app=\"starter\">\n    <ion-nav-view></ion-nav-view>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/ionic/www/js/app.js",
    "content": "angular.module('starter', ['ionic', 'satellizer', 'starter.controllers'])\n  .config(function ($stateProvider, $urlRouterProvider) {\n    $stateProvider\n      .state('app', {\n        abstract: true,\n        templateUrl: 'templates/menu.html',\n        controller: 'AppCtrl'\n      })\n      .state('app.home', {\n        url: '/',\n        views: {\n          'menuContent': {\n            templateUrl: 'templates/home.html',\n            controller: 'HomeCtrl'\n          }\n        }\n      });\n\n    $urlRouterProvider.otherwise('/');\n  })\n  .config(function($authProvider) {\n    var commonConfig = {\n      popupOptions: {\n        location: 'no',\n        toolbar: 'yes',\n        width: window.screen.width,\n        height: window.screen.height\n      }\n    };\n\n    if (ionic.Platform.isIOS() || ionic.Platform.isAndroid()) {\n      commonConfig.redirectUri = 'http://localhost/';\n    }\n\n    $authProvider.facebook(angular.extend({}, commonConfig, {\n      clientId: 'YOUR_FACEBOOK_APP_ID',\n      url: 'http://localhost:3000/auth/facebook'\n    }));\n\n    $authProvider.twitter(angular.extend({}, commonConfig, {\n      url: 'http://localhost:3000/auth/twitter'\n    }));\n\n    $authProvider.google(angular.extend({}, commonConfig, {\n      clientId: 'YOUR_GOOGLE_CLIENT_ID',\n      url: 'http://localhost:3000/auth/google'\n    }));\n  })\n  .run(function ($ionicPlatform) {\n    $ionicPlatform.ready(function () {\n      if (window.cordova && window.cordova.plugins.Keyboard) {\n        cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);\n      }\n      if (window.StatusBar) {\n        StatusBar.styleDefault();\n      }\n    });\n  });\n"
  },
  {
    "path": "examples/ionic/www/js/controllers.js",
    "content": "angular.module('starter.controllers', [])\n  .controller('AppCtrl', function($scope, $ionicModal, $timeout) {\n  })\n  .controller('HomeCtrl', function($scope, $ionicPopup, $auth) {\n\n    $scope.authenticate = function(provider) {\n      $auth.authenticate(provider)\n        .then(function() {\n          $ionicPopup.alert({\n            title: 'Success',\n            content: 'You have successfully logged in!'\n          })\n        })\n        .catch(function(error) {\n          $ionicPopup.alert({\n            title: 'Error',\n            content: error.message || (error.data && error.data.message) || error\n          });\n        });\n    };\n\n\n    $scope.logout = function() {\n      $auth.logout();\n    };\n\n    $scope.isAuthenticated = function() {\n      return $auth.isAuthenticated();\n    };\n  });"
  },
  {
    "path": "examples/ionic/www/lib/ionic/css/ionic.css",
    "content": "/*!\n * Copyright 2014 Drifty Co.\n * http://drifty.com/\n *\n * Ionic, v1.0.0\n * A powerful HTML5 mobile app framework.\n * http://ionicframework.com/\n *\n * By @maxlynch, @benjsperry, @adamdbradley <3\n *\n * Licensed under the MIT license. Please see LICENSE for more information.\n *\n */\n/*!\n  Ionicons, v2.0.1\n  Created by Ben Sperry for the Ionic Framework, http://ionicons.com/\n  https://twitter.com/benjsperry  https://twitter.com/ionicframework\n  MIT License: https://github.com/driftyco/ionicons\n\n  Android-style icons originally built by Google’s\n  Material Design Icons: https://github.com/google/material-design-icons\n  used under CC BY http://creativecommons.org/licenses/by/4.0/\n  Modified icons to fit ionicon’s grid from original.\n*/\n@font-face {\n  font-family: \"Ionicons\";\n  src: url(\"../fonts/ionicons.eot?v=2.0.1\");\n  src: url(\"../fonts/ionicons.eot?v=2.0.1#iefix\") format(\"embedded-opentype\"), url(\"../fonts/ionicons.ttf?v=2.0.1\") format(\"truetype\"), url(\"../fonts/ionicons.woff?v=2.0.1\") format(\"woff\"), url(\"../fonts/ionicons.woff\") format(\"woff\"), url(\"../fonts/ionicons.svg?v=2.0.1#Ionicons\") format(\"svg\");\n  font-weight: normal;\n  font-style: normal; }\n\n.ion, .ionicons, .ion-alert:before, .ion-alert-circled:before, .ion-android-add:before, .ion-android-add-circle:before, .ion-android-alarm-clock:before, .ion-android-alert:before, .ion-android-apps:before, .ion-android-archive:before, .ion-android-arrow-back:before, .ion-android-arrow-down:before, .ion-android-arrow-dropdown:before, .ion-android-arrow-dropdown-circle:before, .ion-android-arrow-dropleft:before, .ion-android-arrow-dropleft-circle:before, .ion-android-arrow-dropright:before, .ion-android-arrow-dropright-circle:before, .ion-android-arrow-dropup:before, .ion-android-arrow-dropup-circle:before, .ion-android-arrow-forward:before, .ion-android-arrow-up:before, .ion-android-attach:before, .ion-android-bar:before, .ion-android-bicycle:before, .ion-android-boat:before, .ion-android-bookmark:before, .ion-android-bulb:before, .ion-android-bus:before, .ion-android-calendar:before, .ion-android-call:before, .ion-android-camera:before, .ion-android-cancel:before, .ion-android-car:before, .ion-android-cart:before, .ion-android-chat:before, .ion-android-checkbox:before, .ion-android-checkbox-blank:before, .ion-android-checkbox-outline:before, .ion-android-checkbox-outline-blank:before, .ion-android-checkmark-circle:before, .ion-android-clipboard:before, .ion-android-close:before, .ion-android-cloud:before, .ion-android-cloud-circle:before, .ion-android-cloud-done:before, .ion-android-cloud-outline:before, .ion-android-color-palette:before, .ion-android-compass:before, .ion-android-contact:before, .ion-android-contacts:before, .ion-android-contract:before, .ion-android-create:before, .ion-android-delete:before, .ion-android-desktop:before, .ion-android-document:before, .ion-android-done:before, .ion-android-done-all:before, .ion-android-download:before, .ion-android-drafts:before, .ion-android-exit:before, .ion-android-expand:before, .ion-android-favorite:before, .ion-android-favorite-outline:before, .ion-android-film:before, .ion-android-folder:before, .ion-android-folder-open:before, .ion-android-funnel:before, .ion-android-globe:before, .ion-android-hand:before, .ion-android-hangout:before, .ion-android-happy:before, .ion-android-home:before, .ion-android-image:before, .ion-android-laptop:before, .ion-android-list:before, .ion-android-locate:before, .ion-android-lock:before, .ion-android-mail:before, .ion-android-map:before, .ion-android-menu:before, .ion-android-microphone:before, .ion-android-microphone-off:before, .ion-android-more-horizontal:before, .ion-android-more-vertical:before, .ion-android-navigate:before, .ion-android-notifications:before, .ion-android-notifications-none:before, .ion-android-notifications-off:before, .ion-android-open:before, .ion-android-options:before, .ion-android-people:before, .ion-android-person:before, .ion-android-person-add:before, .ion-android-phone-landscape:before, .ion-android-phone-portrait:before, .ion-android-pin:before, .ion-android-plane:before, .ion-android-playstore:before, .ion-android-print:before, .ion-android-radio-button-off:before, .ion-android-radio-button-on:before, .ion-android-refresh:before, .ion-android-remove:before, .ion-android-remove-circle:before, .ion-android-restaurant:before, .ion-android-sad:before, .ion-android-search:before, .ion-android-send:before, .ion-android-settings:before, .ion-android-share:before, .ion-android-share-alt:before, .ion-android-star:before, .ion-android-star-half:before, .ion-android-star-outline:before, .ion-android-stopwatch:before, .ion-android-subway:before, .ion-android-sunny:before, .ion-android-sync:before, .ion-android-textsms:before, .ion-android-time:before, .ion-android-train:before, .ion-android-unlock:before, .ion-android-upload:before, .ion-android-volume-down:before, .ion-android-volume-mute:before, .ion-android-volume-off:before, .ion-android-volume-up:before, .ion-android-walk:before, .ion-android-warning:before, .ion-android-watch:before, .ion-android-wifi:before, .ion-aperture:before, .ion-archive:before, .ion-arrow-down-a:before, .ion-arrow-down-b:before, .ion-arrow-down-c:before, .ion-arrow-expand:before, .ion-arrow-graph-down-left:before, .ion-arrow-graph-down-right:before, .ion-arrow-graph-up-left:before, .ion-arrow-graph-up-right:before, .ion-arrow-left-a:before, .ion-arrow-left-b:before, .ion-arrow-left-c:before, .ion-arrow-move:before, .ion-arrow-resize:before, .ion-arrow-return-left:before, .ion-arrow-return-right:before, .ion-arrow-right-a:before, .ion-arrow-right-b:before, .ion-arrow-right-c:before, .ion-arrow-shrink:before, .ion-arrow-swap:before, .ion-arrow-up-a:before, .ion-arrow-up-b:before, .ion-arrow-up-c:before, .ion-asterisk:before, .ion-at:before, .ion-backspace:before, .ion-backspace-outline:before, .ion-bag:before, .ion-battery-charging:before, .ion-battery-empty:before, .ion-battery-full:before, .ion-battery-half:before, .ion-battery-low:before, .ion-beaker:before, .ion-beer:before, .ion-bluetooth:before, .ion-bonfire:before, .ion-bookmark:before, .ion-bowtie:before, .ion-briefcase:before, .ion-bug:before, .ion-calculator:before, .ion-calendar:before, .ion-camera:before, .ion-card:before, .ion-cash:before, .ion-chatbox:before, .ion-chatbox-working:before, .ion-chatboxes:before, .ion-chatbubble:before, .ion-chatbubble-working:before, .ion-chatbubbles:before, .ion-checkmark:before, .ion-checkmark-circled:before, .ion-checkmark-round:before, .ion-chevron-down:before, .ion-chevron-left:before, .ion-chevron-right:before, .ion-chevron-up:before, .ion-clipboard:before, .ion-clock:before, .ion-close:before, .ion-close-circled:before, .ion-close-round:before, .ion-closed-captioning:before, .ion-cloud:before, .ion-code:before, .ion-code-download:before, .ion-code-working:before, .ion-coffee:before, .ion-compass:before, .ion-compose:before, .ion-connection-bars:before, .ion-contrast:before, .ion-crop:before, .ion-cube:before, .ion-disc:before, .ion-document:before, .ion-document-text:before, .ion-drag:before, .ion-earth:before, .ion-easel:before, .ion-edit:before, .ion-egg:before, .ion-eject:before, .ion-email:before, .ion-email-unread:before, .ion-erlenmeyer-flask:before, .ion-erlenmeyer-flask-bubbles:before, .ion-eye:before, .ion-eye-disabled:before, .ion-female:before, .ion-filing:before, .ion-film-marker:before, .ion-fireball:before, .ion-flag:before, .ion-flame:before, .ion-flash:before, .ion-flash-off:before, .ion-folder:before, .ion-fork:before, .ion-fork-repo:before, .ion-forward:before, .ion-funnel:before, .ion-gear-a:before, .ion-gear-b:before, .ion-grid:before, .ion-hammer:before, .ion-happy:before, .ion-happy-outline:before, .ion-headphone:before, .ion-heart:before, .ion-heart-broken:before, .ion-help:before, .ion-help-buoy:before, .ion-help-circled:before, .ion-home:before, .ion-icecream:before, .ion-image:before, .ion-images:before, .ion-information:before, .ion-information-circled:before, .ion-ionic:before, .ion-ios-alarm:before, .ion-ios-alarm-outline:before, .ion-ios-albums:before, .ion-ios-albums-outline:before, .ion-ios-americanfootball:before, .ion-ios-americanfootball-outline:before, .ion-ios-analytics:before, .ion-ios-analytics-outline:before, .ion-ios-arrow-back:before, .ion-ios-arrow-down:before, .ion-ios-arrow-forward:before, .ion-ios-arrow-left:before, .ion-ios-arrow-right:before, .ion-ios-arrow-thin-down:before, .ion-ios-arrow-thin-left:before, .ion-ios-arrow-thin-right:before, .ion-ios-arrow-thin-up:before, .ion-ios-arrow-up:before, .ion-ios-at:before, .ion-ios-at-outline:before, .ion-ios-barcode:before, .ion-ios-barcode-outline:before, .ion-ios-baseball:before, .ion-ios-baseball-outline:before, .ion-ios-basketball:before, .ion-ios-basketball-outline:before, .ion-ios-bell:before, .ion-ios-bell-outline:before, .ion-ios-body:before, .ion-ios-body-outline:before, .ion-ios-bolt:before, .ion-ios-bolt-outline:before, .ion-ios-book:before, .ion-ios-book-outline:before, .ion-ios-bookmarks:before, .ion-ios-bookmarks-outline:before, .ion-ios-box:before, .ion-ios-box-outline:before, .ion-ios-briefcase:before, .ion-ios-briefcase-outline:before, .ion-ios-browsers:before, .ion-ios-browsers-outline:before, .ion-ios-calculator:before, .ion-ios-calculator-outline:before, .ion-ios-calendar:before, .ion-ios-calendar-outline:before, .ion-ios-camera:before, .ion-ios-camera-outline:before, .ion-ios-cart:before, .ion-ios-cart-outline:before, .ion-ios-chatboxes:before, .ion-ios-chatboxes-outline:before, .ion-ios-chatbubble:before, .ion-ios-chatbubble-outline:before, .ion-ios-checkmark:before, .ion-ios-checkmark-empty:before, .ion-ios-checkmark-outline:before, .ion-ios-circle-filled:before, .ion-ios-circle-outline:before, .ion-ios-clock:before, .ion-ios-clock-outline:before, .ion-ios-close:before, .ion-ios-close-empty:before, .ion-ios-close-outline:before, .ion-ios-cloud:before, .ion-ios-cloud-download:before, .ion-ios-cloud-download-outline:before, .ion-ios-cloud-outline:before, .ion-ios-cloud-upload:before, .ion-ios-cloud-upload-outline:before, .ion-ios-cloudy:before, .ion-ios-cloudy-night:before, .ion-ios-cloudy-night-outline:before, .ion-ios-cloudy-outline:before, .ion-ios-cog:before, .ion-ios-cog-outline:before, .ion-ios-color-filter:before, .ion-ios-color-filter-outline:before, .ion-ios-color-wand:before, .ion-ios-color-wand-outline:before, .ion-ios-compose:before, .ion-ios-compose-outline:before, .ion-ios-contact:before, .ion-ios-contact-outline:before, .ion-ios-copy:before, .ion-ios-copy-outline:before, .ion-ios-crop:before, .ion-ios-crop-strong:before, .ion-ios-download:before, .ion-ios-download-outline:before, .ion-ios-drag:before, .ion-ios-email:before, .ion-ios-email-outline:before, .ion-ios-eye:before, .ion-ios-eye-outline:before, .ion-ios-fastforward:before, .ion-ios-fastforward-outline:before, .ion-ios-filing:before, .ion-ios-filing-outline:before, .ion-ios-film:before, .ion-ios-film-outline:before, .ion-ios-flag:before, .ion-ios-flag-outline:before, .ion-ios-flame:before, .ion-ios-flame-outline:before, .ion-ios-flask:before, .ion-ios-flask-outline:before, .ion-ios-flower:before, .ion-ios-flower-outline:before, .ion-ios-folder:before, .ion-ios-folder-outline:before, .ion-ios-football:before, .ion-ios-football-outline:before, .ion-ios-game-controller-a:before, .ion-ios-game-controller-a-outline:before, .ion-ios-game-controller-b:before, .ion-ios-game-controller-b-outline:before, .ion-ios-gear:before, .ion-ios-gear-outline:before, .ion-ios-glasses:before, .ion-ios-glasses-outline:before, .ion-ios-grid-view:before, .ion-ios-grid-view-outline:before, .ion-ios-heart:before, .ion-ios-heart-outline:before, .ion-ios-help:before, .ion-ios-help-empty:before, .ion-ios-help-outline:before, .ion-ios-home:before, .ion-ios-home-outline:before, .ion-ios-infinite:before, .ion-ios-infinite-outline:before, .ion-ios-information:before, .ion-ios-information-empty:before, .ion-ios-information-outline:before, .ion-ios-ionic-outline:before, .ion-ios-keypad:before, .ion-ios-keypad-outline:before, .ion-ios-lightbulb:before, .ion-ios-lightbulb-outline:before, .ion-ios-list:before, .ion-ios-list-outline:before, .ion-ios-location:before, .ion-ios-location-outline:before, .ion-ios-locked:before, .ion-ios-locked-outline:before, .ion-ios-loop:before, .ion-ios-loop-strong:before, .ion-ios-medical:before, .ion-ios-medical-outline:before, .ion-ios-medkit:before, .ion-ios-medkit-outline:before, .ion-ios-mic:before, .ion-ios-mic-off:before, .ion-ios-mic-outline:before, .ion-ios-minus:before, .ion-ios-minus-empty:before, .ion-ios-minus-outline:before, .ion-ios-monitor:before, .ion-ios-monitor-outline:before, .ion-ios-moon:before, .ion-ios-moon-outline:before, .ion-ios-more:before, .ion-ios-more-outline:before, .ion-ios-musical-note:before, .ion-ios-musical-notes:before, .ion-ios-navigate:before, .ion-ios-navigate-outline:before, .ion-ios-nutrition:before, .ion-ios-nutrition-outline:before, .ion-ios-paper:before, .ion-ios-paper-outline:before, .ion-ios-paperplane:before, .ion-ios-paperplane-outline:before, .ion-ios-partlysunny:before, .ion-ios-partlysunny-outline:before, .ion-ios-pause:before, .ion-ios-pause-outline:before, .ion-ios-paw:before, .ion-ios-paw-outline:before, .ion-ios-people:before, .ion-ios-people-outline:before, .ion-ios-person:before, .ion-ios-person-outline:before, .ion-ios-personadd:before, .ion-ios-personadd-outline:before, .ion-ios-photos:before, .ion-ios-photos-outline:before, .ion-ios-pie:before, .ion-ios-pie-outline:before, .ion-ios-pint:before, .ion-ios-pint-outline:before, .ion-ios-play:before, .ion-ios-play-outline:before, .ion-ios-plus:before, .ion-ios-plus-empty:before, .ion-ios-plus-outline:before, .ion-ios-pricetag:before, .ion-ios-pricetag-outline:before, .ion-ios-pricetags:before, .ion-ios-pricetags-outline:before, .ion-ios-printer:before, .ion-ios-printer-outline:before, .ion-ios-pulse:before, .ion-ios-pulse-strong:before, .ion-ios-rainy:before, .ion-ios-rainy-outline:before, .ion-ios-recording:before, .ion-ios-recording-outline:before, .ion-ios-redo:before, .ion-ios-redo-outline:before, .ion-ios-refresh:before, .ion-ios-refresh-empty:before, .ion-ios-refresh-outline:before, .ion-ios-reload:before, .ion-ios-reverse-camera:before, .ion-ios-reverse-camera-outline:before, .ion-ios-rewind:before, .ion-ios-rewind-outline:before, .ion-ios-rose:before, .ion-ios-rose-outline:before, .ion-ios-search:before, .ion-ios-search-strong:before, .ion-ios-settings:before, .ion-ios-settings-strong:before, .ion-ios-shuffle:before, .ion-ios-shuffle-strong:before, .ion-ios-skipbackward:before, .ion-ios-skipbackward-outline:before, .ion-ios-skipforward:before, .ion-ios-skipforward-outline:before, .ion-ios-snowy:before, .ion-ios-speedometer:before, .ion-ios-speedometer-outline:before, .ion-ios-star:before, .ion-ios-star-half:before, .ion-ios-star-outline:before, .ion-ios-stopwatch:before, .ion-ios-stopwatch-outline:before, .ion-ios-sunny:before, .ion-ios-sunny-outline:before, .ion-ios-telephone:before, .ion-ios-telephone-outline:before, .ion-ios-tennisball:before, .ion-ios-tennisball-outline:before, .ion-ios-thunderstorm:before, .ion-ios-thunderstorm-outline:before, .ion-ios-time:before, .ion-ios-time-outline:before, .ion-ios-timer:before, .ion-ios-timer-outline:before, .ion-ios-toggle:before, .ion-ios-toggle-outline:before, .ion-ios-trash:before, .ion-ios-trash-outline:before, .ion-ios-undo:before, .ion-ios-undo-outline:before, .ion-ios-unlocked:before, .ion-ios-unlocked-outline:before, .ion-ios-upload:before, .ion-ios-upload-outline:before, .ion-ios-videocam:before, .ion-ios-videocam-outline:before, .ion-ios-volume-high:before, .ion-ios-volume-low:before, .ion-ios-wineglass:before, .ion-ios-wineglass-outline:before, .ion-ios-world:before, .ion-ios-world-outline:before, .ion-ipad:before, .ion-iphone:before, .ion-ipod:before, .ion-jet:before, .ion-key:before, .ion-knife:before, .ion-laptop:before, .ion-leaf:before, .ion-levels:before, .ion-lightbulb:before, .ion-link:before, .ion-load-a:before, .ion-load-b:before, .ion-load-c:before, .ion-load-d:before, .ion-location:before, .ion-lock-combination:before, .ion-locked:before, .ion-log-in:before, .ion-log-out:before, .ion-loop:before, .ion-magnet:before, .ion-male:before, .ion-man:before, .ion-map:before, .ion-medkit:before, .ion-merge:before, .ion-mic-a:before, .ion-mic-b:before, .ion-mic-c:before, .ion-minus:before, .ion-minus-circled:before, .ion-minus-round:before, .ion-model-s:before, .ion-monitor:before, .ion-more:before, .ion-mouse:before, .ion-music-note:before, .ion-navicon:before, .ion-navicon-round:before, .ion-navigate:before, .ion-network:before, .ion-no-smoking:before, .ion-nuclear:before, .ion-outlet:before, .ion-paintbrush:before, .ion-paintbucket:before, .ion-paper-airplane:before, .ion-paperclip:before, .ion-pause:before, .ion-person:before, .ion-person-add:before, .ion-person-stalker:before, .ion-pie-graph:before, .ion-pin:before, .ion-pinpoint:before, .ion-pizza:before, .ion-plane:before, .ion-planet:before, .ion-play:before, .ion-playstation:before, .ion-plus:before, .ion-plus-circled:before, .ion-plus-round:before, .ion-podium:before, .ion-pound:before, .ion-power:before, .ion-pricetag:before, .ion-pricetags:before, .ion-printer:before, .ion-pull-request:before, .ion-qr-scanner:before, .ion-quote:before, .ion-radio-waves:before, .ion-record:before, .ion-refresh:before, .ion-reply:before, .ion-reply-all:before, .ion-ribbon-a:before, .ion-ribbon-b:before, .ion-sad:before, .ion-sad-outline:before, .ion-scissors:before, .ion-search:before, .ion-settings:before, .ion-share:before, .ion-shuffle:before, .ion-skip-backward:before, .ion-skip-forward:before, .ion-social-android:before, .ion-social-android-outline:before, .ion-social-angular:before, .ion-social-angular-outline:before, .ion-social-apple:before, .ion-social-apple-outline:before, .ion-social-bitcoin:before, .ion-social-bitcoin-outline:before, .ion-social-buffer:before, .ion-social-buffer-outline:before, .ion-social-chrome:before, .ion-social-chrome-outline:before, .ion-social-codepen:before, .ion-social-codepen-outline:before, .ion-social-css3:before, .ion-social-css3-outline:before, .ion-social-designernews:before, .ion-social-designernews-outline:before, .ion-social-dribbble:before, .ion-social-dribbble-outline:before, .ion-social-dropbox:before, .ion-social-dropbox-outline:before, .ion-social-euro:before, .ion-social-euro-outline:before, .ion-social-facebook:before, .ion-social-facebook-outline:before, .ion-social-foursquare:before, .ion-social-foursquare-outline:before, .ion-social-freebsd-devil:before, .ion-social-github:before, .ion-social-github-outline:before, .ion-social-google:before, .ion-social-google-outline:before, .ion-social-googleplus:before, .ion-social-googleplus-outline:before, .ion-social-hackernews:before, .ion-social-hackernews-outline:before, .ion-social-html5:before, .ion-social-html5-outline:before, .ion-social-instagram:before, .ion-social-instagram-outline:before, .ion-social-javascript:before, .ion-social-javascript-outline:before, .ion-social-linkedin:before, .ion-social-linkedin-outline:before, .ion-social-markdown:before, .ion-social-nodejs:before, .ion-social-octocat:before, .ion-social-pinterest:before, .ion-social-pinterest-outline:before, .ion-social-python:before, .ion-social-reddit:before, .ion-social-reddit-outline:before, .ion-social-rss:before, .ion-social-rss-outline:before, .ion-social-sass:before, .ion-social-skype:before, .ion-social-skype-outline:before, .ion-social-snapchat:before, .ion-social-snapchat-outline:before, .ion-social-tumblr:before, .ion-social-tumblr-outline:before, .ion-social-tux:before, .ion-social-twitch:before, .ion-social-twitch-outline:before, .ion-social-twitter:before, .ion-social-twitter-outline:before, .ion-social-usd:before, .ion-social-usd-outline:before, .ion-social-vimeo:before, .ion-social-vimeo-outline:before, .ion-social-whatsapp:before, .ion-social-whatsapp-outline:before, .ion-social-windows:before, .ion-social-windows-outline:before, .ion-social-wordpress:before, .ion-social-wordpress-outline:before, .ion-social-yahoo:before, .ion-social-yahoo-outline:before, .ion-social-yen:before, .ion-social-yen-outline:before, .ion-social-youtube:before, .ion-social-youtube-outline:before, .ion-soup-can:before, .ion-soup-can-outline:before, .ion-speakerphone:before, .ion-speedometer:before, .ion-spoon:before, .ion-star:before, .ion-stats-bars:before, .ion-steam:before, .ion-stop:before, .ion-thermometer:before, .ion-thumbsdown:before, .ion-thumbsup:before, .ion-toggle:before, .ion-toggle-filled:before, .ion-transgender:before, .ion-trash-a:before, .ion-trash-b:before, .ion-trophy:before, .ion-tshirt:before, .ion-tshirt-outline:before, .ion-umbrella:before, .ion-university:before, .ion-unlocked:before, .ion-upload:before, .ion-usb:before, .ion-videocamera:before, .ion-volume-high:before, .ion-volume-low:before, .ion-volume-medium:before, .ion-volume-mute:before, .ion-wand:before, .ion-waterdrop:before, .ion-wifi:before, .ion-wineglass:before, .ion-woman:before, .ion-wrench:before, .ion-xbox:before {\n  display: inline-block;\n  font-family: \"Ionicons\";\n  speak: none;\n  font-style: normal;\n  font-weight: normal;\n  font-variant: normal;\n  text-transform: none;\n  text-rendering: auto;\n  line-height: 1;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale; }\n\n.ion-alert:before {\n  content: \"\\f101\"; }\n\n.ion-alert-circled:before {\n  content: \"\\f100\"; }\n\n.ion-android-add:before {\n  content: \"\\f2c7\"; }\n\n.ion-android-add-circle:before {\n  content: \"\\f359\"; }\n\n.ion-android-alarm-clock:before {\n  content: \"\\f35a\"; }\n\n.ion-android-alert:before {\n  content: \"\\f35b\"; }\n\n.ion-android-apps:before {\n  content: \"\\f35c\"; }\n\n.ion-android-archive:before {\n  content: \"\\f2c9\"; }\n\n.ion-android-arrow-back:before {\n  content: \"\\f2ca\"; }\n\n.ion-android-arrow-down:before {\n  content: \"\\f35d\"; }\n\n.ion-android-arrow-dropdown:before {\n  content: \"\\f35f\"; }\n\n.ion-android-arrow-dropdown-circle:before {\n  content: \"\\f35e\"; }\n\n.ion-android-arrow-dropleft:before {\n  content: \"\\f361\"; }\n\n.ion-android-arrow-dropleft-circle:before {\n  content: \"\\f360\"; }\n\n.ion-android-arrow-dropright:before {\n  content: \"\\f363\"; }\n\n.ion-android-arrow-dropright-circle:before {\n  content: \"\\f362\"; }\n\n.ion-android-arrow-dropup:before {\n  content: \"\\f365\"; }\n\n.ion-android-arrow-dropup-circle:before {\n  content: \"\\f364\"; }\n\n.ion-android-arrow-forward:before {\n  content: \"\\f30f\"; }\n\n.ion-android-arrow-up:before {\n  content: \"\\f366\"; }\n\n.ion-android-attach:before {\n  content: \"\\f367\"; }\n\n.ion-android-bar:before {\n  content: \"\\f368\"; }\n\n.ion-android-bicycle:before {\n  content: \"\\f369\"; }\n\n.ion-android-boat:before {\n  content: \"\\f36a\"; }\n\n.ion-android-bookmark:before {\n  content: \"\\f36b\"; }\n\n.ion-android-bulb:before {\n  content: \"\\f36c\"; }\n\n.ion-android-bus:before {\n  content: \"\\f36d\"; }\n\n.ion-android-calendar:before {\n  content: \"\\f2d1\"; }\n\n.ion-android-call:before {\n  content: \"\\f2d2\"; }\n\n.ion-android-camera:before {\n  content: \"\\f2d3\"; }\n\n.ion-android-cancel:before {\n  content: \"\\f36e\"; }\n\n.ion-android-car:before {\n  content: \"\\f36f\"; }\n\n.ion-android-cart:before {\n  content: \"\\f370\"; }\n\n.ion-android-chat:before {\n  content: \"\\f2d4\"; }\n\n.ion-android-checkbox:before {\n  content: \"\\f374\"; }\n\n.ion-android-checkbox-blank:before {\n  content: \"\\f371\"; }\n\n.ion-android-checkbox-outline:before {\n  content: \"\\f373\"; }\n\n.ion-android-checkbox-outline-blank:before {\n  content: \"\\f372\"; }\n\n.ion-android-checkmark-circle:before {\n  content: \"\\f375\"; }\n\n.ion-android-clipboard:before {\n  content: \"\\f376\"; }\n\n.ion-android-close:before {\n  content: \"\\f2d7\"; }\n\n.ion-android-cloud:before {\n  content: \"\\f37a\"; }\n\n.ion-android-cloud-circle:before {\n  content: \"\\f377\"; }\n\n.ion-android-cloud-done:before {\n  content: \"\\f378\"; }\n\n.ion-android-cloud-outline:before {\n  content: \"\\f379\"; }\n\n.ion-android-color-palette:before {\n  content: \"\\f37b\"; }\n\n.ion-android-compass:before {\n  content: \"\\f37c\"; }\n\n.ion-android-contact:before {\n  content: \"\\f2d8\"; }\n\n.ion-android-contacts:before {\n  content: \"\\f2d9\"; }\n\n.ion-android-contract:before {\n  content: \"\\f37d\"; }\n\n.ion-android-create:before {\n  content: \"\\f37e\"; }\n\n.ion-android-delete:before {\n  content: \"\\f37f\"; }\n\n.ion-android-desktop:before {\n  content: \"\\f380\"; }\n\n.ion-android-document:before {\n  content: \"\\f381\"; }\n\n.ion-android-done:before {\n  content: \"\\f383\"; }\n\n.ion-android-done-all:before {\n  content: \"\\f382\"; }\n\n.ion-android-download:before {\n  content: \"\\f2dd\"; }\n\n.ion-android-drafts:before {\n  content: \"\\f384\"; }\n\n.ion-android-exit:before {\n  content: \"\\f385\"; }\n\n.ion-android-expand:before {\n  content: \"\\f386\"; }\n\n.ion-android-favorite:before {\n  content: \"\\f388\"; }\n\n.ion-android-favorite-outline:before {\n  content: \"\\f387\"; }\n\n.ion-android-film:before {\n  content: \"\\f389\"; }\n\n.ion-android-folder:before {\n  content: \"\\f2e0\"; }\n\n.ion-android-folder-open:before {\n  content: \"\\f38a\"; }\n\n.ion-android-funnel:before {\n  content: \"\\f38b\"; }\n\n.ion-android-globe:before {\n  content: \"\\f38c\"; }\n\n.ion-android-hand:before {\n  content: \"\\f2e3\"; }\n\n.ion-android-hangout:before {\n  content: \"\\f38d\"; }\n\n.ion-android-happy:before {\n  content: \"\\f38e\"; }\n\n.ion-android-home:before {\n  content: \"\\f38f\"; }\n\n.ion-android-image:before {\n  content: \"\\f2e4\"; }\n\n.ion-android-laptop:before {\n  content: \"\\f390\"; }\n\n.ion-android-list:before {\n  content: \"\\f391\"; }\n\n.ion-android-locate:before {\n  content: \"\\f2e9\"; }\n\n.ion-android-lock:before {\n  content: \"\\f392\"; }\n\n.ion-android-mail:before {\n  content: \"\\f2eb\"; }\n\n.ion-android-map:before {\n  content: \"\\f393\"; }\n\n.ion-android-menu:before {\n  content: \"\\f394\"; }\n\n.ion-android-microphone:before {\n  content: \"\\f2ec\"; }\n\n.ion-android-microphone-off:before {\n  content: \"\\f395\"; }\n\n.ion-android-more-horizontal:before {\n  content: \"\\f396\"; }\n\n.ion-android-more-vertical:before {\n  content: \"\\f397\"; }\n\n.ion-android-navigate:before {\n  content: \"\\f398\"; }\n\n.ion-android-notifications:before {\n  content: \"\\f39b\"; }\n\n.ion-android-notifications-none:before {\n  content: \"\\f399\"; }\n\n.ion-android-notifications-off:before {\n  content: \"\\f39a\"; }\n\n.ion-android-open:before {\n  content: \"\\f39c\"; }\n\n.ion-android-options:before {\n  content: \"\\f39d\"; }\n\n.ion-android-people:before {\n  content: \"\\f39e\"; }\n\n.ion-android-person:before {\n  content: \"\\f3a0\"; }\n\n.ion-android-person-add:before {\n  content: \"\\f39f\"; }\n\n.ion-android-phone-landscape:before {\n  content: \"\\f3a1\"; }\n\n.ion-android-phone-portrait:before {\n  content: \"\\f3a2\"; }\n\n.ion-android-pin:before {\n  content: \"\\f3a3\"; }\n\n.ion-android-plane:before {\n  content: \"\\f3a4\"; }\n\n.ion-android-playstore:before {\n  content: \"\\f2f0\"; }\n\n.ion-android-print:before {\n  content: \"\\f3a5\"; }\n\n.ion-android-radio-button-off:before {\n  content: \"\\f3a6\"; }\n\n.ion-android-radio-button-on:before {\n  content: \"\\f3a7\"; }\n\n.ion-android-refresh:before {\n  content: \"\\f3a8\"; }\n\n.ion-android-remove:before {\n  content: \"\\f2f4\"; }\n\n.ion-android-remove-circle:before {\n  content: \"\\f3a9\"; }\n\n.ion-android-restaurant:before {\n  content: \"\\f3aa\"; }\n\n.ion-android-sad:before {\n  content: \"\\f3ab\"; }\n\n.ion-android-search:before {\n  content: \"\\f2f5\"; }\n\n.ion-android-send:before {\n  content: \"\\f2f6\"; }\n\n.ion-android-settings:before {\n  content: \"\\f2f7\"; }\n\n.ion-android-share:before {\n  content: \"\\f2f8\"; }\n\n.ion-android-share-alt:before {\n  content: \"\\f3ac\"; }\n\n.ion-android-star:before {\n  content: \"\\f2fc\"; }\n\n.ion-android-star-half:before {\n  content: \"\\f3ad\"; }\n\n.ion-android-star-outline:before {\n  content: \"\\f3ae\"; }\n\n.ion-android-stopwatch:before {\n  content: \"\\f2fd\"; }\n\n.ion-android-subway:before {\n  content: \"\\f3af\"; }\n\n.ion-android-sunny:before {\n  content: \"\\f3b0\"; }\n\n.ion-android-sync:before {\n  content: \"\\f3b1\"; }\n\n.ion-android-textsms:before {\n  content: \"\\f3b2\"; }\n\n.ion-android-time:before {\n  content: \"\\f3b3\"; }\n\n.ion-android-train:before {\n  content: \"\\f3b4\"; }\n\n.ion-android-unlock:before {\n  content: \"\\f3b5\"; }\n\n.ion-android-upload:before {\n  content: \"\\f3b6\"; }\n\n.ion-android-volume-down:before {\n  content: \"\\f3b7\"; }\n\n.ion-android-volume-mute:before {\n  content: \"\\f3b8\"; }\n\n.ion-android-volume-off:before {\n  content: \"\\f3b9\"; }\n\n.ion-android-volume-up:before {\n  content: \"\\f3ba\"; }\n\n.ion-android-walk:before {\n  content: \"\\f3bb\"; }\n\n.ion-android-warning:before {\n  content: \"\\f3bc\"; }\n\n.ion-android-watch:before {\n  content: \"\\f3bd\"; }\n\n.ion-android-wifi:before {\n  content: \"\\f305\"; }\n\n.ion-aperture:before {\n  content: \"\\f313\"; }\n\n.ion-archive:before {\n  content: \"\\f102\"; }\n\n.ion-arrow-down-a:before {\n  content: \"\\f103\"; }\n\n.ion-arrow-down-b:before {\n  content: \"\\f104\"; }\n\n.ion-arrow-down-c:before {\n  content: \"\\f105\"; }\n\n.ion-arrow-expand:before {\n  content: \"\\f25e\"; }\n\n.ion-arrow-graph-down-left:before {\n  content: \"\\f25f\"; }\n\n.ion-arrow-graph-down-right:before {\n  content: \"\\f260\"; }\n\n.ion-arrow-graph-up-left:before {\n  content: \"\\f261\"; }\n\n.ion-arrow-graph-up-right:before {\n  content: \"\\f262\"; }\n\n.ion-arrow-left-a:before {\n  content: \"\\f106\"; }\n\n.ion-arrow-left-b:before {\n  content: \"\\f107\"; }\n\n.ion-arrow-left-c:before {\n  content: \"\\f108\"; }\n\n.ion-arrow-move:before {\n  content: \"\\f263\"; }\n\n.ion-arrow-resize:before {\n  content: \"\\f264\"; }\n\n.ion-arrow-return-left:before {\n  content: \"\\f265\"; }\n\n.ion-arrow-return-right:before {\n  content: \"\\f266\"; }\n\n.ion-arrow-right-a:before {\n  content: \"\\f109\"; }\n\n.ion-arrow-right-b:before {\n  content: \"\\f10a\"; }\n\n.ion-arrow-right-c:before {\n  content: \"\\f10b\"; }\n\n.ion-arrow-shrink:before {\n  content: \"\\f267\"; }\n\n.ion-arrow-swap:before {\n  content: \"\\f268\"; }\n\n.ion-arrow-up-a:before {\n  content: \"\\f10c\"; }\n\n.ion-arrow-up-b:before {\n  content: \"\\f10d\"; }\n\n.ion-arrow-up-c:before {\n  content: \"\\f10e\"; }\n\n.ion-asterisk:before {\n  content: \"\\f314\"; }\n\n.ion-at:before {\n  content: \"\\f10f\"; }\n\n.ion-backspace:before {\n  content: \"\\f3bf\"; }\n\n.ion-backspace-outline:before {\n  content: \"\\f3be\"; }\n\n.ion-bag:before {\n  content: \"\\f110\"; }\n\n.ion-battery-charging:before {\n  content: \"\\f111\"; }\n\n.ion-battery-empty:before {\n  content: \"\\f112\"; }\n\n.ion-battery-full:before {\n  content: \"\\f113\"; }\n\n.ion-battery-half:before {\n  content: \"\\f114\"; }\n\n.ion-battery-low:before {\n  content: \"\\f115\"; }\n\n.ion-beaker:before {\n  content: \"\\f269\"; }\n\n.ion-beer:before {\n  content: \"\\f26a\"; }\n\n.ion-bluetooth:before {\n  content: \"\\f116\"; }\n\n.ion-bonfire:before {\n  content: \"\\f315\"; }\n\n.ion-bookmark:before {\n  content: \"\\f26b\"; }\n\n.ion-bowtie:before {\n  content: \"\\f3c0\"; }\n\n.ion-briefcase:before {\n  content: \"\\f26c\"; }\n\n.ion-bug:before {\n  content: \"\\f2be\"; }\n\n.ion-calculator:before {\n  content: \"\\f26d\"; }\n\n.ion-calendar:before {\n  content: \"\\f117\"; }\n\n.ion-camera:before {\n  content: \"\\f118\"; }\n\n.ion-card:before {\n  content: \"\\f119\"; }\n\n.ion-cash:before {\n  content: \"\\f316\"; }\n\n.ion-chatbox:before {\n  content: \"\\f11b\"; }\n\n.ion-chatbox-working:before {\n  content: \"\\f11a\"; }\n\n.ion-chatboxes:before {\n  content: \"\\f11c\"; }\n\n.ion-chatbubble:before {\n  content: \"\\f11e\"; }\n\n.ion-chatbubble-working:before {\n  content: \"\\f11d\"; }\n\n.ion-chatbubbles:before {\n  content: \"\\f11f\"; }\n\n.ion-checkmark:before {\n  content: \"\\f122\"; }\n\n.ion-checkmark-circled:before {\n  content: \"\\f120\"; }\n\n.ion-checkmark-round:before {\n  content: \"\\f121\"; }\n\n.ion-chevron-down:before {\n  content: \"\\f123\"; }\n\n.ion-chevron-left:before {\n  content: \"\\f124\"; }\n\n.ion-chevron-right:before {\n  content: \"\\f125\"; }\n\n.ion-chevron-up:before {\n  content: \"\\f126\"; }\n\n.ion-clipboard:before {\n  content: \"\\f127\"; }\n\n.ion-clock:before {\n  content: \"\\f26e\"; }\n\n.ion-close:before {\n  content: \"\\f12a\"; }\n\n.ion-close-circled:before {\n  content: \"\\f128\"; }\n\n.ion-close-round:before {\n  content: \"\\f129\"; }\n\n.ion-closed-captioning:before {\n  content: \"\\f317\"; }\n\n.ion-cloud:before {\n  content: \"\\f12b\"; }\n\n.ion-code:before {\n  content: \"\\f271\"; }\n\n.ion-code-download:before {\n  content: \"\\f26f\"; }\n\n.ion-code-working:before {\n  content: \"\\f270\"; }\n\n.ion-coffee:before {\n  content: \"\\f272\"; }\n\n.ion-compass:before {\n  content: \"\\f273\"; }\n\n.ion-compose:before {\n  content: \"\\f12c\"; }\n\n.ion-connection-bars:before {\n  content: \"\\f274\"; }\n\n.ion-contrast:before {\n  content: \"\\f275\"; }\n\n.ion-crop:before {\n  content: \"\\f3c1\"; }\n\n.ion-cube:before {\n  content: \"\\f318\"; }\n\n.ion-disc:before {\n  content: \"\\f12d\"; }\n\n.ion-document:before {\n  content: \"\\f12f\"; }\n\n.ion-document-text:before {\n  content: \"\\f12e\"; }\n\n.ion-drag:before {\n  content: \"\\f130\"; }\n\n.ion-earth:before {\n  content: \"\\f276\"; }\n\n.ion-easel:before {\n  content: \"\\f3c2\"; }\n\n.ion-edit:before {\n  content: \"\\f2bf\"; }\n\n.ion-egg:before {\n  content: \"\\f277\"; }\n\n.ion-eject:before {\n  content: \"\\f131\"; }\n\n.ion-email:before {\n  content: \"\\f132\"; }\n\n.ion-email-unread:before {\n  content: \"\\f3c3\"; }\n\n.ion-erlenmeyer-flask:before {\n  content: \"\\f3c5\"; }\n\n.ion-erlenmeyer-flask-bubbles:before {\n  content: \"\\f3c4\"; }\n\n.ion-eye:before {\n  content: \"\\f133\"; }\n\n.ion-eye-disabled:before {\n  content: \"\\f306\"; }\n\n.ion-female:before {\n  content: \"\\f278\"; }\n\n.ion-filing:before {\n  content: \"\\f134\"; }\n\n.ion-film-marker:before {\n  content: \"\\f135\"; }\n\n.ion-fireball:before {\n  content: \"\\f319\"; }\n\n.ion-flag:before {\n  content: \"\\f279\"; }\n\n.ion-flame:before {\n  content: \"\\f31a\"; }\n\n.ion-flash:before {\n  content: \"\\f137\"; }\n\n.ion-flash-off:before {\n  content: \"\\f136\"; }\n\n.ion-folder:before {\n  content: \"\\f139\"; }\n\n.ion-fork:before {\n  content: \"\\f27a\"; }\n\n.ion-fork-repo:before {\n  content: \"\\f2c0\"; }\n\n.ion-forward:before {\n  content: \"\\f13a\"; }\n\n.ion-funnel:before {\n  content: \"\\f31b\"; }\n\n.ion-gear-a:before {\n  content: \"\\f13d\"; }\n\n.ion-gear-b:before {\n  content: \"\\f13e\"; }\n\n.ion-grid:before {\n  content: \"\\f13f\"; }\n\n.ion-hammer:before {\n  content: \"\\f27b\"; }\n\n.ion-happy:before {\n  content: \"\\f31c\"; }\n\n.ion-happy-outline:before {\n  content: \"\\f3c6\"; }\n\n.ion-headphone:before {\n  content: \"\\f140\"; }\n\n.ion-heart:before {\n  content: \"\\f141\"; }\n\n.ion-heart-broken:before {\n  content: \"\\f31d\"; }\n\n.ion-help:before {\n  content: \"\\f143\"; }\n\n.ion-help-buoy:before {\n  content: \"\\f27c\"; }\n\n.ion-help-circled:before {\n  content: \"\\f142\"; }\n\n.ion-home:before {\n  content: \"\\f144\"; }\n\n.ion-icecream:before {\n  content: \"\\f27d\"; }\n\n.ion-image:before {\n  content: \"\\f147\"; }\n\n.ion-images:before {\n  content: \"\\f148\"; }\n\n.ion-information:before {\n  content: \"\\f14a\"; }\n\n.ion-information-circled:before {\n  content: \"\\f149\"; }\n\n.ion-ionic:before {\n  content: \"\\f14b\"; }\n\n.ion-ios-alarm:before {\n  content: \"\\f3c8\"; }\n\n.ion-ios-alarm-outline:before {\n  content: \"\\f3c7\"; }\n\n.ion-ios-albums:before {\n  content: \"\\f3ca\"; }\n\n.ion-ios-albums-outline:before {\n  content: \"\\f3c9\"; }\n\n.ion-ios-americanfootball:before {\n  content: \"\\f3cc\"; }\n\n.ion-ios-americanfootball-outline:before {\n  content: \"\\f3cb\"; }\n\n.ion-ios-analytics:before {\n  content: \"\\f3ce\"; }\n\n.ion-ios-analytics-outline:before {\n  content: \"\\f3cd\"; }\n\n.ion-ios-arrow-back:before {\n  content: \"\\f3cf\"; }\n\n.ion-ios-arrow-down:before {\n  content: \"\\f3d0\"; }\n\n.ion-ios-arrow-forward:before {\n  content: \"\\f3d1\"; }\n\n.ion-ios-arrow-left:before {\n  content: \"\\f3d2\"; }\n\n.ion-ios-arrow-right:before {\n  content: \"\\f3d3\"; }\n\n.ion-ios-arrow-thin-down:before {\n  content: \"\\f3d4\"; }\n\n.ion-ios-arrow-thin-left:before {\n  content: \"\\f3d5\"; }\n\n.ion-ios-arrow-thin-right:before {\n  content: \"\\f3d6\"; }\n\n.ion-ios-arrow-thin-up:before {\n  content: \"\\f3d7\"; }\n\n.ion-ios-arrow-up:before {\n  content: \"\\f3d8\"; }\n\n.ion-ios-at:before {\n  content: \"\\f3da\"; }\n\n.ion-ios-at-outline:before {\n  content: \"\\f3d9\"; }\n\n.ion-ios-barcode:before {\n  content: \"\\f3dc\"; }\n\n.ion-ios-barcode-outline:before {\n  content: \"\\f3db\"; }\n\n.ion-ios-baseball:before {\n  content: \"\\f3de\"; }\n\n.ion-ios-baseball-outline:before {\n  content: \"\\f3dd\"; }\n\n.ion-ios-basketball:before {\n  content: \"\\f3e0\"; }\n\n.ion-ios-basketball-outline:before {\n  content: \"\\f3df\"; }\n\n.ion-ios-bell:before {\n  content: \"\\f3e2\"; }\n\n.ion-ios-bell-outline:before {\n  content: \"\\f3e1\"; }\n\n.ion-ios-body:before {\n  content: \"\\f3e4\"; }\n\n.ion-ios-body-outline:before {\n  content: \"\\f3e3\"; }\n\n.ion-ios-bolt:before {\n  content: \"\\f3e6\"; }\n\n.ion-ios-bolt-outline:before {\n  content: \"\\f3e5\"; }\n\n.ion-ios-book:before {\n  content: \"\\f3e8\"; }\n\n.ion-ios-book-outline:before {\n  content: \"\\f3e7\"; }\n\n.ion-ios-bookmarks:before {\n  content: \"\\f3ea\"; }\n\n.ion-ios-bookmarks-outline:before {\n  content: \"\\f3e9\"; }\n\n.ion-ios-box:before {\n  content: \"\\f3ec\"; }\n\n.ion-ios-box-outline:before {\n  content: \"\\f3eb\"; }\n\n.ion-ios-briefcase:before {\n  content: \"\\f3ee\"; }\n\n.ion-ios-briefcase-outline:before {\n  content: \"\\f3ed\"; }\n\n.ion-ios-browsers:before {\n  content: \"\\f3f0\"; }\n\n.ion-ios-browsers-outline:before {\n  content: \"\\f3ef\"; }\n\n.ion-ios-calculator:before {\n  content: \"\\f3f2\"; }\n\n.ion-ios-calculator-outline:before {\n  content: \"\\f3f1\"; }\n\n.ion-ios-calendar:before {\n  content: \"\\f3f4\"; }\n\n.ion-ios-calendar-outline:before {\n  content: \"\\f3f3\"; }\n\n.ion-ios-camera:before {\n  content: \"\\f3f6\"; }\n\n.ion-ios-camera-outline:before {\n  content: \"\\f3f5\"; }\n\n.ion-ios-cart:before {\n  content: \"\\f3f8\"; }\n\n.ion-ios-cart-outline:before {\n  content: \"\\f3f7\"; }\n\n.ion-ios-chatboxes:before {\n  content: \"\\f3fa\"; }\n\n.ion-ios-chatboxes-outline:before {\n  content: \"\\f3f9\"; }\n\n.ion-ios-chatbubble:before {\n  content: \"\\f3fc\"; }\n\n.ion-ios-chatbubble-outline:before {\n  content: \"\\f3fb\"; }\n\n.ion-ios-checkmark:before {\n  content: \"\\f3ff\"; }\n\n.ion-ios-checkmark-empty:before {\n  content: \"\\f3fd\"; }\n\n.ion-ios-checkmark-outline:before {\n  content: \"\\f3fe\"; }\n\n.ion-ios-circle-filled:before {\n  content: \"\\f400\"; }\n\n.ion-ios-circle-outline:before {\n  content: \"\\f401\"; }\n\n.ion-ios-clock:before {\n  content: \"\\f403\"; }\n\n.ion-ios-clock-outline:before {\n  content: \"\\f402\"; }\n\n.ion-ios-close:before {\n  content: \"\\f406\"; }\n\n.ion-ios-close-empty:before {\n  content: \"\\f404\"; }\n\n.ion-ios-close-outline:before {\n  content: \"\\f405\"; }\n\n.ion-ios-cloud:before {\n  content: \"\\f40c\"; }\n\n.ion-ios-cloud-download:before {\n  content: \"\\f408\"; }\n\n.ion-ios-cloud-download-outline:before {\n  content: \"\\f407\"; }\n\n.ion-ios-cloud-outline:before {\n  content: \"\\f409\"; }\n\n.ion-ios-cloud-upload:before {\n  content: \"\\f40b\"; }\n\n.ion-ios-cloud-upload-outline:before {\n  content: \"\\f40a\"; }\n\n.ion-ios-cloudy:before {\n  content: \"\\f410\"; }\n\n.ion-ios-cloudy-night:before {\n  content: \"\\f40e\"; }\n\n.ion-ios-cloudy-night-outline:before {\n  content: \"\\f40d\"; }\n\n.ion-ios-cloudy-outline:before {\n  content: \"\\f40f\"; }\n\n.ion-ios-cog:before {\n  content: \"\\f412\"; }\n\n.ion-ios-cog-outline:before {\n  content: \"\\f411\"; }\n\n.ion-ios-color-filter:before {\n  content: \"\\f414\"; }\n\n.ion-ios-color-filter-outline:before {\n  content: \"\\f413\"; }\n\n.ion-ios-color-wand:before {\n  content: \"\\f416\"; }\n\n.ion-ios-color-wand-outline:before {\n  content: \"\\f415\"; }\n\n.ion-ios-compose:before {\n  content: \"\\f418\"; }\n\n.ion-ios-compose-outline:before {\n  content: \"\\f417\"; }\n\n.ion-ios-contact:before {\n  content: \"\\f41a\"; }\n\n.ion-ios-contact-outline:before {\n  content: \"\\f419\"; }\n\n.ion-ios-copy:before {\n  content: \"\\f41c\"; }\n\n.ion-ios-copy-outline:before {\n  content: \"\\f41b\"; }\n\n.ion-ios-crop:before {\n  content: \"\\f41e\"; }\n\n.ion-ios-crop-strong:before {\n  content: \"\\f41d\"; }\n\n.ion-ios-download:before {\n  content: \"\\f420\"; }\n\n.ion-ios-download-outline:before {\n  content: \"\\f41f\"; }\n\n.ion-ios-drag:before {\n  content: \"\\f421\"; }\n\n.ion-ios-email:before {\n  content: \"\\f423\"; }\n\n.ion-ios-email-outline:before {\n  content: \"\\f422\"; }\n\n.ion-ios-eye:before {\n  content: \"\\f425\"; }\n\n.ion-ios-eye-outline:before {\n  content: \"\\f424\"; }\n\n.ion-ios-fastforward:before {\n  content: \"\\f427\"; }\n\n.ion-ios-fastforward-outline:before {\n  content: \"\\f426\"; }\n\n.ion-ios-filing:before {\n  content: \"\\f429\"; }\n\n.ion-ios-filing-outline:before {\n  content: \"\\f428\"; }\n\n.ion-ios-film:before {\n  content: \"\\f42b\"; }\n\n.ion-ios-film-outline:before {\n  content: \"\\f42a\"; }\n\n.ion-ios-flag:before {\n  content: \"\\f42d\"; }\n\n.ion-ios-flag-outline:before {\n  content: \"\\f42c\"; }\n\n.ion-ios-flame:before {\n  content: \"\\f42f\"; }\n\n.ion-ios-flame-outline:before {\n  content: \"\\f42e\"; }\n\n.ion-ios-flask:before {\n  content: \"\\f431\"; }\n\n.ion-ios-flask-outline:before {\n  content: \"\\f430\"; }\n\n.ion-ios-flower:before {\n  content: \"\\f433\"; }\n\n.ion-ios-flower-outline:before {\n  content: \"\\f432\"; }\n\n.ion-ios-folder:before {\n  content: \"\\f435\"; }\n\n.ion-ios-folder-outline:before {\n  content: \"\\f434\"; }\n\n.ion-ios-football:before {\n  content: \"\\f437\"; }\n\n.ion-ios-football-outline:before {\n  content: \"\\f436\"; }\n\n.ion-ios-game-controller-a:before {\n  content: \"\\f439\"; }\n\n.ion-ios-game-controller-a-outline:before {\n  content: \"\\f438\"; }\n\n.ion-ios-game-controller-b:before {\n  content: \"\\f43b\"; }\n\n.ion-ios-game-controller-b-outline:before {\n  content: \"\\f43a\"; }\n\n.ion-ios-gear:before {\n  content: \"\\f43d\"; }\n\n.ion-ios-gear-outline:before {\n  content: \"\\f43c\"; }\n\n.ion-ios-glasses:before {\n  content: \"\\f43f\"; }\n\n.ion-ios-glasses-outline:before {\n  content: \"\\f43e\"; }\n\n.ion-ios-grid-view:before {\n  content: \"\\f441\"; }\n\n.ion-ios-grid-view-outline:before {\n  content: \"\\f440\"; }\n\n.ion-ios-heart:before {\n  content: \"\\f443\"; }\n\n.ion-ios-heart-outline:before {\n  content: \"\\f442\"; }\n\n.ion-ios-help:before {\n  content: \"\\f446\"; }\n\n.ion-ios-help-empty:before {\n  content: \"\\f444\"; }\n\n.ion-ios-help-outline:before {\n  content: \"\\f445\"; }\n\n.ion-ios-home:before {\n  content: \"\\f448\"; }\n\n.ion-ios-home-outline:before {\n  content: \"\\f447\"; }\n\n.ion-ios-infinite:before {\n  content: \"\\f44a\"; }\n\n.ion-ios-infinite-outline:before {\n  content: \"\\f449\"; }\n\n.ion-ios-information:before {\n  content: \"\\f44d\"; }\n\n.ion-ios-information-empty:before {\n  content: \"\\f44b\"; }\n\n.ion-ios-information-outline:before {\n  content: \"\\f44c\"; }\n\n.ion-ios-ionic-outline:before {\n  content: \"\\f44e\"; }\n\n.ion-ios-keypad:before {\n  content: \"\\f450\"; }\n\n.ion-ios-keypad-outline:before {\n  content: \"\\f44f\"; }\n\n.ion-ios-lightbulb:before {\n  content: \"\\f452\"; }\n\n.ion-ios-lightbulb-outline:before {\n  content: \"\\f451\"; }\n\n.ion-ios-list:before {\n  content: \"\\f454\"; }\n\n.ion-ios-list-outline:before {\n  content: \"\\f453\"; }\n\n.ion-ios-location:before {\n  content: \"\\f456\"; }\n\n.ion-ios-location-outline:before {\n  content: \"\\f455\"; }\n\n.ion-ios-locked:before {\n  content: \"\\f458\"; }\n\n.ion-ios-locked-outline:before {\n  content: \"\\f457\"; }\n\n.ion-ios-loop:before {\n  content: \"\\f45a\"; }\n\n.ion-ios-loop-strong:before {\n  content: \"\\f459\"; }\n\n.ion-ios-medical:before {\n  content: \"\\f45c\"; }\n\n.ion-ios-medical-outline:before {\n  content: \"\\f45b\"; }\n\n.ion-ios-medkit:before {\n  content: \"\\f45e\"; }\n\n.ion-ios-medkit-outline:before {\n  content: \"\\f45d\"; }\n\n.ion-ios-mic:before {\n  content: \"\\f461\"; }\n\n.ion-ios-mic-off:before {\n  content: \"\\f45f\"; }\n\n.ion-ios-mic-outline:before {\n  content: \"\\f460\"; }\n\n.ion-ios-minus:before {\n  content: \"\\f464\"; }\n\n.ion-ios-minus-empty:before {\n  content: \"\\f462\"; }\n\n.ion-ios-minus-outline:before {\n  content: \"\\f463\"; }\n\n.ion-ios-monitor:before {\n  content: \"\\f466\"; }\n\n.ion-ios-monitor-outline:before {\n  content: \"\\f465\"; }\n\n.ion-ios-moon:before {\n  content: \"\\f468\"; }\n\n.ion-ios-moon-outline:before {\n  content: \"\\f467\"; }\n\n.ion-ios-more:before {\n  content: \"\\f46a\"; }\n\n.ion-ios-more-outline:before {\n  content: \"\\f469\"; }\n\n.ion-ios-musical-note:before {\n  content: \"\\f46b\"; }\n\n.ion-ios-musical-notes:before {\n  content: \"\\f46c\"; }\n\n.ion-ios-navigate:before {\n  content: \"\\f46e\"; }\n\n.ion-ios-navigate-outline:before {\n  content: \"\\f46d\"; }\n\n.ion-ios-nutrition:before {\n  content: \"\\f470\"; }\n\n.ion-ios-nutrition-outline:before {\n  content: \"\\f46f\"; }\n\n.ion-ios-paper:before {\n  content: \"\\f472\"; }\n\n.ion-ios-paper-outline:before {\n  content: \"\\f471\"; }\n\n.ion-ios-paperplane:before {\n  content: \"\\f474\"; }\n\n.ion-ios-paperplane-outline:before {\n  content: \"\\f473\"; }\n\n.ion-ios-partlysunny:before {\n  content: \"\\f476\"; }\n\n.ion-ios-partlysunny-outline:before {\n  content: \"\\f475\"; }\n\n.ion-ios-pause:before {\n  content: \"\\f478\"; }\n\n.ion-ios-pause-outline:before {\n  content: \"\\f477\"; }\n\n.ion-ios-paw:before {\n  content: \"\\f47a\"; }\n\n.ion-ios-paw-outline:before {\n  content: \"\\f479\"; }\n\n.ion-ios-people:before {\n  content: \"\\f47c\"; }\n\n.ion-ios-people-outline:before {\n  content: \"\\f47b\"; }\n\n.ion-ios-person:before {\n  content: \"\\f47e\"; }\n\n.ion-ios-person-outline:before {\n  content: \"\\f47d\"; }\n\n.ion-ios-personadd:before {\n  content: \"\\f480\"; }\n\n.ion-ios-personadd-outline:before {\n  content: \"\\f47f\"; }\n\n.ion-ios-photos:before {\n  content: \"\\f482\"; }\n\n.ion-ios-photos-outline:before {\n  content: \"\\f481\"; }\n\n.ion-ios-pie:before {\n  content: \"\\f484\"; }\n\n.ion-ios-pie-outline:before {\n  content: \"\\f483\"; }\n\n.ion-ios-pint:before {\n  content: \"\\f486\"; }\n\n.ion-ios-pint-outline:before {\n  content: \"\\f485\"; }\n\n.ion-ios-play:before {\n  content: \"\\f488\"; }\n\n.ion-ios-play-outline:before {\n  content: \"\\f487\"; }\n\n.ion-ios-plus:before {\n  content: \"\\f48b\"; }\n\n.ion-ios-plus-empty:before {\n  content: \"\\f489\"; }\n\n.ion-ios-plus-outline:before {\n  content: \"\\f48a\"; }\n\n.ion-ios-pricetag:before {\n  content: \"\\f48d\"; }\n\n.ion-ios-pricetag-outline:before {\n  content: \"\\f48c\"; }\n\n.ion-ios-pricetags:before {\n  content: \"\\f48f\"; }\n\n.ion-ios-pricetags-outline:before {\n  content: \"\\f48e\"; }\n\n.ion-ios-printer:before {\n  content: \"\\f491\"; }\n\n.ion-ios-printer-outline:before {\n  content: \"\\f490\"; }\n\n.ion-ios-pulse:before {\n  content: \"\\f493\"; }\n\n.ion-ios-pulse-strong:before {\n  content: \"\\f492\"; }\n\n.ion-ios-rainy:before {\n  content: \"\\f495\"; }\n\n.ion-ios-rainy-outline:before {\n  content: \"\\f494\"; }\n\n.ion-ios-recording:before {\n  content: \"\\f497\"; }\n\n.ion-ios-recording-outline:before {\n  content: \"\\f496\"; }\n\n.ion-ios-redo:before {\n  content: \"\\f499\"; }\n\n.ion-ios-redo-outline:before {\n  content: \"\\f498\"; }\n\n.ion-ios-refresh:before {\n  content: \"\\f49c\"; }\n\n.ion-ios-refresh-empty:before {\n  content: \"\\f49a\"; }\n\n.ion-ios-refresh-outline:before {\n  content: \"\\f49b\"; }\n\n.ion-ios-reload:before {\n  content: \"\\f49d\"; }\n\n.ion-ios-reverse-camera:before {\n  content: \"\\f49f\"; }\n\n.ion-ios-reverse-camera-outline:before {\n  content: \"\\f49e\"; }\n\n.ion-ios-rewind:before {\n  content: \"\\f4a1\"; }\n\n.ion-ios-rewind-outline:before {\n  content: \"\\f4a0\"; }\n\n.ion-ios-rose:before {\n  content: \"\\f4a3\"; }\n\n.ion-ios-rose-outline:before {\n  content: \"\\f4a2\"; }\n\n.ion-ios-search:before {\n  content: \"\\f4a5\"; }\n\n.ion-ios-search-strong:before {\n  content: \"\\f4a4\"; }\n\n.ion-ios-settings:before {\n  content: \"\\f4a7\"; }\n\n.ion-ios-settings-strong:before {\n  content: \"\\f4a6\"; }\n\n.ion-ios-shuffle:before {\n  content: \"\\f4a9\"; }\n\n.ion-ios-shuffle-strong:before {\n  content: \"\\f4a8\"; }\n\n.ion-ios-skipbackward:before {\n  content: \"\\f4ab\"; }\n\n.ion-ios-skipbackward-outline:before {\n  content: \"\\f4aa\"; }\n\n.ion-ios-skipforward:before {\n  content: \"\\f4ad\"; }\n\n.ion-ios-skipforward-outline:before {\n  content: \"\\f4ac\"; }\n\n.ion-ios-snowy:before {\n  content: \"\\f4ae\"; }\n\n.ion-ios-speedometer:before {\n  content: \"\\f4b0\"; }\n\n.ion-ios-speedometer-outline:before {\n  content: \"\\f4af\"; }\n\n.ion-ios-star:before {\n  content: \"\\f4b3\"; }\n\n.ion-ios-star-half:before {\n  content: \"\\f4b1\"; }\n\n.ion-ios-star-outline:before {\n  content: \"\\f4b2\"; }\n\n.ion-ios-stopwatch:before {\n  content: \"\\f4b5\"; }\n\n.ion-ios-stopwatch-outline:before {\n  content: \"\\f4b4\"; }\n\n.ion-ios-sunny:before {\n  content: \"\\f4b7\"; }\n\n.ion-ios-sunny-outline:before {\n  content: \"\\f4b6\"; }\n\n.ion-ios-telephone:before {\n  content: \"\\f4b9\"; }\n\n.ion-ios-telephone-outline:before {\n  content: \"\\f4b8\"; }\n\n.ion-ios-tennisball:before {\n  content: \"\\f4bb\"; }\n\n.ion-ios-tennisball-outline:before {\n  content: \"\\f4ba\"; }\n\n.ion-ios-thunderstorm:before {\n  content: \"\\f4bd\"; }\n\n.ion-ios-thunderstorm-outline:before {\n  content: \"\\f4bc\"; }\n\n.ion-ios-time:before {\n  content: \"\\f4bf\"; }\n\n.ion-ios-time-outline:before {\n  content: \"\\f4be\"; }\n\n.ion-ios-timer:before {\n  content: \"\\f4c1\"; }\n\n.ion-ios-timer-outline:before {\n  content: \"\\f4c0\"; }\n\n.ion-ios-toggle:before {\n  content: \"\\f4c3\"; }\n\n.ion-ios-toggle-outline:before {\n  content: \"\\f4c2\"; }\n\n.ion-ios-trash:before {\n  content: \"\\f4c5\"; }\n\n.ion-ios-trash-outline:before {\n  content: \"\\f4c4\"; }\n\n.ion-ios-undo:before {\n  content: \"\\f4c7\"; }\n\n.ion-ios-undo-outline:before {\n  content: \"\\f4c6\"; }\n\n.ion-ios-unlocked:before {\n  content: \"\\f4c9\"; }\n\n.ion-ios-unlocked-outline:before {\n  content: \"\\f4c8\"; }\n\n.ion-ios-upload:before {\n  content: \"\\f4cb\"; }\n\n.ion-ios-upload-outline:before {\n  content: \"\\f4ca\"; }\n\n.ion-ios-videocam:before {\n  content: \"\\f4cd\"; }\n\n.ion-ios-videocam-outline:before {\n  content: \"\\f4cc\"; }\n\n.ion-ios-volume-high:before {\n  content: \"\\f4ce\"; }\n\n.ion-ios-volume-low:before {\n  content: \"\\f4cf\"; }\n\n.ion-ios-wineglass:before {\n  content: \"\\f4d1\"; }\n\n.ion-ios-wineglass-outline:before {\n  content: \"\\f4d0\"; }\n\n.ion-ios-world:before {\n  content: \"\\f4d3\"; }\n\n.ion-ios-world-outline:before {\n  content: \"\\f4d2\"; }\n\n.ion-ipad:before {\n  content: \"\\f1f9\"; }\n\n.ion-iphone:before {\n  content: \"\\f1fa\"; }\n\n.ion-ipod:before {\n  content: \"\\f1fb\"; }\n\n.ion-jet:before {\n  content: \"\\f295\"; }\n\n.ion-key:before {\n  content: \"\\f296\"; }\n\n.ion-knife:before {\n  content: \"\\f297\"; }\n\n.ion-laptop:before {\n  content: \"\\f1fc\"; }\n\n.ion-leaf:before {\n  content: \"\\f1fd\"; }\n\n.ion-levels:before {\n  content: \"\\f298\"; }\n\n.ion-lightbulb:before {\n  content: \"\\f299\"; }\n\n.ion-link:before {\n  content: \"\\f1fe\"; }\n\n.ion-load-a:before {\n  content: \"\\f29a\"; }\n\n.ion-load-b:before {\n  content: \"\\f29b\"; }\n\n.ion-load-c:before {\n  content: \"\\f29c\"; }\n\n.ion-load-d:before {\n  content: \"\\f29d\"; }\n\n.ion-location:before {\n  content: \"\\f1ff\"; }\n\n.ion-lock-combination:before {\n  content: \"\\f4d4\"; }\n\n.ion-locked:before {\n  content: \"\\f200\"; }\n\n.ion-log-in:before {\n  content: \"\\f29e\"; }\n\n.ion-log-out:before {\n  content: \"\\f29f\"; }\n\n.ion-loop:before {\n  content: \"\\f201\"; }\n\n.ion-magnet:before {\n  content: \"\\f2a0\"; }\n\n.ion-male:before {\n  content: \"\\f2a1\"; }\n\n.ion-man:before {\n  content: \"\\f202\"; }\n\n.ion-map:before {\n  content: \"\\f203\"; }\n\n.ion-medkit:before {\n  content: \"\\f2a2\"; }\n\n.ion-merge:before {\n  content: \"\\f33f\"; }\n\n.ion-mic-a:before {\n  content: \"\\f204\"; }\n\n.ion-mic-b:before {\n  content: \"\\f205\"; }\n\n.ion-mic-c:before {\n  content: \"\\f206\"; }\n\n.ion-minus:before {\n  content: \"\\f209\"; }\n\n.ion-minus-circled:before {\n  content: \"\\f207\"; }\n\n.ion-minus-round:before {\n  content: \"\\f208\"; }\n\n.ion-model-s:before {\n  content: \"\\f2c1\"; }\n\n.ion-monitor:before {\n  content: \"\\f20a\"; }\n\n.ion-more:before {\n  content: \"\\f20b\"; }\n\n.ion-mouse:before {\n  content: \"\\f340\"; }\n\n.ion-music-note:before {\n  content: \"\\f20c\"; }\n\n.ion-navicon:before {\n  content: \"\\f20e\"; }\n\n.ion-navicon-round:before {\n  content: \"\\f20d\"; }\n\n.ion-navigate:before {\n  content: \"\\f2a3\"; }\n\n.ion-network:before {\n  content: \"\\f341\"; }\n\n.ion-no-smoking:before {\n  content: \"\\f2c2\"; }\n\n.ion-nuclear:before {\n  content: \"\\f2a4\"; }\n\n.ion-outlet:before {\n  content: \"\\f342\"; }\n\n.ion-paintbrush:before {\n  content: \"\\f4d5\"; }\n\n.ion-paintbucket:before {\n  content: \"\\f4d6\"; }\n\n.ion-paper-airplane:before {\n  content: \"\\f2c3\"; }\n\n.ion-paperclip:before {\n  content: \"\\f20f\"; }\n\n.ion-pause:before {\n  content: \"\\f210\"; }\n\n.ion-person:before {\n  content: \"\\f213\"; }\n\n.ion-person-add:before {\n  content: \"\\f211\"; }\n\n.ion-person-stalker:before {\n  content: \"\\f212\"; }\n\n.ion-pie-graph:before {\n  content: \"\\f2a5\"; }\n\n.ion-pin:before {\n  content: \"\\f2a6\"; }\n\n.ion-pinpoint:before {\n  content: \"\\f2a7\"; }\n\n.ion-pizza:before {\n  content: \"\\f2a8\"; }\n\n.ion-plane:before {\n  content: \"\\f214\"; }\n\n.ion-planet:before {\n  content: \"\\f343\"; }\n\n.ion-play:before {\n  content: \"\\f215\"; }\n\n.ion-playstation:before {\n  content: \"\\f30a\"; }\n\n.ion-plus:before {\n  content: \"\\f218\"; }\n\n.ion-plus-circled:before {\n  content: \"\\f216\"; }\n\n.ion-plus-round:before {\n  content: \"\\f217\"; }\n\n.ion-podium:before {\n  content: \"\\f344\"; }\n\n.ion-pound:before {\n  content: \"\\f219\"; }\n\n.ion-power:before {\n  content: \"\\f2a9\"; }\n\n.ion-pricetag:before {\n  content: \"\\f2aa\"; }\n\n.ion-pricetags:before {\n  content: \"\\f2ab\"; }\n\n.ion-printer:before {\n  content: \"\\f21a\"; }\n\n.ion-pull-request:before {\n  content: \"\\f345\"; }\n\n.ion-qr-scanner:before {\n  content: \"\\f346\"; }\n\n.ion-quote:before {\n  content: \"\\f347\"; }\n\n.ion-radio-waves:before {\n  content: \"\\f2ac\"; }\n\n.ion-record:before {\n  content: \"\\f21b\"; }\n\n.ion-refresh:before {\n  content: \"\\f21c\"; }\n\n.ion-reply:before {\n  content: \"\\f21e\"; }\n\n.ion-reply-all:before {\n  content: \"\\f21d\"; }\n\n.ion-ribbon-a:before {\n  content: \"\\f348\"; }\n\n.ion-ribbon-b:before {\n  content: \"\\f349\"; }\n\n.ion-sad:before {\n  content: \"\\f34a\"; }\n\n.ion-sad-outline:before {\n  content: \"\\f4d7\"; }\n\n.ion-scissors:before {\n  content: \"\\f34b\"; }\n\n.ion-search:before {\n  content: \"\\f21f\"; }\n\n.ion-settings:before {\n  content: \"\\f2ad\"; }\n\n.ion-share:before {\n  content: \"\\f220\"; }\n\n.ion-shuffle:before {\n  content: \"\\f221\"; }\n\n.ion-skip-backward:before {\n  content: \"\\f222\"; }\n\n.ion-skip-forward:before {\n  content: \"\\f223\"; }\n\n.ion-social-android:before {\n  content: \"\\f225\"; }\n\n.ion-social-android-outline:before {\n  content: \"\\f224\"; }\n\n.ion-social-angular:before {\n  content: \"\\f4d9\"; }\n\n.ion-social-angular-outline:before {\n  content: \"\\f4d8\"; }\n\n.ion-social-apple:before {\n  content: \"\\f227\"; }\n\n.ion-social-apple-outline:before {\n  content: \"\\f226\"; }\n\n.ion-social-bitcoin:before {\n  content: \"\\f2af\"; }\n\n.ion-social-bitcoin-outline:before {\n  content: \"\\f2ae\"; }\n\n.ion-social-buffer:before {\n  content: \"\\f229\"; }\n\n.ion-social-buffer-outline:before {\n  content: \"\\f228\"; }\n\n.ion-social-chrome:before {\n  content: \"\\f4db\"; }\n\n.ion-social-chrome-outline:before {\n  content: \"\\f4da\"; }\n\n.ion-social-codepen:before {\n  content: \"\\f4dd\"; }\n\n.ion-social-codepen-outline:before {\n  content: \"\\f4dc\"; }\n\n.ion-social-css3:before {\n  content: \"\\f4df\"; }\n\n.ion-social-css3-outline:before {\n  content: \"\\f4de\"; }\n\n.ion-social-designernews:before {\n  content: \"\\f22b\"; }\n\n.ion-social-designernews-outline:before {\n  content: \"\\f22a\"; }\n\n.ion-social-dribbble:before {\n  content: \"\\f22d\"; }\n\n.ion-social-dribbble-outline:before {\n  content: \"\\f22c\"; }\n\n.ion-social-dropbox:before {\n  content: \"\\f22f\"; }\n\n.ion-social-dropbox-outline:before {\n  content: \"\\f22e\"; }\n\n.ion-social-euro:before {\n  content: \"\\f4e1\"; }\n\n.ion-social-euro-outline:before {\n  content: \"\\f4e0\"; }\n\n.ion-social-facebook:before {\n  content: \"\\f231\"; }\n\n.ion-social-facebook-outline:before {\n  content: \"\\f230\"; }\n\n.ion-social-foursquare:before {\n  content: \"\\f34d\"; }\n\n.ion-social-foursquare-outline:before {\n  content: \"\\f34c\"; }\n\n.ion-social-freebsd-devil:before {\n  content: \"\\f2c4\"; }\n\n.ion-social-github:before {\n  content: \"\\f233\"; }\n\n.ion-social-github-outline:before {\n  content: \"\\f232\"; }\n\n.ion-social-google:before {\n  content: \"\\f34f\"; }\n\n.ion-social-google-outline:before {\n  content: \"\\f34e\"; }\n\n.ion-social-googleplus:before {\n  content: \"\\f235\"; }\n\n.ion-social-googleplus-outline:before {\n  content: \"\\f234\"; }\n\n.ion-social-hackernews:before {\n  content: \"\\f237\"; }\n\n.ion-social-hackernews-outline:before {\n  content: \"\\f236\"; }\n\n.ion-social-html5:before {\n  content: \"\\f4e3\"; }\n\n.ion-social-html5-outline:before {\n  content: \"\\f4e2\"; }\n\n.ion-social-instagram:before {\n  content: \"\\f351\"; }\n\n.ion-social-instagram-outline:before {\n  content: \"\\f350\"; }\n\n.ion-social-javascript:before {\n  content: \"\\f4e5\"; }\n\n.ion-social-javascript-outline:before {\n  content: \"\\f4e4\"; }\n\n.ion-social-linkedin:before {\n  content: \"\\f239\"; }\n\n.ion-social-linkedin-outline:before {\n  content: \"\\f238\"; }\n\n.ion-social-markdown:before {\n  content: \"\\f4e6\"; }\n\n.ion-social-nodejs:before {\n  content: \"\\f4e7\"; }\n\n.ion-social-octocat:before {\n  content: \"\\f4e8\"; }\n\n.ion-social-pinterest:before {\n  content: \"\\f2b1\"; }\n\n.ion-social-pinterest-outline:before {\n  content: \"\\f2b0\"; }\n\n.ion-social-python:before {\n  content: \"\\f4e9\"; }\n\n.ion-social-reddit:before {\n  content: \"\\f23b\"; }\n\n.ion-social-reddit-outline:before {\n  content: \"\\f23a\"; }\n\n.ion-social-rss:before {\n  content: \"\\f23d\"; }\n\n.ion-social-rss-outline:before {\n  content: \"\\f23c\"; }\n\n.ion-social-sass:before {\n  content: \"\\f4ea\"; }\n\n.ion-social-skype:before {\n  content: \"\\f23f\"; }\n\n.ion-social-skype-outline:before {\n  content: \"\\f23e\"; }\n\n.ion-social-snapchat:before {\n  content: \"\\f4ec\"; }\n\n.ion-social-snapchat-outline:before {\n  content: \"\\f4eb\"; }\n\n.ion-social-tumblr:before {\n  content: \"\\f241\"; }\n\n.ion-social-tumblr-outline:before {\n  content: \"\\f240\"; }\n\n.ion-social-tux:before {\n  content: \"\\f2c5\"; }\n\n.ion-social-twitch:before {\n  content: \"\\f4ee\"; }\n\n.ion-social-twitch-outline:before {\n  content: \"\\f4ed\"; }\n\n.ion-social-twitter:before {\n  content: \"\\f243\"; }\n\n.ion-social-twitter-outline:before {\n  content: \"\\f242\"; }\n\n.ion-social-usd:before {\n  content: \"\\f353\"; }\n\n.ion-social-usd-outline:before {\n  content: \"\\f352\"; }\n\n.ion-social-vimeo:before {\n  content: \"\\f245\"; }\n\n.ion-social-vimeo-outline:before {\n  content: \"\\f244\"; }\n\n.ion-social-whatsapp:before {\n  content: \"\\f4f0\"; }\n\n.ion-social-whatsapp-outline:before {\n  content: \"\\f4ef\"; }\n\n.ion-social-windows:before {\n  content: \"\\f247\"; }\n\n.ion-social-windows-outline:before {\n  content: \"\\f246\"; }\n\n.ion-social-wordpress:before {\n  content: \"\\f249\"; }\n\n.ion-social-wordpress-outline:before {\n  content: \"\\f248\"; }\n\n.ion-social-yahoo:before {\n  content: \"\\f24b\"; }\n\n.ion-social-yahoo-outline:before {\n  content: \"\\f24a\"; }\n\n.ion-social-yen:before {\n  content: \"\\f4f2\"; }\n\n.ion-social-yen-outline:before {\n  content: \"\\f4f1\"; }\n\n.ion-social-youtube:before {\n  content: \"\\f24d\"; }\n\n.ion-social-youtube-outline:before {\n  content: \"\\f24c\"; }\n\n.ion-soup-can:before {\n  content: \"\\f4f4\"; }\n\n.ion-soup-can-outline:before {\n  content: \"\\f4f3\"; }\n\n.ion-speakerphone:before {\n  content: \"\\f2b2\"; }\n\n.ion-speedometer:before {\n  content: \"\\f2b3\"; }\n\n.ion-spoon:before {\n  content: \"\\f2b4\"; }\n\n.ion-star:before {\n  content: \"\\f24e\"; }\n\n.ion-stats-bars:before {\n  content: \"\\f2b5\"; }\n\n.ion-steam:before {\n  content: \"\\f30b\"; }\n\n.ion-stop:before {\n  content: \"\\f24f\"; }\n\n.ion-thermometer:before {\n  content: \"\\f2b6\"; }\n\n.ion-thumbsdown:before {\n  content: \"\\f250\"; }\n\n.ion-thumbsup:before {\n  content: \"\\f251\"; }\n\n.ion-toggle:before {\n  content: \"\\f355\"; }\n\n.ion-toggle-filled:before {\n  content: \"\\f354\"; }\n\n.ion-transgender:before {\n  content: \"\\f4f5\"; }\n\n.ion-trash-a:before {\n  content: \"\\f252\"; }\n\n.ion-trash-b:before {\n  content: \"\\f253\"; }\n\n.ion-trophy:before {\n  content: \"\\f356\"; }\n\n.ion-tshirt:before {\n  content: \"\\f4f7\"; }\n\n.ion-tshirt-outline:before {\n  content: \"\\f4f6\"; }\n\n.ion-umbrella:before {\n  content: \"\\f2b7\"; }\n\n.ion-university:before {\n  content: \"\\f357\"; }\n\n.ion-unlocked:before {\n  content: \"\\f254\"; }\n\n.ion-upload:before {\n  content: \"\\f255\"; }\n\n.ion-usb:before {\n  content: \"\\f2b8\"; }\n\n.ion-videocamera:before {\n  content: \"\\f256\"; }\n\n.ion-volume-high:before {\n  content: \"\\f257\"; }\n\n.ion-volume-low:before {\n  content: \"\\f258\"; }\n\n.ion-volume-medium:before {\n  content: \"\\f259\"; }\n\n.ion-volume-mute:before {\n  content: \"\\f25a\"; }\n\n.ion-wand:before {\n  content: \"\\f358\"; }\n\n.ion-waterdrop:before {\n  content: \"\\f25b\"; }\n\n.ion-wifi:before {\n  content: \"\\f25c\"; }\n\n.ion-wineglass:before {\n  content: \"\\f2b9\"; }\n\n.ion-woman:before {\n  content: \"\\f25d\"; }\n\n.ion-wrench:before {\n  content: \"\\f2ba\"; }\n\n.ion-xbox:before {\n  content: \"\\f30c\"; }\n\n/**\n * Resets\n * --------------------------------------------------\n * Adapted from normalize.css and some reset.css. We don't care even one\n * bit about old IE, so we don't need any hacks for that in here.\n *\n * There are probably other things we could remove here, as well.\n *\n * normalize.css v2.1.2 | MIT License | git.io/normalize\n\n * Eric Meyer's Reset CSS v2.0 (http://meyerweb.com/eric/tools/css/reset/)\n * http://cssreset.com\n */\nhtml, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, i, u, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, fieldset, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {\n  margin: 0;\n  padding: 0;\n  border: 0;\n  vertical-align: baseline;\n  font: inherit;\n  font-size: 100%; }\n\nol, ul {\n  list-style: none; }\n\nblockquote, q {\n  quotes: none; }\n\nblockquote:before, blockquote:after, q:before, q:after {\n  content: '';\n  content: none; }\n\n/**\n * Prevent modern browsers from displaying `audio` without controls.\n * Remove excess height in iOS 5 devices.\n */\naudio:not([controls]) {\n  display: none;\n  height: 0; }\n\n/**\n * Hide the `template` element in IE, Safari, and Firefox < 22.\n */\n[hidden], template {\n  display: none; }\n\nscript {\n  display: none !important; }\n\n/* ==========================================================================\n   Base\n   ========================================================================== */\n/**\n * 1. Set default font family to sans-serif.\n * 2. Prevent iOS text size adjust after orientation change, without disabling\n *  user zoom.\n */\nhtml {\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n  font-family: sans-serif;\n  /* 1 */\n  -webkit-text-size-adjust: 100%;\n  -ms-text-size-adjust: 100%;\n  /* 2 */\n  -webkit-text-size-adjust: 100%;\n  /* 2 */ }\n\n/**\n * Remove default margin.\n */\nbody {\n  margin: 0;\n  line-height: 1; }\n\n/**\n * Remove default outlines.\n */\na, button, :focus, a:focus, button:focus, a:active, a:hover {\n  outline: 0; }\n\n/* *\n * Remove tap highlight color\n */\na {\n  -webkit-user-drag: none;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n  -webkit-tap-highlight-color: transparent; }\n  a[href]:hover {\n    cursor: pointer; }\n\n/* ==========================================================================\n   Typography\n   ========================================================================== */\n/**\n * Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.\n */\nb, strong {\n  font-weight: bold; }\n\n/**\n * Address styling not present in Safari 5 and Chrome.\n */\ndfn {\n  font-style: italic; }\n\n/**\n * Address differences between Firefox and other browsers.\n */\nhr {\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n  height: 0; }\n\n/**\n * Correct font family set oddly in Safari 5 and Chrome.\n */\ncode, kbd, pre, samp {\n  font-size: 1em;\n  font-family: monospace, serif; }\n\n/**\n * Improve readability of pre-formatted text in all browsers.\n */\npre {\n  white-space: pre-wrap; }\n\n/**\n * Set consistent quote types.\n */\nq {\n  quotes: \"\\201C\" \"\\201D\" \"\\2018\" \"\\2019\"; }\n\n/**\n * Address inconsistent and variable font size in all browsers.\n */\nsmall {\n  font-size: 80%; }\n\n/**\n * Prevent `sub` and `sup` affecting `line-height` in all browsers.\n */\nsub, sup {\n  position: relative;\n  vertical-align: baseline;\n  font-size: 75%;\n  line-height: 0; }\n\nsup {\n  top: -0.5em; }\n\nsub {\n  bottom: -0.25em; }\n\n/**\n * Define consistent border, margin, and padding.\n */\nfieldset {\n  margin: 0 2px;\n  padding: 0.35em 0.625em 0.75em;\n  border: 1px solid #c0c0c0; }\n\n/**\n * 1. Correct `color` not being inherited in IE 8/9.\n * 2. Remove padding so people aren't caught out if they zero out fieldsets.\n */\nlegend {\n  padding: 0;\n  /* 2 */\n  border: 0;\n  /* 1 */ }\n\n/**\n * 1. Correct font family not being inherited in all browsers.\n * 2. Correct font size not being inherited in all browsers.\n * 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.\n * 4. Remove any default :focus styles\n * 5. Make sure webkit font smoothing is being inherited\n * 6. Remove default gradient in Android Firefox / FirefoxOS\n */\nbutton, input, select, textarea {\n  margin: 0;\n  /* 3 */\n  font-size: 100%;\n  /* 2 */\n  font-family: inherit;\n  /* 1 */\n  outline-offset: 0;\n  /* 4 */\n  outline-style: none;\n  /* 4 */\n  outline-width: 0;\n  /* 4 */\n  -webkit-font-smoothing: inherit;\n  /* 5 */\n  background-image: none;\n  /* 6 */ }\n\n/**\n * Address Firefox 4+ setting `line-height` on `input` using `importnt` in\n * the UA stylesheet.\n */\nbutton, input {\n  line-height: normal; }\n\n/**\n * Address inconsistent `text-transform` inheritance for `button` and `select`.\n * All other form control elements do not inherit `text-transform` values.\n * Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+.\n * Correct `select` style inheritance in Firefox 4+ and Opera.\n */\nbutton, select {\n  text-transform: none; }\n\n/**\n * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`\n *  and `video` controls.\n * 2. Correct inability to style clickable `input` types in iOS.\n * 3. Improve usability and consistency of cursor style between image-type\n *  `input` and others.\n */\nbutton, html input[type=\"button\"], input[type=\"reset\"], input[type=\"submit\"] {\n  cursor: pointer;\n  /* 3 */\n  -webkit-appearance: button;\n  /* 2 */ }\n\n/**\n * Re-set default cursor for disabled elements.\n */\nbutton[disabled], html input[disabled] {\n  cursor: default; }\n\n/**\n * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.\n * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome\n *  (include `-moz` to future-proof).\n */\ninput[type=\"search\"] {\n  -webkit-box-sizing: content-box;\n  /* 2 */\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n  -webkit-appearance: textfield;\n  /* 1 */ }\n\n/**\n * Remove inner padding and search cancel button in Safari 5 and Chrome\n * on OS X.\n */\ninput[type=\"search\"]::-webkit-search-cancel-button, input[type=\"search\"]::-webkit-search-decoration {\n  -webkit-appearance: none; }\n\n/**\n * Remove inner padding and border in Firefox 4+.\n */\nbutton::-moz-focus-inner, input::-moz-focus-inner {\n  padding: 0;\n  border: 0; }\n\n/**\n * 1. Remove default vertical scrollbar in IE 8/9.\n * 2. Improve readability and alignment in all browsers.\n */\ntextarea {\n  overflow: auto;\n  /* 1 */\n  vertical-align: top;\n  /* 2 */ }\n\nimg {\n  -webkit-user-drag: none; }\n\n/* ==========================================================================\n   Tables\n   ========================================================================== */\n/**\n * Remove most spacing between table cells.\n */\ntable {\n  border-spacing: 0;\n  border-collapse: collapse; }\n\n/**\n * Scaffolding\n * --------------------------------------------------\n */\n*, *:before, *:after {\n  -webkit-box-sizing: border-box;\n  -moz-box-sizing: border-box;\n  box-sizing: border-box; }\n\nhtml {\n  overflow: hidden;\n  -ms-touch-action: pan-y;\n  touch-action: pan-y; }\n\nbody, .ionic-body {\n  -webkit-touch-callout: none;\n  -webkit-font-smoothing: antialiased;\n  font-smoothing: antialiased;\n  -webkit-text-size-adjust: none;\n  -moz-text-size-adjust: none;\n  text-size-adjust: none;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n  -webkit-tap-highlight-color: transparent;\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  overflow: hidden;\n  margin: 0;\n  padding: 0;\n  color: #000;\n  word-wrap: break-word;\n  font-size: 14px;\n  font-family: \"Helvetica Neue\", \"Roboto\", \"Segoe UI\", sans-serif;\n  line-height: 20px;\n  text-rendering: optimizeLegibility;\n  -webkit-backface-visibility: hidden;\n  -webkit-user-drag: none;\n  -ms-content-zooming: none; }\n\nbody.grade-b, body.grade-c {\n  text-rendering: auto; }\n\n.content {\n  position: relative; }\n\n.scroll-content {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  overflow: hidden;\n  margin-top: -1px;\n  padding-top: 1px;\n  margin-bottom: -1px;\n  width: auto;\n  height: auto; }\n\n.menu .scroll-content.scroll-content-false {\n  z-index: 11; }\n\n.scroll-view {\n  position: relative;\n  display: block;\n  overflow: hidden;\n  margin-top: -1px; }\n\n/**\n * Scroll is the scroll view component available for complex and custom\n * scroll view functionality.\n */\n.scroll {\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n  -webkit-touch-callout: none;\n  -webkit-text-size-adjust: none;\n  -moz-text-size-adjust: none;\n  text-size-adjust: none;\n  -webkit-transform-origin: left top;\n  transform-origin: left top; }\n\n/**\n * Set ms-viewport to prevent MS \"page squish\" and allow fluid scrolling\n * https://msdn.microsoft.com/en-us/library/ie/hh869615(v=vs.85).aspx\n */\n@-ms-viewport {\n  width: device-width; }\n\n.scroll-bar {\n  position: absolute;\n  z-index: 9999; }\n\n.ng-animate .scroll-bar {\n  visibility: hidden; }\n\n.scroll-bar-h {\n  right: 2px;\n  bottom: 3px;\n  left: 2px;\n  height: 3px; }\n  .scroll-bar-h .scroll-bar-indicator {\n    height: 100%; }\n\n.scroll-bar-v {\n  top: 2px;\n  right: 3px;\n  bottom: 2px;\n  width: 3px; }\n  .scroll-bar-v .scroll-bar-indicator {\n    width: 100%; }\n\n.scroll-bar-indicator {\n  position: absolute;\n  border-radius: 4px;\n  background: rgba(0, 0, 0, 0.3);\n  opacity: 1;\n  -webkit-transition: opacity 0.3s linear;\n  transition: opacity 0.3s linear; }\n  .scroll-bar-indicator.scroll-bar-fade-out {\n    opacity: 0; }\n\n.platform-android .scroll-bar-indicator {\n  border-radius: 0; }\n\n.grade-b .scroll-bar-indicator, .grade-c .scroll-bar-indicator {\n  background: #aaa; }\n  .grade-b .scroll-bar-indicator.scroll-bar-fade-out, .grade-c .scroll-bar-indicator.scroll-bar-fade-out {\n    -webkit-transition: none;\n    transition: none; }\n\nion-infinite-scroll {\n  height: 60px;\n  width: 100%;\n  display: block;\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-direction: normal;\n  -webkit-box-orient: horizontal;\n  -webkit-flex-direction: row;\n  -moz-flex-direction: row;\n  -ms-flex-direction: row;\n  flex-direction: row;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  -webkit-justify-content: center;\n  -moz-justify-content: center;\n  justify-content: center;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center; }\n  ion-infinite-scroll .icon {\n    color: #666666;\n    font-size: 30px;\n    color: #666666; }\n  ion-infinite-scroll .icon:before, ion-infinite-scroll .spinner {\n    -webkit-transform: translate3d(0, 0, 0);\n    transform: translate3d(0, 0, 0); }\n  ion-infinite-scroll:not(.active) .spinner, ion-infinite-scroll:not(.active) .icon:before {\n    -webkit-transform: translate3d(-1000px, 0, 0);\n    transform: translate3d(-1000px, 0, 0); }\n\n.overflow-scroll {\n  overflow-x: hidden;\n  overflow-y: scroll;\n  -webkit-overflow-scrolling: touch;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  position: absolute; }\n  .overflow-scroll .scroll {\n    position: static;\n    height: 100%;\n    -webkit-transform: translate3d(0, 0, 0); }\n\n/* If you change these, change platform.scss as well */\n.has-header {\n  top: 44px; }\n\n.no-header {\n  top: 0; }\n\n.has-subheader {\n  top: 88px; }\n\n.has-tabs-top {\n  top: 93px; }\n\n.has-header.has-subheader.has-tabs-top {\n  top: 137px; }\n\n.has-footer {\n  bottom: 44px; }\n\n.has-subfooter {\n  bottom: 88px; }\n\n.has-tabs, .bar-footer.has-tabs {\n  bottom: 49px; }\n  .has-tabs.pane, .bar-footer.has-tabs.pane {\n    bottom: 49px;\n    height: auto; }\n\n.has-footer.has-tabs {\n  bottom: 93px; }\n\n.pane {\n  -webkit-transform: translate3d(0, 0, 0);\n  transform: translate3d(0, 0, 0);\n  -webkit-transition-duration: 0;\n  transition-duration: 0;\n  z-index: 1; }\n\n.view {\n  z-index: 1; }\n\n.pane, .view {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background-color: #fff;\n  overflow: hidden; }\n\n.view-container {\n  position: absolute;\n  display: block;\n  width: 100%;\n  height: 100%; }\n\n/**\n * Typography\n * --------------------------------------------------\n */\np {\n  margin: 0 0 10px; }\n\nsmall {\n  font-size: 85%; }\n\ncite {\n  font-style: normal; }\n\n.text-left {\n  text-align: left; }\n\n.text-right {\n  text-align: right; }\n\n.text-center {\n  text-align: center; }\n\nh1, h2, h3, h4, h5, h6, .h1, .h2, .h3, .h4, .h5, .h6 {\n  color: #000;\n  font-weight: 500;\n  font-family: \"Helvetica Neue\", \"Roboto\", \"Segoe UI\", sans-serif;\n  line-height: 1.2; }\n  h1 small, h2 small, h3 small, h4 small, h5 small, h6 small, .h1 small, .h2 small, .h3 small, .h4 small, .h5 small, .h6 small {\n    font-weight: normal;\n    line-height: 1; }\n\nh1, .h1, h2, .h2, h3, .h3 {\n  margin-top: 20px;\n  margin-bottom: 10px; }\n  h1:first-child, .h1:first-child, h2:first-child, .h2:first-child, h3:first-child, .h3:first-child {\n    margin-top: 0; }\n  h1 + h1, h1 + .h1, h1 + h2, h1 + .h2, h1 + h3, h1 + .h3, .h1 + h1, .h1 + .h1, .h1 + h2, .h1 + .h2, .h1 + h3, .h1 + .h3, h2 + h1, h2 + .h1, h2 + h2, h2 + .h2, h2 + h3, h2 + .h3, .h2 + h1, .h2 + .h1, .h2 + h2, .h2 + .h2, .h2 + h3, .h2 + .h3, h3 + h1, h3 + .h1, h3 + h2, h3 + .h2, h3 + h3, h3 + .h3, .h3 + h1, .h3 + .h1, .h3 + h2, .h3 + .h2, .h3 + h3, .h3 + .h3 {\n    margin-top: 10px; }\n\nh4, .h4, h5, .h5, h6, .h6 {\n  margin-top: 10px;\n  margin-bottom: 10px; }\n\nh1, .h1 {\n  font-size: 36px; }\n\nh2, .h2 {\n  font-size: 30px; }\n\nh3, .h3 {\n  font-size: 24px; }\n\nh4, .h4 {\n  font-size: 18px; }\n\nh5, .h5 {\n  font-size: 14px; }\n\nh6, .h6 {\n  font-size: 12px; }\n\nh1 small, .h1 small {\n  font-size: 24px; }\n\nh2 small, .h2 small {\n  font-size: 18px; }\n\nh3 small, .h3 small, h4 small, .h4 small {\n  font-size: 14px; }\n\ndl {\n  margin-bottom: 20px; }\n\ndt, dd {\n  line-height: 1.42857; }\n\ndt {\n  font-weight: bold; }\n\nblockquote {\n  margin: 0 0 20px;\n  padding: 10px 20px;\n  border-left: 5px solid gray; }\n  blockquote p {\n    font-weight: 300;\n    font-size: 17.5px;\n    line-height: 1.25; }\n  blockquote p:last-child {\n    margin-bottom: 0; }\n  blockquote small {\n    display: block;\n    line-height: 1.42857; }\n    blockquote small:before {\n      content: '\\2014 \\00A0'; }\n\nq:before, q:after, blockquote:before, blockquote:after {\n  content: \"\"; }\n\naddress {\n  display: block;\n  margin-bottom: 20px;\n  font-style: normal;\n  line-height: 1.42857; }\n\na.subdued {\n  padding-right: 10px;\n  color: #888;\n  text-decoration: none; }\n  a.subdued:hover {\n    text-decoration: none; }\n  a.subdued:last-child {\n    padding-right: 0; }\n\n/**\n * Action Sheets\n * --------------------------------------------------\n */\n.action-sheet-backdrop {\n  -webkit-transition: background-color 150ms ease-in-out;\n  transition: background-color 150ms ease-in-out;\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 11;\n  width: 100%;\n  height: 100%;\n  background-color: rgba(0, 0, 0, 0); }\n  .action-sheet-backdrop.active {\n    background-color: rgba(0, 0, 0, 0.4); }\n\n.action-sheet-wrapper {\n  -webkit-transform: translate3d(0, 100%, 0);\n  transform: translate3d(0, 100%, 0);\n  -webkit-transition: all cubic-bezier(0.36, 0.66, 0.04, 1) 500ms;\n  transition: all cubic-bezier(0.36, 0.66, 0.04, 1) 500ms;\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  right: 0;\n  width: 100%;\n  max-width: 500px;\n  margin: auto; }\n\n.action-sheet-up {\n  -webkit-transform: translate3d(0, 0, 0);\n  transform: translate3d(0, 0, 0); }\n\n.action-sheet {\n  margin-left: 8px;\n  margin-right: 8px;\n  width: auto;\n  z-index: 11;\n  overflow: hidden; }\n  .action-sheet .button {\n    display: block;\n    padding: 1px;\n    width: 100%;\n    border-radius: 0;\n    border-color: #d1d3d6;\n    background-color: transparent;\n    color: #007aff;\n    font-size: 21px; }\n    .action-sheet .button:hover {\n      color: #007aff; }\n    .action-sheet .button.destructive {\n      color: #ff3b30; }\n      .action-sheet .button.destructive:hover {\n        color: #ff3b30; }\n  .action-sheet .button.active, .action-sheet .button.activated {\n    box-shadow: none;\n    border-color: #d1d3d6;\n    color: #007aff;\n    background: #e4e5e7; }\n\n.action-sheet-has-icons .icon {\n  position: absolute;\n  left: 16px; }\n\n.action-sheet-title {\n  padding: 16px;\n  color: #8f8f8f;\n  text-align: center;\n  font-size: 13px; }\n\n.action-sheet-group {\n  margin-bottom: 8px;\n  border-radius: 4px;\n  background-color: #fff;\n  overflow: hidden; }\n  .action-sheet-group .button {\n    border-width: 1px 0px 0px 0px; }\n  .action-sheet-group .button:first-child:last-child {\n    border-width: 0; }\n\n.action-sheet-options {\n  background: #f1f2f3; }\n\n.action-sheet-cancel .button {\n  font-weight: 500; }\n\n.action-sheet-open {\n  pointer-events: none; }\n  .action-sheet-open.modal-open .modal {\n    pointer-events: none; }\n  .action-sheet-open .action-sheet-backdrop {\n    pointer-events: auto; }\n\n.platform-android .action-sheet-backdrop.active {\n  background-color: rgba(0, 0, 0, 0.2); }\n.platform-android .action-sheet {\n  margin: 0; }\n  .platform-android .action-sheet .action-sheet-title, .platform-android .action-sheet .button {\n    text-align: left;\n    border-color: transparent;\n    font-size: 16px;\n    color: inherit; }\n  .platform-android .action-sheet .action-sheet-title {\n    font-size: 14px;\n    padding: 16px;\n    color: #666; }\n  .platform-android .action-sheet .button.active, .platform-android .action-sheet .button.activated {\n    background: #e8e8e8; }\n.platform-android .action-sheet-group {\n  margin: 0;\n  border-radius: 0;\n  background-color: #fafafa; }\n.platform-android .action-sheet-cancel {\n  display: none; }\n.platform-android .action-sheet-has-icons .button {\n  padding-left: 56px; }\n\n.backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 11;\n  width: 100%;\n  height: 100%;\n  background-color: rgba(0, 0, 0, 0.4);\n  visibility: hidden;\n  opacity: 0;\n  -webkit-transition: 0.1s opacity linear;\n  transition: 0.1s opacity linear; }\n  .backdrop.visible {\n    visibility: visible; }\n  .backdrop.active {\n    opacity: 1; }\n\n/**\n * Bar (Headers and Footers)\n * --------------------------------------------------\n */\n.bar {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-transform: translate3d(0, 0, 0);\n  transform: translate3d(0, 0, 0);\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n  position: absolute;\n  right: 0;\n  left: 0;\n  z-index: 9;\n  box-sizing: border-box;\n  padding: 5px;\n  width: 100%;\n  height: 44px;\n  border-width: 0;\n  border-style: solid;\n  border-top: 1px solid transparent;\n  border-bottom: 1px solid #ddd;\n  background-color: white;\n  /* border-width: 1px will actually create 2 device pixels on retina */\n  /* this nifty trick sets an actual 1px border on hi-res displays */\n  background-size: 0; }\n  @media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n    .bar {\n      border: none;\n      background-image: linear-gradient(0deg, #ddd, #ddd 50%, transparent 50%);\n      background-position: bottom;\n      background-size: 100% 1px;\n      background-repeat: no-repeat; } }\n  .bar.bar-clear {\n    border: none;\n    background: none;\n    color: #fff; }\n    .bar.bar-clear .button {\n      color: #fff; }\n    .bar.bar-clear .title {\n      color: #fff; }\n  .bar.item-input-inset .item-input-wrapper {\n    margin-top: -1px; }\n    .bar.item-input-inset .item-input-wrapper input {\n      padding-left: 8px;\n      width: 94%;\n      height: 28px;\n      background: transparent; }\n  .bar.bar-light {\n    border-color: #ddd;\n    background-color: white;\n    background-image: linear-gradient(0deg, #ddd, #ddd 50%, transparent 50%);\n    color: #444; }\n    .bar.bar-light .title {\n      color: #444; }\n    .bar.bar-light.bar-footer {\n      background-image: linear-gradient(180deg, #ddd, #ddd 50%, transparent 50%); }\n  .bar.bar-stable {\n    border-color: #b2b2b2;\n    background-color: #f8f8f8;\n    background-image: linear-gradient(0deg, #b2b2b2, #b2b2b2 50%, transparent 50%);\n    color: #444; }\n    .bar.bar-stable .title {\n      color: #444; }\n    .bar.bar-stable.bar-footer {\n      background-image: linear-gradient(180deg, #b2b2b2, #b2b2b2 50%, transparent 50%); }\n  .bar.bar-positive {\n    border-color: #0c63ee;\n    background-color: #387ef5;\n    background-image: linear-gradient(0deg, #0c63ee, #0c63ee 50%, transparent 50%);\n    color: #fff; }\n    .bar.bar-positive .title {\n      color: #fff; }\n    .bar.bar-positive.bar-footer {\n      background-image: linear-gradient(180deg, #0c63ee, #0c63ee 50%, transparent 50%); }\n  .bar.bar-calm {\n    border-color: #0a9ec7;\n    background-color: #11c1f3;\n    background-image: linear-gradient(0deg, #0a9ec7, #0a9ec7 50%, transparent 50%);\n    color: #fff; }\n    .bar.bar-calm .title {\n      color: #fff; }\n    .bar.bar-calm.bar-footer {\n      background-image: linear-gradient(180deg, #0a9ec7, #0a9ec7 50%, transparent 50%); }\n  .bar.bar-assertive {\n    border-color: #e42012;\n    background-color: #ef473a;\n    background-image: linear-gradient(0deg, #e42012, #e42012 50%, transparent 50%);\n    color: #fff; }\n    .bar.bar-assertive .title {\n      color: #fff; }\n    .bar.bar-assertive.bar-footer {\n      background-image: linear-gradient(180deg, #e42012, #e42012 50%, transparent 50%); }\n  .bar.bar-balanced {\n    border-color: #28a54c;\n    background-color: #33cd5f;\n    background-image: linear-gradient(0deg, #28a54c, #28a54c 50%, transparent 50%);\n    color: #fff; }\n    .bar.bar-balanced .title {\n      color: #fff; }\n    .bar.bar-balanced.bar-footer {\n      background-image: linear-gradient(180deg, #28a54c, #0c63ee 50%, transparent 50%); }\n  .bar.bar-energized {\n    border-color: #e6b400;\n    background-color: #ffc900;\n    background-image: linear-gradient(0deg, #e6b400, #e6b400 50%, transparent 50%);\n    color: #fff; }\n    .bar.bar-energized .title {\n      color: #fff; }\n    .bar.bar-energized.bar-footer {\n      background-image: linear-gradient(180deg, #e6b400, #e6b400 50%, transparent 50%); }\n  .bar.bar-royal {\n    border-color: #6b46e5;\n    background-color: #886aea;\n    background-image: linear-gradient(0deg, #6b46e5, #6b46e5 50%, transparent 50%);\n    color: #fff; }\n    .bar.bar-royal .title {\n      color: #fff; }\n    .bar.bar-royal.bar-footer {\n      background-image: linear-gradient(180deg, #6b46e5, #6b46e5 50%, transparent 50%); }\n  .bar.bar-dark {\n    border-color: #111;\n    background-color: #444444;\n    background-image: linear-gradient(0deg, #111, #111 50%, transparent 50%);\n    color: #fff; }\n    .bar.bar-dark .title {\n      color: #fff; }\n    .bar.bar-dark.bar-footer {\n      background-image: linear-gradient(180deg, #111, #111 50%, transparent 50%); }\n  .bar .title {\n    position: absolute;\n    top: 0;\n    right: 0;\n    left: 0;\n    z-index: 0;\n    overflow: hidden;\n    margin: 0 10px;\n    min-width: 30px;\n    height: 43px;\n    text-align: center;\n    text-overflow: ellipsis;\n    white-space: nowrap;\n    font-size: 17px;\n    font-weight: 500;\n    line-height: 44px; }\n    .bar .title.title-left {\n      text-align: left; }\n    .bar .title.title-right {\n      text-align: right; }\n  .bar .title a {\n    color: inherit; }\n  .bar .button {\n    z-index: 1;\n    padding: 0 8px;\n    min-width: initial;\n    min-height: 31px;\n    font-weight: 400;\n    font-size: 13px;\n    line-height: 32px; }\n    .bar .button.button-icon:before, .bar .button .icon:before, .bar .button.icon:before, .bar .button.icon-left:before, .bar .button.icon-right:before {\n      padding-right: 2px;\n      padding-left: 2px;\n      font-size: 20px;\n      line-height: 32px; }\n    .bar .button.button-icon {\n      font-size: 17px; }\n      .bar .button.button-icon .icon:before, .bar .button.button-icon:before, .bar .button.button-icon.icon-left:before, .bar .button.button-icon.icon-right:before {\n        vertical-align: top;\n        font-size: 32px;\n        line-height: 32px; }\n    .bar .button.button-clear {\n      padding-right: 2px;\n      padding-left: 2px;\n      font-weight: 300;\n      font-size: 17px; }\n      .bar .button.button-clear .icon:before, .bar .button.button-clear.icon:before, .bar .button.button-clear.icon-left:before, .bar .button.button-clear.icon-right:before {\n        font-size: 32px;\n        line-height: 32px; }\n    .bar .button.back-button {\n      display: block;\n      margin-right: 5px;\n      padding: 0;\n      white-space: nowrap;\n      font-weight: 400; }\n    .bar .button.back-button.active, .bar .button.back-button.activated {\n      opacity: 0.2; }\n  .bar .button-bar > .button, .bar .buttons > .button {\n    min-height: 31px;\n    line-height: 32px; }\n  .bar .button-bar + .button, .bar .button + .button-bar {\n    margin-left: 5px; }\n  .bar .buttons, .bar .buttons.primary-buttons, .bar .buttons.secondary-buttons {\n    display: inherit; }\n  .bar .buttons span {\n    display: inline-block; }\n  .bar .buttons-left span {\n    margin-right: 5px;\n    display: inherit; }\n  .bar .buttons-right span {\n    margin-left: 5px;\n    display: inherit; }\n  .bar .title + .button:last-child, .bar > .button + .button:last-child, .bar > .button.pull-right, .bar .buttons.pull-right, .bar .title + .buttons {\n    position: absolute;\n    top: 5px;\n    right: 5px;\n    bottom: 5px; }\n\n.platform-android .nav-bar-has-subheader .bar {\n  background-image: none; }\n.platform-android .bar .back-button .icon:before {\n  font-size: 24px; }\n.platform-android .bar .title {\n  font-size: 19px;\n  line-height: 44px; }\n\n.bar-light .button {\n  border-color: #ddd;\n  background-color: white;\n  color: #444; }\n  .bar-light .button:hover {\n    color: #444;\n    text-decoration: none; }\n  .bar-light .button.active, .bar-light .button.activated {\n    border-color: #ccc;\n    background-color: #fafafa;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-light .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #444;\n    font-size: 17px; }\n  .bar-light .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-stable .button {\n  border-color: #b2b2b2;\n  background-color: #f8f8f8;\n  color: #444; }\n  .bar-stable .button:hover {\n    color: #444;\n    text-decoration: none; }\n  .bar-stable .button.active, .bar-stable .button.activated {\n    border-color: #a2a2a2;\n    background-color: #e5e5e5;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-stable .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #444;\n    font-size: 17px; }\n  .bar-stable .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-positive .button {\n  border-color: #0c63ee;\n  background-color: #387ef5;\n  color: #fff; }\n  .bar-positive .button:hover {\n    color: #fff;\n    text-decoration: none; }\n  .bar-positive .button.active, .bar-positive .button.activated {\n    border-color: #0c63ee;\n    background-color: #0c63ee;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-positive .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #fff;\n    font-size: 17px; }\n  .bar-positive .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-calm .button {\n  border-color: #0a9ec7;\n  background-color: #11c1f3;\n  color: #fff; }\n  .bar-calm .button:hover {\n    color: #fff;\n    text-decoration: none; }\n  .bar-calm .button.active, .bar-calm .button.activated {\n    border-color: #0a9ec7;\n    background-color: #0a9ec7;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-calm .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #fff;\n    font-size: 17px; }\n  .bar-calm .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-assertive .button {\n  border-color: #e42012;\n  background-color: #ef473a;\n  color: #fff; }\n  .bar-assertive .button:hover {\n    color: #fff;\n    text-decoration: none; }\n  .bar-assertive .button.active, .bar-assertive .button.activated {\n    border-color: #e42012;\n    background-color: #e42012;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-assertive .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #fff;\n    font-size: 17px; }\n  .bar-assertive .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-balanced .button {\n  border-color: #28a54c;\n  background-color: #33cd5f;\n  color: #fff; }\n  .bar-balanced .button:hover {\n    color: #fff;\n    text-decoration: none; }\n  .bar-balanced .button.active, .bar-balanced .button.activated {\n    border-color: #28a54c;\n    background-color: #28a54c;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-balanced .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #fff;\n    font-size: 17px; }\n  .bar-balanced .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-energized .button {\n  border-color: #e6b400;\n  background-color: #ffc900;\n  color: #fff; }\n  .bar-energized .button:hover {\n    color: #fff;\n    text-decoration: none; }\n  .bar-energized .button.active, .bar-energized .button.activated {\n    border-color: #e6b400;\n    background-color: #e6b400;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-energized .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #fff;\n    font-size: 17px; }\n  .bar-energized .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-royal .button {\n  border-color: #6b46e5;\n  background-color: #886aea;\n  color: #fff; }\n  .bar-royal .button:hover {\n    color: #fff;\n    text-decoration: none; }\n  .bar-royal .button.active, .bar-royal .button.activated {\n    border-color: #6b46e5;\n    background-color: #6b46e5;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-royal .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #fff;\n    font-size: 17px; }\n  .bar-royal .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-dark .button {\n  border-color: #111;\n  background-color: #444444;\n  color: #fff; }\n  .bar-dark .button:hover {\n    color: #fff;\n    text-decoration: none; }\n  .bar-dark .button.active, .bar-dark .button.activated {\n    border-color: #000;\n    background-color: #262626;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .bar-dark .button.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #fff;\n    font-size: 17px; }\n  .bar-dark .button.button-icon {\n    border-color: transparent;\n    background: none; }\n\n.bar-header {\n  top: 0;\n  border-top-width: 0;\n  border-bottom-width: 1px; }\n  .bar-header.has-tabs-top {\n    border-bottom-width: 0px;\n    background-image: none; }\n\n.tabs-top .bar-header {\n  border-bottom-width: 0px;\n  background-image: none; }\n\n.bar-footer {\n  bottom: 0;\n  border-top-width: 1px;\n  border-bottom-width: 0;\n  background-position: top;\n  height: 44px; }\n  .bar-footer.item-input-inset {\n    position: absolute; }\n\n.bar-tabs {\n  padding: 0; }\n\n.bar-subheader {\n  top: 44px;\n  display: block;\n  height: 44px; }\n\n.bar-subfooter {\n  bottom: 44px;\n  display: block;\n  height: 44px; }\n\n.nav-bar-block {\n  position: absolute;\n  top: 0;\n  right: 0;\n  left: 0;\n  z-index: 9; }\n\n.bar .back-button.hide, .bar .buttons .hide {\n  display: none; }\n\n.nav-bar-tabs-top .bar {\n  background-image: none; }\n\n/**\n * Tabs\n * --------------------------------------------------\n * A navigation bar with any number of tab items supported.\n */\n.tabs {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-direction: normal;\n  -webkit-box-orient: horizontal;\n  -webkit-flex-direction: horizontal;\n  -moz-flex-direction: horizontal;\n  -ms-flex-direction: horizontal;\n  flex-direction: horizontal;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  -webkit-justify-content: center;\n  -moz-justify-content: center;\n  justify-content: center;\n  -webkit-transform: translate3d(0, 0, 0);\n  transform: translate3d(0, 0, 0);\n  border-color: #b2b2b2;\n  background-color: #f8f8f8;\n  background-image: linear-gradient(0deg, #b2b2b2, #b2b2b2 50%, transparent 50%);\n  color: #444;\n  position: absolute;\n  bottom: 0;\n  z-index: 5;\n  width: 100%;\n  height: 49px;\n  border-style: solid;\n  border-top-width: 1px;\n  background-size: 0;\n  line-height: 49px; }\n  .tabs .tab-item .badge {\n    background-color: #444;\n    color: #f8f8f8; }\n  @media (min--moz-device-pixel-ratio: 1.5), (-webkit-min-device-pixel-ratio: 1.5), (min-device-pixel-ratio: 1.5), (min-resolution: 144dpi), (min-resolution: 1.5dppx) {\n    .tabs {\n      padding-top: 2px;\n      border-top: none !important;\n      border-bottom: none;\n      background-position: top;\n      background-size: 100% 1px;\n      background-repeat: no-repeat; } }\n\n/* Allow parent element of tabs to define color, or just the tab itself */\n.tabs-light > .tabs, .tabs.tabs-light {\n  border-color: #ddd;\n  background-color: #fff;\n  background-image: linear-gradient(0deg, #ddd, #ddd 50%, transparent 50%);\n  color: #444; }\n  .tabs-light > .tabs .tab-item .badge, .tabs.tabs-light .tab-item .badge {\n    background-color: #444;\n    color: #fff; }\n\n.tabs-stable > .tabs, .tabs.tabs-stable {\n  border-color: #b2b2b2;\n  background-color: #f8f8f8;\n  background-image: linear-gradient(0deg, #b2b2b2, #b2b2b2 50%, transparent 50%);\n  color: #444; }\n  .tabs-stable > .tabs .tab-item .badge, .tabs.tabs-stable .tab-item .badge {\n    background-color: #444;\n    color: #f8f8f8; }\n\n.tabs-positive > .tabs, .tabs.tabs-positive {\n  border-color: #0c63ee;\n  background-color: #387ef5;\n  background-image: linear-gradient(0deg, #0c63ee, #0c63ee 50%, transparent 50%);\n  color: #fff; }\n  .tabs-positive > .tabs .tab-item .badge, .tabs.tabs-positive .tab-item .badge {\n    background-color: #fff;\n    color: #387ef5; }\n\n.tabs-calm > .tabs, .tabs.tabs-calm {\n  border-color: #0a9ec7;\n  background-color: #11c1f3;\n  background-image: linear-gradient(0deg, #0a9ec7, #0a9ec7 50%, transparent 50%);\n  color: #fff; }\n  .tabs-calm > .tabs .tab-item .badge, .tabs.tabs-calm .tab-item .badge {\n    background-color: #fff;\n    color: #11c1f3; }\n\n.tabs-assertive > .tabs, .tabs.tabs-assertive {\n  border-color: #e42012;\n  background-color: #ef473a;\n  background-image: linear-gradient(0deg, #e42012, #e42012 50%, transparent 50%);\n  color: #fff; }\n  .tabs-assertive > .tabs .tab-item .badge, .tabs.tabs-assertive .tab-item .badge {\n    background-color: #fff;\n    color: #ef473a; }\n\n.tabs-balanced > .tabs, .tabs.tabs-balanced {\n  border-color: #28a54c;\n  background-color: #33cd5f;\n  background-image: linear-gradient(0deg, #28a54c, #28a54c 50%, transparent 50%);\n  color: #fff; }\n  .tabs-balanced > .tabs .tab-item .badge, .tabs.tabs-balanced .tab-item .badge {\n    background-color: #fff;\n    color: #33cd5f; }\n\n.tabs-energized > .tabs, .tabs.tabs-energized {\n  border-color: #e6b400;\n  background-color: #ffc900;\n  background-image: linear-gradient(0deg, #e6b400, #e6b400 50%, transparent 50%);\n  color: #fff; }\n  .tabs-energized > .tabs .tab-item .badge, .tabs.tabs-energized .tab-item .badge {\n    background-color: #fff;\n    color: #ffc900; }\n\n.tabs-royal > .tabs, .tabs.tabs-royal {\n  border-color: #6b46e5;\n  background-color: #886aea;\n  background-image: linear-gradient(0deg, #6b46e5, #6b46e5 50%, transparent 50%);\n  color: #fff; }\n  .tabs-royal > .tabs .tab-item .badge, .tabs.tabs-royal .tab-item .badge {\n    background-color: #fff;\n    color: #886aea; }\n\n.tabs-dark > .tabs, .tabs.tabs-dark {\n  border-color: #111;\n  background-color: #444;\n  background-image: linear-gradient(0deg, #111, #111 50%, transparent 50%);\n  color: #fff; }\n  .tabs-dark > .tabs .tab-item .badge, .tabs.tabs-dark .tab-item .badge {\n    background-color: #fff;\n    color: #444; }\n\n.tabs-striped .tabs {\n  background-color: white;\n  background-image: none;\n  border: none;\n  border-bottom: 1px solid #ddd;\n  padding-top: 2px; }\n.tabs-striped .tab-item.tab-item-active, .tabs-striped .tab-item.active, .tabs-striped .tab-item.activated {\n  margin-top: -2px;\n  border-style: solid;\n  border-width: 2px 0 0 0;\n  border-color: #444; }\n  .tabs-striped .tab-item.tab-item-active .badge, .tabs-striped .tab-item.active .badge, .tabs-striped .tab-item.activated .badge {\n    top: 2px;\n    opacity: 1; }\n.tabs-striped.tabs-light .tabs {\n  background-color: #fff; }\n.tabs-striped.tabs-light .tab-item {\n  color: rgba(68, 68, 68, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-light .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-light .tab-item.tab-item-active, .tabs-striped.tabs-light .tab-item.active, .tabs-striped.tabs-light .tab-item.activated {\n    margin-top: -2px;\n    color: #444;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #444; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-stable .tabs {\n  background-color: #f8f8f8; }\n.tabs-striped.tabs-stable .tab-item {\n  color: rgba(68, 68, 68, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-stable .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-stable .tab-item.tab-item-active, .tabs-striped.tabs-stable .tab-item.active, .tabs-striped.tabs-stable .tab-item.activated {\n    margin-top: -2px;\n    color: #444;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #444; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-positive .tabs {\n  background-color: #387ef5; }\n.tabs-striped.tabs-positive .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-positive .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-positive .tab-item.tab-item-active, .tabs-striped.tabs-positive .tab-item.active, .tabs-striped.tabs-positive .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #fff; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-calm .tabs {\n  background-color: #11c1f3; }\n.tabs-striped.tabs-calm .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-calm .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-calm .tab-item.tab-item-active, .tabs-striped.tabs-calm .tab-item.active, .tabs-striped.tabs-calm .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #fff; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-assertive .tabs {\n  background-color: #ef473a; }\n.tabs-striped.tabs-assertive .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-assertive .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-assertive .tab-item.tab-item-active, .tabs-striped.tabs-assertive .tab-item.active, .tabs-striped.tabs-assertive .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #fff; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-balanced .tabs {\n  background-color: #33cd5f; }\n.tabs-striped.tabs-balanced .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-balanced .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-balanced .tab-item.tab-item-active, .tabs-striped.tabs-balanced .tab-item.active, .tabs-striped.tabs-balanced .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #fff; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-energized .tabs {\n  background-color: #ffc900; }\n.tabs-striped.tabs-energized .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-energized .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-energized .tab-item.tab-item-active, .tabs-striped.tabs-energized .tab-item.active, .tabs-striped.tabs-energized .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #fff; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-royal .tabs {\n  background-color: #886aea; }\n.tabs-striped.tabs-royal .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-royal .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-royal .tab-item.tab-item-active, .tabs-striped.tabs-royal .tab-item.active, .tabs-striped.tabs-royal .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #fff; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-dark .tabs {\n  background-color: #444; }\n.tabs-striped.tabs-dark .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-dark .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-dark .tab-item.tab-item-active, .tabs-striped.tabs-dark .tab-item.active, .tabs-striped.tabs-dark .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border-style: solid;\n    border-width: 2px 0 0 0;\n    border-color: #fff; }\n.tabs-striped.tabs-top .tab-item.tab-item-active .badge, .tabs-striped.tabs-top .tab-item.active .badge, .tabs-striped.tabs-top .tab-item.activated .badge {\n  top: 4%; }\n.tabs-striped.tabs-background-light .tabs {\n  background-color: #fff;\n  background-image: none; }\n.tabs-striped.tabs-background-stable .tabs {\n  background-color: #f8f8f8;\n  background-image: none; }\n.tabs-striped.tabs-background-positive .tabs {\n  background-color: #387ef5;\n  background-image: none; }\n.tabs-striped.tabs-background-calm .tabs {\n  background-color: #11c1f3;\n  background-image: none; }\n.tabs-striped.tabs-background-assertive .tabs {\n  background-color: #ef473a;\n  background-image: none; }\n.tabs-striped.tabs-background-balanced .tabs {\n  background-color: #33cd5f;\n  background-image: none; }\n.tabs-striped.tabs-background-energized .tabs {\n  background-color: #ffc900;\n  background-image: none; }\n.tabs-striped.tabs-background-royal .tabs {\n  background-color: #886aea;\n  background-image: none; }\n.tabs-striped.tabs-background-dark .tabs {\n  background-color: #444;\n  background-image: none; }\n.tabs-striped.tabs-color-light .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-light .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-light .tab-item.tab-item-active, .tabs-striped.tabs-color-light .tab-item.active, .tabs-striped.tabs-color-light .tab-item.activated {\n    margin-top: -2px;\n    color: #fff;\n    border: 0 solid #fff;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-light .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-light .tab-item.active .badge, .tabs-striped.tabs-color-light .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-stable .tab-item {\n  color: rgba(248, 248, 248, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-stable .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-stable .tab-item.tab-item-active, .tabs-striped.tabs-color-stable .tab-item.active, .tabs-striped.tabs-color-stable .tab-item.activated {\n    margin-top: -2px;\n    color: #f8f8f8;\n    border: 0 solid #f8f8f8;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-stable .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-stable .tab-item.active .badge, .tabs-striped.tabs-color-stable .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-positive .tab-item {\n  color: rgba(56, 126, 245, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-positive .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-positive .tab-item.tab-item-active, .tabs-striped.tabs-color-positive .tab-item.active, .tabs-striped.tabs-color-positive .tab-item.activated {\n    margin-top: -2px;\n    color: #387ef5;\n    border: 0 solid #387ef5;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-positive .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-positive .tab-item.active .badge, .tabs-striped.tabs-color-positive .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-calm .tab-item {\n  color: rgba(17, 193, 243, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-calm .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-calm .tab-item.tab-item-active, .tabs-striped.tabs-color-calm .tab-item.active, .tabs-striped.tabs-color-calm .tab-item.activated {\n    margin-top: -2px;\n    color: #11c1f3;\n    border: 0 solid #11c1f3;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-calm .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-calm .tab-item.active .badge, .tabs-striped.tabs-color-calm .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-assertive .tab-item {\n  color: rgba(239, 71, 58, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-assertive .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-assertive .tab-item.tab-item-active, .tabs-striped.tabs-color-assertive .tab-item.active, .tabs-striped.tabs-color-assertive .tab-item.activated {\n    margin-top: -2px;\n    color: #ef473a;\n    border: 0 solid #ef473a;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-assertive .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-assertive .tab-item.active .badge, .tabs-striped.tabs-color-assertive .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-balanced .tab-item {\n  color: rgba(51, 205, 95, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-balanced .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-balanced .tab-item.tab-item-active, .tabs-striped.tabs-color-balanced .tab-item.active, .tabs-striped.tabs-color-balanced .tab-item.activated {\n    margin-top: -2px;\n    color: #33cd5f;\n    border: 0 solid #33cd5f;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-balanced .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-balanced .tab-item.active .badge, .tabs-striped.tabs-color-balanced .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-energized .tab-item {\n  color: rgba(255, 201, 0, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-energized .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-energized .tab-item.tab-item-active, .tabs-striped.tabs-color-energized .tab-item.active, .tabs-striped.tabs-color-energized .tab-item.activated {\n    margin-top: -2px;\n    color: #ffc900;\n    border: 0 solid #ffc900;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-energized .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-energized .tab-item.active .badge, .tabs-striped.tabs-color-energized .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-royal .tab-item {\n  color: rgba(136, 106, 234, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-royal .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-royal .tab-item.tab-item-active, .tabs-striped.tabs-color-royal .tab-item.active, .tabs-striped.tabs-color-royal .tab-item.activated {\n    margin-top: -2px;\n    color: #886aea;\n    border: 0 solid #886aea;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-royal .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-royal .tab-item.active .badge, .tabs-striped.tabs-color-royal .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n.tabs-striped.tabs-color-dark .tab-item {\n  color: rgba(68, 68, 68, 0.4);\n  opacity: 1; }\n  .tabs-striped.tabs-color-dark .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-striped.tabs-color-dark .tab-item.tab-item-active, .tabs-striped.tabs-color-dark .tab-item.active, .tabs-striped.tabs-color-dark .tab-item.activated {\n    margin-top: -2px;\n    color: #444;\n    border: 0 solid #444;\n    border-top-width: 2px; }\n    .tabs-striped.tabs-color-dark .tab-item.tab-item-active .badge, .tabs-striped.tabs-color-dark .tab-item.active .badge, .tabs-striped.tabs-color-dark .tab-item.activated .badge {\n      top: 2px;\n      opacity: 1; }\n\n.tabs-background-light .tabs, .tabs-background-light > .tabs {\n  background-color: #fff;\n  background-image: linear-gradient(0deg, #ddd, #ddd 50%, transparent 50%);\n  border-color: #ddd; }\n\n.tabs-background-stable .tabs, .tabs-background-stable > .tabs {\n  background-color: #f8f8f8;\n  background-image: linear-gradient(0deg, #b2b2b2, #b2b2b2 50%, transparent 50%);\n  border-color: #b2b2b2; }\n\n.tabs-background-positive .tabs, .tabs-background-positive > .tabs {\n  background-color: #387ef5;\n  background-image: linear-gradient(0deg, #0c63ee, #0c63ee 50%, transparent 50%);\n  border-color: #0c63ee; }\n\n.tabs-background-calm .tabs, .tabs-background-calm > .tabs {\n  background-color: #11c1f3;\n  background-image: linear-gradient(0deg, #0a9ec7, #0a9ec7 50%, transparent 50%);\n  border-color: #0a9ec7; }\n\n.tabs-background-assertive .tabs, .tabs-background-assertive > .tabs {\n  background-color: #ef473a;\n  background-image: linear-gradient(0deg, #e42012, #e42012 50%, transparent 50%);\n  border-color: #e42012; }\n\n.tabs-background-balanced .tabs, .tabs-background-balanced > .tabs {\n  background-color: #33cd5f;\n  background-image: linear-gradient(0deg, #28a54c, #28a54c 50%, transparent 50%);\n  border-color: #28a54c; }\n\n.tabs-background-energized .tabs, .tabs-background-energized > .tabs {\n  background-color: #ffc900;\n  background-image: linear-gradient(0deg, #e6b400, #e6b400 50%, transparent 50%);\n  border-color: #e6b400; }\n\n.tabs-background-royal .tabs, .tabs-background-royal > .tabs {\n  background-color: #886aea;\n  background-image: linear-gradient(0deg, #6b46e5, #6b46e5 50%, transparent 50%);\n  border-color: #6b46e5; }\n\n.tabs-background-dark .tabs, .tabs-background-dark > .tabs {\n  background-color: #444;\n  background-image: linear-gradient(0deg, #111, #111 50%, transparent 50%);\n  border-color: #111; }\n\n.tabs-color-light .tab-item {\n  color: rgba(255, 255, 255, 0.4);\n  opacity: 1; }\n  .tabs-color-light .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-light .tab-item.tab-item-active, .tabs-color-light .tab-item.active, .tabs-color-light .tab-item.activated {\n    color: #fff;\n    border: 0 solid #fff; }\n    .tabs-color-light .tab-item.tab-item-active .badge, .tabs-color-light .tab-item.active .badge, .tabs-color-light .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-stable .tab-item {\n  color: rgba(248, 248, 248, 0.4);\n  opacity: 1; }\n  .tabs-color-stable .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-stable .tab-item.tab-item-active, .tabs-color-stable .tab-item.active, .tabs-color-stable .tab-item.activated {\n    color: #f8f8f8;\n    border: 0 solid #f8f8f8; }\n    .tabs-color-stable .tab-item.tab-item-active .badge, .tabs-color-stable .tab-item.active .badge, .tabs-color-stable .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-positive .tab-item {\n  color: rgba(56, 126, 245, 0.4);\n  opacity: 1; }\n  .tabs-color-positive .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-positive .tab-item.tab-item-active, .tabs-color-positive .tab-item.active, .tabs-color-positive .tab-item.activated {\n    color: #387ef5;\n    border: 0 solid #387ef5; }\n    .tabs-color-positive .tab-item.tab-item-active .badge, .tabs-color-positive .tab-item.active .badge, .tabs-color-positive .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-calm .tab-item {\n  color: rgba(17, 193, 243, 0.4);\n  opacity: 1; }\n  .tabs-color-calm .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-calm .tab-item.tab-item-active, .tabs-color-calm .tab-item.active, .tabs-color-calm .tab-item.activated {\n    color: #11c1f3;\n    border: 0 solid #11c1f3; }\n    .tabs-color-calm .tab-item.tab-item-active .badge, .tabs-color-calm .tab-item.active .badge, .tabs-color-calm .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-assertive .tab-item {\n  color: rgba(239, 71, 58, 0.4);\n  opacity: 1; }\n  .tabs-color-assertive .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-assertive .tab-item.tab-item-active, .tabs-color-assertive .tab-item.active, .tabs-color-assertive .tab-item.activated {\n    color: #ef473a;\n    border: 0 solid #ef473a; }\n    .tabs-color-assertive .tab-item.tab-item-active .badge, .tabs-color-assertive .tab-item.active .badge, .tabs-color-assertive .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-balanced .tab-item {\n  color: rgba(51, 205, 95, 0.4);\n  opacity: 1; }\n  .tabs-color-balanced .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-balanced .tab-item.tab-item-active, .tabs-color-balanced .tab-item.active, .tabs-color-balanced .tab-item.activated {\n    color: #33cd5f;\n    border: 0 solid #33cd5f; }\n    .tabs-color-balanced .tab-item.tab-item-active .badge, .tabs-color-balanced .tab-item.active .badge, .tabs-color-balanced .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-energized .tab-item {\n  color: rgba(255, 201, 0, 0.4);\n  opacity: 1; }\n  .tabs-color-energized .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-energized .tab-item.tab-item-active, .tabs-color-energized .tab-item.active, .tabs-color-energized .tab-item.activated {\n    color: #ffc900;\n    border: 0 solid #ffc900; }\n    .tabs-color-energized .tab-item.tab-item-active .badge, .tabs-color-energized .tab-item.active .badge, .tabs-color-energized .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-royal .tab-item {\n  color: rgba(136, 106, 234, 0.4);\n  opacity: 1; }\n  .tabs-color-royal .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-royal .tab-item.tab-item-active, .tabs-color-royal .tab-item.active, .tabs-color-royal .tab-item.activated {\n    color: #886aea;\n    border: 0 solid #886aea; }\n    .tabs-color-royal .tab-item.tab-item-active .badge, .tabs-color-royal .tab-item.active .badge, .tabs-color-royal .tab-item.activated .badge {\n      opacity: 1; }\n\n.tabs-color-dark .tab-item {\n  color: rgba(68, 68, 68, 0.4);\n  opacity: 1; }\n  .tabs-color-dark .tab-item .badge {\n    opacity: 0.4; }\n  .tabs-color-dark .tab-item.tab-item-active, .tabs-color-dark .tab-item.active, .tabs-color-dark .tab-item.activated {\n    color: #444;\n    border: 0 solid #444; }\n    .tabs-color-dark .tab-item.tab-item-active .badge, .tabs-color-dark .tab-item.active .badge, .tabs-color-dark .tab-item.activated .badge {\n      opacity: 1; }\n\nion-tabs.tabs-color-active-light .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-light .tab-item.tab-item-active, ion-tabs.tabs-color-active-light .tab-item.active, ion-tabs.tabs-color-active-light .tab-item.activated {\n    color: #fff; }\nion-tabs.tabs-color-active-stable .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-stable .tab-item.tab-item-active, ion-tabs.tabs-color-active-stable .tab-item.active, ion-tabs.tabs-color-active-stable .tab-item.activated {\n    color: #f8f8f8; }\nion-tabs.tabs-color-active-positive .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-positive .tab-item.tab-item-active, ion-tabs.tabs-color-active-positive .tab-item.active, ion-tabs.tabs-color-active-positive .tab-item.activated {\n    color: #387ef5; }\nion-tabs.tabs-color-active-calm .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-calm .tab-item.tab-item-active, ion-tabs.tabs-color-active-calm .tab-item.active, ion-tabs.tabs-color-active-calm .tab-item.activated {\n    color: #11c1f3; }\nion-tabs.tabs-color-active-assertive .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-assertive .tab-item.tab-item-active, ion-tabs.tabs-color-active-assertive .tab-item.active, ion-tabs.tabs-color-active-assertive .tab-item.activated {\n    color: #ef473a; }\nion-tabs.tabs-color-active-balanced .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-balanced .tab-item.tab-item-active, ion-tabs.tabs-color-active-balanced .tab-item.active, ion-tabs.tabs-color-active-balanced .tab-item.activated {\n    color: #33cd5f; }\nion-tabs.tabs-color-active-energized .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-energized .tab-item.tab-item-active, ion-tabs.tabs-color-active-energized .tab-item.active, ion-tabs.tabs-color-active-energized .tab-item.activated {\n    color: #ffc900; }\nion-tabs.tabs-color-active-royal .tab-item {\n  color: #444; }\n  ion-tabs.tabs-color-active-royal .tab-item.tab-item-active, ion-tabs.tabs-color-active-royal .tab-item.active, ion-tabs.tabs-color-active-royal .tab-item.activated {\n    color: #886aea; }\nion-tabs.tabs-color-active-dark .tab-item {\n  color: #fff; }\n  ion-tabs.tabs-color-active-dark .tab-item.tab-item-active, ion-tabs.tabs-color-active-dark .tab-item.active, ion-tabs.tabs-color-active-dark .tab-item.activated {\n    color: #444; }\n\n.tabs-top.tabs-striped {\n  padding-bottom: 0; }\n  .tabs-top.tabs-striped .tab-item {\n    background: transparent;\n    -webkit-transition: color 0.1s ease;\n    -moz-transition: color 0.1s ease;\n    -ms-transition: color 0.1s ease;\n    -o-transition: color 0.1s ease;\n    transition: color 0.1s ease; }\n    .tabs-top.tabs-striped .tab-item.tab-item-active, .tabs-top.tabs-striped .tab-item.active, .tabs-top.tabs-striped .tab-item.activated {\n      margin-top: 1px;\n      border-width: 0px 0px 2px 0px !important;\n      border-style: solid; }\n      .tabs-top.tabs-striped .tab-item.tab-item-active > .badge, .tabs-top.tabs-striped .tab-item.tab-item-active > i, .tabs-top.tabs-striped .tab-item.active > .badge, .tabs-top.tabs-striped .tab-item.active > i, .tabs-top.tabs-striped .tab-item.activated > .badge, .tabs-top.tabs-striped .tab-item.activated > i {\n        margin-top: -1px; }\n    .tabs-top.tabs-striped .tab-item .badge {\n      -webkit-transition: color 0.2s ease;\n      -moz-transition: color 0.2s ease;\n      -ms-transition: color 0.2s ease;\n      -o-transition: color 0.2s ease;\n      transition: color 0.2s ease; }\n\n/* Allow parent element to have tabs-top */\n/* If you change this, change platform.scss as well */\n.tabs-top > .tabs, .tabs.tabs-top {\n  top: 44px;\n  padding-top: 0;\n  background-position: bottom;\n  border-top-width: 0;\n  border-bottom-width: 1px; }\n  .tabs-top > .tabs .tab-item.tab-item-active .badge, .tabs-top > .tabs .tab-item.active .badge, .tabs-top > .tabs .tab-item.activated .badge, .tabs.tabs-top .tab-item.tab-item-active .badge, .tabs.tabs-top .tab-item.active .badge, .tabs.tabs-top .tab-item.activated .badge {\n    top: 4%; }\n\n.tabs-top ~ .bar-header {\n  border-bottom-width: 0; }\n\n.tab-item {\n  -webkit-box-flex: 1;\n  -webkit-flex: 1;\n  -moz-box-flex: 1;\n  -moz-flex: 1;\n  -ms-flex: 1;\n  flex: 1;\n  display: block;\n  overflow: hidden;\n  max-width: 150px;\n  height: 100%;\n  color: inherit;\n  text-align: center;\n  text-decoration: none;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n  font-weight: 400;\n  font-size: 14px;\n  font-family: \"Helvetica Neue\", \"Roboto\", \"Segoe UI\", sans-serif;\n  opacity: 0.7; }\n  .tab-item:hover {\n    cursor: pointer; }\n  .tab-item.tab-hidden {\n    display: none; }\n\n.tabs-item-hide > .tabs, .tabs.tabs-item-hide {\n  display: none; }\n\n.tabs-icon-top > .tabs .tab-item, .tabs-icon-top.tabs .tab-item, .tabs-icon-bottom > .tabs .tab-item, .tabs-icon-bottom.tabs .tab-item {\n  font-size: 10px;\n  line-height: 14px; }\n\n.tab-item .icon {\n  display: block;\n  margin: 0 auto;\n  height: 32px;\n  font-size: 32px; }\n\n.tabs-icon-left.tabs .tab-item, .tabs-icon-left > .tabs .tab-item, .tabs-icon-right.tabs .tab-item, .tabs-icon-right > .tabs .tab-item {\n  font-size: 10px; }\n  .tabs-icon-left.tabs .tab-item .icon, .tabs-icon-left > .tabs .tab-item .icon, .tabs-icon-right.tabs .tab-item .icon, .tabs-icon-right > .tabs .tab-item .icon {\n    display: inline-block;\n    vertical-align: top;\n    margin-top: -0.1em; }\n    .tabs-icon-left.tabs .tab-item .icon:before, .tabs-icon-left > .tabs .tab-item .icon:before, .tabs-icon-right.tabs .tab-item .icon:before, .tabs-icon-right > .tabs .tab-item .icon:before {\n      font-size: 24px;\n      line-height: 49px; }\n\n.tabs-icon-left > .tabs .tab-item .icon, .tabs-icon-left.tabs .tab-item .icon {\n  padding-right: 3px; }\n\n.tabs-icon-right > .tabs .tab-item .icon, .tabs-icon-right.tabs .tab-item .icon {\n  padding-left: 3px; }\n\n.tabs-icon-only > .tabs .icon, .tabs-icon-only.tabs .icon {\n  line-height: inherit; }\n\n.tab-item.has-badge {\n  position: relative; }\n\n.tab-item .badge {\n  position: absolute;\n  top: 4%;\n  right: 33%;\n  right: calc(50% - 26px);\n  padding: 1px 6px;\n  height: auto;\n  font-size: 12px;\n  line-height: 16px; }\n\n/* Navigational tab */\n/* Active state for tab */\n.tab-item.tab-item-active, .tab-item.active, .tab-item.activated {\n  opacity: 1; }\n  .tab-item.tab-item-active.tab-item-light, .tab-item.active.tab-item-light, .tab-item.activated.tab-item-light {\n    color: #fff; }\n  .tab-item.tab-item-active.tab-item-stable, .tab-item.active.tab-item-stable, .tab-item.activated.tab-item-stable {\n    color: #f8f8f8; }\n  .tab-item.tab-item-active.tab-item-positive, .tab-item.active.tab-item-positive, .tab-item.activated.tab-item-positive {\n    color: #387ef5; }\n  .tab-item.tab-item-active.tab-item-calm, .tab-item.active.tab-item-calm, .tab-item.activated.tab-item-calm {\n    color: #11c1f3; }\n  .tab-item.tab-item-active.tab-item-assertive, .tab-item.active.tab-item-assertive, .tab-item.activated.tab-item-assertive {\n    color: #ef473a; }\n  .tab-item.tab-item-active.tab-item-balanced, .tab-item.active.tab-item-balanced, .tab-item.activated.tab-item-balanced {\n    color: #33cd5f; }\n  .tab-item.tab-item-active.tab-item-energized, .tab-item.active.tab-item-energized, .tab-item.activated.tab-item-energized {\n    color: #ffc900; }\n  .tab-item.tab-item-active.tab-item-royal, .tab-item.active.tab-item-royal, .tab-item.activated.tab-item-royal {\n    color: #886aea; }\n  .tab-item.tab-item-active.tab-item-dark, .tab-item.active.tab-item-dark, .tab-item.activated.tab-item-dark {\n    color: #444; }\n\n.item.tabs {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  padding: 0; }\n  .item.tabs .icon:before {\n    position: relative; }\n\n.tab-item.disabled, .tab-item[disabled] {\n  opacity: 0.4;\n  cursor: default;\n  pointer-events: none; }\n\n/**\n * Menus\n * --------------------------------------------------\n * Side panel structure\n */\n.menu {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  z-index: 0;\n  overflow: hidden;\n  min-height: 100%;\n  max-height: 100%;\n  width: 275px;\n  background-color: #fff; }\n  .menu .scroll-content {\n    z-index: 10; }\n  .menu .bar-header {\n    z-index: 11; }\n\n.menu-content {\n  -webkit-transform: none;\n  transform: none;\n  box-shadow: -1px 0px 2px rgba(0, 0, 0, 0.2), 1px 0px 2px rgba(0, 0, 0, 0.2); }\n\n.menu-open .menu-content .pane, .menu-open .menu-content .scroll-content {\n  pointer-events: none; }\n\n.grade-b .menu-content, .grade-c .menu-content {\n  -webkit-box-sizing: content-box;\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n  right: -1px;\n  left: -1px;\n  border-right: 1px solid #ccc;\n  border-left: 1px solid #ccc;\n  box-shadow: none; }\n\n.menu-left {\n  left: 0; }\n\n.menu-right {\n  right: 0; }\n\n.aside-open.aside-resizing .menu-right {\n  display: none; }\n\n.menu-animated {\n  -webkit-transition: -webkit-transform 200ms ease;\n  transition: transform 200ms ease; }\n\n/**\n * Modals\n * --------------------------------------------------\n * Modals are independent windows that slide in from off-screen.\n */\n.modal-backdrop, .modal-backdrop-bg {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 10;\n  width: 100%;\n  height: 100%; }\n\n.modal-backdrop-bg {\n  pointer-events: none; }\n\n.modal {\n  display: block;\n  position: absolute;\n  top: 0;\n  z-index: 10;\n  overflow: hidden;\n  min-height: 100%;\n  width: 100%;\n  background-color: #fff; }\n\n@media (min-width: 680px) {\n  .modal {\n    top: 20%;\n    right: 20%;\n    bottom: 20%;\n    left: 20%;\n    min-height: 240px;\n    width: 60%; }\n  .modal.ng-leave-active {\n    bottom: 0; }\n  .platform-ios.platform-cordova .modal-wrapper .modal .bar-header:not(.bar-subheader) {\n    height: 44px; }\n    .platform-ios.platform-cordova .modal-wrapper .modal .bar-header:not(.bar-subheader) > * {\n      margin-top: 0; }\n  .platform-ios.platform-cordova .modal-wrapper .modal .tabs-top > .tabs, .platform-ios.platform-cordova .modal-wrapper .modal .tabs.tabs-top {\n    top: 44px; }\n  .platform-ios.platform-cordova .modal-wrapper .modal .has-header, .platform-ios.platform-cordova .modal-wrapper .modal .bar-subheader {\n    top: 44px; }\n  .platform-ios.platform-cordova .modal-wrapper .modal .has-subheader {\n    top: 88px; }\n  .platform-ios.platform-cordova .modal-wrapper .modal .has-header.has-tabs-top {\n    top: 93px; }\n  .platform-ios.platform-cordova .modal-wrapper .modal .has-header.has-subheader.has-tabs-top {\n    top: 137px; }\n  .modal-backdrop-bg {\n    -webkit-transition: opacity 300ms ease-in-out;\n    transition: opacity 300ms ease-in-out;\n    background-color: #000;\n    opacity: 0; }\n  .active .modal-backdrop-bg {\n    opacity: 0.5; } }\n\n.modal-open {\n  pointer-events: none; }\n  .modal-open .modal, .modal-open .modal-backdrop {\n    pointer-events: auto; }\n  .modal-open.loading-active .modal, .modal-open.loading-active .modal-backdrop {\n    pointer-events: none; }\n\n/**\n * Popovers\n * --------------------------------------------------\n * Popovers are independent views which float over content\n */\n.popover-backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: 10;\n  width: 100%;\n  height: 100%;\n  background-color: rgba(0, 0, 0, 0); }\n  .popover-backdrop.active {\n    background-color: rgba(0, 0, 0, 0.1); }\n\n.popover {\n  position: absolute;\n  top: 25%;\n  left: 50%;\n  z-index: 10;\n  display: block;\n  margin-top: 12px;\n  margin-left: -110px;\n  height: 280px;\n  width: 220px;\n  background-color: #fff;\n  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);\n  opacity: 0; }\n  .popover .item:first-child {\n    border-top: 0; }\n  .popover .item:last-child {\n    border-bottom: 0; }\n  .popover.popover-bottom {\n    margin-top: -12px; }\n\n.popover, .popover .bar-header {\n  border-radius: 2px; }\n\n.popover .scroll-content {\n  z-index: 1;\n  margin: 2px 0; }\n\n.popover .bar-header {\n  border-bottom-right-radius: 0;\n  border-bottom-left-radius: 0; }\n\n.popover .has-header {\n  border-top-right-radius: 0;\n  border-top-left-radius: 0; }\n\n.popover-arrow {\n  display: none; }\n\n.platform-ios .popover {\n  box-shadow: 0 0 40px rgba(0, 0, 0, 0.08);\n  border-radius: 10px; }\n.platform-ios .popover .bar-header {\n  -webkit-border-top-right-radius: 10px;\n  border-top-right-radius: 10px;\n  -webkit-border-top-left-radius: 10px;\n  border-top-left-radius: 10px; }\n.platform-ios .popover .scroll-content {\n  margin: 8px 0;\n  border-radius: 10px; }\n.platform-ios .popover .scroll-content.has-header {\n  margin-top: 0; }\n.platform-ios .popover-arrow {\n  position: absolute;\n  display: block;\n  top: -17px;\n  width: 30px;\n  height: 19px;\n  overflow: hidden; }\n  .platform-ios .popover-arrow:after {\n    position: absolute;\n    top: 12px;\n    left: 5px;\n    width: 20px;\n    height: 20px;\n    background-color: #fff;\n    border-radius: 3px;\n    content: '';\n    -webkit-transform: rotate(-45deg);\n    transform: rotate(-45deg); }\n.platform-ios .popover-bottom .popover-arrow {\n  top: auto;\n  bottom: -10px; }\n  .platform-ios .popover-bottom .popover-arrow:after {\n    top: -6px; }\n\n.platform-android .popover {\n  margin-top: -32px;\n  background-color: #fafafa;\n  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.35); }\n  .platform-android .popover .item {\n    border-color: #fafafa;\n    background-color: #fafafa;\n    color: #4d4d4d; }\n  .platform-android .popover.popover-bottom {\n    margin-top: 32px; }\n.platform-android .popover-backdrop, .platform-android .popover-backdrop.active {\n  background-color: transparent; }\n\n.popover-open {\n  pointer-events: none; }\n  .popover-open .popover, .popover-open .popover-backdrop {\n    pointer-events: auto; }\n  .popover-open.loading-active .popover, .popover-open.loading-active .popover-backdrop {\n    pointer-events: none; }\n\n@media (min-width: 680px) {\n  .popover {\n    width: 360px; } }\n\n/**\n * Popups\n * --------------------------------------------------\n */\n.popup-container {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  background: rgba(0, 0, 0, 0);\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  -webkit-justify-content: center;\n  -moz-justify-content: center;\n  justify-content: center;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  z-index: 12;\n  visibility: hidden; }\n  .popup-container.popup-showing {\n    visibility: visible; }\n  .popup-container.popup-hidden .popup {\n    -webkit-animation-name: scaleOut;\n    animation-name: scaleOut;\n    -webkit-animation-duration: 0.1s;\n    animation-duration: 0.1s;\n    -webkit-animation-timing-function: ease-in-out;\n    animation-timing-function: ease-in-out;\n    -webkit-animation-fill-mode: both;\n    animation-fill-mode: both; }\n  .popup-container.active .popup {\n    -webkit-animation-name: superScaleIn;\n    animation-name: superScaleIn;\n    -webkit-animation-duration: 0.2s;\n    animation-duration: 0.2s;\n    -webkit-animation-timing-function: ease-in-out;\n    animation-timing-function: ease-in-out;\n    -webkit-animation-fill-mode: both;\n    animation-fill-mode: both; }\n  .popup-container .popup {\n    width: 250px;\n    max-width: 100%;\n    max-height: 90%;\n    border-radius: 0px;\n    background-color: rgba(255, 255, 255, 0.9);\n    display: -webkit-box;\n    display: -webkit-flex;\n    display: -moz-box;\n    display: -moz-flex;\n    display: -ms-flexbox;\n    display: flex;\n    -webkit-box-direction: normal;\n    -webkit-box-orient: vertical;\n    -webkit-flex-direction: column;\n    -moz-flex-direction: column;\n    -ms-flex-direction: column;\n    flex-direction: column; }\n  .popup-container input, .popup-container textarea {\n    width: 100%; }\n\n.popup-head {\n  padding: 15px 10px;\n  border-bottom: 1px solid #eee;\n  text-align: center; }\n\n.popup-title {\n  margin: 0;\n  padding: 0;\n  font-size: 15px; }\n\n.popup-sub-title {\n  margin: 5px 0 0 0;\n  padding: 0;\n  font-weight: normal;\n  font-size: 11px; }\n\n.popup-body {\n  padding: 10px;\n  overflow: auto; }\n\n.popup-buttons {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-direction: normal;\n  -webkit-box-orient: horizontal;\n  -webkit-flex-direction: row;\n  -moz-flex-direction: row;\n  -ms-flex-direction: row;\n  flex-direction: row;\n  padding: 10px;\n  min-height: 65px; }\n  .popup-buttons .button {\n    -webkit-box-flex: 1;\n    -webkit-flex: 1;\n    -moz-box-flex: 1;\n    -moz-flex: 1;\n    -ms-flex: 1;\n    flex: 1;\n    display: block;\n    min-height: 45px;\n    border-radius: 2px;\n    line-height: 20px;\n    margin-right: 5px; }\n    .popup-buttons .button:last-child {\n      margin-right: 0px; }\n\n.popup-open {\n  pointer-events: none; }\n  .popup-open.modal-open .modal {\n    pointer-events: none; }\n  .popup-open .popup-backdrop, .popup-open .popup {\n    pointer-events: auto; }\n\n/**\n * Loading\n * --------------------------------------------------\n */\n.loading-container {\n  position: absolute;\n  left: 0;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  z-index: 13;\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-pack: center;\n  -ms-flex-pack: center;\n  -webkit-justify-content: center;\n  -moz-justify-content: center;\n  justify-content: center;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  -webkit-transition: 0.2s opacity linear;\n  transition: 0.2s opacity linear;\n  visibility: hidden;\n  opacity: 0; }\n  .loading-container:not(.visible) .icon {\n    display: none; }\n  .loading-container.visible {\n    visibility: visible; }\n  .loading-container.active {\n    opacity: 1; }\n  .loading-container .loading {\n    padding: 20px;\n    border-radius: 5px;\n    background-color: rgba(0, 0, 0, 0.7);\n    color: #fff;\n    text-align: center;\n    text-overflow: ellipsis;\n    font-size: 15px; }\n    .loading-container .loading h1, .loading-container .loading h2, .loading-container .loading h3, .loading-container .loading h4, .loading-container .loading h5, .loading-container .loading h6 {\n      color: #fff; }\n\n/**\n * Items\n * --------------------------------------------------\n */\n.item {\n  border-color: #ddd;\n  background-color: #fff;\n  color: #444;\n  position: relative;\n  z-index: 2;\n  display: block;\n  margin: -1px;\n  padding: 16px;\n  border-width: 1px;\n  border-style: solid;\n  font-size: 16px; }\n  .item h2 {\n    margin: 0 0 2px 0;\n    font-size: 16px;\n    font-weight: normal; }\n  .item h3 {\n    margin: 0 0 4px 0;\n    font-size: 14px; }\n  .item h4 {\n    margin: 0 0 4px 0;\n    font-size: 12px; }\n  .item h5, .item h6 {\n    margin: 0 0 3px 0;\n    font-size: 10px; }\n  .item p {\n    color: #666;\n    font-size: 14px;\n    margin-bottom: 2px; }\n  .item h1:last-child, .item h2:last-child, .item h3:last-child, .item h4:last-child, .item h5:last-child, .item h6:last-child, .item p:last-child {\n    margin-bottom: 0; }\n  .item .badge {\n    display: -webkit-box;\n    display: -webkit-flex;\n    display: -moz-box;\n    display: -moz-flex;\n    display: -ms-flexbox;\n    display: flex;\n    position: absolute;\n    top: 16px;\n    right: 32px; }\n  .item.item-button-right .badge {\n    right: 67px; }\n  .item.item-divider .badge {\n    top: 8px; }\n  .item .badge + .badge {\n    margin-right: 5px; }\n  .item.item-light {\n    border-color: #ddd;\n    background-color: #fff;\n    color: #444; }\n  .item.item-stable {\n    border-color: #b2b2b2;\n    background-color: #f8f8f8;\n    color: #444; }\n  .item.item-positive {\n    border-color: #0c63ee;\n    background-color: #387ef5;\n    color: #fff; }\n  .item.item-calm {\n    border-color: #0a9ec7;\n    background-color: #11c1f3;\n    color: #fff; }\n  .item.item-assertive {\n    border-color: #e42012;\n    background-color: #ef473a;\n    color: #fff; }\n  .item.item-balanced {\n    border-color: #28a54c;\n    background-color: #33cd5f;\n    color: #fff; }\n  .item.item-energized {\n    border-color: #e6b400;\n    background-color: #ffc900;\n    color: #fff; }\n  .item.item-royal {\n    border-color: #6b46e5;\n    background-color: #886aea;\n    color: #fff; }\n  .item.item-dark {\n    border-color: #111;\n    background-color: #444;\n    color: #fff; }\n  .item[ng-click]:hover {\n    cursor: pointer; }\n\n.list-borderless .item, .item-borderless {\n  border-width: 0; }\n\n.item.active, .item.activated, .item-complex.active .item-content, .item-complex.activated .item-content, .item .item-content.active, .item .item-content.activated {\n  border-color: #ccc;\n  background-color: #D9D9D9; }\n  .item.active.item-light, .item.activated.item-light, .item-complex.active .item-content.item-light, .item-complex.activated .item-content.item-light, .item .item-content.active.item-light, .item .item-content.activated.item-light {\n    border-color: #ccc;\n    background-color: #fafafa; }\n  .item.active.item-stable, .item.activated.item-stable, .item-complex.active .item-content.item-stable, .item-complex.activated .item-content.item-stable, .item .item-content.active.item-stable, .item .item-content.activated.item-stable {\n    border-color: #a2a2a2;\n    background-color: #e5e5e5; }\n  .item.active.item-positive, .item.activated.item-positive, .item-complex.active .item-content.item-positive, .item-complex.activated .item-content.item-positive, .item .item-content.active.item-positive, .item .item-content.activated.item-positive {\n    border-color: #0c63ee;\n    background-color: #0c63ee; }\n  .item.active.item-calm, .item.activated.item-calm, .item-complex.active .item-content.item-calm, .item-complex.activated .item-content.item-calm, .item .item-content.active.item-calm, .item .item-content.activated.item-calm {\n    border-color: #0a9ec7;\n    background-color: #0a9ec7; }\n  .item.active.item-assertive, .item.activated.item-assertive, .item-complex.active .item-content.item-assertive, .item-complex.activated .item-content.item-assertive, .item .item-content.active.item-assertive, .item .item-content.activated.item-assertive {\n    border-color: #e42012;\n    background-color: #e42012; }\n  .item.active.item-balanced, .item.activated.item-balanced, .item-complex.active .item-content.item-balanced, .item-complex.activated .item-content.item-balanced, .item .item-content.active.item-balanced, .item .item-content.activated.item-balanced {\n    border-color: #28a54c;\n    background-color: #28a54c; }\n  .item.active.item-energized, .item.activated.item-energized, .item-complex.active .item-content.item-energized, .item-complex.activated .item-content.item-energized, .item .item-content.active.item-energized, .item .item-content.activated.item-energized {\n    border-color: #e6b400;\n    background-color: #e6b400; }\n  .item.active.item-royal, .item.activated.item-royal, .item-complex.active .item-content.item-royal, .item-complex.activated .item-content.item-royal, .item .item-content.active.item-royal, .item .item-content.activated.item-royal {\n    border-color: #6b46e5;\n    background-color: #6b46e5; }\n  .item.active.item-dark, .item.activated.item-dark, .item-complex.active .item-content.item-dark, .item-complex.activated .item-content.item-dark, .item .item-content.active.item-dark, .item .item-content.activated.item-dark {\n    border-color: #000;\n    background-color: #262626; }\n\n.item, .item h1, .item h2, .item h3, .item h4, .item h5, .item h6, .item p, .item-content, .item-content h1, .item-content h2, .item-content h3, .item-content h4, .item-content h5, .item-content h6, .item-content p {\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap; }\n\na.item {\n  color: inherit;\n  text-decoration: none; }\n  a.item:hover, a.item:focus {\n    text-decoration: none; }\n\n/**\n * Complex Items\n * --------------------------------------------------\n * Adding .item-complex allows the .item to be slidable and\n * have options underneath the button, but also requires an\n * additional .item-content element inside .item.\n * Basically .item-complex removes any default settings which\n * .item added, so that .item-content looks them as just .item.\n */\n.item-complex, a.item.item-complex, button.item.item-complex {\n  padding: 0; }\n\n.item-complex .item-content, .item-radio .item-content {\n  position: relative;\n  z-index: 2;\n  padding: 16px 49px 16px 16px;\n  border: none;\n  background-color: white; }\n\na.item-content {\n  display: block;\n  color: inherit;\n  text-decoration: none; }\n\n.item-text-wrap .item, .item-text-wrap .item-content, .item-text-wrap, .item-text-wrap h1, .item-text-wrap h2, .item-text-wrap h3, .item-text-wrap h4, .item-text-wrap h5, .item-text-wrap h6, .item-text-wrap p, .item-complex.item-text-wrap .item-content, .item-body h1, .item-body h2, .item-body h3, .item-body h4, .item-body h5, .item-body h6, .item-body p {\n  overflow: visible;\n  white-space: normal; }\n\n.item-complex.item-text-wrap, .item-complex.item-text-wrap h1, .item-complex.item-text-wrap h2, .item-complex.item-text-wrap h3, .item-complex.item-text-wrap h4, .item-complex.item-text-wrap h5, .item-complex.item-text-wrap h6, .item-complex.item-text-wrap p {\n  overflow: visible;\n  white-space: normal; }\n\n.item-complex.item-light > .item-content {\n  border-color: #ddd;\n  background-color: #fff;\n  color: #444; }\n  .item-complex.item-light > .item-content.active, .item-complex.item-light > .item-content:active {\n    border-color: #ccc;\n    background-color: #fafafa; }\n.item-complex.item-stable > .item-content {\n  border-color: #b2b2b2;\n  background-color: #f8f8f8;\n  color: #444; }\n  .item-complex.item-stable > .item-content.active, .item-complex.item-stable > .item-content:active {\n    border-color: #a2a2a2;\n    background-color: #e5e5e5; }\n.item-complex.item-positive > .item-content {\n  border-color: #0c63ee;\n  background-color: #387ef5;\n  color: #fff; }\n  .item-complex.item-positive > .item-content.active, .item-complex.item-positive > .item-content:active {\n    border-color: #0c63ee;\n    background-color: #0c63ee; }\n.item-complex.item-calm > .item-content {\n  border-color: #0a9ec7;\n  background-color: #11c1f3;\n  color: #fff; }\n  .item-complex.item-calm > .item-content.active, .item-complex.item-calm > .item-content:active {\n    border-color: #0a9ec7;\n    background-color: #0a9ec7; }\n.item-complex.item-assertive > .item-content {\n  border-color: #e42012;\n  background-color: #ef473a;\n  color: #fff; }\n  .item-complex.item-assertive > .item-content.active, .item-complex.item-assertive > .item-content:active {\n    border-color: #e42012;\n    background-color: #e42012; }\n.item-complex.item-balanced > .item-content {\n  border-color: #28a54c;\n  background-color: #33cd5f;\n  color: #fff; }\n  .item-complex.item-balanced > .item-content.active, .item-complex.item-balanced > .item-content:active {\n    border-color: #28a54c;\n    background-color: #28a54c; }\n.item-complex.item-energized > .item-content {\n  border-color: #e6b400;\n  background-color: #ffc900;\n  color: #fff; }\n  .item-complex.item-energized > .item-content.active, .item-complex.item-energized > .item-content:active {\n    border-color: #e6b400;\n    background-color: #e6b400; }\n.item-complex.item-royal > .item-content {\n  border-color: #6b46e5;\n  background-color: #886aea;\n  color: #fff; }\n  .item-complex.item-royal > .item-content.active, .item-complex.item-royal > .item-content:active {\n    border-color: #6b46e5;\n    background-color: #6b46e5; }\n.item-complex.item-dark > .item-content {\n  border-color: #111;\n  background-color: #444;\n  color: #fff; }\n  .item-complex.item-dark > .item-content.active, .item-complex.item-dark > .item-content:active {\n    border-color: #000;\n    background-color: #262626; }\n\n/**\n * Item Icons\n * --------------------------------------------------\n */\n.item-icon-left .icon, .item-icon-right .icon {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  position: absolute;\n  top: 0;\n  height: 100%;\n  font-size: 32px; }\n  .item-icon-left .icon:before, .item-icon-right .icon:before {\n    display: block;\n    width: 32px;\n    text-align: center; }\n\n.item .fill-icon {\n  min-width: 30px;\n  min-height: 30px;\n  font-size: 28px; }\n\n.item-icon-left {\n  padding-left: 54px; }\n  .item-icon-left .icon {\n    left: 11px; }\n\n.item-complex.item-icon-left {\n  padding-left: 0; }\n  .item-complex.item-icon-left .item-content {\n    padding-left: 54px; }\n\n.item-icon-right {\n  padding-right: 54px; }\n  .item-icon-right .icon {\n    right: 11px; }\n\n.item-complex.item-icon-right {\n  padding-right: 0; }\n  .item-complex.item-icon-right .item-content {\n    padding-right: 54px; }\n\n.item-icon-left.item-icon-right .icon:first-child {\n  right: auto; }\n\n.item-icon-left.item-icon-right .icon:last-child, .item-icon-left .item-delete .icon {\n  left: auto; }\n\n.item-icon-left .icon-accessory, .item-icon-right .icon-accessory {\n  color: #ccc;\n  font-size: 16px; }\n\n.item-icon-left .icon-accessory {\n  left: 3px; }\n\n.item-icon-right .icon-accessory {\n  right: 3px; }\n\n/**\n * Item Button\n * --------------------------------------------------\n * An item button is a child button inside an .item (not the entire .item)\n */\n.item-button-left {\n  padding-left: 72px; }\n\n.item-button-left > .button, .item-button-left .item-content > .button {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  position: absolute;\n  top: 8px;\n  left: 11px;\n  min-width: 34px;\n  min-height: 34px;\n  font-size: 18px;\n  line-height: 32px; }\n  .item-button-left > .button .icon:before, .item-button-left .item-content > .button .icon:before {\n    position: relative;\n    left: auto;\n    width: auto;\n    line-height: 31px; }\n  .item-button-left > .button > .button, .item-button-left .item-content > .button > .button {\n    margin: 0px 2px;\n    min-height: 34px;\n    font-size: 18px;\n    line-height: 32px; }\n\n.item-button-right, a.item.item-button-right, button.item.item-button-right {\n  padding-right: 80px; }\n\n.item-button-right > .button, .item-button-right .item-content > .button, .item-button-right > .buttons, .item-button-right .item-content > .buttons {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  position: absolute;\n  top: 8px;\n  right: 16px;\n  min-width: 34px;\n  min-height: 34px;\n  font-size: 18px;\n  line-height: 32px; }\n  .item-button-right > .button .icon:before, .item-button-right .item-content > .button .icon:before, .item-button-right > .buttons .icon:before, .item-button-right .item-content > .buttons .icon:before {\n    position: relative;\n    left: auto;\n    width: auto;\n    line-height: 31px; }\n  .item-button-right > .button > .button, .item-button-right .item-content > .button > .button, .item-button-right > .buttons > .button, .item-button-right .item-content > .buttons > .button {\n    margin: 0px 2px;\n    min-width: 34px;\n    min-height: 34px;\n    font-size: 18px;\n    line-height: 32px; }\n\n.item-avatar, .item-avatar .item-content, .item-avatar-left, .item-avatar-left .item-content {\n  padding-left: 72px;\n  min-height: 72px; }\n  .item-avatar > img:first-child, .item-avatar .item-image, .item-avatar .item-content > img:first-child, .item-avatar .item-content .item-image, .item-avatar-left > img:first-child, .item-avatar-left .item-image, .item-avatar-left .item-content > img:first-child, .item-avatar-left .item-content .item-image {\n    position: absolute;\n    top: 16px;\n    left: 16px;\n    max-width: 40px;\n    max-height: 40px;\n    width: 100%;\n    height: 100%;\n    border-radius: 50%; }\n\n.item-avatar-right, .item-avatar-right .item-content {\n  padding-right: 72px;\n  min-height: 72px; }\n  .item-avatar-right > img:first-child, .item-avatar-right .item-image, .item-avatar-right .item-content > img:first-child, .item-avatar-right .item-content .item-image {\n    position: absolute;\n    top: 16px;\n    right: 16px;\n    max-width: 40px;\n    max-height: 40px;\n    width: 100%;\n    height: 100%;\n    border-radius: 50%; }\n\n.item-thumbnail-left, .item-thumbnail-left .item-content {\n  padding-top: 8px;\n  padding-left: 106px;\n  min-height: 100px; }\n  .item-thumbnail-left > img:first-child, .item-thumbnail-left .item-image, .item-thumbnail-left .item-content > img:first-child, .item-thumbnail-left .item-content .item-image {\n    position: absolute;\n    top: 10px;\n    left: 10px;\n    max-width: 80px;\n    max-height: 80px;\n    width: 100%;\n    height: 100%; }\n\n.item-avatar.item-complex, .item-avatar-left.item-complex, .item-thumbnail-left.item-complex {\n  padding-top: 0;\n  padding-left: 0; }\n\n.item-thumbnail-right, .item-thumbnail-right .item-content {\n  padding-top: 8px;\n  padding-right: 106px;\n  min-height: 100px; }\n  .item-thumbnail-right > img:first-child, .item-thumbnail-right .item-image, .item-thumbnail-right .item-content > img:first-child, .item-thumbnail-right .item-content .item-image {\n    position: absolute;\n    top: 10px;\n    right: 10px;\n    max-width: 80px;\n    max-height: 80px;\n    width: 100%;\n    height: 100%; }\n\n.item-avatar-right.item-complex, .item-thumbnail-right.item-complex {\n  padding-top: 0;\n  padding-right: 0; }\n\n.item-image {\n  padding: 0;\n  text-align: center; }\n  .item-image img:first-child, .item-image .list-img {\n    width: 100%;\n    vertical-align: middle; }\n\n.item-body {\n  overflow: auto;\n  padding: 16px;\n  text-overflow: inherit;\n  white-space: normal; }\n  .item-body h1, .item-body h2, .item-body h3, .item-body h4, .item-body h5, .item-body h6, .item-body p {\n    margin-top: 16px;\n    margin-bottom: 16px; }\n\n.item-divider {\n  padding-top: 8px;\n  padding-bottom: 8px;\n  min-height: 30px;\n  background-color: #f5f5f5;\n  color: #222;\n  font-weight: 500; }\n\n.platform-ios .item-divider-platform, .item-divider-ios {\n  padding-top: 26px;\n  text-transform: uppercase;\n  font-weight: 300;\n  font-size: 13px;\n  background-color: #efeff4;\n  color: #555; }\n\n.platform-android .item-divider-platform, .item-divider-android {\n  font-weight: 300;\n  font-size: 13px; }\n\n.item-note {\n  float: right;\n  color: #aaa;\n  font-size: 14px; }\n\n.item-left-editable .item-content, .item-right-editable .item-content {\n  -webkit-transition-duration: 250ms;\n  transition-duration: 250ms;\n  -webkit-transition-timing-function: ease-in-out;\n  transition-timing-function: ease-in-out;\n  -webkit-transition-property: -webkit-transform;\n  -moz-transition-property: -moz-transform;\n  transition-property: transform; }\n\n.list-left-editing .item-left-editable .item-content, .item-left-editing.item-left-editable .item-content {\n  -webkit-transform: translate3d(50px, 0, 0);\n  transform: translate3d(50px, 0, 0); }\n\n.item-remove-animate.ng-leave {\n  -webkit-transition-duration: 300ms;\n  transition-duration: 300ms; }\n.item-remove-animate.ng-leave .item-content, .item-remove-animate.ng-leave:last-of-type {\n  -webkit-transition-duration: 300ms;\n  transition-duration: 300ms;\n  -webkit-transition-timing-function: ease-in;\n  transition-timing-function: ease-in;\n  -webkit-transition-property: all;\n  transition-property: all; }\n.item-remove-animate.ng-leave.ng-leave-active .item-content {\n  opacity: 0;\n  -webkit-transform: translate3d(-100%, 0, 0) !important;\n  transform: translate3d(-100%, 0, 0) !important; }\n.item-remove-animate.ng-leave.ng-leave-active:last-of-type {\n  opacity: 0; }\n.item-remove-animate.ng-leave.ng-leave-active ~ ion-item:not(.ng-leave) {\n  -webkit-transform: translate3d(0, -webkit-calc(-100% + 1px), 0);\n  transform: translate3d(0, calc(-100% + 1px), 0);\n  -webkit-transition-duration: 300ms;\n  transition-duration: 300ms;\n  -webkit-transition-timing-function: cubic-bezier(0.25, 0.81, 0.24, 1);\n  transition-timing-function: cubic-bezier(0.25, 0.81, 0.24, 1);\n  -webkit-transition-property: all;\n  transition-property: all; }\n\n.item-left-edit {\n  -webkit-transition: all ease-in-out 125ms;\n  transition: all ease-in-out 125ms;\n  position: absolute;\n  top: 0;\n  left: 0;\n  z-index: 0;\n  width: 50px;\n  height: 100%;\n  line-height: 100%;\n  display: none;\n  opacity: 0;\n  -webkit-transform: translate3d(-21px, 0, 0);\n  transform: translate3d(-21px, 0, 0); }\n  .item-left-edit .button {\n    height: 100%; }\n    .item-left-edit .button.icon {\n      display: -webkit-box;\n      display: -webkit-flex;\n      display: -moz-box;\n      display: -moz-flex;\n      display: -ms-flexbox;\n      display: flex;\n      -webkit-box-align: center;\n      -ms-flex-align: center;\n      -webkit-align-items: center;\n      -moz-align-items: center;\n      align-items: center;\n      position: absolute;\n      top: 0;\n      height: 100%; }\n  .item-left-edit.visible {\n    display: block; }\n    .item-left-edit.visible.active {\n      opacity: 1;\n      -webkit-transform: translate3d(8px, 0, 0);\n      transform: translate3d(8px, 0, 0); }\n\n.list-left-editing .item-left-edit {\n  -webkit-transition-delay: 125ms;\n  transition-delay: 125ms; }\n\n.item-delete .button.icon {\n  color: #ef473a;\n  font-size: 24px; }\n  .item-delete .button.icon:hover {\n    opacity: 0.7; }\n\n.item-right-edit {\n  -webkit-transition: all ease-in-out 250ms;\n  transition: all ease-in-out 250ms;\n  position: absolute;\n  top: 0;\n  right: 0;\n  z-index: 3;\n  width: 75px;\n  height: 100%;\n  background: inherit;\n  padding-left: 20px;\n  display: block;\n  opacity: 0;\n  -webkit-transform: translate3d(75px, 0, 0);\n  transform: translate3d(75px, 0, 0); }\n  .item-right-edit .button {\n    min-width: 50px;\n    height: 100%; }\n    .item-right-edit .button.icon {\n      display: -webkit-box;\n      display: -webkit-flex;\n      display: -moz-box;\n      display: -moz-flex;\n      display: -ms-flexbox;\n      display: flex;\n      -webkit-box-align: center;\n      -ms-flex-align: center;\n      -webkit-align-items: center;\n      -moz-align-items: center;\n      align-items: center;\n      position: absolute;\n      top: 0;\n      height: 100%;\n      font-size: 32px; }\n  .item-right-edit.visible {\n    display: block; }\n    .item-right-edit.visible.active {\n      opacity: 1;\n      -webkit-transform: translate3d(0, 0, 0);\n      transform: translate3d(0, 0, 0); }\n\n.item-reorder .button.icon {\n  color: #444;\n  font-size: 32px; }\n\n.item-reordering {\n  position: absolute;\n  left: 0;\n  top: 0;\n  z-index: 9;\n  width: 100%;\n  box-shadow: 0px 0px 10px 0px #aaa; }\n  .item-reordering .item-reorder {\n    z-index: 9; }\n\n.item-placeholder {\n  opacity: 0.7; }\n\n/**\n * The hidden right-side buttons that can be exposed under a list item\n * with dragging.\n */\n.item-options {\n  position: absolute;\n  top: 0;\n  right: 0;\n  z-index: 1;\n  height: 100%; }\n  .item-options .button {\n    height: 100%;\n    border: none;\n    border-radius: 0;\n    display: -webkit-inline-box;\n    display: -webkit-inline-flex;\n    display: -moz-inline-flex;\n    display: -ms-inline-flexbox;\n    display: inline-flex;\n    -webkit-box-align: center;\n    -ms-flex-align: center;\n    -webkit-align-items: center;\n    -moz-align-items: center;\n    align-items: center; }\n    .item-options .button:before {\n      margin: 0 auto; }\n\n/**\n * Lists\n * --------------------------------------------------\n */\n.list {\n  position: relative;\n  padding-top: 1px;\n  padding-bottom: 1px;\n  padding-left: 0;\n  margin-bottom: 20px; }\n\n.list:last-child {\n  margin-bottom: 0px; }\n  .list:last-child.card {\n    margin-bottom: 40px; }\n\n/**\n * List Header\n * --------------------------------------------------\n */\n.list-header {\n  margin-top: 20px;\n  padding: 5px 15px;\n  background-color: transparent;\n  color: #222;\n  font-weight: bold; }\n\n.card.list .list-item {\n  padding-right: 1px;\n  padding-left: 1px; }\n\n/**\n * Cards and Inset Lists\n * --------------------------------------------------\n * A card and list-inset are close to the same thing, except a card as a box shadow.\n */\n.card, .list-inset {\n  overflow: hidden;\n  margin: 20px 10px;\n  border-radius: 2px;\n  background-color: #fff; }\n\n.card {\n  padding-top: 1px;\n  padding-bottom: 1px;\n  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3); }\n  .card .item {\n    border-left: 0;\n    border-right: 0; }\n  .card .item:first-child {\n    border-top: 0; }\n  .card .item:last-child {\n    border-bottom: 0; }\n\n.padding .card, .padding .list-inset {\n  margin-left: 0;\n  margin-right: 0; }\n\n.card .item:first-child, .list-inset .item:first-child, .padding > .list .item:first-child {\n  border-top-left-radius: 2px;\n  border-top-right-radius: 2px; }\n  .card .item:first-child .item-content, .list-inset .item:first-child .item-content, .padding > .list .item:first-child .item-content {\n    border-top-left-radius: 2px;\n    border-top-right-radius: 2px; }\n.card .item:last-child, .list-inset .item:last-child, .padding > .list .item:last-child {\n  border-bottom-right-radius: 2px;\n  border-bottom-left-radius: 2px; }\n  .card .item:last-child .item-content, .list-inset .item:last-child .item-content, .padding > .list .item:last-child .item-content {\n    border-bottom-right-radius: 2px;\n    border-bottom-left-radius: 2px; }\n\n.card .item:last-child, .list-inset .item:last-child {\n  margin-bottom: -1px; }\n\n.card .item, .list-inset .item, .padding > .list .item, .padding-horizontal > .list .item {\n  margin-right: 0;\n  margin-left: 0; }\n  .card .item.item-input input, .list-inset .item.item-input input, .padding > .list .item.item-input input, .padding-horizontal > .list .item.item-input input {\n    padding-right: 44px; }\n\n.padding-left > .list .item {\n  margin-left: 0; }\n\n.padding-right > .list .item {\n  margin-right: 0; }\n\n/**\n * Badges\n * --------------------------------------------------\n */\n.badge {\n  background-color: transparent;\n  color: #AAAAAA;\n  z-index: 1;\n  display: inline-block;\n  padding: 3px 8px;\n  min-width: 10px;\n  border-radius: 10px;\n  vertical-align: baseline;\n  text-align: center;\n  white-space: nowrap;\n  font-weight: bold;\n  font-size: 14px;\n  line-height: 16px; }\n  .badge:empty {\n    display: none; }\n\n.tabs .tab-item .badge.badge-light, .badge.badge-light {\n  background-color: #fff;\n  color: #444; }\n.tabs .tab-item .badge.badge-stable, .badge.badge-stable {\n  background-color: #f8f8f8;\n  color: #444; }\n.tabs .tab-item .badge.badge-positive, .badge.badge-positive {\n  background-color: #387ef5;\n  color: #fff; }\n.tabs .tab-item .badge.badge-calm, .badge.badge-calm {\n  background-color: #11c1f3;\n  color: #fff; }\n.tabs .tab-item .badge.badge-assertive, .badge.badge-assertive {\n  background-color: #ef473a;\n  color: #fff; }\n.tabs .tab-item .badge.badge-balanced, .badge.badge-balanced {\n  background-color: #33cd5f;\n  color: #fff; }\n.tabs .tab-item .badge.badge-energized, .badge.badge-energized {\n  background-color: #ffc900;\n  color: #fff; }\n.tabs .tab-item .badge.badge-royal, .badge.badge-royal {\n  background-color: #886aea;\n  color: #fff; }\n.tabs .tab-item .badge.badge-dark, .badge.badge-dark {\n  background-color: #444;\n  color: #fff; }\n\n.button .badge {\n  position: relative;\n  top: -1px; }\n\n/**\n * Slide Box\n * --------------------------------------------------\n */\n.slider {\n  position: relative;\n  visibility: hidden;\n  overflow: hidden; }\n\n.slider-slides {\n  position: relative;\n  height: 100%; }\n\n.slider-slide {\n  position: relative;\n  display: block;\n  float: left;\n  width: 100%;\n  height: 100%;\n  vertical-align: top; }\n\n.slider-slide-image > img {\n  width: 100%; }\n\n.slider-pager {\n  position: absolute;\n  bottom: 20px;\n  z-index: 1;\n  width: 100%;\n  height: 15px;\n  text-align: center; }\n  .slider-pager .slider-pager-page {\n    display: inline-block;\n    margin: 0px 3px;\n    width: 15px;\n    color: #000;\n    text-decoration: none;\n    opacity: 0.3; }\n    .slider-pager .slider-pager-page.active {\n      -webkit-transition: opacity 0.4s ease-in;\n      transition: opacity 0.4s ease-in;\n      opacity: 1; }\n\n.scroll-refresher {\n  position: absolute;\n  top: -60px;\n  right: 0;\n  left: 0;\n  overflow: hidden;\n  margin: auto;\n  height: 60px; }\n  .scroll-refresher .ionic-refresher-content {\n    position: absolute;\n    bottom: 15px;\n    left: 0;\n    width: 100%;\n    color: #666666;\n    text-align: center;\n    font-size: 30px; }\n    .scroll-refresher .ionic-refresher-content .text-refreshing, .scroll-refresher .ionic-refresher-content .text-pulling {\n      font-size: 16px;\n      line-height: 16px; }\n    .scroll-refresher .ionic-refresher-content.ionic-refresher-with-text {\n      bottom: 10px; }\n  .scroll-refresher .icon-refreshing, .scroll-refresher .icon-pulling {\n    width: 100%;\n    -webkit-backface-visibility: hidden;\n    backface-visibility: hidden;\n    -webkit-transform-style: preserve-3d;\n    transform-style: preserve-3d; }\n  .scroll-refresher .icon-pulling {\n    -webkit-animation-name: refresh-spin-back;\n    animation-name: refresh-spin-back;\n    -webkit-animation-duration: 200ms;\n    animation-duration: 200ms;\n    -webkit-animation-timing-function: linear;\n    animation-timing-function: linear;\n    -webkit-animation-fill-mode: none;\n    animation-fill-mode: none;\n    -webkit-transform: translate3d(0, 0, 0) rotate(0deg);\n    transform: translate3d(0, 0, 0) rotate(0deg); }\n  .scroll-refresher .icon-refreshing, .scroll-refresher .text-refreshing {\n    display: none; }\n  .scroll-refresher .icon-refreshing {\n    -webkit-animation-duration: 1.5s;\n    animation-duration: 1.5s; }\n  .scroll-refresher.active .icon-pulling:not(.pulling-rotation-disabled) {\n    -webkit-animation-name: refresh-spin;\n    animation-name: refresh-spin;\n    -webkit-transform: translate3d(0, 0, 0) rotate(-180deg);\n    transform: translate3d(0, 0, 0) rotate(-180deg); }\n  .scroll-refresher.active.refreshing {\n    -webkit-transition: -webkit-transform 0.2s;\n    transition: -webkit-transform 0.2s;\n    -webkit-transition: transform 0.2s;\n    transition: transform 0.2s;\n    -webkit-transform: scale(1, 1);\n    transform: scale(1, 1); }\n    .scroll-refresher.active.refreshing .icon-pulling, .scroll-refresher.active.refreshing .text-pulling {\n      display: none; }\n    .scroll-refresher.active.refreshing .icon-refreshing, .scroll-refresher.active.refreshing .text-refreshing {\n      display: block; }\n    .scroll-refresher.active.refreshing.refreshing-tail {\n      -webkit-transform: scale(0, 0);\n      transform: scale(0, 0); }\n\n.overflow-scroll > .scroll {\n  -webkit-overflow-scrolling: touch;\n  width: 100%; }\n  .overflow-scroll > .scroll.overscroll {\n    position: fixed; }\n\n@-webkit-keyframes refresh-spin {\n  0% {\n    -webkit-transform: translate3d(0, 0, 0) rotate(0); }\n\n  100% {\n    -webkit-transform: translate3d(0, 0, 0) rotate(180deg); } }\n\n@keyframes refresh-spin {\n  0% {\n    transform: translate3d(0, 0, 0) rotate(0); }\n\n  100% {\n    transform: translate3d(0, 0, 0) rotate(180deg); } }\n\n@-webkit-keyframes refresh-spin-back {\n  0% {\n    -webkit-transform: translate3d(0, 0, 0) rotate(180deg); }\n\n  100% {\n    -webkit-transform: translate3d(0, 0, 0) rotate(0); } }\n\n@keyframes refresh-spin-back {\n  0% {\n    transform: translate3d(0, 0, 0) rotate(180deg); }\n\n  100% {\n    transform: translate3d(0, 0, 0) rotate(0); } }\n\n/**\n * Spinners\n * --------------------------------------------------\n */\n.spinner {\n  stroke: #444;\n  fill: #444; }\n  .spinner svg {\n    width: 28px;\n    height: 28px; }\n  .spinner.spinner-light {\n    stroke: #fff;\n    fill: #fff; }\n  .spinner.spinner-stable {\n    stroke: #f8f8f8;\n    fill: #f8f8f8; }\n  .spinner.spinner-positive {\n    stroke: #387ef5;\n    fill: #387ef5; }\n  .spinner.spinner-calm {\n    stroke: #11c1f3;\n    fill: #11c1f3; }\n  .spinner.spinner-balanced {\n    stroke: #33cd5f;\n    fill: #33cd5f; }\n  .spinner.spinner-assertive {\n    stroke: #ef473a;\n    fill: #ef473a; }\n  .spinner.spinner-energized {\n    stroke: #ffc900;\n    fill: #ffc900; }\n  .spinner.spinner-royal {\n    stroke: #886aea;\n    fill: #886aea; }\n  .spinner.spinner-dark {\n    stroke: #444;\n    fill: #444; }\n\n.spinner-android {\n  stroke: #4b8bf4; }\n\n.spinner-ios, .spinner-ios-small {\n  stroke: #69717d; }\n\n.spinner-spiral .stop1 {\n  stop-color: #fff;\n  stop-opacity: 0; }\n.spinner-spiral.spinner-light .stop1 {\n  stop-color: #444; }\n.spinner-spiral.spinner-light .stop2 {\n  stop-color: #fff; }\n.spinner-spiral.spinner-stable .stop2 {\n  stop-color: #f8f8f8; }\n.spinner-spiral.spinner-positive .stop2 {\n  stop-color: #387ef5; }\n.spinner-spiral.spinner-calm .stop2 {\n  stop-color: #11c1f3; }\n.spinner-spiral.spinner-balanced .stop2 {\n  stop-color: #33cd5f; }\n.spinner-spiral.spinner-assertive .stop2 {\n  stop-color: #ef473a; }\n.spinner-spiral.spinner-energized .stop2 {\n  stop-color: #ffc900; }\n.spinner-spiral.spinner-royal .stop2 {\n  stop-color: #886aea; }\n.spinner-spiral.spinner-dark .stop2 {\n  stop-color: #444; }\n\n/**\n * Forms\n * --------------------------------------------------\n */\nform {\n  margin: 0 0 1.42857; }\n\nlegend {\n  display: block;\n  margin-bottom: 1.42857;\n  padding: 0;\n  width: 100%;\n  border: 1px solid #ddd;\n  color: #444;\n  font-size: 21px;\n  line-height: 2.85714; }\n  legend small {\n    color: #f8f8f8;\n    font-size: 1.07143; }\n\nlabel, input, button, select, textarea {\n  font-weight: normal;\n  font-size: 14px;\n  line-height: 1.42857; }\n\ninput, button, select, textarea {\n  font-family: \"Helvetica Neue\", \"Roboto\", \"Segoe UI\", sans-serif; }\n\n.item-input {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  position: relative;\n  overflow: hidden;\n  padding: 6px 0 5px 16px; }\n  .item-input input {\n    -webkit-border-radius: 0;\n    border-radius: 0;\n    -webkit-box-flex: 1;\n    -webkit-flex: 1 220px;\n    -moz-box-flex: 1;\n    -moz-flex: 1 220px;\n    -ms-flex: 1 220px;\n    flex: 1 220px;\n    -webkit-appearance: none;\n    -moz-appearance: none;\n    appearance: none;\n    margin: 0;\n    padding-right: 24px;\n    background-color: transparent; }\n  .item-input .button .icon {\n    -webkit-box-flex: 0;\n    -webkit-flex: 0 0 24px;\n    -moz-box-flex: 0;\n    -moz-flex: 0 0 24px;\n    -ms-flex: 0 0 24px;\n    flex: 0 0 24px;\n    position: static;\n    display: inline-block;\n    height: auto;\n    text-align: center;\n    font-size: 16px; }\n  .item-input .button-bar {\n    -webkit-border-radius: 0;\n    border-radius: 0;\n    -webkit-box-flex: 1;\n    -webkit-flex: 1 0 220px;\n    -moz-box-flex: 1;\n    -moz-flex: 1 0 220px;\n    -ms-flex: 1 0 220px;\n    flex: 1 0 220px;\n    -webkit-appearance: none;\n    -moz-appearance: none;\n    appearance: none; }\n  .item-input .icon {\n    min-width: 14px; }\n\n.platform-windowsphone .item-input input {\n  flex-shrink: 1; }\n\n.item-input-inset {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  position: relative;\n  overflow: hidden;\n  padding: 10.66667px; }\n\n.item-input-wrapper {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-flex: 1;\n  -webkit-flex: 1 0;\n  -moz-box-flex: 1;\n  -moz-flex: 1 0;\n  -ms-flex: 1 0;\n  flex: 1 0;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  -webkit-border-radius: 4px;\n  border-radius: 4px;\n  padding-right: 8px;\n  padding-left: 8px;\n  background: #eee; }\n\n.item-input-inset .item-input-wrapper input {\n  padding-left: 4px;\n  height: 29px;\n  background: transparent;\n  line-height: 18px; }\n\n.item-input-wrapper ~ .button {\n  margin-left: 10.66667px; }\n\n.input-label {\n  display: table;\n  padding: 7px 10px 7px 0px;\n  max-width: 200px;\n  width: 35%;\n  color: #444;\n  font-size: 16px; }\n\n.placeholder-icon {\n  color: #aaa; }\n  .placeholder-icon:first-child {\n    padding-right: 6px; }\n  .placeholder-icon:last-child {\n    padding-left: 6px; }\n\n.item-stacked-label {\n  display: block;\n  background-color: transparent;\n  box-shadow: none; }\n  .item-stacked-label .input-label, .item-stacked-label .icon {\n    display: inline-block;\n    padding: 4px 0 0 0px;\n    vertical-align: middle; }\n\n.item-stacked-label input, .item-stacked-label textarea {\n  -webkit-border-radius: 2px;\n  border-radius: 2px;\n  padding: 4px 8px 3px 0;\n  border: none;\n  background-color: #fff; }\n\n.item-stacked-label input {\n  overflow: hidden;\n  height: 46px; }\n\n.item-floating-label {\n  display: block;\n  background-color: transparent;\n  box-shadow: none; }\n  .item-floating-label .input-label {\n    position: relative;\n    padding: 5px 0 0 0;\n    opacity: 0;\n    top: 10px;\n    -webkit-transition: opacity 0.15s ease-in, top 0.2s linear;\n    transition: opacity 0.15s ease-in, top 0.2s linear; }\n    .item-floating-label .input-label.has-input {\n      opacity: 1;\n      top: 0;\n      -webkit-transition: opacity 0.15s ease-in, top 0.2s linear;\n      transition: opacity 0.15s ease-in, top 0.2s linear; }\n\ntextarea, input[type=\"text\"], input[type=\"password\"], input[type=\"datetime\"], input[type=\"datetime-local\"], input[type=\"date\"], input[type=\"month\"], input[type=\"time\"], input[type=\"week\"], input[type=\"number\"], input[type=\"email\"], input[type=\"url\"], input[type=\"search\"], input[type=\"tel\"], input[type=\"color\"] {\n  display: block;\n  padding-top: 2px;\n  padding-left: 0;\n  height: 34px;\n  color: #111;\n  vertical-align: middle;\n  font-size: 14px;\n  line-height: 16px; }\n\n.platform-ios input[type=\"datetime-local\"], .platform-ios input[type=\"date\"], .platform-ios input[type=\"month\"], .platform-ios input[type=\"time\"], .platform-ios input[type=\"week\"], .platform-android input[type=\"datetime-local\"], .platform-android input[type=\"date\"], .platform-android input[type=\"month\"], .platform-android input[type=\"time\"], .platform-android input[type=\"week\"] {\n  padding-top: 8px; }\n\n.item-input input, .item-input textarea {\n  width: 100%; }\n\ntextarea {\n  padding-left: 0; }\n  textarea::-moz-placeholder {\n    color: #aaaaaa; }\n  textarea:-ms-input-placeholder {\n    color: #aaaaaa; }\n  textarea::-webkit-input-placeholder {\n    color: #aaaaaa;\n    text-indent: -3px; }\n\ntextarea {\n  height: auto; }\n\ntextarea, input[type=\"text\"], input[type=\"password\"], input[type=\"datetime\"], input[type=\"datetime-local\"], input[type=\"date\"], input[type=\"month\"], input[type=\"time\"], input[type=\"week\"], input[type=\"number\"], input[type=\"email\"], input[type=\"url\"], input[type=\"search\"], input[type=\"tel\"], input[type=\"color\"] {\n  border: 0; }\n\ninput[type=\"radio\"], input[type=\"checkbox\"] {\n  margin: 0;\n  line-height: normal; }\n\n.item-input input[type=\"file\"], .item-input input[type=\"image\"], .item-input input[type=\"submit\"], .item-input input[type=\"reset\"], .item-input input[type=\"button\"], .item-input input[type=\"radio\"], .item-input input[type=\"checkbox\"] {\n  width: auto; }\n\ninput[type=\"file\"] {\n  line-height: 34px; }\n\n.previous-input-focus, .cloned-text-input + input, .cloned-text-input + textarea {\n  position: absolute !important;\n  left: -9999px;\n  width: 200px; }\n\ninput::-moz-placeholder, textarea::-moz-placeholder {\n  color: #aaaaaa; }\ninput:-ms-input-placeholder, textarea:-ms-input-placeholder {\n  color: #aaaaaa; }\ninput::-webkit-input-placeholder, textarea::-webkit-input-placeholder {\n  color: #aaaaaa;\n  text-indent: 0; }\n\ninput[disabled], select[disabled], textarea[disabled], input[readonly]:not(.cloned-text-input), textarea[readonly]:not(.cloned-text-input), select[readonly] {\n  background-color: #f8f8f8;\n  cursor: not-allowed; }\n\ninput[type=\"radio\"][disabled], input[type=\"checkbox\"][disabled], input[type=\"radio\"][readonly], input[type=\"checkbox\"][readonly] {\n  background-color: transparent; }\n\n/**\n * Checkbox\n * --------------------------------------------------\n */\n.checkbox {\n  position: relative;\n  display: inline-block;\n  padding: 7px 7px;\n  cursor: pointer; }\n  .checkbox input:before, .checkbox .checkbox-icon:before {\n    border-color: #ddd; }\n  .checkbox input:checked:before, .checkbox input:checked + .checkbox-icon:before {\n    background: #387ef5;\n    border-color: #387ef5; }\n\n.checkbox-light input:before, .checkbox-light .checkbox-icon:before {\n  border-color: #ddd; }\n.checkbox-light input:checked:before, .checkbox-light input:checked + .checkbox-icon:before {\n  background: #ddd;\n  border-color: #ddd; }\n\n.checkbox-stable input:before, .checkbox-stable .checkbox-icon:before {\n  border-color: #b2b2b2; }\n.checkbox-stable input:checked:before, .checkbox-stable input:checked + .checkbox-icon:before {\n  background: #b2b2b2;\n  border-color: #b2b2b2; }\n\n.checkbox-positive input:before, .checkbox-positive .checkbox-icon:before {\n  border-color: #387ef5; }\n.checkbox-positive input:checked:before, .checkbox-positive input:checked + .checkbox-icon:before {\n  background: #387ef5;\n  border-color: #387ef5; }\n\n.checkbox-calm input:before, .checkbox-calm .checkbox-icon:before {\n  border-color: #11c1f3; }\n.checkbox-calm input:checked:before, .checkbox-calm input:checked + .checkbox-icon:before {\n  background: #11c1f3;\n  border-color: #11c1f3; }\n\n.checkbox-assertive input:before, .checkbox-assertive .checkbox-icon:before {\n  border-color: #ef473a; }\n.checkbox-assertive input:checked:before, .checkbox-assertive input:checked + .checkbox-icon:before {\n  background: #ef473a;\n  border-color: #ef473a; }\n\n.checkbox-balanced input:before, .checkbox-balanced .checkbox-icon:before {\n  border-color: #33cd5f; }\n.checkbox-balanced input:checked:before, .checkbox-balanced input:checked + .checkbox-icon:before {\n  background: #33cd5f;\n  border-color: #33cd5f; }\n\n.checkbox-energized input:before, .checkbox-energized .checkbox-icon:before {\n  border-color: #ffc900; }\n.checkbox-energized input:checked:before, .checkbox-energized input:checked + .checkbox-icon:before {\n  background: #ffc900;\n  border-color: #ffc900; }\n\n.checkbox-royal input:before, .checkbox-royal .checkbox-icon:before {\n  border-color: #886aea; }\n.checkbox-royal input:checked:before, .checkbox-royal input:checked + .checkbox-icon:before {\n  background: #886aea;\n  border-color: #886aea; }\n\n.checkbox-dark input:before, .checkbox-dark .checkbox-icon:before {\n  border-color: #444; }\n.checkbox-dark input:checked:before, .checkbox-dark input:checked + .checkbox-icon:before {\n  background: #444;\n  border-color: #444; }\n\n.checkbox input:disabled:before, .checkbox input:disabled + .checkbox-icon:before {\n  border-color: #ddd; }\n\n.checkbox input:disabled:checked:before, .checkbox input:disabled:checked + .checkbox-icon:before {\n  background: #ddd; }\n\n.checkbox.checkbox-input-hidden input {\n  display: none !important; }\n\n.checkbox input, .checkbox-icon {\n  position: relative;\n  width: 28px;\n  height: 28px;\n  display: block;\n  border: 0;\n  background: transparent;\n  cursor: pointer;\n  -webkit-appearance: none; }\n  .checkbox input:before, .checkbox-icon:before {\n    display: table;\n    width: 100%;\n    height: 100%;\n    border-width: 1px;\n    border-style: solid;\n    border-radius: 28px;\n    background: #fff;\n    content: ' ';\n    -webkit-transition: background-color 20ms ease-in-out;\n    transition: background-color 20ms ease-in-out; }\n\n.checkbox input:checked:before, input:checked + .checkbox-icon:before {\n  border-width: 2px; }\n\n.checkbox input:after, .checkbox-icon:after {\n  -webkit-transition: opacity 0.05s ease-in-out;\n  transition: opacity 0.05s ease-in-out;\n  -webkit-transform: rotate(-45deg);\n  transform: rotate(-45deg);\n  position: absolute;\n  top: 33%;\n  left: 25%;\n  display: table;\n  width: 14px;\n  height: 6px;\n  border: 1px solid #fff;\n  border-top: 0;\n  border-right: 0;\n  content: ' ';\n  opacity: 0; }\n\n.platform-android .checkbox-platform input:before, .platform-android .checkbox-platform .checkbox-icon:before, .checkbox-square input:before, .checkbox-square .checkbox-icon:before {\n  border-radius: 2px;\n  width: 72%;\n  height: 72%;\n  margin-top: 14%;\n  margin-left: 14%;\n  border-width: 2px; }\n\n.platform-android .checkbox-platform input:after, .platform-android .checkbox-platform .checkbox-icon:after, .checkbox-square input:after, .checkbox-square .checkbox-icon:after {\n  border-width: 2px;\n  top: 19%;\n  left: 25%;\n  width: 13px;\n  height: 7px; }\n\n.grade-c .checkbox input:after, .grade-c .checkbox-icon:after {\n  -webkit-transform: rotate(0);\n  transform: rotate(0);\n  top: 3px;\n  left: 4px;\n  border: none;\n  color: #fff;\n  content: '\\2713';\n  font-weight: bold;\n  font-size: 20px; }\n\n.checkbox input:checked:after, input:checked + .checkbox-icon:after {\n  opacity: 1; }\n\n.item-checkbox {\n  padding-left: 60px; }\n  .item-checkbox.active {\n    box-shadow: none; }\n\n.item-checkbox .checkbox {\n  position: absolute;\n  top: 50%;\n  right: 8px;\n  left: 8px;\n  z-index: 3;\n  margin-top: -21px; }\n\n.item-checkbox.item-checkbox-right {\n  padding-right: 60px;\n  padding-left: 16px; }\n\n.item-checkbox-right .checkbox input, .item-checkbox-right .checkbox-icon {\n  float: right; }\n\n/**\n * Toggle\n * --------------------------------------------------\n */\n.item-toggle {\n  pointer-events: none; }\n\n.toggle {\n  position: relative;\n  display: inline-block;\n  pointer-events: auto;\n  margin: -5px;\n  padding: 5px; }\n  .toggle input:checked + .track {\n    border-color: #4cd964;\n    background-color: #4cd964; }\n  .toggle.dragging .handle {\n    background-color: #f2f2f2 !important; }\n\n.toggle.toggle-light input:checked + .track {\n  border-color: #ddd;\n  background-color: #ddd; }\n.toggle.toggle-stable input:checked + .track {\n  border-color: #b2b2b2;\n  background-color: #b2b2b2; }\n.toggle.toggle-positive input:checked + .track {\n  border-color: #387ef5;\n  background-color: #387ef5; }\n.toggle.toggle-calm input:checked + .track {\n  border-color: #11c1f3;\n  background-color: #11c1f3; }\n.toggle.toggle-assertive input:checked + .track {\n  border-color: #ef473a;\n  background-color: #ef473a; }\n.toggle.toggle-balanced input:checked + .track {\n  border-color: #33cd5f;\n  background-color: #33cd5f; }\n.toggle.toggle-energized input:checked + .track {\n  border-color: #ffc900;\n  background-color: #ffc900; }\n.toggle.toggle-royal input:checked + .track {\n  border-color: #886aea;\n  background-color: #886aea; }\n.toggle.toggle-dark input:checked + .track {\n  border-color: #444;\n  background-color: #444; }\n\n.toggle input {\n  display: none; }\n\n/* the track appearance when the toggle is \"off\" */\n.toggle .track {\n  -webkit-transition-timing-function: ease-in-out;\n  transition-timing-function: ease-in-out;\n  -webkit-transition-duration: 0.3s;\n  transition-duration: 0.3s;\n  -webkit-transition-property: background-color, border;\n  transition-property: background-color, border;\n  display: inline-block;\n  box-sizing: border-box;\n  width: 51px;\n  height: 31px;\n  border: solid 2px #e6e6e6;\n  border-radius: 20px;\n  background-color: #fff;\n  content: ' ';\n  cursor: pointer;\n  pointer-events: none; }\n\n/* Fix to avoid background color bleeding */\n/* (occured on (at least) Android 4.2, Asus MeMO Pad HD7 ME173X) */\n.platform-android4_2 .toggle .track {\n  -webkit-background-clip: padding-box; }\n\n/* the handle (circle) thats inside the toggle's track area */\n/* also the handle's appearance when it is \"off\" */\n.toggle .handle {\n  -webkit-transition: 0.3s cubic-bezier(0, 1.1, 1, 1.1);\n  transition: 0.3s cubic-bezier(0, 1.1, 1, 1.1);\n  -webkit-transition-property: background-color, transform;\n  transition-property: background-color, transform;\n  position: absolute;\n  display: block;\n  width: 27px;\n  height: 27px;\n  border-radius: 27px;\n  background-color: #fff;\n  top: 7px;\n  left: 7px;\n  box-shadow: 0 2px 7px rgba(0, 0, 0, 0.35), 0 1px 1px rgba(0, 0, 0, 0.15); }\n  .toggle .handle:before {\n    position: absolute;\n    top: -4px;\n    left: -21.5px;\n    padding: 18.5px 34px;\n    content: \" \"; }\n\n.toggle input:checked + .track .handle {\n  -webkit-transform: translate3d(20px, 0, 0);\n  transform: translate3d(20px, 0, 0);\n  background-color: #fff; }\n\n.item-toggle.active {\n  box-shadow: none; }\n\n.item-toggle, .item-toggle.item-complex .item-content {\n  padding-right: 99px; }\n\n.item-toggle.item-complex {\n  padding-right: 0; }\n\n.item-toggle .toggle {\n  position: absolute;\n  top: 10px;\n  right: 16px;\n  z-index: 3; }\n\n.toggle input:disabled + .track {\n  opacity: 0.6; }\n\n.toggle-small .track {\n  border: 0;\n  width: 34px;\n  height: 15px;\n  background: #9e9e9e; }\n.toggle-small input:checked + .track {\n  background: rgba(0, 150, 137, 0.5); }\n.toggle-small .handle {\n  top: 2px;\n  left: 4px;\n  width: 21px;\n  height: 21px;\n  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.25); }\n.toggle-small input:checked + .track .handle {\n  -webkit-transform: translate3d(16px, 0, 0);\n  transform: translate3d(16px, 0, 0);\n  background: #009689; }\n.toggle-small.item-toggle .toggle {\n  top: 19px; }\n.toggle-small .toggle-light input:checked + .track {\n  background-color: rgba(221, 221, 221, 0.5); }\n.toggle-small .toggle-light input:checked + .track .handle {\n  background-color: #ddd; }\n.toggle-small .toggle-stable input:checked + .track {\n  background-color: rgba(178, 178, 178, 0.5); }\n.toggle-small .toggle-stable input:checked + .track .handle {\n  background-color: #b2b2b2; }\n.toggle-small .toggle-positive input:checked + .track {\n  background-color: rgba(56, 126, 245, 0.5); }\n.toggle-small .toggle-positive input:checked + .track .handle {\n  background-color: #387ef5; }\n.toggle-small .toggle-calm input:checked + .track {\n  background-color: rgba(17, 193, 243, 0.5); }\n.toggle-small .toggle-calm input:checked + .track .handle {\n  background-color: #11c1f3; }\n.toggle-small .toggle-assertive input:checked + .track {\n  background-color: rgba(239, 71, 58, 0.5); }\n.toggle-small .toggle-assertive input:checked + .track .handle {\n  background-color: #ef473a; }\n.toggle-small .toggle-balanced input:checked + .track {\n  background-color: rgba(51, 205, 95, 0.5); }\n.toggle-small .toggle-balanced input:checked + .track .handle {\n  background-color: #33cd5f; }\n.toggle-small .toggle-energized input:checked + .track {\n  background-color: rgba(255, 201, 0, 0.5); }\n.toggle-small .toggle-energized input:checked + .track .handle {\n  background-color: #ffc900; }\n.toggle-small .toggle-royal input:checked + .track {\n  background-color: rgba(136, 106, 234, 0.5); }\n.toggle-small .toggle-royal input:checked + .track .handle {\n  background-color: #886aea; }\n.toggle-small .toggle-dark input:checked + .track {\n  background-color: rgba(68, 68, 68, 0.5); }\n.toggle-small .toggle-dark input:checked + .track .handle {\n  background-color: #444; }\n\n/**\n * Radio Button Inputs\n * --------------------------------------------------\n */\n.item-radio {\n  padding: 0; }\n  .item-radio:hover {\n    cursor: pointer; }\n\n.item-radio .item-content {\n  /* give some room to the right for the checkmark icon */\n  padding-right: 64px; }\n\n.item-radio .radio-icon {\n  /* checkmark icon will be hidden by default */\n  position: absolute;\n  top: 0;\n  right: 0;\n  z-index: 3;\n  visibility: hidden;\n  padding: 14px;\n  height: 100%;\n  font-size: 24px; }\n\n.item-radio input {\n  /* hide any radio button inputs elements (the ugly circles) */\n  position: absolute;\n  left: -9999px; }\n  .item-radio input:checked ~ .item-content {\n    /* style the item content when its checked */\n    background: #f7f7f7; }\n  .item-radio input:checked ~ .radio-icon {\n    /* show the checkmark icon when its checked */\n    visibility: visible; }\n\n.platform-android.grade-b .item-radio, .platform-android.grade-c .item-radio {\n  -webkit-animation: androidCheckedbugfix infinite 1s; }\n\n@-webkit-keyframes androidCheckedbugfix {\n  from {\n    padding: 0; }\n\n  to {\n    padding: 0; } }\n\n/**\n * Range\n * --------------------------------------------------\n */\n.range input {\n  display: inline-block;\n  overflow: hidden;\n  margin-top: 5px;\n  margin-bottom: 5px;\n  padding-right: 2px;\n  padding-left: 1px;\n  width: auto;\n  height: 43px;\n  outline: none;\n  background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, #ccc), color-stop(100%, #ccc));\n  background: linear-gradient(to right, #ccc 0%, #ccc 100%);\n  background-position: center;\n  background-size: 99% 2px;\n  background-repeat: no-repeat;\n  -webkit-appearance: none; }\n  .range input::-webkit-slider-thumb {\n    position: relative;\n    width: 28px;\n    height: 28px;\n    border-radius: 50%;\n    background-color: #fff;\n    box-shadow: 0 0 2px rgba(0, 0, 0, 0.3), 0 3px 5px rgba(0, 0, 0, 0.2);\n    cursor: pointer;\n    -webkit-appearance: none;\n    border: 0; }\n  .range input::-webkit-slider-thumb:before {\n    /* what creates the colorful line on the left side of the slider */\n    position: absolute;\n    top: 13px;\n    left: -2001px;\n    width: 2000px;\n    height: 2px;\n    background: #444;\n    content: ' '; }\n  .range input::-webkit-slider-thumb:after {\n    /* create a larger (but hidden) hit area */\n    position: absolute;\n    top: -15px;\n    left: -15px;\n    padding: 30px;\n    content: ' '; }\n  .range input::-ms-track {\n    background: transparent;\n    border-color: transparent;\n    border-width: 11px 0 16px;\n    color: transparent;\n    margin-top: 20px; }\n  .range input::-ms-thumb {\n    width: 28px;\n    height: 28px;\n    border-radius: 50%;\n    background-color: #fff;\n    border-color: #fff;\n    box-shadow: 0 0 2px rgba(0, 0, 0, 0.3), 0 3px 5px rgba(0, 0, 0, 0.2);\n    margin-left: 1px;\n    margin-right: 1px;\n    outline: none; }\n  .range input::-ms-fill-lower {\n    height: 2px;\n    background: #444; }\n  .range input::-ms-fill-upper {\n    height: 2px;\n    background: #ccc; }\n\n.range {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center;\n  padding: 2px 11px; }\n  .range.range-light input::-webkit-slider-thumb:before {\n    background: #ddd; }\n  .range.range-light input::-ms-fill-lower {\n    background: #ddd; }\n  .range.range-stable input::-webkit-slider-thumb:before {\n    background: #b2b2b2; }\n  .range.range-stable input::-ms-fill-lower {\n    background: #b2b2b2; }\n  .range.range-positive input::-webkit-slider-thumb:before {\n    background: #387ef5; }\n  .range.range-positive input::-ms-fill-lower {\n    background: #387ef5; }\n  .range.range-calm input::-webkit-slider-thumb:before {\n    background: #11c1f3; }\n  .range.range-calm input::-ms-fill-lower {\n    background: #11c1f3; }\n  .range.range-balanced input::-webkit-slider-thumb:before {\n    background: #33cd5f; }\n  .range.range-balanced input::-ms-fill-lower {\n    background: #33cd5f; }\n  .range.range-assertive input::-webkit-slider-thumb:before {\n    background: #ef473a; }\n  .range.range-assertive input::-ms-fill-lower {\n    background: #ef473a; }\n  .range.range-energized input::-webkit-slider-thumb:before {\n    background: #ffc900; }\n  .range.range-energized input::-ms-fill-lower {\n    background: #ffc900; }\n  .range.range-royal input::-webkit-slider-thumb:before {\n    background: #886aea; }\n  .range.range-royal input::-ms-fill-lower {\n    background: #886aea; }\n  .range.range-dark input::-webkit-slider-thumb:before {\n    background: #444; }\n  .range.range-dark input::-ms-fill-lower {\n    background: #444; }\n\n.range .icon {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0;\n  -moz-box-flex: 0;\n  -moz-flex: 0;\n  -ms-flex: 0;\n  flex: 0;\n  display: block;\n  min-width: 24px;\n  text-align: center;\n  font-size: 24px; }\n\n.range input {\n  -webkit-box-flex: 1;\n  -webkit-flex: 1;\n  -moz-box-flex: 1;\n  -moz-flex: 1;\n  -ms-flex: 1;\n  flex: 1;\n  display: block;\n  margin-right: 10px;\n  margin-left: 10px; }\n\n.range-label {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 auto;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 auto;\n  -ms-flex: 0 0 auto;\n  flex: 0 0 auto;\n  display: block;\n  white-space: nowrap; }\n\n.range-label:first-child {\n  padding-left: 5px; }\n\n.range input + .range-label {\n  padding-right: 5px;\n  padding-left: 0; }\n\n.platform-windowsphone .range input {\n  height: auto; }\n\n/**\n * Select\n * --------------------------------------------------\n */\n.item-select {\n  position: relative; }\n  .item-select select {\n    -webkit-appearance: none;\n    -moz-appearance: none;\n    appearance: none;\n    position: absolute;\n    top: 0;\n    bottom: 0;\n    right: 0;\n    padding: 14px 48px 16px 16px;\n    max-width: 65%;\n    border: none;\n    background: #fff;\n    color: #333;\n    text-indent: 0.01px;\n    text-overflow: '';\n    white-space: nowrap;\n    font-size: 14px;\n    cursor: pointer;\n    direction: rtl; }\n  .item-select select::-ms-expand {\n    display: none; }\n  .item-select option {\n    direction: ltr; }\n  .item-select:after {\n    position: absolute;\n    top: 50%;\n    right: 16px;\n    margin-top: -3px;\n    width: 0;\n    height: 0;\n    border-top: 5px solid;\n    border-right: 5px solid rgba(0, 0, 0, 0);\n    border-left: 5px solid rgba(0, 0, 0, 0);\n    color: #999;\n    content: \"\";\n    pointer-events: none; }\n  .item-select.item-light select {\n    background: #fff;\n    color: #444; }\n  .item-select.item-stable select {\n    background: #f8f8f8;\n    color: #444; }\n  .item-select.item-stable:after, .item-select.item-stable .input-label {\n    color: #656565; }\n  .item-select.item-positive select {\n    background: #387ef5;\n    color: #fff; }\n  .item-select.item-positive:after, .item-select.item-positive .input-label {\n    color: #fff; }\n  .item-select.item-calm select {\n    background: #11c1f3;\n    color: #fff; }\n  .item-select.item-calm:after, .item-select.item-calm .input-label {\n    color: #fff; }\n  .item-select.item-assertive select {\n    background: #ef473a;\n    color: #fff; }\n  .item-select.item-assertive:after, .item-select.item-assertive .input-label {\n    color: #fff; }\n  .item-select.item-balanced select {\n    background: #33cd5f;\n    color: #fff; }\n  .item-select.item-balanced:after, .item-select.item-balanced .input-label {\n    color: #fff; }\n  .item-select.item-energized select {\n    background: #ffc900;\n    color: #fff; }\n  .item-select.item-energized:after, .item-select.item-energized .input-label {\n    color: #fff; }\n  .item-select.item-royal select {\n    background: #886aea;\n    color: #fff; }\n  .item-select.item-royal:after, .item-select.item-royal .input-label {\n    color: #fff; }\n  .item-select.item-dark select {\n    background: #444;\n    color: #fff; }\n  .item-select.item-dark:after, .item-select.item-dark .input-label {\n    color: #fff; }\n\nselect[multiple], select[size] {\n  height: auto; }\n\n/**\n * Progress\n * --------------------------------------------------\n */\nprogress {\n  display: block;\n  margin: 15px auto;\n  width: 100%; }\n\n/**\n * Buttons\n * --------------------------------------------------\n */\n.button {\n  border-color: #b2b2b2;\n  background-color: #f8f8f8;\n  color: #444;\n  position: relative;\n  display: inline-block;\n  margin: 0;\n  padding: 0 12px;\n  min-width: 52px;\n  min-height: 47px;\n  border-width: 1px;\n  border-style: solid;\n  border-radius: 2px;\n  vertical-align: top;\n  text-align: center;\n  text-overflow: ellipsis;\n  font-size: 16px;\n  line-height: 42px;\n  cursor: pointer; }\n  .button:hover {\n    color: #444;\n    text-decoration: none; }\n  .button.active, .button.activated {\n    border-color: #a2a2a2;\n    background-color: #e5e5e5;\n    box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n  .button:after {\n    position: absolute;\n    top: -6px;\n    right: -6px;\n    bottom: -6px;\n    left: -6px;\n    content: ' '; }\n  .button .icon {\n    vertical-align: top;\n    pointer-events: none; }\n  .button .icon:before, .button.icon:before, .button.icon-left:before, .button.icon-right:before {\n    display: inline-block;\n    padding: 0 0 1px 0;\n    vertical-align: inherit;\n    font-size: 24px;\n    line-height: 41px;\n    pointer-events: none; }\n  .button.icon-left:before {\n    float: left;\n    padding-right: 0.2em;\n    padding-left: 0; }\n  .button.icon-right:before {\n    float: right;\n    padding-right: 0;\n    padding-left: 0.2em; }\n  .button.button-block, .button.button-full {\n    margin-top: 10px;\n    margin-bottom: 10px; }\n  .button.button-light {\n    border-color: #ddd;\n    background-color: #fff;\n    color: #444; }\n    .button.button-light:hover {\n      color: #444;\n      text-decoration: none; }\n    .button.button-light.active, .button.button-light.activated {\n      border-color: #ccc;\n      background-color: #fafafa;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-light.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #ddd; }\n    .button.button-light.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-light.button-outline {\n      border-color: #ddd;\n      background: transparent;\n      color: #ddd; }\n      .button.button-light.button-outline.active, .button.button-light.button-outline.activated {\n        background-color: #ddd;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-stable {\n    border-color: #b2b2b2;\n    background-color: #f8f8f8;\n    color: #444; }\n    .button.button-stable:hover {\n      color: #444;\n      text-decoration: none; }\n    .button.button-stable.active, .button.button-stable.activated {\n      border-color: #a2a2a2;\n      background-color: #e5e5e5;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-stable.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #b2b2b2; }\n    .button.button-stable.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-stable.button-outline {\n      border-color: #b2b2b2;\n      background: transparent;\n      color: #b2b2b2; }\n      .button.button-stable.button-outline.active, .button.button-stable.button-outline.activated {\n        background-color: #b2b2b2;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-positive {\n    border-color: #0c63ee;\n    background-color: #387ef5;\n    color: #fff; }\n    .button.button-positive:hover {\n      color: #fff;\n      text-decoration: none; }\n    .button.button-positive.active, .button.button-positive.activated {\n      border-color: #0c63ee;\n      background-color: #0c63ee;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-positive.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #387ef5; }\n    .button.button-positive.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-positive.button-outline {\n      border-color: #387ef5;\n      background: transparent;\n      color: #387ef5; }\n      .button.button-positive.button-outline.active, .button.button-positive.button-outline.activated {\n        background-color: #387ef5;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-calm {\n    border-color: #0a9ec7;\n    background-color: #11c1f3;\n    color: #fff; }\n    .button.button-calm:hover {\n      color: #fff;\n      text-decoration: none; }\n    .button.button-calm.active, .button.button-calm.activated {\n      border-color: #0a9ec7;\n      background-color: #0a9ec7;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-calm.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #11c1f3; }\n    .button.button-calm.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-calm.button-outline {\n      border-color: #11c1f3;\n      background: transparent;\n      color: #11c1f3; }\n      .button.button-calm.button-outline.active, .button.button-calm.button-outline.activated {\n        background-color: #11c1f3;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-assertive {\n    border-color: #e42012;\n    background-color: #ef473a;\n    color: #fff; }\n    .button.button-assertive:hover {\n      color: #fff;\n      text-decoration: none; }\n    .button.button-assertive.active, .button.button-assertive.activated {\n      border-color: #e42012;\n      background-color: #e42012;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-assertive.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #ef473a; }\n    .button.button-assertive.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-assertive.button-outline {\n      border-color: #ef473a;\n      background: transparent;\n      color: #ef473a; }\n      .button.button-assertive.button-outline.active, .button.button-assertive.button-outline.activated {\n        background-color: #ef473a;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-balanced {\n    border-color: #28a54c;\n    background-color: #33cd5f;\n    color: #fff; }\n    .button.button-balanced:hover {\n      color: #fff;\n      text-decoration: none; }\n    .button.button-balanced.active, .button.button-balanced.activated {\n      border-color: #28a54c;\n      background-color: #28a54c;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-balanced.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #33cd5f; }\n    .button.button-balanced.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-balanced.button-outline {\n      border-color: #33cd5f;\n      background: transparent;\n      color: #33cd5f; }\n      .button.button-balanced.button-outline.active, .button.button-balanced.button-outline.activated {\n        background-color: #33cd5f;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-energized {\n    border-color: #e6b400;\n    background-color: #ffc900;\n    color: #fff; }\n    .button.button-energized:hover {\n      color: #fff;\n      text-decoration: none; }\n    .button.button-energized.active, .button.button-energized.activated {\n      border-color: #e6b400;\n      background-color: #e6b400;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-energized.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #ffc900; }\n    .button.button-energized.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-energized.button-outline {\n      border-color: #ffc900;\n      background: transparent;\n      color: #ffc900; }\n      .button.button-energized.button-outline.active, .button.button-energized.button-outline.activated {\n        background-color: #ffc900;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-royal {\n    border-color: #6b46e5;\n    background-color: #886aea;\n    color: #fff; }\n    .button.button-royal:hover {\n      color: #fff;\n      text-decoration: none; }\n    .button.button-royal.active, .button.button-royal.activated {\n      border-color: #6b46e5;\n      background-color: #6b46e5;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-royal.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #886aea; }\n    .button.button-royal.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-royal.button-outline {\n      border-color: #886aea;\n      background: transparent;\n      color: #886aea; }\n      .button.button-royal.button-outline.active, .button.button-royal.button-outline.activated {\n        background-color: #886aea;\n        box-shadow: none;\n        color: #fff; }\n  .button.button-dark {\n    border-color: #111;\n    background-color: #444;\n    color: #fff; }\n    .button.button-dark:hover {\n      color: #fff;\n      text-decoration: none; }\n    .button.button-dark.active, .button.button-dark.activated {\n      border-color: #000;\n      background-color: #262626;\n      box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.1); }\n    .button.button-dark.button-clear {\n      border-color: transparent;\n      background: none;\n      box-shadow: none;\n      color: #444; }\n    .button.button-dark.button-icon {\n      border-color: transparent;\n      background: none; }\n    .button.button-dark.button-outline {\n      border-color: #444;\n      background: transparent;\n      color: #444; }\n      .button.button-dark.button-outline.active, .button.button-dark.button-outline.activated {\n        background-color: #444;\n        box-shadow: none;\n        color: #fff; }\n\n.button-small {\n  padding: 2px 4px 1px;\n  min-width: 28px;\n  min-height: 30px;\n  font-size: 12px;\n  line-height: 26px; }\n  .button-small .icon:before, .button-small.icon:before, .button-small.icon-left:before, .button-small.icon-right:before {\n    font-size: 16px;\n    line-height: 19px;\n    margin-top: 3px; }\n\n.button-large {\n  padding: 0 16px;\n  min-width: 68px;\n  min-height: 59px;\n  font-size: 20px;\n  line-height: 53px; }\n  .button-large .icon:before, .button-large.icon:before, .button-large.icon-left:before, .button-large.icon-right:before {\n    padding-bottom: 2px;\n    font-size: 32px;\n    line-height: 51px; }\n\n.button-icon {\n  -webkit-transition: opacity 0.1s;\n  transition: opacity 0.1s;\n  padding: 0 6px;\n  min-width: initial;\n  border-color: transparent;\n  background: none; }\n  .button-icon.button.active, .button-icon.button.activated {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    opacity: 0.3; }\n  .button-icon .icon:before, .button-icon.icon:before {\n    font-size: 32px; }\n\n.button-clear {\n  -webkit-transition: opacity 0.1s;\n  transition: opacity 0.1s;\n  padding: 0 6px;\n  max-height: 42px;\n  border-color: transparent;\n  background: none;\n  box-shadow: none; }\n  .button-clear.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: #b2b2b2; }\n  .button-clear.button-icon {\n    border-color: transparent;\n    background: none; }\n  .button-clear.active, .button-clear.activated {\n    opacity: 0.3; }\n\n.button-outline {\n  -webkit-transition: opacity 0.1s;\n  transition: opacity 0.1s;\n  background: none;\n  box-shadow: none; }\n  .button-outline.button-outline {\n    border-color: #b2b2b2;\n    background: transparent;\n    color: #b2b2b2; }\n    .button-outline.button-outline.active, .button-outline.button-outline.activated {\n      background-color: #b2b2b2;\n      box-shadow: none;\n      color: #fff; }\n\n.padding > .button.button-block:first-child {\n  margin-top: 0; }\n\n.button-block {\n  display: block;\n  clear: both; }\n  .button-block:after {\n    clear: both; }\n\n.button-full, .button-full > .button {\n  display: block;\n  margin-right: 0;\n  margin-left: 0;\n  border-right-width: 0;\n  border-left-width: 0;\n  border-radius: 0; }\n\nbutton.button-block, button.button-full, .button-full > button.button, input.button.button-block {\n  width: 100%; }\n\na.button {\n  text-decoration: none; }\n  a.button .icon:before, a.button.icon:before, a.button.icon-left:before, a.button.icon-right:before {\n    margin-top: 2px; }\n\n.button.disabled, .button[disabled] {\n  opacity: 0.4;\n  cursor: default !important;\n  pointer-events: none; }\n\n/**\n * Button Bar\n * --------------------------------------------------\n */\n.button-bar {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  -webkit-box-flex: 1;\n  -webkit-flex: 1;\n  -moz-box-flex: 1;\n  -moz-flex: 1;\n  -ms-flex: 1;\n  flex: 1;\n  width: 100%; }\n  .button-bar.button-bar-inline {\n    display: block;\n    width: auto;\n    *zoom: 1; }\n    .button-bar.button-bar-inline:before, .button-bar.button-bar-inline:after {\n      display: table;\n      content: \"\";\n      line-height: 0; }\n    .button-bar.button-bar-inline:after {\n      clear: both; }\n    .button-bar.button-bar-inline > .button {\n      width: auto;\n      display: inline-block;\n      float: left; }\n\n.button-bar > .button {\n  -webkit-box-flex: 1;\n  -webkit-flex: 1;\n  -moz-box-flex: 1;\n  -moz-flex: 1;\n  -ms-flex: 1;\n  flex: 1;\n  display: block;\n  overflow: hidden;\n  padding: 0 16px;\n  width: 0;\n  border-width: 1px 0px 1px 1px;\n  border-radius: 0;\n  text-align: center;\n  text-overflow: ellipsis;\n  white-space: nowrap; }\n  .button-bar > .button:before, .button-bar > .button .icon:before {\n    line-height: 44px; }\n  .button-bar > .button:first-child {\n    border-radius: 2px 0px 0px 2px; }\n  .button-bar > .button:last-child {\n    border-right-width: 1px;\n    border-radius: 0px 2px 2px 0px; }\n\n/**\n * Grid\n * --------------------------------------------------\n * Using flexbox for the grid, inspired by Philip Walton:\n * http://philipwalton.github.io/solved-by-flexbox/demos/grids/\n * By default each .col within a .row will evenly take up\n * available width, and the height of each .col with take\n * up the height of the tallest .col in the same .row.\n */\n.row {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n  padding: 5px;\n  width: 100%; }\n\n.row-wrap {\n  -webkit-flex-wrap: wrap;\n  -moz-flex-wrap: wrap;\n  -ms-flex-wrap: wrap;\n  flex-wrap: wrap; }\n\n.row-no-padding {\n  padding: 0; }\n  .row-no-padding > .col {\n    padding: 0; }\n\n.row + .row {\n  margin-top: -5px;\n  padding-top: 0; }\n\n.col {\n  -webkit-box-flex: 1;\n  -webkit-flex: 1;\n  -moz-box-flex: 1;\n  -moz-flex: 1;\n  -ms-flex: 1;\n  flex: 1;\n  display: block;\n  padding: 5px;\n  width: 100%; }\n\n/* Vertically Align Columns */\n/* .row-* vertically aligns every .col in the .row */\n.row-top {\n  -webkit-box-align: start;\n  -ms-flex-align: start;\n  -webkit-align-items: flex-start;\n  -moz-align-items: flex-start;\n  align-items: flex-start; }\n\n.row-bottom {\n  -webkit-box-align: end;\n  -ms-flex-align: end;\n  -webkit-align-items: flex-end;\n  -moz-align-items: flex-end;\n  align-items: flex-end; }\n\n.row-center {\n  -webkit-box-align: center;\n  -ms-flex-align: center;\n  -webkit-align-items: center;\n  -moz-align-items: center;\n  align-items: center; }\n\n.row-stretch {\n  -webkit-box-align: stretch;\n  -ms-flex-align: stretch;\n  -webkit-align-items: stretch;\n  -moz-align-items: stretch;\n  align-items: stretch; }\n\n.row-baseline {\n  -webkit-box-align: baseline;\n  -ms-flex-align: baseline;\n  -webkit-align-items: baseline;\n  -moz-align-items: baseline;\n  align-items: baseline; }\n\n/* .col-* vertically aligns an individual .col */\n.col-top {\n  -webkit-align-self: flex-start;\n  -moz-align-self: flex-start;\n  -ms-flex-item-align: start;\n  align-self: flex-start; }\n\n.col-bottom {\n  -webkit-align-self: flex-end;\n  -moz-align-self: flex-end;\n  -ms-flex-item-align: end;\n  align-self: flex-end; }\n\n.col-center {\n  -webkit-align-self: center;\n  -moz-align-self: center;\n  -ms-flex-item-align: center;\n  align-self: center; }\n\n/* Column Offsets */\n.col-offset-10 {\n  margin-left: 10%; }\n\n.col-offset-20 {\n  margin-left: 20%; }\n\n.col-offset-25 {\n  margin-left: 25%; }\n\n.col-offset-33, .col-offset-34 {\n  margin-left: 33.3333%; }\n\n.col-offset-50 {\n  margin-left: 50%; }\n\n.col-offset-66, .col-offset-67 {\n  margin-left: 66.6666%; }\n\n.col-offset-75 {\n  margin-left: 75%; }\n\n.col-offset-80 {\n  margin-left: 80%; }\n\n.col-offset-90 {\n  margin-left: 90%; }\n\n/* Explicit Column Percent Sizes */\n/* By default each grid column will evenly distribute */\n/* across the grid. However, you can specify individual */\n/* columns to take up a certain size of the available area */\n.col-10 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 10%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 10%;\n  -ms-flex: 0 0 10%;\n  flex: 0 0 10%;\n  max-width: 10%; }\n\n.col-20 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 20%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 20%;\n  -ms-flex: 0 0 20%;\n  flex: 0 0 20%;\n  max-width: 20%; }\n\n.col-25 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 25%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 25%;\n  -ms-flex: 0 0 25%;\n  flex: 0 0 25%;\n  max-width: 25%; }\n\n.col-33, .col-34 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 33.3333%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 33.3333%;\n  -ms-flex: 0 0 33.3333%;\n  flex: 0 0 33.3333%;\n  max-width: 33.3333%; }\n\n.col-50 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 50%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 50%;\n  -ms-flex: 0 0 50%;\n  flex: 0 0 50%;\n  max-width: 50%; }\n\n.col-66, .col-67 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 66.6666%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 66.6666%;\n  -ms-flex: 0 0 66.6666%;\n  flex: 0 0 66.6666%;\n  max-width: 66.6666%; }\n\n.col-75 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 75%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 75%;\n  -ms-flex: 0 0 75%;\n  flex: 0 0 75%;\n  max-width: 75%; }\n\n.col-80 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 80%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 80%;\n  -ms-flex: 0 0 80%;\n  flex: 0 0 80%;\n  max-width: 80%; }\n\n.col-90 {\n  -webkit-box-flex: 0;\n  -webkit-flex: 0 0 90%;\n  -moz-box-flex: 0;\n  -moz-flex: 0 0 90%;\n  -ms-flex: 0 0 90%;\n  flex: 0 0 90%;\n  max-width: 90%; }\n\n/* Responsive Grid Classes */\n/* Adding a class of responsive-X to a row */\n/* will trigger the flex-direction to */\n/* change to column and add some margin */\n/* to any columns in the row for clearity */\n@media (max-width: 567px) {\n  .responsive-sm {\n    -webkit-box-direction: normal;\n    -moz-box-direction: normal;\n    -webkit-box-orient: vertical;\n    -moz-box-orient: vertical;\n    -webkit-flex-direction: column;\n    -ms-flex-direction: column;\n    flex-direction: column; }\n    .responsive-sm .col, .responsive-sm .col-10, .responsive-sm .col-20, .responsive-sm .col-25, .responsive-sm .col-33, .responsive-sm .col-34, .responsive-sm .col-50, .responsive-sm .col-66, .responsive-sm .col-67, .responsive-sm .col-75, .responsive-sm .col-80, .responsive-sm .col-90 {\n      -webkit-box-flex: 1;\n      -webkit-flex: 1;\n      -moz-box-flex: 1;\n      -moz-flex: 1;\n      -ms-flex: 1;\n      flex: 1;\n      margin-bottom: 15px;\n      margin-left: 0;\n      max-width: 100%;\n      width: 100%; } }\n\n@media (max-width: 767px) {\n  .responsive-md {\n    -webkit-box-direction: normal;\n    -moz-box-direction: normal;\n    -webkit-box-orient: vertical;\n    -moz-box-orient: vertical;\n    -webkit-flex-direction: column;\n    -ms-flex-direction: column;\n    flex-direction: column; }\n    .responsive-md .col, .responsive-md .col-10, .responsive-md .col-20, .responsive-md .col-25, .responsive-md .col-33, .responsive-md .col-34, .responsive-md .col-50, .responsive-md .col-66, .responsive-md .col-67, .responsive-md .col-75, .responsive-md .col-80, .responsive-md .col-90 {\n      -webkit-box-flex: 1;\n      -webkit-flex: 1;\n      -moz-box-flex: 1;\n      -moz-flex: 1;\n      -ms-flex: 1;\n      flex: 1;\n      margin-bottom: 15px;\n      margin-left: 0;\n      max-width: 100%;\n      width: 100%; } }\n\n@media (max-width: 1023px) {\n  .responsive-lg {\n    -webkit-box-direction: normal;\n    -moz-box-direction: normal;\n    -webkit-box-orient: vertical;\n    -moz-box-orient: vertical;\n    -webkit-flex-direction: column;\n    -ms-flex-direction: column;\n    flex-direction: column; }\n    .responsive-lg .col, .responsive-lg .col-10, .responsive-lg .col-20, .responsive-lg .col-25, .responsive-lg .col-33, .responsive-lg .col-34, .responsive-lg .col-50, .responsive-lg .col-66, .responsive-lg .col-67, .responsive-lg .col-75, .responsive-lg .col-80, .responsive-lg .col-90 {\n      -webkit-box-flex: 1;\n      -webkit-flex: 1;\n      -moz-box-flex: 1;\n      -moz-flex: 1;\n      -ms-flex: 1;\n      flex: 1;\n      margin-bottom: 15px;\n      margin-left: 0;\n      max-width: 100%;\n      width: 100%; } }\n\n/**\n * Utility Classes\n * --------------------------------------------------\n */\n.hide {\n  display: none; }\n\n.opacity-hide {\n  opacity: 0; }\n\n.grade-b .opacity-hide, .grade-c .opacity-hide {\n  opacity: 1;\n  display: none; }\n\n.show {\n  display: block; }\n\n.opacity-show {\n  opacity: 1; }\n\n.invisible {\n  visibility: hidden; }\n\n.keyboard-open .hide-on-keyboard-open {\n  display: none; }\n\n.keyboard-open .tabs.hide-on-keyboard-open + .pane .has-tabs, .keyboard-open .bar-footer.hide-on-keyboard-open + .pane .has-footer {\n  bottom: 0; }\n\n.inline {\n  display: inline-block; }\n\n.disable-pointer-events {\n  pointer-events: none; }\n\n.enable-pointer-events {\n  pointer-events: auto; }\n\n.disable-user-behavior {\n  -webkit-user-select: none;\n  -moz-user-select: none;\n  -ms-user-select: none;\n  user-select: none;\n  -webkit-touch-callout: none;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n  -webkit-tap-highlight-color: transparent;\n  -webkit-user-drag: none;\n  -ms-touch-action: none;\n  -ms-content-zooming: none; }\n\n.click-block {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  opacity: 0;\n  z-index: 99999;\n  -webkit-transform: translate3d(0, 0, 0);\n  transform: translate3d(0, 0, 0);\n  overflow: hidden; }\n\n.click-block-hide {\n  -webkit-transform: translate3d(-9999px, 0, 0);\n  transform: translate3d(-9999px, 0, 0); }\n\n.no-resize {\n  resize: none; }\n\n.block {\n  display: block;\n  clear: both; }\n  .block:after {\n    display: block;\n    visibility: hidden;\n    clear: both;\n    height: 0;\n    content: \".\"; }\n\n.full-image {\n  width: 100%; }\n\n.clearfix {\n  *zoom: 1; }\n  .clearfix:before, .clearfix:after {\n    display: table;\n    content: \"\";\n    line-height: 0; }\n  .clearfix:after {\n    clear: both; }\n\n/**\n * Content Padding\n * --------------------------------------------------\n */\n.padding {\n  padding: 10px; }\n\n.padding-top, .padding-vertical {\n  padding-top: 10px; }\n\n.padding-right, .padding-horizontal {\n  padding-right: 10px; }\n\n.padding-bottom, .padding-vertical {\n  padding-bottom: 10px; }\n\n.padding-left, .padding-horizontal {\n  padding-left: 10px; }\n\n/**\n * Scrollable iFrames\n * --------------------------------------------------\n */\n.iframe-wrapper {\n  position: fixed;\n  -webkit-overflow-scrolling: touch;\n  overflow: scroll; }\n  .iframe-wrapper iframe {\n    height: 100%;\n    width: 100%; }\n\n/**\n * Rounded\n * --------------------------------------------------\n */\n.rounded {\n  border-radius: 4px; }\n\n/**\n * Utility Colors\n * --------------------------------------------------\n * Utility colors are added to help set a naming convention. You'll\n * notice we purposely do not use words like \"red\" or \"blue\", but\n * instead have colors which represent an emotion or generic theme.\n */\n.light, a.light {\n  color: #fff; }\n\n.light-bg {\n  background-color: #fff; }\n\n.light-border {\n  border-color: #ddd; }\n\n.stable, a.stable {\n  color: #f8f8f8; }\n\n.stable-bg {\n  background-color: #f8f8f8; }\n\n.stable-border {\n  border-color: #b2b2b2; }\n\n.positive, a.positive {\n  color: #387ef5; }\n\n.positive-bg {\n  background-color: #387ef5; }\n\n.positive-border {\n  border-color: #0c63ee; }\n\n.calm, a.calm {\n  color: #11c1f3; }\n\n.calm-bg {\n  background-color: #11c1f3; }\n\n.calm-border {\n  border-color: #0a9ec7; }\n\n.assertive, a.assertive {\n  color: #ef473a; }\n\n.assertive-bg {\n  background-color: #ef473a; }\n\n.assertive-border {\n  border-color: #e42012; }\n\n.balanced, a.balanced {\n  color: #33cd5f; }\n\n.balanced-bg {\n  background-color: #33cd5f; }\n\n.balanced-border {\n  border-color: #28a54c; }\n\n.energized, a.energized {\n  color: #ffc900; }\n\n.energized-bg {\n  background-color: #ffc900; }\n\n.energized-border {\n  border-color: #e6b400; }\n\n.royal, a.royal {\n  color: #886aea; }\n\n.royal-bg {\n  background-color: #886aea; }\n\n.royal-border {\n  border-color: #6b46e5; }\n\n.dark, a.dark {\n  color: #444; }\n\n.dark-bg {\n  background-color: #444; }\n\n.dark-border {\n  border-color: #111; }\n\n[collection-repeat] {\n  /* Position is set by transforms */\n  left: 0 !important;\n  top: 0 !important;\n  position: absolute !important;\n  z-index: 1; }\n\n.collection-repeat-container {\n  position: relative;\n  z-index: 1; }\n\n.collection-repeat-after-container {\n  z-index: 0;\n  display: block;\n  /* when scrolling horizontally, make sure the after container doesn't take up 100% width */ }\n  .collection-repeat-after-container.horizontal {\n    display: inline-block; }\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak, .ng-hide:not(.ng-hide-animate) {\n  display: none !important; }\n\n/**\n * Platform\n * --------------------------------------------------\n * Platform specific tweaks\n */\n.platform-ios.platform-cordova:not(.fullscreen) .bar-header:not(.bar-subheader) {\n  height: 64px; }\n  .platform-ios.platform-cordova:not(.fullscreen) .bar-header:not(.bar-subheader).item-input-inset .item-input-wrapper {\n    margin-top: 19px !important; }\n  .platform-ios.platform-cordova:not(.fullscreen) .bar-header:not(.bar-subheader) > * {\n    margin-top: 20px; }\n.platform-ios.platform-cordova:not(.fullscreen) .tabs-top > .tabs, .platform-ios.platform-cordova:not(.fullscreen) .tabs.tabs-top {\n  top: 64px; }\n.platform-ios.platform-cordova:not(.fullscreen) .has-header, .platform-ios.platform-cordova:not(.fullscreen) .bar-subheader {\n  top: 64px; }\n.platform-ios.platform-cordova:not(.fullscreen) .has-subheader {\n  top: 108px; }\n.platform-ios.platform-cordova:not(.fullscreen) .has-header.has-tabs-top {\n  top: 113px; }\n.platform-ios.platform-cordova:not(.fullscreen) .has-header.has-subheader.has-tabs-top {\n  top: 157px; }\n.platform-ios.platform-cordova.status-bar-hide {\n  margin-bottom: 20px; }\n\n@media (orientation: landscape) {\n  .platform-ios.platform-browser.platform-ipad {\n    position: fixed; } }\n\n.platform-c:not(.enable-transitions) * {\n  -webkit-transition: none !important;\n  transition: none !important; }\n\n.slide-in-up {\n  -webkit-transform: translate3d(0, 100%, 0);\n  transform: translate3d(0, 100%, 0); }\n\n.slide-in-up.ng-enter, .slide-in-up > .ng-enter {\n  -webkit-transition: all cubic-bezier(0.1, 0.7, 0.1, 1) 400ms;\n  transition: all cubic-bezier(0.1, 0.7, 0.1, 1) 400ms; }\n\n.slide-in-up.ng-enter-active, .slide-in-up > .ng-enter-active {\n  -webkit-transform: translate3d(0, 0, 0);\n  transform: translate3d(0, 0, 0); }\n\n.slide-in-up.ng-leave, .slide-in-up > .ng-leave {\n  -webkit-transition: all ease-in-out 250ms;\n  transition: all ease-in-out 250ms; }\n\n@-webkit-keyframes scaleOut {\n  from {\n    -webkit-transform: scale(1);\n    opacity: 1; }\n\n  to {\n    -webkit-transform: scale(0.8);\n    opacity: 0; } }\n\n@keyframes scaleOut {\n  from {\n    transform: scale(1);\n    opacity: 1; }\n\n  to {\n    transform: scale(0.8);\n    opacity: 0; } }\n\n@-webkit-keyframes superScaleIn {\n  from {\n    -webkit-transform: scale(1.2);\n    opacity: 0; }\n\n  to {\n    -webkit-transform: scale(1);\n    opacity: 1; } }\n\n@keyframes superScaleIn {\n  from {\n    transform: scale(1.2);\n    opacity: 0; }\n\n  to {\n    transform: scale(1);\n    opacity: 1; } }\n\n[nav-view-transition=\"ios\"] [nav-view=\"entering\"], [nav-view-transition=\"ios\"] [nav-view=\"leaving\"] {\n  -webkit-transition-duration: 500ms;\n  transition-duration: 500ms;\n  -webkit-transition-timing-function: cubic-bezier(0.36, 0.66, 0.04, 1);\n  transition-timing-function: cubic-bezier(0.36, 0.66, 0.04, 1);\n  -webkit-transition-property: opacity, -webkit-transform, box-shadow;\n  transition-property: opacity, transform, box-shadow; }\n[nav-view-transition=\"ios\"][nav-view-direction=\"forward\"], [nav-view-transition=\"ios\"][nav-view-direction=\"back\"] {\n  background-color: #000; }\n[nav-view-transition=\"ios\"] [nav-view=\"active\"], [nav-view-transition=\"ios\"][nav-view-direction=\"forward\"] [nav-view=\"entering\"], [nav-view-transition=\"ios\"][nav-view-direction=\"back\"] [nav-view=\"leaving\"] {\n  z-index: 3; }\n[nav-view-transition=\"ios\"][nav-view-direction=\"back\"] [nav-view=\"entering\"], [nav-view-transition=\"ios\"][nav-view-direction=\"forward\"] [nav-view=\"leaving\"] {\n  z-index: 2; }\n\n[nav-bar-transition=\"ios\"] .title, [nav-bar-transition=\"ios\"] .buttons, [nav-bar-transition=\"ios\"] .back-text {\n  -webkit-transition-duration: 500ms;\n  transition-duration: 500ms;\n  -webkit-transition-timing-function: cubic-bezier(0.36, 0.66, 0.04, 1);\n  transition-timing-function: cubic-bezier(0.36, 0.66, 0.04, 1);\n  -webkit-transition-property: opacity, -webkit-transform;\n  transition-property: opacity, transform; }\n[nav-bar-transition=\"ios\"] [nav-bar=\"active\"], [nav-bar-transition=\"ios\"] [nav-bar=\"entering\"] {\n  z-index: 10; }\n  [nav-bar-transition=\"ios\"] [nav-bar=\"active\"] .bar, [nav-bar-transition=\"ios\"] [nav-bar=\"entering\"] .bar {\n    background: transparent; }\n[nav-bar-transition=\"ios\"] [nav-bar=\"cached\"] {\n  display: block; }\n  [nav-bar-transition=\"ios\"] [nav-bar=\"cached\"] .header-item {\n    display: none; }\n\n[nav-view-transition=\"android\"] [nav-view=\"entering\"], [nav-view-transition=\"android\"] [nav-view=\"leaving\"] {\n  -webkit-transition-duration: 200ms;\n  transition-duration: 200ms;\n  -webkit-transition-timing-function: cubic-bezier(0.4, 0.6, 0.2, 1);\n  transition-timing-function: cubic-bezier(0.4, 0.6, 0.2, 1);\n  -webkit-transition-property: -webkit-transform;\n  transition-property: transform; }\n[nav-view-transition=\"android\"] [nav-view=\"active\"], [nav-view-transition=\"android\"][nav-view-direction=\"forward\"] [nav-view=\"entering\"], [nav-view-transition=\"android\"][nav-view-direction=\"back\"] [nav-view=\"leaving\"] {\n  z-index: 3; }\n[nav-view-transition=\"android\"][nav-view-direction=\"back\"] [nav-view=\"entering\"], [nav-view-transition=\"android\"][nav-view-direction=\"forward\"] [nav-view=\"leaving\"] {\n  z-index: 2; }\n\n[nav-bar-transition=\"android\"] .title, [nav-bar-transition=\"android\"] .buttons {\n  -webkit-transition-duration: 200ms;\n  transition-duration: 200ms;\n  -webkit-transition-timing-function: cubic-bezier(0.4, 0.6, 0.2, 1);\n  transition-timing-function: cubic-bezier(0.4, 0.6, 0.2, 1);\n  -webkit-transition-property: opacity;\n  transition-property: opacity; }\n[nav-bar-transition=\"android\"] [nav-bar=\"active\"], [nav-bar-transition=\"android\"] [nav-bar=\"entering\"] {\n  z-index: 10; }\n  [nav-bar-transition=\"android\"] [nav-bar=\"active\"] .bar, [nav-bar-transition=\"android\"] [nav-bar=\"entering\"] .bar {\n    background: transparent; }\n[nav-bar-transition=\"android\"] [nav-bar=\"cached\"] {\n  display: block; }\n  [nav-bar-transition=\"android\"] [nav-bar=\"cached\"] .header-item {\n    display: none; }\n\n[nav-swipe=\"fast\"] [nav-view], [nav-swipe=\"fast\"] .title, [nav-swipe=\"fast\"] .buttons, [nav-swipe=\"fast\"] .back-text {\n  -webkit-transition-duration: 50ms;\n  transition-duration: 50ms;\n  -webkit-transition-timing-function: linear;\n  transition-timing-function: linear; }\n\n[nav-swipe=\"slow\"] [nav-view], [nav-swipe=\"slow\"] .title, [nav-swipe=\"slow\"] .buttons, [nav-swipe=\"slow\"] .back-text {\n  -webkit-transition-duration: 160ms;\n  transition-duration: 160ms;\n  -webkit-transition-timing-function: linear;\n  transition-timing-function: linear; }\n\n[nav-view=\"cached\"], [nav-bar=\"cached\"] {\n  display: none; }\n\n[nav-view=\"stage\"] {\n  opacity: 0;\n  -webkit-transition-duration: 0;\n  transition-duration: 0; }\n\n[nav-bar=\"stage\"] .title, [nav-bar=\"stage\"] .buttons, [nav-bar=\"stage\"] .back-text {\n  position: absolute;\n  opacity: 0;\n  -webkit-transition-duration: 0s;\n  transition-duration: 0s; }\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/angular/angular-animate.js",
    "content": "/**\n * @license AngularJS v1.3.13\n * (c) 2010-2014 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* jshint maxlen: false */\n\n/**\n * @ngdoc module\n * @name ngAnimate\n * @description\n *\n * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.\n *\n * <div doc-module-components=\"ngAnimate\"></div>\n *\n * # Usage\n *\n * To see animations in action, all that is required is to define the appropriate CSS classes\n * or to register a JavaScript animation via the `myModule.animation()` function. The directives that support animation automatically are:\n * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation\n * by using the `$animate` service.\n *\n * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:\n *\n * | Directive                                                                                                | Supported Animations                                                     |\n * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|\n * | {@link ng.directive:ngRepeat#animations ngRepeat}                                                        | enter, leave and move                                                    |\n * | {@link ngRoute.directive:ngView#animations ngView}                                                       | enter and leave                                                          |\n * | {@link ng.directive:ngInclude#animations ngInclude}                                                      | enter and leave                                                          |\n * | {@link ng.directive:ngSwitch#animations ngSwitch}                                                        | enter and leave                                                          |\n * | {@link ng.directive:ngIf#animations ngIf}                                                                | enter and leave                                                          |\n * | {@link ng.directive:ngClass#animations ngClass}                                                          | add and remove (the CSS class(es) present)                               |\n * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide}            | add and remove (the ng-hide class value)                                 |\n * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel}    | add and remove (dirty, pristine, valid, invalid & all other validations) |\n * | {@link module:ngMessages#animations ngMessages}                                                          | add and remove (ng-active & ng-inactive)                                 |\n * | {@link module:ngMessages#animations ngMessage}                                                           | enter and leave                                                          |\n *\n * You can find out more information about animations upon visiting each directive page.\n *\n * Below is an example of how to apply animations to a directive that supports animation hooks:\n *\n * ```html\n * <style type=\"text/css\">\n * .slide.ng-enter, .slide.ng-leave {\n *   -webkit-transition:0.5s linear all;\n *   transition:0.5s linear all;\n * }\n *\n * .slide.ng-enter { }        /&#42; starting animations for enter &#42;/\n * .slide.ng-enter.ng-enter-active { } /&#42; terminal animations for enter &#42;/\n * .slide.ng-leave { }        /&#42; starting animations for leave &#42;/\n * .slide.ng-leave.ng-leave-active { } /&#42; terminal animations for leave &#42;/\n * </style>\n *\n * <!--\n * the animate service will automatically add .ng-enter and .ng-leave to the element\n * to trigger the CSS transition/animations\n * -->\n * <ANY class=\"slide\" ng-include=\"...\"></ANY>\n * ```\n *\n * Keep in mind that, by default, if an animation is running, any child elements cannot be animated\n * until the parent element's animation has completed. This blocking feature can be overridden by\n * placing the `ng-animate-children` attribute on a parent container tag.\n *\n * ```html\n * <div class=\"slide-animation\" ng-if=\"on\" ng-animate-children>\n *   <div class=\"fade-animation\" ng-if=\"on\">\n *     <div class=\"explode-animation\" ng-if=\"on\">\n *        ...\n *     </div>\n *   </div>\n * </div>\n * ```\n *\n * When the `on` expression value changes and an animation is triggered then each of the elements within\n * will all animate without the block being applied to child elements.\n *\n * ## Are animations run when the application starts?\n * No they are not. When an application is bootstrapped Angular will disable animations from running to avoid\n * a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work,\n * Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering\n * layout changes in the application will trigger animations as normal.\n *\n * In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular\n * will automatically extend the wait time to enable animations once **all** of the outbound HTTP requests\n * are complete.\n *\n * ## CSS-defined Animations\n * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes\n * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported\n * and can be used to play along with this naming structure.\n *\n * The following code below demonstrates how to perform animations using **CSS transitions** with Angular:\n *\n * ```html\n * <style type=\"text/css\">\n * /&#42;\n *  The animate class is apart of the element and the ng-enter class\n *  is attached to the element once the enter animation event is triggered\n * &#42;/\n * .reveal-animation.ng-enter {\n *  -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/\n *  transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/\n *\n *  /&#42; The animation preparation code &#42;/\n *  opacity: 0;\n * }\n *\n * /&#42;\n *  Keep in mind that you want to combine both CSS\n *  classes together to avoid any CSS-specificity\n *  conflicts\n * &#42;/\n * .reveal-animation.ng-enter.ng-enter-active {\n *  /&#42; The animation code itself &#42;/\n *  opacity: 1;\n * }\n * </style>\n *\n * <div class=\"view-container\">\n *   <div ng-view class=\"reveal-animation\"></div>\n * </div>\n * ```\n *\n * The following code below demonstrates how to perform animations using **CSS animations** with Angular:\n *\n * ```html\n * <style type=\"text/css\">\n * .reveal-animation.ng-enter {\n *   -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/\n *   animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/\n * }\n * @-webkit-keyframes enter_sequence {\n *   from { opacity:0; }\n *   to { opacity:1; }\n * }\n * @keyframes enter_sequence {\n *   from { opacity:0; }\n *   to { opacity:1; }\n * }\n * </style>\n *\n * <div class=\"view-container\">\n *   <div ng-view class=\"reveal-animation\"></div>\n * </div>\n * ```\n *\n * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.\n *\n * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add\n * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically\n * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be\n * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end\n * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element\n * has no CSS transition/animation classes applied to it.\n *\n * ### Structural transition animations\n *\n * Structural transitions (such as enter, leave and move) will always apply a `0s none` transition\n * value to force the browser into rendering the styles defined in the setup (`.ng-enter`, `.ng-leave`\n * or `.ng-move`) class. This means that any active transition animations operating on the element\n * will be cut off to make way for the enter, leave or move animation.\n *\n * ### Class-based transition animations\n *\n * Class-based transitions refer to transition animations that are triggered when a CSS class is\n * added to or removed from the element (via `$animate.addClass`, `$animate.removeClass`,\n * `$animate.setClass`, or by directives such as `ngClass`, `ngModel` and `form`).\n * They are different when compared to structural animations since they **do not cancel existing\n * animations** nor do they **block successive transitions** from rendering on the same element.\n * This distinction allows for **multiple class-based transitions** to be performed on the same element.\n *\n * In addition to ngAnimate supporting the default (natural) functionality of class-based transition\n * animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the\n * developer in further styling the element throughout the transition animation. Earlier versions\n * of ngAnimate may have caused natural CSS transitions to break and not render properly due to\n * $animate temporarily blocking transitions using `0s none` in order to allow the setup CSS class\n * (the `-add` or `-remove` class) to be applied without triggering an animation. However, as of\n * **version 1.3**, this workaround has been removed with ngAnimate and all non-ngAnimate CSS\n * class transitions are compatible with ngAnimate.\n *\n * There is, however, one special case when dealing with class-based transitions in ngAnimate.\n * When rendering class-based transitions that make use of the setup and active CSS classes\n * (e.g. `.fade-add` and `.fade-add-active` for when `.fade` is added) be sure to define\n * the transition value **on the active CSS class** and not the setup class.\n *\n * ```css\n * .fade-add {\n *   /&#42; remember to place a 0s transition here\n *      to ensure that the styles are applied instantly\n *      even if the element already has a transition style &#42;/\n *   transition:0s linear all;\n *\n *   /&#42; starting CSS styles &#42;/\n *   opacity:1;\n * }\n * .fade-add.fade-add-active {\n *   /&#42; this will be the length of the animation &#42;/\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * The setup CSS class (in this case `.fade-add`) also has a transition style property, however, it\n * has a duration of zero. This may not be required, however, incase the browser is unable to render\n * the styling present in this CSS class instantly then it could be that the browser is attempting\n * to perform an unnecessary transition.\n *\n * This workaround, however, does not apply to  standard class-based transitions that are rendered\n * when a CSS class containing a transition is applied to an element:\n *\n * ```css\n * /&#42; this works as expected &#42;/\n * .fade {\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * Please keep this in mind when coding the CSS markup that will be used within class-based transitions.\n * Also, try not to mix the two class-based animation flavors together since the CSS code may become\n * overly complex.\n *\n *\n * ### Preventing Collisions With Third Party Libraries\n *\n * Some third-party frameworks place animation duration defaults across many element or className\n * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which\n * is expecting actual animations on these elements and has to wait for their completion.\n *\n * You can prevent this unwanted behavior by using a prefix on all your animation classes:\n *\n * ```css\n * /&#42; prefixed with animate- &#42;/\n * .animate-fade-add.animate-fade-add-active {\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * You then configure `$animate` to enforce this prefix:\n *\n * ```js\n * $animateProvider.classNameFilter(/animate-/);\n * ```\n * </div>\n *\n * ### CSS Staggering Animations\n * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a\n * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be\n * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for\n * the animation. The style property expected within the stagger class can either be a **transition-delay** or an\n * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).\n *\n * ```css\n * .my-animation.ng-enter {\n *   /&#42; standard transition code &#42;/\n *   -webkit-transition: 1s linear all;\n *   transition: 1s linear all;\n *   opacity:0;\n * }\n * .my-animation.ng-enter-stagger {\n *   /&#42; this will have a 100ms delay between each successive leave animation &#42;/\n *   -webkit-transition-delay: 0.1s;\n *   transition-delay: 0.1s;\n *\n *   /&#42; in case the stagger doesn't work then these two values\n *    must be set to 0 to avoid an accidental CSS inheritance &#42;/\n *   -webkit-transition-duration: 0s;\n *   transition-duration: 0s;\n * }\n * .my-animation.ng-enter.ng-enter-active {\n *   /&#42; standard transition styles &#42;/\n *   opacity:1;\n * }\n * ```\n *\n * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations\n * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this\n * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation\n * will also be reset if more than 10ms has passed after the last animation has been fired.\n *\n * The following code will issue the **ng-leave-stagger** event on the element provided:\n *\n * ```js\n * var kids = parent.children();\n *\n * $animate.leave(kids[0]); //stagger index=0\n * $animate.leave(kids[1]); //stagger index=1\n * $animate.leave(kids[2]); //stagger index=2\n * $animate.leave(kids[3]); //stagger index=3\n * $animate.leave(kids[4]); //stagger index=4\n *\n * $timeout(function() {\n *   //stagger has reset itself\n *   $animate.leave(kids[5]); //stagger index=0\n *   $animate.leave(kids[6]); //stagger index=1\n * }, 100, false);\n * ```\n *\n * Stagger animations are currently only supported within CSS-defined animations.\n *\n * ## JavaScript-defined Animations\n * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not\n * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.\n *\n * ```js\n * //!annotate=\"YourApp\" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.\n * var ngModule = angular.module('YourApp', ['ngAnimate']);\n * ngModule.animation('.my-crazy-animation', function() {\n *   return {\n *     enter: function(element, done) {\n *       //run the animation here and call done when the animation is complete\n *       return function(cancelled) {\n *         //this (optional) function will be called when the animation\n *         //completes or when the animation is cancelled (the cancelled\n *         //flag will be set to true if cancelled).\n *       };\n *     },\n *     leave: function(element, done) { },\n *     move: function(element, done) { },\n *\n *     //animation that can be triggered before the class is added\n *     beforeAddClass: function(element, className, done) { },\n *\n *     //animation that can be triggered after the class is added\n *     addClass: function(element, className, done) { },\n *\n *     //animation that can be triggered before the class is removed\n *     beforeRemoveClass: function(element, className, done) { },\n *\n *     //animation that can be triggered after the class is removed\n *     removeClass: function(element, className, done) { }\n *   };\n * });\n * ```\n *\n * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run\n * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits\n * the element's CSS class attribute value and then run the matching animation event function (if found).\n * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will\n * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).\n *\n * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned.\n * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run,\n * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation\n * or transition code that is defined via a stylesheet).\n *\n *\n * ### Applying Directive-specific Styles to an Animation\n * In some cases a directive or service may want to provide `$animate` with extra details that the animation will\n * include into its animation. Let's say for example we wanted to render an animation that animates an element\n * towards the mouse coordinates as to where the user clicked last. By collecting the X/Y coordinates of the click\n * (via the event parameter) we can set the `top` and `left` styles into an object and pass that into our function\n * call to `$animate.addClass`.\n *\n * ```js\n * canvas.on('click', function(e) {\n *   $animate.addClass(element, 'on', {\n *     to: {\n *       left : e.client.x + 'px',\n *       top : e.client.y + 'px'\n *     }\n *   }):\n * });\n * ```\n *\n * Now when the animation runs, and a transition or keyframe animation is picked up, then the animation itself will\n * also include and transition the styling of the `left` and `top` properties into its running animation. If we want\n * to provide some starting animation values then we can do so by placing the starting animations styles into an object\n * called `from` in the same object as the `to` animations.\n *\n * ```js\n * canvas.on('click', function(e) {\n *   $animate.addClass(element, 'on', {\n *     from: {\n *        position: 'absolute',\n *        left: '0px',\n *        top: '0px'\n *     },\n *     to: {\n *       left : e.client.x + 'px',\n *       top : e.client.y + 'px'\n *     }\n *   }):\n * });\n * ```\n *\n * Once the animation is complete or cancelled then the union of both the before and after styles are applied to the\n * element. If `ngAnimate` is not present then the styles will be applied immediately.\n *\n */\n\nangular.module('ngAnimate', ['ng'])\n\n  /**\n   * @ngdoc provider\n   * @name $animateProvider\n   * @description\n   *\n   * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module.\n   * When an animation is triggered, the $animate service will query the $animate service to find any animations that match\n   * the provided name value.\n   *\n   * Requires the {@link ngAnimate `ngAnimate`} module to be installed.\n   *\n   * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.\n   *\n   */\n  .directive('ngAnimateChildren', function() {\n    var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';\n    return function(scope, element, attrs) {\n      var val = attrs.ngAnimateChildren;\n      if (angular.isString(val) && val.length === 0) { //empty attribute\n        element.data(NG_ANIMATE_CHILDREN, true);\n      } else {\n        scope.$watch(val, function(value) {\n          element.data(NG_ANIMATE_CHILDREN, !!value);\n        });\n      }\n    };\n  })\n\n  //this private service is only used within CSS-enabled animations\n  //IE8 + IE9 do not support rAF natively, but that is fine since they\n  //also don't support transitions and keyframes which means that the code\n  //below will never be used by the two browsers.\n  .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) {\n    var bod = $document[0].body;\n    return function(fn) {\n      //the returned function acts as the cancellation function\n      return $$rAF(function() {\n        //the line below will force the browser to perform a repaint\n        //so that all the animated elements within the animation frame\n        //will be properly updated and drawn on screen. This is\n        //required to perform multi-class CSS based animations with\n        //Firefox. DO NOT REMOVE THIS LINE.\n        var a = bod.offsetWidth + 1;\n        fn();\n      });\n    };\n  }])\n\n  .config(['$provide', '$animateProvider', function($provide, $animateProvider) {\n    var noop = angular.noop;\n    var forEach = angular.forEach;\n    var selectors = $animateProvider.$$selectors;\n    var isArray = angular.isArray;\n    var isString = angular.isString;\n    var isObject = angular.isObject;\n\n    var ELEMENT_NODE = 1;\n    var NG_ANIMATE_STATE = '$$ngAnimateState';\n    var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';\n    var NG_ANIMATE_CLASS_NAME = 'ng-animate';\n    var rootAnimateState = {running: true};\n\n    function extractElementNode(element) {\n      for (var i = 0; i < element.length; i++) {\n        var elm = element[i];\n        if (elm.nodeType == ELEMENT_NODE) {\n          return elm;\n        }\n      }\n    }\n\n    function prepareElement(element) {\n      return element && angular.element(element);\n    }\n\n    function stripCommentsFromElement(element) {\n      return angular.element(extractElementNode(element));\n    }\n\n    function isMatchingElement(elm1, elm2) {\n      return extractElementNode(elm1) == extractElementNode(elm2);\n    }\n    var $$jqLite;\n    $provide.decorator('$animate',\n        ['$delegate', '$$q', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', '$templateRequest', '$$jqLite',\n function($delegate,   $$q,   $injector,   $sniffer,   $rootElement,   $$asyncCallback,   $rootScope,   $document,   $templateRequest,   $$$jqLite) {\n\n      $$jqLite = $$$jqLite;\n      $rootElement.data(NG_ANIMATE_STATE, rootAnimateState);\n\n      // Wait until all directive and route-related templates are downloaded and\n      // compiled. The $templateRequest.totalPendingRequests variable keeps track of\n      // all of the remote templates being currently downloaded. If there are no\n      // templates currently downloading then the watcher will still fire anyway.\n      var deregisterWatch = $rootScope.$watch(\n        function() { return $templateRequest.totalPendingRequests; },\n        function(val, oldVal) {\n          if (val !== 0) return;\n          deregisterWatch();\n\n          // Now that all templates have been downloaded, $animate will wait until\n          // the post digest queue is empty before enabling animations. By having two\n          // calls to $postDigest calls we can ensure that the flag is enabled at the\n          // very end of the post digest queue. Since all of the animations in $animate\n          // use $postDigest, it's important that the code below executes at the end.\n          // This basically means that the page is fully downloaded and compiled before\n          // any animations are triggered.\n          $rootScope.$$postDigest(function() {\n            $rootScope.$$postDigest(function() {\n              rootAnimateState.running = false;\n            });\n          });\n        }\n      );\n\n      var globalAnimationCounter = 0;\n      var classNameFilter = $animateProvider.classNameFilter();\n      var isAnimatableClassName = !classNameFilter\n              ? function() { return true; }\n              : function(className) {\n                return classNameFilter.test(className);\n              };\n\n      function classBasedAnimationsBlocked(element, setter) {\n        var data = element.data(NG_ANIMATE_STATE) || {};\n        if (setter) {\n          data.running = true;\n          data.structural = true;\n          element.data(NG_ANIMATE_STATE, data);\n        }\n        return data.disabled || (data.running && data.structural);\n      }\n\n      function runAnimationPostDigest(fn) {\n        var cancelFn, defer = $$q.defer();\n        defer.promise.$$cancelFn = function() {\n          cancelFn && cancelFn();\n        };\n        $rootScope.$$postDigest(function() {\n          cancelFn = fn(function() {\n            defer.resolve();\n          });\n        });\n        return defer.promise;\n      }\n\n      function parseAnimateOptions(options) {\n        // some plugin code may still be passing in the callback\n        // function as the last param for the $animate methods so\n        // it's best to only allow string or array values for now\n        if (isObject(options)) {\n          if (options.tempClasses && isString(options.tempClasses)) {\n            options.tempClasses = options.tempClasses.split(/\\s+/);\n          }\n          return options;\n        }\n      }\n\n      function resolveElementClasses(element, cache, runningAnimations) {\n        runningAnimations = runningAnimations || {};\n\n        var lookup = {};\n        forEach(runningAnimations, function(data, selector) {\n          forEach(selector.split(' '), function(s) {\n            lookup[s]=data;\n          });\n        });\n\n        var hasClasses = Object.create(null);\n        forEach((element.attr('class') || '').split(/\\s+/), function(className) {\n          hasClasses[className] = true;\n        });\n\n        var toAdd = [], toRemove = [];\n        forEach((cache && cache.classes) || [], function(status, className) {\n          var hasClass = hasClasses[className];\n          var matchingAnimation = lookup[className] || {};\n\n          // When addClass and removeClass is called then $animate will check to\n          // see if addClass and removeClass cancel each other out. When there are\n          // more calls to removeClass than addClass then the count falls below 0\n          // and then the removeClass animation will be allowed. Otherwise if the\n          // count is above 0 then that means an addClass animation will commence.\n          // Once an animation is allowed then the code will also check to see if\n          // there exists any on-going animation that is already adding or remvoing\n          // the matching CSS class.\n          if (status === false) {\n            //does it have the class or will it have the class\n            if (hasClass || matchingAnimation.event == 'addClass') {\n              toRemove.push(className);\n            }\n          } else if (status === true) {\n            //is the class missing or will it be removed?\n            if (!hasClass || matchingAnimation.event == 'removeClass') {\n              toAdd.push(className);\n            }\n          }\n        });\n\n        return (toAdd.length + toRemove.length) > 0 && [toAdd.join(' '), toRemove.join(' ')];\n      }\n\n      function lookup(name) {\n        if (name) {\n          var matches = [],\n              flagMap = {},\n              classes = name.substr(1).split('.');\n\n          //the empty string value is the default animation\n          //operation which performs CSS transition and keyframe\n          //animations sniffing. This is always included for each\n          //element animation procedure if the browser supports\n          //transitions and/or keyframe animations. The default\n          //animation is added to the top of the list to prevent\n          //any previous animations from affecting the element styling\n          //prior to the element being animated.\n          if ($sniffer.transitions || $sniffer.animations) {\n            matches.push($injector.get(selectors['']));\n          }\n\n          for (var i=0; i < classes.length; i++) {\n            var klass = classes[i],\n                selectorFactoryName = selectors[klass];\n            if (selectorFactoryName && !flagMap[klass]) {\n              matches.push($injector.get(selectorFactoryName));\n              flagMap[klass] = true;\n            }\n          }\n          return matches;\n        }\n      }\n\n      function animationRunner(element, animationEvent, className, options) {\n        //transcluded directives may sometimes fire an animation using only comment nodes\n        //best to catch this early on to prevent any animation operations from occurring\n        var node = element[0];\n        if (!node) {\n          return;\n        }\n\n        if (options) {\n          options.to = options.to || {};\n          options.from = options.from || {};\n        }\n\n        var classNameAdd;\n        var classNameRemove;\n        if (isArray(className)) {\n          classNameAdd = className[0];\n          classNameRemove = className[1];\n          if (!classNameAdd) {\n            className = classNameRemove;\n            animationEvent = 'removeClass';\n          } else if (!classNameRemove) {\n            className = classNameAdd;\n            animationEvent = 'addClass';\n          } else {\n            className = classNameAdd + ' ' + classNameRemove;\n          }\n        }\n\n        var isSetClassOperation = animationEvent == 'setClass';\n        var isClassBased = isSetClassOperation\n                           || animationEvent == 'addClass'\n                           || animationEvent == 'removeClass'\n                           || animationEvent == 'animate';\n\n        var currentClassName = element.attr('class');\n        var classes = currentClassName + ' ' + className;\n        if (!isAnimatableClassName(classes)) {\n          return;\n        }\n\n        var beforeComplete = noop,\n            beforeCancel = [],\n            before = [],\n            afterComplete = noop,\n            afterCancel = [],\n            after = [];\n\n        var animationLookup = (' ' + classes).replace(/\\s+/g,'.');\n        forEach(lookup(animationLookup), function(animationFactory) {\n          var created = registerAnimation(animationFactory, animationEvent);\n          if (!created && isSetClassOperation) {\n            registerAnimation(animationFactory, 'addClass');\n            registerAnimation(animationFactory, 'removeClass');\n          }\n        });\n\n        function registerAnimation(animationFactory, event) {\n          var afterFn = animationFactory[event];\n          var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)];\n          if (afterFn || beforeFn) {\n            if (event == 'leave') {\n              beforeFn = afterFn;\n              //when set as null then animation knows to skip this phase\n              afterFn = null;\n            }\n            after.push({\n              event: event, fn: afterFn\n            });\n            before.push({\n              event: event, fn: beforeFn\n            });\n            return true;\n          }\n        }\n\n        function run(fns, cancellations, allCompleteFn) {\n          var animations = [];\n          forEach(fns, function(animation) {\n            animation.fn && animations.push(animation);\n          });\n\n          var count = 0;\n          function afterAnimationComplete(index) {\n            if (cancellations) {\n              (cancellations[index] || noop)();\n              if (++count < animations.length) return;\n              cancellations = null;\n            }\n            allCompleteFn();\n          }\n\n          //The code below adds directly to the array in order to work with\n          //both sync and async animations. Sync animations are when the done()\n          //operation is called right away. DO NOT REFACTOR!\n          forEach(animations, function(animation, index) {\n            var progress = function() {\n              afterAnimationComplete(index);\n            };\n            switch (animation.event) {\n              case 'setClass':\n                cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress, options));\n                break;\n              case 'animate':\n                cancellations.push(animation.fn(element, className, options.from, options.to, progress));\n                break;\n              case 'addClass':\n                cancellations.push(animation.fn(element, classNameAdd || className,     progress, options));\n                break;\n              case 'removeClass':\n                cancellations.push(animation.fn(element, classNameRemove || className,  progress, options));\n                break;\n              default:\n                cancellations.push(animation.fn(element, progress, options));\n                break;\n            }\n          });\n\n          if (cancellations && cancellations.length === 0) {\n            allCompleteFn();\n          }\n        }\n\n        return {\n          node: node,\n          event: animationEvent,\n          className: className,\n          isClassBased: isClassBased,\n          isSetClassOperation: isSetClassOperation,\n          applyStyles: function() {\n            if (options) {\n              element.css(angular.extend(options.from || {}, options.to || {}));\n            }\n          },\n          before: function(allCompleteFn) {\n            beforeComplete = allCompleteFn;\n            run(before, beforeCancel, function() {\n              beforeComplete = noop;\n              allCompleteFn();\n            });\n          },\n          after: function(allCompleteFn) {\n            afterComplete = allCompleteFn;\n            run(after, afterCancel, function() {\n              afterComplete = noop;\n              allCompleteFn();\n            });\n          },\n          cancel: function() {\n            if (beforeCancel) {\n              forEach(beforeCancel, function(cancelFn) {\n                (cancelFn || noop)(true);\n              });\n              beforeComplete(true);\n            }\n            if (afterCancel) {\n              forEach(afterCancel, function(cancelFn) {\n                (cancelFn || noop)(true);\n              });\n              afterComplete(true);\n            }\n          }\n        };\n      }\n\n      /**\n       * @ngdoc service\n       * @name $animate\n       * @kind object\n       *\n       * @description\n       * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations.\n       * When any of these operations are run, the $animate service\n       * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object)\n       * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.\n       *\n       * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives\n       * will work out of the box without any extra configuration.\n       *\n       * Requires the {@link ngAnimate `ngAnimate`} module to be installed.\n       *\n       * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.\n       * ## Callback Promises\n       * With AngularJS 1.3, each of the animation methods, on the `$animate` service, return a promise when called. The\n       * promise itself is then resolved once the animation has completed itself, has been cancelled or has been\n       * skipped due to animations being disabled. (Note that even if the animation is cancelled it will still\n       * call the resolve function of the animation.)\n       *\n       * ```js\n       * $animate.enter(element, container).then(function() {\n       *   //...this is called once the animation is complete...\n       * });\n       * ```\n       *\n       * Also note that, due to the nature of the callback promise, if any Angular-specific code (like changing the scope,\n       * location of the page, etc...) is executed within the callback promise then be sure to wrap the code using\n       * `$scope.$apply(...)`;\n       *\n       * ```js\n       * $animate.leave(element).then(function() {\n       *   $scope.$apply(function() {\n       *     $location.path('/new-page');\n       *   });\n       * });\n       * ```\n       *\n       * An animation can also be cancelled by calling the `$animate.cancel(promise)` method with the provided\n       * promise that was returned when the animation was started.\n       *\n       * ```js\n       * var promise = $animate.addClass(element, 'super-long-animation');\n       * promise.then(function() {\n       *   //this will still be called even if cancelled\n       * });\n       *\n       * element.on('click', function() {\n       *   //tooo lazy to wait for the animation to end\n       *   $animate.cancel(promise);\n       * });\n       * ```\n       *\n       * (Keep in mind that the promise cancellation is unique to `$animate` since promises in\n       * general cannot be cancelled.)\n       *\n       */\n      return {\n        /**\n         * @ngdoc method\n         * @name $animate#animate\n         * @kind function\n         *\n         * @description\n         * Performs an inline animation on the element which applies the provided `to` and `from` CSS styles to the element.\n         * If any detected CSS transition, keyframe or JavaScript matches the provided `className` value then the animation\n         * will take on the provided styles. For example, if a transition animation is set for the given className then the\n         * provided `from` and `to` styles will be applied alongside the given transition. If a JavaScript animation is\n         * detected then the provided styles will be given in as function paramters.\n         *\n         * ```js\n         * ngModule.animation('.my-inline-animation', function() {\n         *   return {\n         *     animate : function(element, className, from, to, done) {\n         *       //styles\n         *     }\n         *   }\n         * });\n         * ```\n         *\n         * Below is a breakdown of each step that occurs during the `animate` animation:\n         *\n         * | Animation Step                                                                                                        | What the element class attribute looks like                  |\n         * |-----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|\n         * | 1. `$animate.animate(...)` is called                                                                                  | `class=\"my-animation\"`                                       |\n         * | 2. `$animate` waits for the next digest to start the animation                                                        | `class=\"my-animation ng-animate\"`                            |\n         * | 3. `$animate` runs the JavaScript-defined animations detected on the element                                          | `class=\"my-animation ng-animate\"`                            |\n         * | 4. the `className` class value is added to the element                                                                | `class=\"my-animation ng-animate className\"`                  |\n         * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay                         | `class=\"my-animation ng-animate className\"`                  |\n         * | 6. `$animate` blocks all CSS transitions on the element to ensure the `.className` class styling is applied right away| `class=\"my-animation ng-animate className\"`                  |\n         * | 7. `$animate` applies the provided collection of `from` CSS styles to the element                                     | `class=\"my-animation ng-animate className\"`                  |\n         * | 8. `$animate` waits for a single animation frame (this performs a reflow)                                             | `class=\"my-animation ng-animate className\"`                  |\n         * | 9. `$animate` removes the CSS transition block placed on the element                                                  | `class=\"my-animation ng-animate className\"`                  |\n         * | 10. the `className-active` class is added (this triggers the CSS transition/animation)                                | `class=\"my-animation ng-animate className className-active\"` |\n         * | 11. `$animate` applies the collection of `to` CSS styles to the element which are then handled by the transition      | `class=\"my-animation ng-animate className className-active\"` |\n         * | 12. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate className className-active\"` |\n         * | 13. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                       |\n         * | 14. The returned promise is resolved.                                                                                 | `class=\"my-animation\"`                                       |\n         *\n         * @param {DOMElement} element the element that will be the focus of the enter animation\n         * @param {object} from a collection of CSS styles that will be applied to the element at the start of the animation\n         * @param {object} to a collection of CSS styles that the element will animate towards\n         * @param {string=} className an optional CSS class that will be added to the element for the duration of the animation (the default class is `ng-inline-animate`)\n         * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        animate: function(element, from, to, className, options) {\n          className = className || 'ng-inline-animate';\n          options = parseAnimateOptions(options) || {};\n          options.from = to ? from : null;\n          options.to   = to ? to : from;\n\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('animate', className, stripCommentsFromElement(element), null, null, noop, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#enter\n         * @kind function\n         *\n         * @description\n         * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once\n         * the animation is started, the following CSS classes will be present on the element for the duration of the animation:\n         *\n         * Below is a breakdown of each step that occurs during enter animation:\n         *\n         * | Animation Step                                                                                                        | What the element class attribute looks like                |\n         * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|\n         * | 1. `$animate.enter(...)` is called                                                                                    | `class=\"my-animation\"`                                     |\n         * | 2. element is inserted into the `parentElement` element or beside the `afterElement` element                          | `class=\"my-animation\"`                                     |\n         * | 3. `$animate` waits for the next digest to start the animation                                                        | `class=\"my-animation ng-animate\"`                          |\n         * | 4. `$animate` runs the JavaScript-defined animations detected on the element                                          | `class=\"my-animation ng-animate\"`                          |\n         * | 5. the `.ng-enter` class is added to the element                                                                      | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                         | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 7. `$animate` blocks all CSS transitions on the element to ensure the `.ng-enter` class styling is applied right away | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 8. `$animate` waits for a single animation frame (this performs a reflow)                                             | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 9. `$animate` removes the CSS transition block placed on the element                                                  | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 10. the `.ng-enter-active` class is added (this triggers the CSS transition/animation)                                | `class=\"my-animation ng-animate ng-enter ng-enter-active\"` |\n         * | 11. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate ng-enter ng-enter-active\"` |\n         * | 12. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                     |\n         * | 13. The returned promise is resolved.                                                                                 | `class=\"my-animation\"`                                     |\n         *\n         * @param {DOMElement} element the element that will be the focus of the enter animation\n         * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation\n         * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation\n         * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        enter: function(element, parentElement, afterElement, options) {\n          options = parseAnimateOptions(options);\n          element = angular.element(element);\n          parentElement = prepareElement(parentElement);\n          afterElement = prepareElement(afterElement);\n\n          classBasedAnimationsBlocked(element, true);\n          $delegate.enter(element, parentElement, afterElement);\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#leave\n         * @kind function\n         *\n         * @description\n         * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once\n         * the animation is started, the following CSS classes will be added for the duration of the animation:\n         *\n         * Below is a breakdown of each step that occurs during leave animation:\n         *\n         * | Animation Step                                                                                                        | What the element class attribute looks like                |\n         * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|\n         * | 1. `$animate.leave(...)` is called                                                                                    | `class=\"my-animation\"`                                     |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                                          | `class=\"my-animation ng-animate\"`                          |\n         * | 3. `$animate` waits for the next digest to start the animation                                                        | `class=\"my-animation ng-animate\"`                          |\n         * | 4. the `.ng-leave` class is added to the element                                                                      | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay                         | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 6. `$animate` blocks all CSS transitions on the element to ensure the `.ng-leave` class styling is applied right away | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 7. `$animate` waits for a single animation frame (this performs a reflow)                                             | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 8. `$animate` removes the CSS transition block placed on the element                                                  | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 9. the `.ng-leave-active` class is added (this triggers the CSS transition/animation)                                 | `class=\"my-animation ng-animate ng-leave ng-leave-active\"` |\n         * | 10. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate ng-leave ng-leave-active\"` |\n         * | 11. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                     |\n         * | 12. The element is removed from the DOM                                                                               | ...                                                        |\n         * | 13. The returned promise is resolved.                                                                                 | ...                                                        |\n         *\n         * @param {DOMElement} element the element that will be the focus of the leave animation\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        leave: function(element, options) {\n          options = parseAnimateOptions(options);\n          element = angular.element(element);\n\n          cancelChildAnimations(element);\n          classBasedAnimationsBlocked(element, true);\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() {\n              $delegate.leave(element);\n            }, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#move\n         * @kind function\n         *\n         * @description\n         * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or\n         * add the element directly after the afterElement element if present. Then the move animation will be run. Once\n         * the animation is started, the following CSS classes will be added for the duration of the animation:\n         *\n         * Below is a breakdown of each step that occurs during move animation:\n         *\n         * | Animation Step                                                                                                       | What the element class attribute looks like              |\n         * |----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|\n         * | 1. `$animate.move(...)` is called                                                                                    | `class=\"my-animation\"`                                   |\n         * | 2. element is moved into the parentElement element or beside the afterElement element                                | `class=\"my-animation\"`                                   |\n         * | 3. `$animate` waits for the next digest to start the animation                                                       | `class=\"my-animation ng-animate\"`                        |\n         * | 4. `$animate` runs the JavaScript-defined animations detected on the element                                         | `class=\"my-animation ng-animate\"`                        |\n         * | 5. the `.ng-move` class is added to the element                                                                      | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                        | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 7. `$animate` blocks all CSS transitions on the element to ensure the `.ng-move` class styling is applied right away | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 8. `$animate` waits for a single animation frame (this performs a reflow)                                            | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 9. `$animate` removes the CSS transition block placed on the element                                                 | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 10. the `.ng-move-active` class is added (this triggers the CSS transition/animation)                                | `class=\"my-animation ng-animate ng-move ng-move-active\"` |\n         * | 11. `$animate` waits for the animation to complete (via events and timeout)                                          | `class=\"my-animation ng-animate ng-move ng-move-active\"` |\n         * | 12. The animation ends and all generated CSS classes are removed from the element                                    | `class=\"my-animation\"`                                   |\n         * | 13. The returned promise is resolved.                                                                                | `class=\"my-animation\"`                                   |\n         *\n         * @param {DOMElement} element the element that will be the focus of the move animation\n         * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation\n         * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        move: function(element, parentElement, afterElement, options) {\n          options = parseAnimateOptions(options);\n          element = angular.element(element);\n          parentElement = prepareElement(parentElement);\n          afterElement = prepareElement(afterElement);\n\n          cancelChildAnimations(element);\n          classBasedAnimationsBlocked(element, true);\n          $delegate.move(element, parentElement, afterElement);\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#addClass\n         *\n         * @description\n         * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class.\n         * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide\n         * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions\n         * or keyframes are defined on the -add-active or base CSS class).\n         *\n         * Below is a breakdown of each step that occurs during addClass animation:\n         *\n         * | Animation Step                                                                                         | What the element class attribute looks like                        |\n         * |--------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|\n         * | 1. `$animate.addClass(element, 'super')` is called                                                     | `class=\"my-animation\"`                                             |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                           | `class=\"my-animation ng-animate\"`                                  |\n         * | 3. the `.super-add` class is added to the element                                                      | `class=\"my-animation ng-animate super-add\"`                        |\n         * | 4. `$animate` waits for a single animation frame (this performs a reflow)                              | `class=\"my-animation ng-animate super-add\"`                        |\n         * | 5. the `.super` and `.super-add-active` classes are added (this triggers the CSS transition/animation) | `class=\"my-animation ng-animate super super-add super-add-active\"` |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay          | `class=\"my-animation ng-animate super super-add super-add-active\"` |\n         * | 7. `$animate` waits for the animation to complete (via events and timeout)                             | `class=\"my-animation ng-animate super super-add super-add-active\"` |\n         * | 8. The animation ends and all generated CSS classes are removed from the element                       | `class=\"my-animation super\"`                                       |\n         * | 9. The super class is kept on the element                                                              | `class=\"my-animation super\"`                                       |\n         * | 10. The returned promise is resolved.                                                                  | `class=\"my-animation super\"`                                       |\n         *\n         * @param {DOMElement} element the element that will be animated\n         * @param {string} className the CSS class that will be added to the element and then animated\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        addClass: function(element, className, options) {\n          return this.setClass(element, className, [], options);\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#removeClass\n         *\n         * @description\n         * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value\n         * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in\n         * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if\n         * no CSS transitions or keyframes are defined on the -remove or base CSS classes).\n         *\n         * Below is a breakdown of each step that occurs during removeClass animation:\n         *\n         * | Animation Step                                                                                                       | What the element class attribute looks like                        |\n         * |----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|\n         * | 1. `$animate.removeClass(element, 'super')` is called                                                                | `class=\"my-animation super\"`                                       |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                                         | `class=\"my-animation super ng-animate\"`                            |\n         * | 3. the `.super-remove` class is added to the element                                                                 | `class=\"my-animation super ng-animate super-remove\"`               |\n         * | 4. `$animate` waits for a single animation frame (this performs a reflow)                                            | `class=\"my-animation super ng-animate super-remove\"`               |\n         * | 5. the `.super-remove-active` classes are added and `.super` is removed (this triggers the CSS transition/animation) | `class=\"my-animation ng-animate super-remove super-remove-active\"` |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                        | `class=\"my-animation ng-animate super-remove super-remove-active\"` |\n         * | 7. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate super-remove super-remove-active\"` |\n         * | 8. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                             |\n         * | 9. The returned promise is resolved.                                                                                 | `class=\"my-animation\"`                                             |\n         *\n         *\n         * @param {DOMElement} element the element that will be animated\n         * @param {string} className the CSS class that will be animated and then removed from the element\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        removeClass: function(element, className, options) {\n          return this.setClass(element, [], className, options);\n        },\n\n        /**\n         *\n         * @ngdoc method\n         * @name $animate#setClass\n         *\n         * @description Adds and/or removes the given CSS classes to and from the element.\n         * Once complete, the `done()` callback will be fired (if provided).\n         *\n         * | Animation Step                                                                                                                               | What the element class attribute looks like                                            |\n         * |----------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|\n         * | 1. `$animate.setClass(element, 'on', 'off')` is called                                                                                       | `class=\"my-animation off\"`                                                             |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                                                                 | `class=\"my-animation ng-animate off\"`                                                  |\n         * | 3. the `.on-add` and `.off-remove` classes are added to the element                                                                          | `class=\"my-animation ng-animate on-add off-remove off\"`                                |\n         * | 4. `$animate` waits for a single animation frame (this performs a reflow)                                                                    | `class=\"my-animation ng-animate on-add off-remove off\"`                                |\n         * | 5. the `.on`, `.on-add-active` and `.off-remove-active` classes are added and `.off` is removed (this triggers the CSS transition/animation) | `class=\"my-animation ng-animate on on-add on-add-active off-remove off-remove-active\"` |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                                                | `class=\"my-animation ng-animate on on-add on-add-active off-remove off-remove-active\"` |\n         * | 7. `$animate` waits for the animation to complete (via events and timeout)                                                                   | `class=\"my-animation ng-animate on on-add on-add-active off-remove off-remove-active\"` |\n         * | 8. The animation ends and all generated CSS classes are removed from the element                                                             | `class=\"my-animation on\"`                                                              |\n         * | 9. The returned promise is resolved.                                                                                                         | `class=\"my-animation on\"`                                                              |\n         *\n         * @param {DOMElement} element the element which will have its CSS classes changed\n         *   removed from it\n         * @param {string} add the CSS classes which will be added to the element\n         * @param {string} remove the CSS class which will be removed from the element\n         *   CSS classes have been set on the element\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n         */\n        setClass: function(element, add, remove, options) {\n          options = parseAnimateOptions(options);\n\n          var STORAGE_KEY = '$$animateClasses';\n          element = angular.element(element);\n          element = stripCommentsFromElement(element);\n\n          if (classBasedAnimationsBlocked(element)) {\n            return $delegate.$$setClassImmediately(element, add, remove, options);\n          }\n\n          // we're using a combined array for both the add and remove\n          // operations since the ORDER OF addClass and removeClass matters\n          var classes, cache = element.data(STORAGE_KEY);\n          var hasCache = !!cache;\n          if (!cache) {\n            cache = {};\n            cache.classes = {};\n          }\n          classes = cache.classes;\n\n          add = isArray(add) ? add : add.split(' ');\n          forEach(add, function(c) {\n            if (c && c.length) {\n              classes[c] = true;\n            }\n          });\n\n          remove = isArray(remove) ? remove : remove.split(' ');\n          forEach(remove, function(c) {\n            if (c && c.length) {\n              classes[c] = false;\n            }\n          });\n\n          if (hasCache) {\n            if (options && cache.options) {\n              cache.options = angular.extend(cache.options || {}, options);\n            }\n\n            //the digest cycle will combine all the animations into one function\n            return cache.promise;\n          } else {\n            element.data(STORAGE_KEY, cache = {\n              classes: classes,\n              options: options\n            });\n          }\n\n          return cache.promise = runAnimationPostDigest(function(done) {\n            var parentElement = element.parent();\n            var elementNode = extractElementNode(element);\n            var parentNode = elementNode.parentNode;\n            // TODO(matsko): move this code into the animationsDisabled() function once #8092 is fixed\n            if (!parentNode || parentNode['$$NG_REMOVED'] || elementNode['$$NG_REMOVED']) {\n              done();\n              return;\n            }\n\n            var cache = element.data(STORAGE_KEY);\n            element.removeData(STORAGE_KEY);\n\n            var state = element.data(NG_ANIMATE_STATE) || {};\n            var classes = resolveElementClasses(element, cache, state.active);\n            return !classes\n              ? done()\n              : performAnimation('setClass', classes, element, parentElement, null, function() {\n                  if (classes[0]) $delegate.$$addClassImmediately(element, classes[0]);\n                  if (classes[1]) $delegate.$$removeClassImmediately(element, classes[1]);\n                }, cache.options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#cancel\n         * @kind function\n         *\n         * @param {Promise} animationPromise The animation promise that is returned when an animation is started.\n         *\n         * @description\n         * Cancels the provided animation.\n        */\n        cancel: function(promise) {\n          promise.$$cancelFn();\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#enabled\n         * @kind function\n         *\n         * @param {boolean=} value If provided then set the animation on or off.\n         * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation\n         * @return {boolean} Current animation state.\n         *\n         * @description\n         * Globally enables/disables animations.\n         *\n        */\n        enabled: function(value, element) {\n          switch (arguments.length) {\n            case 2:\n              if (value) {\n                cleanup(element);\n              } else {\n                var data = element.data(NG_ANIMATE_STATE) || {};\n                data.disabled = true;\n                element.data(NG_ANIMATE_STATE, data);\n              }\n            break;\n\n            case 1:\n              rootAnimateState.disabled = !value;\n            break;\n\n            default:\n              value = !rootAnimateState.disabled;\n            break;\n          }\n          return !!value;\n         }\n      };\n\n      /*\n        all animations call this shared animation triggering function internally.\n        The animationEvent variable refers to the JavaScript animation event that will be triggered\n        and the className value is the name of the animation that will be applied within the\n        CSS code. Element, `parentElement` and `afterElement` are provided DOM elements for the animation\n        and the onComplete callback will be fired once the animation is fully complete.\n      */\n      function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, options, doneCallback) {\n        var noopCancel = noop;\n        var runner = animationRunner(element, animationEvent, className, options);\n        if (!runner) {\n          fireDOMOperation();\n          fireBeforeCallbackAsync();\n          fireAfterCallbackAsync();\n          closeAnimation();\n          return noopCancel;\n        }\n\n        animationEvent = runner.event;\n        className = runner.className;\n        var elementEvents = angular.element._data(runner.node);\n        elementEvents = elementEvents && elementEvents.events;\n\n        if (!parentElement) {\n          parentElement = afterElement ? afterElement.parent() : element.parent();\n        }\n\n        //skip the animation if animations are disabled, a parent is already being animated,\n        //the element is not currently attached to the document body or then completely close\n        //the animation if any matching animations are not found at all.\n        //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found.\n        if (animationsDisabled(element, parentElement)) {\n          fireDOMOperation();\n          fireBeforeCallbackAsync();\n          fireAfterCallbackAsync();\n          closeAnimation();\n          return noopCancel;\n        }\n\n        var ngAnimateState  = element.data(NG_ANIMATE_STATE) || {};\n        var runningAnimations     = ngAnimateState.active || {};\n        var totalActiveAnimations = ngAnimateState.totalActive || 0;\n        var lastAnimation         = ngAnimateState.last;\n        var skipAnimation = false;\n\n        if (totalActiveAnimations > 0) {\n          var animationsToCancel = [];\n          if (!runner.isClassBased) {\n            if (animationEvent == 'leave' && runningAnimations['ng-leave']) {\n              skipAnimation = true;\n            } else {\n              //cancel all animations when a structural animation takes place\n              for (var klass in runningAnimations) {\n                animationsToCancel.push(runningAnimations[klass]);\n              }\n              ngAnimateState = {};\n              cleanup(element, true);\n            }\n          } else if (lastAnimation.event == 'setClass') {\n            animationsToCancel.push(lastAnimation);\n            cleanup(element, className);\n          } else if (runningAnimations[className]) {\n            var current = runningAnimations[className];\n            if (current.event == animationEvent) {\n              skipAnimation = true;\n            } else {\n              animationsToCancel.push(current);\n              cleanup(element, className);\n            }\n          }\n\n          if (animationsToCancel.length > 0) {\n            forEach(animationsToCancel, function(operation) {\n              operation.cancel();\n            });\n          }\n        }\n\n        if (runner.isClassBased\n            && !runner.isSetClassOperation\n            && animationEvent != 'animate'\n            && !skipAnimation) {\n          skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR\n        }\n\n        if (skipAnimation) {\n          fireDOMOperation();\n          fireBeforeCallbackAsync();\n          fireAfterCallbackAsync();\n          fireDoneCallbackAsync();\n          return noopCancel;\n        }\n\n        runningAnimations     = ngAnimateState.active || {};\n        totalActiveAnimations = ngAnimateState.totalActive || 0;\n\n        if (animationEvent == 'leave') {\n          //there's no need to ever remove the listener since the element\n          //will be removed (destroyed) after the leave animation ends or\n          //is cancelled midway\n          element.one('$destroy', function(e) {\n            var element = angular.element(this);\n            var state = element.data(NG_ANIMATE_STATE);\n            if (state) {\n              var activeLeaveAnimation = state.active['ng-leave'];\n              if (activeLeaveAnimation) {\n                activeLeaveAnimation.cancel();\n                cleanup(element, 'ng-leave');\n              }\n            }\n          });\n        }\n\n        //the ng-animate class does nothing, but it's here to allow for\n        //parent animations to find and cancel child animations when needed\n        $$jqLite.addClass(element, NG_ANIMATE_CLASS_NAME);\n        if (options && options.tempClasses) {\n          forEach(options.tempClasses, function(className) {\n            $$jqLite.addClass(element, className);\n          });\n        }\n\n        var localAnimationCount = globalAnimationCounter++;\n        totalActiveAnimations++;\n        runningAnimations[className] = runner;\n\n        element.data(NG_ANIMATE_STATE, {\n          last: runner,\n          active: runningAnimations,\n          index: localAnimationCount,\n          totalActive: totalActiveAnimations\n        });\n\n        //first we run the before animations and when all of those are complete\n        //then we perform the DOM operation and run the next set of animations\n        fireBeforeCallbackAsync();\n        runner.before(function(cancelled) {\n          var data = element.data(NG_ANIMATE_STATE);\n          cancelled = cancelled ||\n                        !data || !data.active[className] ||\n                        (runner.isClassBased && data.active[className].event != animationEvent);\n\n          fireDOMOperation();\n          if (cancelled === true) {\n            closeAnimation();\n          } else {\n            fireAfterCallbackAsync();\n            runner.after(closeAnimation);\n          }\n        });\n\n        return runner.cancel;\n\n        function fireDOMCallback(animationPhase) {\n          var eventName = '$animate:' + animationPhase;\n          if (elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) {\n            $$asyncCallback(function() {\n              element.triggerHandler(eventName, {\n                event: animationEvent,\n                className: className\n              });\n            });\n          }\n        }\n\n        function fireBeforeCallbackAsync() {\n          fireDOMCallback('before');\n        }\n\n        function fireAfterCallbackAsync() {\n          fireDOMCallback('after');\n        }\n\n        function fireDoneCallbackAsync() {\n          fireDOMCallback('close');\n          doneCallback();\n        }\n\n        //it is less complicated to use a flag than managing and canceling\n        //timeouts containing multiple callbacks.\n        function fireDOMOperation() {\n          if (!fireDOMOperation.hasBeenRun) {\n            fireDOMOperation.hasBeenRun = true;\n            domOperation();\n          }\n        }\n\n        function closeAnimation() {\n          if (!closeAnimation.hasBeenRun) {\n            if (runner) { //the runner doesn't exist if it fails to instantiate\n              runner.applyStyles();\n            }\n\n            closeAnimation.hasBeenRun = true;\n            if (options && options.tempClasses) {\n              forEach(options.tempClasses, function(className) {\n                $$jqLite.removeClass(element, className);\n              });\n            }\n\n            var data = element.data(NG_ANIMATE_STATE);\n            if (data) {\n\n              /* only structural animations wait for reflow before removing an\n                 animation, but class-based animations don't. An example of this\n                 failing would be when a parent HTML tag has a ng-class attribute\n                 causing ALL directives below to skip animations during the digest */\n              if (runner && runner.isClassBased) {\n                cleanup(element, className);\n              } else {\n                $$asyncCallback(function() {\n                  var data = element.data(NG_ANIMATE_STATE) || {};\n                  if (localAnimationCount == data.index) {\n                    cleanup(element, className, animationEvent);\n                  }\n                });\n                element.data(NG_ANIMATE_STATE, data);\n              }\n            }\n            fireDoneCallbackAsync();\n          }\n        }\n      }\n\n      function cancelChildAnimations(element) {\n        var node = extractElementNode(element);\n        if (node) {\n          var nodes = angular.isFunction(node.getElementsByClassName) ?\n            node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) :\n            node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME);\n          forEach(nodes, function(element) {\n            element = angular.element(element);\n            var data = element.data(NG_ANIMATE_STATE);\n            if (data && data.active) {\n              forEach(data.active, function(runner) {\n                runner.cancel();\n              });\n            }\n          });\n        }\n      }\n\n      function cleanup(element, className) {\n        if (isMatchingElement(element, $rootElement)) {\n          if (!rootAnimateState.disabled) {\n            rootAnimateState.running = false;\n            rootAnimateState.structural = false;\n          }\n        } else if (className) {\n          var data = element.data(NG_ANIMATE_STATE) || {};\n\n          var removeAnimations = className === true;\n          if (!removeAnimations && data.active && data.active[className]) {\n            data.totalActive--;\n            delete data.active[className];\n          }\n\n          if (removeAnimations || !data.totalActive) {\n            $$jqLite.removeClass(element, NG_ANIMATE_CLASS_NAME);\n            element.removeData(NG_ANIMATE_STATE);\n          }\n        }\n      }\n\n      function animationsDisabled(element, parentElement) {\n        if (rootAnimateState.disabled) {\n          return true;\n        }\n\n        if (isMatchingElement(element, $rootElement)) {\n          return rootAnimateState.running;\n        }\n\n        var allowChildAnimations, parentRunningAnimation, hasParent;\n        do {\n          //the element did not reach the root element which means that it\n          //is not apart of the DOM. Therefore there is no reason to do\n          //any animations on it\n          if (parentElement.length === 0) break;\n\n          var isRoot = isMatchingElement(parentElement, $rootElement);\n          var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {});\n          if (state.disabled) {\n            return true;\n          }\n\n          //no matter what, for an animation to work it must reach the root element\n          //this implies that the element is attached to the DOM when the animation is run\n          if (isRoot) {\n            hasParent = true;\n          }\n\n          //once a flag is found that is strictly false then everything before\n          //it will be discarded and all child animations will be restricted\n          if (allowChildAnimations !== false) {\n            var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN);\n            if (angular.isDefined(animateChildrenFlag)) {\n              allowChildAnimations = animateChildrenFlag;\n            }\n          }\n\n          parentRunningAnimation = parentRunningAnimation ||\n                                   state.running ||\n                                   (state.last && !state.last.isClassBased);\n        }\n        while (parentElement = parentElement.parent());\n\n        return !hasParent || (!allowChildAnimations && parentRunningAnimation);\n      }\n    }]);\n\n    $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow',\n                           function($window,   $sniffer,   $timeout,   $$animateReflow) {\n      // Detect proper transitionend/animationend event names.\n      var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;\n\n      // If unprefixed events are not supported but webkit-prefixed are, use the latter.\n      // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.\n      // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`\n      // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.\n      // Register both events in case `window.onanimationend` is not supported because of that,\n      // do the same for `transitionend` as Safari is likely to exhibit similar behavior.\n      // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit\n      // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition\n      if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {\n        CSS_PREFIX = '-webkit-';\n        TRANSITION_PROP = 'WebkitTransition';\n        TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';\n      } else {\n        TRANSITION_PROP = 'transition';\n        TRANSITIONEND_EVENT = 'transitionend';\n      }\n\n      if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {\n        CSS_PREFIX = '-webkit-';\n        ANIMATION_PROP = 'WebkitAnimation';\n        ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';\n      } else {\n        ANIMATION_PROP = 'animation';\n        ANIMATIONEND_EVENT = 'animationend';\n      }\n\n      var DURATION_KEY = 'Duration';\n      var PROPERTY_KEY = 'Property';\n      var DELAY_KEY = 'Delay';\n      var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';\n      var ANIMATION_PLAYSTATE_KEY = 'PlayState';\n      var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey';\n      var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data';\n      var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;\n      var CLOSING_TIME_BUFFER = 1.5;\n      var ONE_SECOND = 1000;\n\n      var lookupCache = {};\n      var parentCounter = 0;\n      var animationReflowQueue = [];\n      var cancelAnimationReflow;\n      function clearCacheAfterReflow() {\n        if (!cancelAnimationReflow) {\n          cancelAnimationReflow = $$animateReflow(function() {\n            animationReflowQueue = [];\n            cancelAnimationReflow = null;\n            lookupCache = {};\n          });\n        }\n      }\n\n      function afterReflow(element, callback) {\n        if (cancelAnimationReflow) {\n          cancelAnimationReflow();\n        }\n        animationReflowQueue.push(callback);\n        cancelAnimationReflow = $$animateReflow(function() {\n          forEach(animationReflowQueue, function(fn) {\n            fn();\n          });\n\n          animationReflowQueue = [];\n          cancelAnimationReflow = null;\n          lookupCache = {};\n        });\n      }\n\n      var closingTimer = null;\n      var closingTimestamp = 0;\n      var animationElementQueue = [];\n      function animationCloseHandler(element, totalTime) {\n        var node = extractElementNode(element);\n        element = angular.element(node);\n\n        //this item will be garbage collected by the closing\n        //animation timeout\n        animationElementQueue.push(element);\n\n        //but it may not need to cancel out the existing timeout\n        //if the timestamp is less than the previous one\n        var futureTimestamp = Date.now() + totalTime;\n        if (futureTimestamp <= closingTimestamp) {\n          return;\n        }\n\n        $timeout.cancel(closingTimer);\n\n        closingTimestamp = futureTimestamp;\n        closingTimer = $timeout(function() {\n          closeAllAnimations(animationElementQueue);\n          animationElementQueue = [];\n        }, totalTime, false);\n      }\n\n      function closeAllAnimations(elements) {\n        forEach(elements, function(element) {\n          var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);\n          if (elementData) {\n            forEach(elementData.closeAnimationFns, function(fn) {\n              fn();\n            });\n          }\n        });\n      }\n\n      function getElementAnimationDetails(element, cacheKey) {\n        var data = cacheKey ? lookupCache[cacheKey] : null;\n        if (!data) {\n          var transitionDuration = 0;\n          var transitionDelay = 0;\n          var animationDuration = 0;\n          var animationDelay = 0;\n\n          //we want all the styles defined before and after\n          forEach(element, function(element) {\n            if (element.nodeType == ELEMENT_NODE) {\n              var elementStyles = $window.getComputedStyle(element) || {};\n\n              var transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY];\n              transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration);\n\n              var transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY];\n              transitionDelay  = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay);\n\n              var animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY];\n              animationDelay   = Math.max(parseMaxTime(elementStyles[ANIMATION_PROP + DELAY_KEY]), animationDelay);\n\n              var aDuration  = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]);\n\n              if (aDuration > 0) {\n                aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1;\n              }\n              animationDuration = Math.max(aDuration, animationDuration);\n            }\n          });\n          data = {\n            total: 0,\n            transitionDelay: transitionDelay,\n            transitionDuration: transitionDuration,\n            animationDelay: animationDelay,\n            animationDuration: animationDuration\n          };\n          if (cacheKey) {\n            lookupCache[cacheKey] = data;\n          }\n        }\n        return data;\n      }\n\n      function parseMaxTime(str) {\n        var maxValue = 0;\n        var values = isString(str) ?\n          str.split(/\\s*,\\s*/) :\n          [];\n        forEach(values, function(value) {\n          maxValue = Math.max(parseFloat(value) || 0, maxValue);\n        });\n        return maxValue;\n      }\n\n      function getCacheKey(element) {\n        var parentElement = element.parent();\n        var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY);\n        if (!parentID) {\n          parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter);\n          parentID = parentCounter;\n        }\n        return parentID + '-' + extractElementNode(element).getAttribute('class');\n      }\n\n      function animateSetup(animationEvent, element, className, styles) {\n        var structural = ['ng-enter','ng-leave','ng-move'].indexOf(className) >= 0;\n\n        var cacheKey = getCacheKey(element);\n        var eventCacheKey = cacheKey + ' ' + className;\n        var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0;\n\n        var stagger = {};\n        if (itemIndex > 0) {\n          var staggerClassName = className + '-stagger';\n          var staggerCacheKey = cacheKey + ' ' + staggerClassName;\n          var applyClasses = !lookupCache[staggerCacheKey];\n\n          applyClasses && $$jqLite.addClass(element, staggerClassName);\n\n          stagger = getElementAnimationDetails(element, staggerCacheKey);\n\n          applyClasses && $$jqLite.removeClass(element, staggerClassName);\n        }\n\n        $$jqLite.addClass(element, className);\n\n        var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {};\n        var timings = getElementAnimationDetails(element, eventCacheKey);\n        var transitionDuration = timings.transitionDuration;\n        var animationDuration = timings.animationDuration;\n\n        if (structural && transitionDuration === 0 && animationDuration === 0) {\n          $$jqLite.removeClass(element, className);\n          return false;\n        }\n\n        var blockTransition = styles || (structural && transitionDuration > 0);\n        var blockAnimation = animationDuration > 0 &&\n                             stagger.animationDelay > 0 &&\n                             stagger.animationDuration === 0;\n\n        var closeAnimationFns = formerData.closeAnimationFns || [];\n        element.data(NG_ANIMATE_CSS_DATA_KEY, {\n          stagger: stagger,\n          cacheKey: eventCacheKey,\n          running: formerData.running || 0,\n          itemIndex: itemIndex,\n          blockTransition: blockTransition,\n          closeAnimationFns: closeAnimationFns\n        });\n\n        var node = extractElementNode(element);\n\n        if (blockTransition) {\n          blockTransitions(node, true);\n          if (styles) {\n            element.css(styles);\n          }\n        }\n\n        if (blockAnimation) {\n          blockAnimations(node, true);\n        }\n\n        return true;\n      }\n\n      function animateRun(animationEvent, element, className, activeAnimationComplete, styles) {\n        var node = extractElementNode(element);\n        var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);\n        if (node.getAttribute('class').indexOf(className) == -1 || !elementData) {\n          activeAnimationComplete();\n          return;\n        }\n\n        var activeClassName = '';\n        var pendingClassName = '';\n        forEach(className.split(' '), function(klass, i) {\n          var prefix = (i > 0 ? ' ' : '') + klass;\n          activeClassName += prefix + '-active';\n          pendingClassName += prefix + '-pending';\n        });\n\n        var style = '';\n        var appliedStyles = [];\n        var itemIndex = elementData.itemIndex;\n        var stagger = elementData.stagger;\n        var staggerTime = 0;\n        if (itemIndex > 0) {\n          var transitionStaggerDelay = 0;\n          if (stagger.transitionDelay > 0 && stagger.transitionDuration === 0) {\n            transitionStaggerDelay = stagger.transitionDelay * itemIndex;\n          }\n\n          var animationStaggerDelay = 0;\n          if (stagger.animationDelay > 0 && stagger.animationDuration === 0) {\n            animationStaggerDelay = stagger.animationDelay * itemIndex;\n            appliedStyles.push(CSS_PREFIX + 'animation-play-state');\n          }\n\n          staggerTime = Math.round(Math.max(transitionStaggerDelay, animationStaggerDelay) * 100) / 100;\n        }\n\n        if (!staggerTime) {\n          $$jqLite.addClass(element, activeClassName);\n          if (elementData.blockTransition) {\n            blockTransitions(node, false);\n          }\n        }\n\n        var eventCacheKey = elementData.cacheKey + ' ' + activeClassName;\n        var timings = getElementAnimationDetails(element, eventCacheKey);\n        var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration);\n        if (maxDuration === 0) {\n          $$jqLite.removeClass(element, activeClassName);\n          animateClose(element, className);\n          activeAnimationComplete();\n          return;\n        }\n\n        if (!staggerTime && styles && Object.keys(styles).length > 0) {\n          if (!timings.transitionDuration) {\n            element.css('transition', timings.animationDuration + 's linear all');\n            appliedStyles.push('transition');\n          }\n          element.css(styles);\n        }\n\n        var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay);\n        var maxDelayTime = maxDelay * ONE_SECOND;\n\n        if (appliedStyles.length > 0) {\n          //the element being animated may sometimes contain comment nodes in\n          //the jqLite object, so we're safe to use a single variable to house\n          //the styles since there is always only one element being animated\n          var oldStyle = node.getAttribute('style') || '';\n          if (oldStyle.charAt(oldStyle.length - 1) !== ';') {\n            oldStyle += ';';\n          }\n          node.setAttribute('style', oldStyle + ' ' + style);\n        }\n\n        var startTime = Date.now();\n        var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT;\n        var animationTime     = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER;\n        var totalTime         = (staggerTime + animationTime) * ONE_SECOND;\n\n        var staggerTimeout;\n        if (staggerTime > 0) {\n          $$jqLite.addClass(element, pendingClassName);\n          staggerTimeout = $timeout(function() {\n            staggerTimeout = null;\n\n            if (timings.transitionDuration > 0) {\n              blockTransitions(node, false);\n            }\n            if (timings.animationDuration > 0) {\n              blockAnimations(node, false);\n            }\n\n            $$jqLite.addClass(element, activeClassName);\n            $$jqLite.removeClass(element, pendingClassName);\n\n            if (styles) {\n              if (timings.transitionDuration === 0) {\n                element.css('transition', timings.animationDuration + 's linear all');\n              }\n              element.css(styles);\n              appliedStyles.push('transition');\n            }\n          }, staggerTime * ONE_SECOND, false);\n        }\n\n        element.on(css3AnimationEvents, onAnimationProgress);\n        elementData.closeAnimationFns.push(function() {\n          onEnd();\n          activeAnimationComplete();\n        });\n\n        elementData.running++;\n        animationCloseHandler(element, totalTime);\n        return onEnd;\n\n        // This will automatically be called by $animate so\n        // there is no need to attach this internally to the\n        // timeout done method.\n        function onEnd() {\n          element.off(css3AnimationEvents, onAnimationProgress);\n          $$jqLite.removeClass(element, activeClassName);\n          $$jqLite.removeClass(element, pendingClassName);\n          if (staggerTimeout) {\n            $timeout.cancel(staggerTimeout);\n          }\n          animateClose(element, className);\n          var node = extractElementNode(element);\n          for (var i in appliedStyles) {\n            node.style.removeProperty(appliedStyles[i]);\n          }\n        }\n\n        function onAnimationProgress(event) {\n          event.stopPropagation();\n          var ev = event.originalEvent || event;\n          var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();\n\n          /* Firefox (or possibly just Gecko) likes to not round values up\n           * when a ms measurement is used for the animation */\n          var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));\n\n          /* $manualTimeStamp is a mocked timeStamp value which is set\n           * within browserTrigger(). This is only here so that tests can\n           * mock animations properly. Real events fallback to event.timeStamp,\n           * or, if they don't, then a timeStamp is automatically created for them.\n           * We're checking to see if the timeStamp surpasses the expected delay,\n           * but we're using elapsedTime instead of the timeStamp on the 2nd\n           * pre-condition since animations sometimes close off early */\n          if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {\n            activeAnimationComplete();\n          }\n        }\n      }\n\n      function blockTransitions(node, bool) {\n        node.style[TRANSITION_PROP + PROPERTY_KEY] = bool ? 'none' : '';\n      }\n\n      function blockAnimations(node, bool) {\n        node.style[ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY] = bool ? 'paused' : '';\n      }\n\n      function animateBefore(animationEvent, element, className, styles) {\n        if (animateSetup(animationEvent, element, className, styles)) {\n          return function(cancelled) {\n            cancelled && animateClose(element, className);\n          };\n        }\n      }\n\n      function animateAfter(animationEvent, element, className, afterAnimationComplete, styles) {\n        if (element.data(NG_ANIMATE_CSS_DATA_KEY)) {\n          return animateRun(animationEvent, element, className, afterAnimationComplete, styles);\n        } else {\n          animateClose(element, className);\n          afterAnimationComplete();\n        }\n      }\n\n      function animate(animationEvent, element, className, animationComplete, options) {\n        //If the animateSetup function doesn't bother returning a\n        //cancellation function then it means that there is no animation\n        //to perform at all\n        var preReflowCancellation = animateBefore(animationEvent, element, className, options.from);\n        if (!preReflowCancellation) {\n          clearCacheAfterReflow();\n          animationComplete();\n          return;\n        }\n\n        //There are two cancellation functions: one is before the first\n        //reflow animation and the second is during the active state\n        //animation. The first function will take care of removing the\n        //data from the element which will not make the 2nd animation\n        //happen in the first place\n        var cancel = preReflowCancellation;\n        afterReflow(element, function() {\n          //once the reflow is complete then we point cancel to\n          //the new cancellation function which will remove all of the\n          //animation properties from the active animation\n          cancel = animateAfter(animationEvent, element, className, animationComplete, options.to);\n        });\n\n        return function(cancelled) {\n          (cancel || noop)(cancelled);\n        };\n      }\n\n      function animateClose(element, className) {\n        $$jqLite.removeClass(element, className);\n        var data = element.data(NG_ANIMATE_CSS_DATA_KEY);\n        if (data) {\n          if (data.running) {\n            data.running--;\n          }\n          if (!data.running || data.running === 0) {\n            element.removeData(NG_ANIMATE_CSS_DATA_KEY);\n          }\n        }\n      }\n\n      return {\n        animate: function(element, className, from, to, animationCompleted, options) {\n          options = options || {};\n          options.from = from;\n          options.to = to;\n          return animate('animate', element, className, animationCompleted, options);\n        },\n\n        enter: function(element, animationCompleted, options) {\n          options = options || {};\n          return animate('enter', element, 'ng-enter', animationCompleted, options);\n        },\n\n        leave: function(element, animationCompleted, options) {\n          options = options || {};\n          return animate('leave', element, 'ng-leave', animationCompleted, options);\n        },\n\n        move: function(element, animationCompleted, options) {\n          options = options || {};\n          return animate('move', element, 'ng-move', animationCompleted, options);\n        },\n\n        beforeSetClass: function(element, add, remove, animationCompleted, options) {\n          options = options || {};\n          var className = suffixClasses(remove, '-remove') + ' ' +\n                          suffixClasses(add, '-add');\n          var cancellationMethod = animateBefore('setClass', element, className, options.from);\n          if (cancellationMethod) {\n            afterReflow(element, animationCompleted);\n            return cancellationMethod;\n          }\n          clearCacheAfterReflow();\n          animationCompleted();\n        },\n\n        beforeAddClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), options.from);\n          if (cancellationMethod) {\n            afterReflow(element, animationCompleted);\n            return cancellationMethod;\n          }\n          clearCacheAfterReflow();\n          animationCompleted();\n        },\n\n        beforeRemoveClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), options.from);\n          if (cancellationMethod) {\n            afterReflow(element, animationCompleted);\n            return cancellationMethod;\n          }\n          clearCacheAfterReflow();\n          animationCompleted();\n        },\n\n        setClass: function(element, add, remove, animationCompleted, options) {\n          options = options || {};\n          remove = suffixClasses(remove, '-remove');\n          add = suffixClasses(add, '-add');\n          var className = remove + ' ' + add;\n          return animateAfter('setClass', element, className, animationCompleted, options.to);\n        },\n\n        addClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted, options.to);\n        },\n\n        removeClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted, options.to);\n        }\n      };\n\n      function suffixClasses(classes, suffix) {\n        var className = '';\n        classes = isArray(classes) ? classes : classes.split(/\\s+/);\n        forEach(classes, function(klass, i) {\n          if (klass && klass.length > 0) {\n            className += (i > 0 ? ' ' : '') + klass + suffix;\n          }\n        });\n        return className;\n      }\n    }]);\n  }]);\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/angular/angular-resource.js",
    "content": "/**\n * @license AngularJS v1.3.13\n * (c) 2010-2014 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\nvar $resourceMinErr = angular.$$minErr('$resource');\n\n// Helper functions and regex to lookup a dotted path on an object\n// stopping at undefined/null.  The path must be composed of ASCII\n// identifiers (just like $parse)\nvar MEMBER_NAME_REGEX = /^(\\.[a-zA-Z_$][0-9a-zA-Z_$]*)+$/;\n\nfunction isValidDottedPath(path) {\n  return (path != null && path !== '' && path !== 'hasOwnProperty' &&\n      MEMBER_NAME_REGEX.test('.' + path));\n}\n\nfunction lookupDottedPath(obj, path) {\n  if (!isValidDottedPath(path)) {\n    throw $resourceMinErr('badmember', 'Dotted member path \"@{0}\" is invalid.', path);\n  }\n  var keys = path.split('.');\n  for (var i = 0, ii = keys.length; i < ii && obj !== undefined; i++) {\n    var key = keys[i];\n    obj = (obj !== null) ? obj[key] : undefined;\n  }\n  return obj;\n}\n\n/**\n * Create a shallow copy of an object and clear other fields from the destination\n */\nfunction shallowClearAndCopy(src, dst) {\n  dst = dst || {};\n\n  angular.forEach(dst, function(value, key) {\n    delete dst[key];\n  });\n\n  for (var key in src) {\n    if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n      dst[key] = src[key];\n    }\n  }\n\n  return dst;\n}\n\n/**\n * @ngdoc module\n * @name ngResource\n * @description\n *\n * # ngResource\n *\n * The `ngResource` module provides interaction support with RESTful services\n * via the $resource service.\n *\n *\n * <div doc-module-components=\"ngResource\"></div>\n *\n * See {@link ngResource.$resource `$resource`} for usage.\n */\n\n/**\n * @ngdoc service\n * @name $resource\n * @requires $http\n *\n * @description\n * A factory which creates a resource object that lets you interact with\n * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.\n *\n * The returned resource object has action methods which provide high-level behaviors without\n * the need to interact with the low level {@link ng.$http $http} service.\n *\n * Requires the {@link ngResource `ngResource`} module to be installed.\n *\n * By default, trailing slashes will be stripped from the calculated URLs,\n * which can pose problems with server backends that do not expect that\n * behavior.  This can be disabled by configuring the `$resourceProvider` like\n * this:\n *\n * ```js\n     app.config(['$resourceProvider', function($resourceProvider) {\n       // Don't strip trailing slashes from calculated URLs\n       $resourceProvider.defaults.stripTrailingSlashes = false;\n     }]);\n * ```\n *\n * @param {string} url A parametrized URL template with parameters prefixed by `:` as in\n *   `/user/:username`. If you are using a URL with a port number (e.g.\n *   `http://example.com:8080/api`), it will be respected.\n *\n *   If you are using a url with a suffix, just add the suffix, like this:\n *   `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`\n *   or even `$resource('http://example.com/resource/:resource_id.:format')`\n *   If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be\n *   collapsed down to a single `.`.  If you need this sequence to appear and not collapse then you\n *   can escape it with `/\\.`.\n *\n * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in\n *   `actions` methods. If any of the parameter value is a function, it will be executed every time\n *   when a param value needs to be obtained for a request (unless the param was overridden).\n *\n *   Each key value in the parameter object is first bound to url template if present and then any\n *   excess keys are appended to the url search query after the `?`.\n *\n *   Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in\n *   URL `/path/greet?salutation=Hello`.\n *\n *   If the parameter value is prefixed with `@` then the value for that parameter will be extracted\n *   from the corresponding property on the `data` object (provided when calling an action method).  For\n *   example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam`\n *   will be `data.someProp`.\n *\n * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend\n *   the default set of resource actions. The declaration should be created in the format of {@link\n *   ng.$http#usage $http.config}:\n *\n *       {action1: {method:?, params:?, isArray:?, headers:?, ...},\n *        action2: {method:?, params:?, isArray:?, headers:?, ...},\n *        ...}\n *\n *   Where:\n *\n *   - **`action`** – {string} – The name of action. This name becomes the name of the method on\n *     your resource object.\n *   - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,\n *     `DELETE`, `JSONP`, etc).\n *   - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of\n *     the parameter value is a function, it will be executed every time when a param value needs to\n *     be obtained for a request (unless the param was overridden).\n *   - **`url`** – {string} – action specific `url` override. The url templating is supported just\n *     like for the resource-level urls.\n *   - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,\n *     see `returns` section.\n *   - **`transformRequest`** –\n *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n *     transform function or an array of such functions. The transform function takes the http\n *     request body and headers and returns its transformed (typically serialized) version.\n *     By default, transformRequest will contain one function that checks if the request data is\n *     an object and serializes to using `angular.toJson`. To prevent this behavior, set\n *     `transformRequest` to an empty array: `transformRequest: []`\n *   - **`transformResponse`** –\n *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n *     transform function or an array of such functions. The transform function takes the http\n *     response body and headers and returns its transformed (typically deserialized) version.\n *     By default, transformResponse will contain one function that checks if the response looks like\n *     a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, set\n *     `transformResponse` to an empty array: `transformResponse: []`\n *   - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\n *     GET request, otherwise if a cache instance built with\n *     {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\n *     caching.\n *   - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that\n *     should abort the request when resolved.\n *   - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the\n *     XHR object. See\n *     [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)\n *     for more information.\n *   - **`responseType`** - `{string}` - see\n *     [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).\n *   - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -\n *     `response` and `responseError`. Both `response` and `responseError` interceptors get called\n *     with `http response` object. See {@link ng.$http $http interceptors}.\n *\n * @param {Object} options Hash with custom settings that should extend the\n *   default `$resourceProvider` behavior.  The only supported option is\n *\n *   Where:\n *\n *   - **`stripTrailingSlashes`** – {boolean} – If true then the trailing\n *   slashes from any calculated URL will be stripped. (Defaults to true.)\n *\n * @returns {Object} A resource \"class\" object with methods for the default set of resource actions\n *   optionally extended with custom `actions`. The default set contains these actions:\n *   ```js\n *   { 'get':    {method:'GET'},\n *     'save':   {method:'POST'},\n *     'query':  {method:'GET', isArray:true},\n *     'remove': {method:'DELETE'},\n *     'delete': {method:'DELETE'} };\n *   ```\n *\n *   Calling these methods invoke an {@link ng.$http} with the specified http method,\n *   destination and parameters. When the data is returned from the server then the object is an\n *   instance of the resource class. The actions `save`, `remove` and `delete` are available on it\n *   as  methods with the `$` prefix. This allows you to easily perform CRUD operations (create,\n *   read, update, delete) on server-side data like this:\n *   ```js\n *   var User = $resource('/user/:userId', {userId:'@id'});\n *   var user = User.get({userId:123}, function() {\n *     user.abc = true;\n *     user.$save();\n *   });\n *   ```\n *\n *   It is important to realize that invoking a $resource object method immediately returns an\n *   empty reference (object or array depending on `isArray`). Once the data is returned from the\n *   server the existing reference is populated with the actual data. This is a useful trick since\n *   usually the resource is assigned to a model which is then rendered by the view. Having an empty\n *   object results in no rendering, once the data arrives from the server then the object is\n *   populated with the data and the view automatically re-renders itself showing the new data. This\n *   means that in most cases one never has to write a callback function for the action methods.\n *\n *   The action methods on the class object or instance object can be invoked with the following\n *   parameters:\n *\n *   - HTTP GET \"class\" actions: `Resource.action([parameters], [success], [error])`\n *   - non-GET \"class\" actions: `Resource.action([parameters], postData, [success], [error])`\n *   - non-GET instance actions:  `instance.$action([parameters], [success], [error])`\n *\n *   Success callback is called with (value, responseHeaders) arguments. Error callback is called\n *   with (httpResponse) argument.\n *\n *   Class actions return empty instance (with additional properties below).\n *   Instance actions return promise of the action.\n *\n *   The Resource instances and collection have these additional properties:\n *\n *   - `$promise`: the {@link ng.$q promise} of the original server interaction that created this\n *     instance or collection.\n *\n *     On success, the promise is resolved with the same resource instance or collection object,\n *     updated with data from server. This makes it easy to use in\n *     {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view\n *     rendering until the resource(s) are loaded.\n *\n *     On failure, the promise is resolved with the {@link ng.$http http response} object, without\n *     the `resource` property.\n *\n *     If an interceptor object was provided, the promise will instead be resolved with the value\n *     returned by the interceptor.\n *\n *   - `$resolved`: `true` after first server interaction is completed (either with success or\n *      rejection), `false` before that. Knowing if the Resource has been resolved is useful in\n *      data-binding.\n *\n * @example\n *\n * # Credit card resource\n *\n * ```js\n     // Define CreditCard class\n     var CreditCard = $resource('/user/:userId/card/:cardId',\n      {userId:123, cardId:'@id'}, {\n       charge: {method:'POST', params:{charge:true}}\n      });\n\n     // We can retrieve a collection from the server\n     var cards = CreditCard.query(function() {\n       // GET: /user/123/card\n       // server returns: [ {id:456, number:'1234', name:'Smith'} ];\n\n       var card = cards[0];\n       // each item is an instance of CreditCard\n       expect(card instanceof CreditCard).toEqual(true);\n       card.name = \"J. Smith\";\n       // non GET methods are mapped onto the instances\n       card.$save();\n       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}\n       // server returns: {id:456, number:'1234', name: 'J. Smith'};\n\n       // our custom method is mapped as well.\n       card.$charge({amount:9.99});\n       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}\n     });\n\n     // we can create an instance as well\n     var newCard = new CreditCard({number:'0123'});\n     newCard.name = \"Mike Smith\";\n     newCard.$save();\n     // POST: /user/123/card {number:'0123', name:'Mike Smith'}\n     // server returns: {id:789, number:'0123', name: 'Mike Smith'};\n     expect(newCard.id).toEqual(789);\n * ```\n *\n * The object returned from this function execution is a resource \"class\" which has \"static\" method\n * for each action in the definition.\n *\n * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and\n * `headers`.\n * When the data is returned from the server then the object is an instance of the resource type and\n * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD\n * operations (create, read, update, delete) on server-side data.\n\n   ```js\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123}, function(user) {\n       user.abc = true;\n       user.$save();\n     });\n   ```\n *\n * It's worth noting that the success callback for `get`, `query` and other methods gets passed\n * in the response that came from the server as well as $http header getter function, so one\n * could rewrite the above example and get access to http headers as:\n *\n   ```js\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123}, function(u, getResponseHeaders){\n       u.abc = true;\n       u.$save(function(u, putResponseHeaders) {\n         //u => saved user object\n         //putResponseHeaders => $http header getter\n       });\n     });\n   ```\n *\n * You can also access the raw `$http` promise via the `$promise` property on the object returned\n *\n   ```\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123})\n         .$promise.then(function(user) {\n           $scope.user = user;\n         });\n   ```\n\n * # Creating a custom 'PUT' request\n * In this example we create a custom method on our resource to make a PUT request\n * ```js\n *    var app = angular.module('app', ['ngResource', 'ngRoute']);\n *\n *    // Some APIs expect a PUT request in the format URL/object/ID\n *    // Here we are creating an 'update' method\n *    app.factory('Notes', ['$resource', function($resource) {\n *    return $resource('/notes/:id', null,\n *        {\n *            'update': { method:'PUT' }\n *        });\n *    }]);\n *\n *    // In our controller we get the ID from the URL using ngRoute and $routeParams\n *    // We pass in $routeParams and our Notes factory along with $scope\n *    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',\n                                      function($scope, $routeParams, Notes) {\n *    // First get a note object from the factory\n *    var note = Notes.get({ id:$routeParams.id });\n *    $id = note.id;\n *\n *    // Now call update passing in the ID first then the object you are updating\n *    Notes.update({ id:$id }, note);\n *\n *    // This will PUT /notes/ID with the note object in the request payload\n *    }]);\n * ```\n */\nangular.module('ngResource', ['ng']).\n  provider('$resource', function() {\n    var provider = this;\n\n    this.defaults = {\n      // Strip slashes by default\n      stripTrailingSlashes: true,\n\n      // Default actions configuration\n      actions: {\n        'get': {method: 'GET'},\n        'save': {method: 'POST'},\n        'query': {method: 'GET', isArray: true},\n        'remove': {method: 'DELETE'},\n        'delete': {method: 'DELETE'}\n      }\n    };\n\n    this.$get = ['$http', '$q', function($http, $q) {\n\n      var noop = angular.noop,\n        forEach = angular.forEach,\n        extend = angular.extend,\n        copy = angular.copy,\n        isFunction = angular.isFunction;\n\n      /**\n       * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n       * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set\n       * (pchar) allowed in path segments:\n       *    segment       = *pchar\n       *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n       *    pct-encoded   = \"%\" HEXDIG HEXDIG\n       *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n       *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n       *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n       */\n      function encodeUriSegment(val) {\n        return encodeUriQuery(val, true).\n          replace(/%26/gi, '&').\n          replace(/%3D/gi, '=').\n          replace(/%2B/gi, '+');\n      }\n\n\n      /**\n       * This method is intended for encoding *key* or *value* parts of query component. We need a\n       * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't\n       * have to be encoded per http://tools.ietf.org/html/rfc3986:\n       *    query       = *( pchar / \"/\" / \"?\" )\n       *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n       *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n       *    pct-encoded   = \"%\" HEXDIG HEXDIG\n       *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n       *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n       */\n      function encodeUriQuery(val, pctEncodeSpaces) {\n        return encodeURIComponent(val).\n          replace(/%40/gi, '@').\n          replace(/%3A/gi, ':').\n          replace(/%24/g, '$').\n          replace(/%2C/gi, ',').\n          replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n      }\n\n      function Route(template, defaults) {\n        this.template = template;\n        this.defaults = extend({}, provider.defaults, defaults);\n        this.urlParams = {};\n      }\n\n      Route.prototype = {\n        setUrlParams: function(config, params, actionUrl) {\n          var self = this,\n            url = actionUrl || self.template,\n            val,\n            encodedVal;\n\n          var urlParams = self.urlParams = {};\n          forEach(url.split(/\\W/), function(param) {\n            if (param === 'hasOwnProperty') {\n              throw $resourceMinErr('badname', \"hasOwnProperty is not a valid parameter name.\");\n            }\n            if (!(new RegExp(\"^\\\\d+$\").test(param)) && param &&\n              (new RegExp(\"(^|[^\\\\\\\\]):\" + param + \"(\\\\W|$)\").test(url))) {\n              urlParams[param] = true;\n            }\n          });\n          url = url.replace(/\\\\:/g, ':');\n\n          params = params || {};\n          forEach(self.urlParams, function(_, urlParam) {\n            val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];\n            if (angular.isDefined(val) && val !== null) {\n              encodedVal = encodeUriSegment(val);\n              url = url.replace(new RegExp(\":\" + urlParam + \"(\\\\W|$)\", \"g\"), function(match, p1) {\n                return encodedVal + p1;\n              });\n            } else {\n              url = url.replace(new RegExp(\"(\\/?):\" + urlParam + \"(\\\\W|$)\", \"g\"), function(match,\n                  leadingSlashes, tail) {\n                if (tail.charAt(0) == '/') {\n                  return tail;\n                } else {\n                  return leadingSlashes + tail;\n                }\n              });\n            }\n          });\n\n          // strip trailing slashes and set the url (unless this behavior is specifically disabled)\n          if (self.defaults.stripTrailingSlashes) {\n            url = url.replace(/\\/+$/, '') || '/';\n          }\n\n          // then replace collapse `/.` if found in the last URL path segment before the query\n          // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`\n          url = url.replace(/\\/\\.(?=\\w+($|\\?))/, '.');\n          // replace escaped `/\\.` with `/.`\n          config.url = url.replace(/\\/\\\\\\./, '/.');\n\n\n          // set params - delegate param encoding to $http\n          forEach(params, function(value, key) {\n            if (!self.urlParams[key]) {\n              config.params = config.params || {};\n              config.params[key] = value;\n            }\n          });\n        }\n      };\n\n\n      function resourceFactory(url, paramDefaults, actions, options) {\n        var route = new Route(url, options);\n\n        actions = extend({}, provider.defaults.actions, actions);\n\n        function extractParams(data, actionParams) {\n          var ids = {};\n          actionParams = extend({}, paramDefaults, actionParams);\n          forEach(actionParams, function(value, key) {\n            if (isFunction(value)) { value = value(); }\n            ids[key] = value && value.charAt && value.charAt(0) == '@' ?\n              lookupDottedPath(data, value.substr(1)) : value;\n          });\n          return ids;\n        }\n\n        function defaultResponseInterceptor(response) {\n          return response.resource;\n        }\n\n        function Resource(value) {\n          shallowClearAndCopy(value || {}, this);\n        }\n\n        Resource.prototype.toJSON = function() {\n          var data = extend({}, this);\n          delete data.$promise;\n          delete data.$resolved;\n          return data;\n        };\n\n        forEach(actions, function(action, name) {\n          var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);\n\n          Resource[name] = function(a1, a2, a3, a4) {\n            var params = {}, data, success, error;\n\n            /* jshint -W086 */ /* (purposefully fall through case statements) */\n            switch (arguments.length) {\n              case 4:\n                error = a4;\n                success = a3;\n              //fallthrough\n              case 3:\n              case 2:\n                if (isFunction(a2)) {\n                  if (isFunction(a1)) {\n                    success = a1;\n                    error = a2;\n                    break;\n                  }\n\n                  success = a2;\n                  error = a3;\n                  //fallthrough\n                } else {\n                  params = a1;\n                  data = a2;\n                  success = a3;\n                  break;\n                }\n              case 1:\n                if (isFunction(a1)) success = a1;\n                else if (hasBody) data = a1;\n                else params = a1;\n                break;\n              case 0: break;\n              default:\n                throw $resourceMinErr('badargs',\n                  \"Expected up to 4 arguments [params, data, success, error], got {0} arguments\",\n                  arguments.length);\n            }\n            /* jshint +W086 */ /* (purposefully fall through case statements) */\n\n            var isInstanceCall = this instanceof Resource;\n            var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));\n            var httpConfig = {};\n            var responseInterceptor = action.interceptor && action.interceptor.response ||\n              defaultResponseInterceptor;\n            var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||\n              undefined;\n\n            forEach(action, function(value, key) {\n              if (key != 'params' && key != 'isArray' && key != 'interceptor') {\n                httpConfig[key] = copy(value);\n              }\n            });\n\n            if (hasBody) httpConfig.data = data;\n            route.setUrlParams(httpConfig,\n              extend({}, extractParams(data, action.params || {}), params),\n              action.url);\n\n            var promise = $http(httpConfig).then(function(response) {\n              var data = response.data,\n                promise = value.$promise;\n\n              if (data) {\n                // Need to convert action.isArray to boolean in case it is undefined\n                // jshint -W018\n                if (angular.isArray(data) !== (!!action.isArray)) {\n                  throw $resourceMinErr('badcfg',\n                      'Error in resource configuration for action `{0}`. Expected response to ' +\n                      'contain an {1} but got an {2}', name, action.isArray ? 'array' : 'object',\n                    angular.isArray(data) ? 'array' : 'object');\n                }\n                // jshint +W018\n                if (action.isArray) {\n                  value.length = 0;\n                  forEach(data, function(item) {\n                    if (typeof item === \"object\") {\n                      value.push(new Resource(item));\n                    } else {\n                      // Valid JSON values may be string literals, and these should not be converted\n                      // into objects. These items will not have access to the Resource prototype\n                      // methods, but unfortunately there\n                      value.push(item);\n                    }\n                  });\n                } else {\n                  shallowClearAndCopy(data, value);\n                  value.$promise = promise;\n                }\n              }\n\n              value.$resolved = true;\n\n              response.resource = value;\n\n              return response;\n            }, function(response) {\n              value.$resolved = true;\n\n              (error || noop)(response);\n\n              return $q.reject(response);\n            });\n\n            promise = promise.then(\n              function(response) {\n                var value = responseInterceptor(response);\n                (success || noop)(value, response.headers);\n                return value;\n              },\n              responseErrorInterceptor);\n\n            if (!isInstanceCall) {\n              // we are creating instance / collection\n              // - set the initial promise\n              // - return the instance / collection\n              value.$promise = promise;\n              value.$resolved = false;\n\n              return value;\n            }\n\n            // instance call\n            return promise;\n          };\n\n\n          Resource.prototype['$' + name] = function(params, success, error) {\n            if (isFunction(params)) {\n              error = success; success = params; params = {};\n            }\n            var result = Resource[name].call(this, params, this, success, error);\n            return result.$promise || result;\n          };\n        });\n\n        Resource.bind = function(additionalParamDefaults) {\n          return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);\n        };\n\n        return Resource;\n      }\n\n      return resourceFactory;\n    }];\n  });\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/angular/angular-sanitize.js",
    "content": "/**\n * @license AngularJS v1.3.13\n * (c) 2010-2014 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\nvar $sanitizeMinErr = angular.$$minErr('$sanitize');\n\n/**\n * @ngdoc module\n * @name ngSanitize\n * @description\n *\n * # ngSanitize\n *\n * The `ngSanitize` module provides functionality to sanitize HTML.\n *\n *\n * <div doc-module-components=\"ngSanitize\"></div>\n *\n * See {@link ngSanitize.$sanitize `$sanitize`} for usage.\n */\n\n/*\n * HTML Parser By Misko Hevery (misko@hevery.com)\n * based on:  HTML Parser By John Resig (ejohn.org)\n * Original code by Erik Arvidsson, Mozilla Public License\n * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js\n *\n * // Use like so:\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n */\n\n\n/**\n * @ngdoc service\n * @name $sanitize\n * @kind function\n *\n * @description\n *   The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are\n *   then serialized back to properly escaped html string. This means that no unsafe input can make\n *   it into the returned string, however, since our parser is more strict than a typical browser\n *   parser, it's possible that some obscure input, which would be recognized as valid HTML by a\n *   browser, won't make it through the sanitizer. The input may also contain SVG markup.\n *   The whitelist is configured using the functions `aHrefSanitizationWhitelist` and\n *   `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.\n *\n * @param {string} html HTML input.\n * @returns {string} Sanitized HTML.\n *\n * @example\n   <example module=\"sanitizeExample\" deps=\"angular-sanitize.js\">\n   <file name=\"index.html\">\n     <script>\n         angular.module('sanitizeExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {\n             $scope.snippet =\n               '<p style=\"color:blue\">an html\\n' +\n               '<em onmouseover=\"this.textContent=\\'PWN3D!\\'\">click here</em>\\n' +\n               'snippet</p>';\n             $scope.deliberatelyTrustDangerousSnippet = function() {\n               return $sce.trustAsHtml($scope.snippet);\n             };\n           }]);\n     </script>\n     <div ng-controller=\"ExampleController\">\n        Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Directive</td>\n           <td>How</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"bind-html-with-sanitize\">\n           <td>ng-bind-html</td>\n           <td>Automatically uses $sanitize</td>\n           <td><pre>&lt;div ng-bind-html=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind-html=\"snippet\"></div></td>\n         </tr>\n         <tr id=\"bind-html-with-trust\">\n           <td>ng-bind-html</td>\n           <td>Bypass $sanitize by explicitly trusting the dangerous value</td>\n           <td>\n           <pre>&lt;div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"&gt;\n&lt;/div&gt;</pre>\n           </td>\n           <td><div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"></div></td>\n         </tr>\n         <tr id=\"bind-default\">\n           <td>ng-bind</td>\n           <td>Automatically escapes</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n       </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should sanitize the html snippet by default', function() {\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('<p>an html\\n<em>click here</em>\\nsnippet</p>');\n     });\n\n     it('should inline raw snippet if bound to a trusted value', function() {\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).\n         toBe(\"<p style=\\\"color:blue\\\">an html\\n\" +\n              \"<em onmouseover=\\\"this.textContent='PWN3D!'\\\">click here</em>\\n\" +\n              \"snippet</p>\");\n     });\n\n     it('should escape snippet without any filter', function() {\n       expect(element(by.css('#bind-default div')).getInnerHtml()).\n         toBe(\"&lt;p style=\\\"color:blue\\\"&gt;an html\\n\" +\n              \"&lt;em onmouseover=\\\"this.textContent='PWN3D!'\\\"&gt;click here&lt;/em&gt;\\n\" +\n              \"snippet&lt;/p&gt;\");\n     });\n\n     it('should update', function() {\n       element(by.model('snippet')).clear();\n       element(by.model('snippet')).sendKeys('new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('new <b>text</b>');\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(\n         'new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(\n         \"new &lt;b onclick=\\\"alert(1)\\\"&gt;text&lt;/b&gt;\");\n     });\n   </file>\n   </example>\n */\nfunction $SanitizeProvider() {\n  this.$get = ['$$sanitizeUri', function($$sanitizeUri) {\n    return function(html) {\n      var buf = [];\n      htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {\n        return !/^unsafe/.test($$sanitizeUri(uri, isImage));\n      }));\n      return buf.join('');\n    };\n  }];\n}\n\nfunction sanitizeText(chars) {\n  var buf = [];\n  var writer = htmlSanitizeWriter(buf, angular.noop);\n  writer.chars(chars);\n  return buf.join('');\n}\n\n\n// Regular Expressions for parsing tags and attributes\nvar START_TAG_REGEXP =\n       /^<((?:[a-zA-Z])[\\w:-]*)((?:\\s+[\\w:-]+(?:\\s*=\\s*(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?)*)\\s*(\\/?)\\s*(>?)/,\n  END_TAG_REGEXP = /^<\\/\\s*([\\w:-]+)[^>]*>/,\n  ATTR_REGEXP = /([\\w:-]+)(?:\\s*=\\s*(?:(?:\"((?:[^\"])*)\")|(?:'((?:[^'])*)')|([^>\\s]+)))?/g,\n  BEGIN_TAG_REGEXP = /^</,\n  BEGING_END_TAGE_REGEXP = /^<\\//,\n  COMMENT_REGEXP = /<!--(.*?)-->/g,\n  DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,\n  CDATA_REGEXP = /<!\\[CDATA\\[(.*?)]]>/g,\n  SURROGATE_PAIR_REGEXP = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g,\n  // Match everything outside of normal chars and \" (quote character)\n  NON_ALPHANUMERIC_REGEXP = /([^\\#-~| |!])/g;\n\n\n// Good source of info about elements and attributes\n// http://dev.w3.org/html5/spec/Overview.html#semantics\n// http://simon.html5.org/html-elements\n\n// Safe Void Elements - HTML5\n// http://dev.w3.org/html5/spec/Overview.html#void-elements\nvar voidElements = makeMap(\"area,br,col,hr,img,wbr\");\n\n// Elements that you can, intentionally, leave open (and which close themselves)\n// http://dev.w3.org/html5/spec/Overview.html#optional-tags\nvar optionalEndTagBlockElements = makeMap(\"colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr\"),\n    optionalEndTagInlineElements = makeMap(\"rp,rt\"),\n    optionalEndTagElements = angular.extend({},\n                                            optionalEndTagInlineElements,\n                                            optionalEndTagBlockElements);\n\n// Safe Block Elements - HTML5\nvar blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap(\"address,article,\" +\n        \"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,\" +\n        \"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul\"));\n\n// Inline Elements - HTML5\nvar inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap(\"a,abbr,acronym,b,\" +\n        \"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,\" +\n        \"samp,small,span,strike,strong,sub,sup,time,tt,u,var\"));\n\n// SVG Elements\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements\nvar svgElements = makeMap(\"animate,animateColor,animateMotion,animateTransform,circle,defs,\" +\n        \"desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,\" +\n        \"line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set,\" +\n        \"stop,svg,switch,text,title,tspan,use\");\n\n// Special Elements (can contain anything)\nvar specialElements = makeMap(\"script,style\");\n\nvar validElements = angular.extend({},\n                                   voidElements,\n                                   blockElements,\n                                   inlineElements,\n                                   optionalEndTagElements,\n                                   svgElements);\n\n//Attributes that have href and hence need to be sanitized\nvar uriAttrs = makeMap(\"background,cite,href,longdesc,src,usemap,xlink:href\");\n\nvar htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +\n    'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +\n    'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +\n    'scope,scrolling,shape,size,span,start,summary,target,title,type,' +\n    'valign,value,vspace,width');\n\n// SVG attributes (without \"id\" and \"name\" attributes)\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes\nvar svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +\n    'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +\n    'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +\n    'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +\n    'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +\n    'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +\n    'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +\n    'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +\n    'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +\n    'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +\n    'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +\n    'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +\n    'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +\n    'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +\n    'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +\n    'zoomAndPan');\n\nvar validAttrs = angular.extend({},\n                                uriAttrs,\n                                svgAttrs,\n                                htmlAttrs);\n\nfunction makeMap(str) {\n  var obj = {}, items = str.split(','), i;\n  for (i = 0; i < items.length; i++) obj[items[i]] = true;\n  return obj;\n}\n\n\n/**\n * @example\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n * @param {string} html string\n * @param {object} handler\n */\nfunction htmlParser(html, handler) {\n  if (typeof html !== 'string') {\n    if (html === null || typeof html === 'undefined') {\n      html = '';\n    } else {\n      html = '' + html;\n    }\n  }\n  var index, chars, match, stack = [], last = html, text;\n  stack.last = function() { return stack[stack.length - 1]; };\n\n  while (html) {\n    text = '';\n    chars = true;\n\n    // Make sure we're not in a script or style element\n    if (!stack.last() || !specialElements[stack.last()]) {\n\n      // Comment\n      if (html.indexOf(\"<!--\") === 0) {\n        // comments containing -- are not allowed unless they terminate the comment\n        index = html.indexOf(\"--\", 4);\n\n        if (index >= 0 && html.lastIndexOf(\"-->\", index) === index) {\n          if (handler.comment) handler.comment(html.substring(4, index));\n          html = html.substring(index + 3);\n          chars = false;\n        }\n      // DOCTYPE\n      } else if (DOCTYPE_REGEXP.test(html)) {\n        match = html.match(DOCTYPE_REGEXP);\n\n        if (match) {\n          html = html.replace(match[0], '');\n          chars = false;\n        }\n      // end tag\n      } else if (BEGING_END_TAGE_REGEXP.test(html)) {\n        match = html.match(END_TAG_REGEXP);\n\n        if (match) {\n          html = html.substring(match[0].length);\n          match[0].replace(END_TAG_REGEXP, parseEndTag);\n          chars = false;\n        }\n\n      // start tag\n      } else if (BEGIN_TAG_REGEXP.test(html)) {\n        match = html.match(START_TAG_REGEXP);\n\n        if (match) {\n          // We only have a valid start-tag if there is a '>'.\n          if (match[4]) {\n            html = html.substring(match[0].length);\n            match[0].replace(START_TAG_REGEXP, parseStartTag);\n          }\n          chars = false;\n        } else {\n          // no ending tag found --- this piece should be encoded as an entity.\n          text += '<';\n          html = html.substring(1);\n        }\n      }\n\n      if (chars) {\n        index = html.indexOf(\"<\");\n\n        text += index < 0 ? html : html.substring(0, index);\n        html = index < 0 ? \"\" : html.substring(index);\n\n        if (handler.chars) handler.chars(decodeEntities(text));\n      }\n\n    } else {\n      // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\\W\\w].\n      html = html.replace(new RegExp(\"([\\\\W\\\\w]*)<\\\\s*\\\\/\\\\s*\" + stack.last() + \"[^>]*>\", 'i'),\n        function(all, text) {\n          text = text.replace(COMMENT_REGEXP, \"$1\").replace(CDATA_REGEXP, \"$1\");\n\n          if (handler.chars) handler.chars(decodeEntities(text));\n\n          return \"\";\n      });\n\n      parseEndTag(\"\", stack.last());\n    }\n\n    if (html == last) {\n      throw $sanitizeMinErr('badparse', \"The sanitizer was unable to parse the following block \" +\n                                        \"of html: {0}\", html);\n    }\n    last = html;\n  }\n\n  // Clean up any remaining tags\n  parseEndTag();\n\n  function parseStartTag(tag, tagName, rest, unary) {\n    tagName = angular.lowercase(tagName);\n    if (blockElements[tagName]) {\n      while (stack.last() && inlineElements[stack.last()]) {\n        parseEndTag(\"\", stack.last());\n      }\n    }\n\n    if (optionalEndTagElements[tagName] && stack.last() == tagName) {\n      parseEndTag(\"\", tagName);\n    }\n\n    unary = voidElements[tagName] || !!unary;\n\n    if (!unary)\n      stack.push(tagName);\n\n    var attrs = {};\n\n    rest.replace(ATTR_REGEXP,\n      function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {\n        var value = doubleQuotedValue\n          || singleQuotedValue\n          || unquotedValue\n          || '';\n\n        attrs[name] = decodeEntities(value);\n    });\n    if (handler.start) handler.start(tagName, attrs, unary);\n  }\n\n  function parseEndTag(tag, tagName) {\n    var pos = 0, i;\n    tagName = angular.lowercase(tagName);\n    if (tagName)\n      // Find the closest opened tag of the same type\n      for (pos = stack.length - 1; pos >= 0; pos--)\n        if (stack[pos] == tagName)\n          break;\n\n    if (pos >= 0) {\n      // Close all the open elements, up the stack\n      for (i = stack.length - 1; i >= pos; i--)\n        if (handler.end) handler.end(stack[i]);\n\n      // Remove the open elements from the stack\n      stack.length = pos;\n    }\n  }\n}\n\nvar hiddenPre=document.createElement(\"pre\");\nvar spaceRe = /^(\\s*)([\\s\\S]*?)(\\s*)$/;\n/**\n * decodes all entities into regular string\n * @param value\n * @returns {string} A string with decoded entities.\n */\nfunction decodeEntities(value) {\n  if (!value) { return ''; }\n\n  // Note: IE8 does not preserve spaces at the start/end of innerHTML\n  // so we must capture them and reattach them afterward\n  var parts = spaceRe.exec(value);\n  var spaceBefore = parts[1];\n  var spaceAfter = parts[3];\n  var content = parts[2];\n  if (content) {\n    hiddenPre.innerHTML=content.replace(/</g,\"&lt;\");\n    // innerText depends on styling as it doesn't display hidden elements.\n    // Therefore, it's better to use textContent not to cause unnecessary\n    // reflows. However, IE<9 don't support textContent so the innerText\n    // fallback is necessary.\n    content = 'textContent' in hiddenPre ?\n      hiddenPre.textContent : hiddenPre.innerText;\n  }\n  return spaceBefore + content + spaceAfter;\n}\n\n/**\n * Escapes all potentially dangerous characters, so that the\n * resulting string can be safely inserted into attribute or\n * element text.\n * @param value\n * @returns {string} escaped text\n */\nfunction encodeEntities(value) {\n  return value.\n    replace(/&/g, '&amp;').\n    replace(SURROGATE_PAIR_REGEXP, function(value) {\n      var hi = value.charCodeAt(0);\n      var low = value.charCodeAt(1);\n      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';\n    }).\n    replace(NON_ALPHANUMERIC_REGEXP, function(value) {\n      return '&#' + value.charCodeAt(0) + ';';\n    }).\n    replace(/</g, '&lt;').\n    replace(/>/g, '&gt;');\n}\n\n/**\n * create an HTML/XML writer which writes to buffer\n * @param {Array} buf use buf.jain('') to get out sanitized html string\n * @returns {object} in the form of {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * }\n */\nfunction htmlSanitizeWriter(buf, uriValidator) {\n  var ignore = false;\n  var out = angular.bind(buf, buf.push);\n  return {\n    start: function(tag, attrs, unary) {\n      tag = angular.lowercase(tag);\n      if (!ignore && specialElements[tag]) {\n        ignore = tag;\n      }\n      if (!ignore && validElements[tag] === true) {\n        out('<');\n        out(tag);\n        angular.forEach(attrs, function(value, key) {\n          var lkey=angular.lowercase(key);\n          var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');\n          if (validAttrs[lkey] === true &&\n            (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {\n            out(' ');\n            out(key);\n            out('=\"');\n            out(encodeEntities(value));\n            out('\"');\n          }\n        });\n        out(unary ? '/>' : '>');\n      }\n    },\n    end: function(tag) {\n        tag = angular.lowercase(tag);\n        if (!ignore && validElements[tag] === true) {\n          out('</');\n          out(tag);\n          out('>');\n        }\n        if (tag == ignore) {\n          ignore = false;\n        }\n      },\n    chars: function(chars) {\n        if (!ignore) {\n          out(encodeEntities(chars));\n        }\n      }\n  };\n}\n\n\n// define ngSanitize module and register $sanitize service\nangular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);\n\n/* global sanitizeText: false */\n\n/**\n * @ngdoc filter\n * @name linky\n * @kind function\n *\n * @description\n * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and\n * plain email address links.\n *\n * Requires the {@link ngSanitize `ngSanitize`} module to be installed.\n *\n * @param {string} text Input text.\n * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.\n * @returns {string} Html-linkified text.\n *\n * @usage\n   <span ng-bind-html=\"linky_expression | linky\"></span>\n *\n * @example\n   <example module=\"linkyExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('linkyExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.snippet =\n               'Pretty text with some links:\\n'+\n               'http://angularjs.org/,\\n'+\n               'mailto:us@somewhere.org,\\n'+\n               'another@somewhere.org,\\n'+\n               'and one more: ftp://127.0.0.1/.';\n             $scope.snippetWithTarget = 'http://angularjs.org/';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n       Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Filter</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"linky-filter\">\n           <td>linky filter</td>\n           <td>\n             <pre>&lt;div ng-bind-html=\"snippet | linky\"&gt;<br>&lt;/div&gt;</pre>\n           </td>\n           <td>\n             <div ng-bind-html=\"snippet | linky\"></div>\n           </td>\n         </tr>\n         <tr id=\"linky-target\">\n          <td>linky target</td>\n          <td>\n            <pre>&lt;div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"&gt;<br>&lt;/div&gt;</pre>\n          </td>\n          <td>\n            <div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"></div>\n          </td>\n         </tr>\n         <tr id=\"escaped-html\">\n           <td>no filter</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should linkify the snippet with urls', function() {\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);\n       });\n\n       it('should not linkify snippet without the linky filter', function() {\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);\n       });\n\n       it('should update', function() {\n         element(by.model('snippet')).clear();\n         element(by.model('snippet')).sendKeys('new http://link.');\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('new http://link.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())\n             .toBe('new http://link.');\n       });\n\n       it('should work with the target property', function() {\n        expect(element(by.id('linky-target')).\n            element(by.binding(\"snippetWithTarget | linky:'_blank'\")).getText()).\n            toBe('http://angularjs.org/');\n        expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');\n       });\n     </file>\n   </example>\n */\nangular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {\n  var LINKY_URL_REGEXP =\n        /((ftp|https?):\\/\\/|(www\\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\\S*[^\\s.;,(){}<>\"”’]/,\n      MAILTO_REGEXP = /^mailto:/;\n\n  return function(text, target) {\n    if (!text) return text;\n    var match;\n    var raw = text;\n    var html = [];\n    var url;\n    var i;\n    while ((match = raw.match(LINKY_URL_REGEXP))) {\n      // We can not end in these as they are sometimes found at the end of the sentence\n      url = match[0];\n      // if we did not match ftp/http/www/mailto then assume mailto\n      if (!match[2] && !match[4]) {\n        url = (match[3] ? 'http://' : 'mailto:') + url;\n      }\n      i = match.index;\n      addText(raw.substr(0, i));\n      addLink(url, match[0].replace(MAILTO_REGEXP, ''));\n      raw = raw.substring(i + match[0].length);\n    }\n    addText(raw);\n    return $sanitize(html.join(''));\n\n    function addText(text) {\n      if (!text) {\n        return;\n      }\n      html.push(sanitizeText(text));\n    }\n\n    function addLink(url, text) {\n      html.push('<a ');\n      if (angular.isDefined(target)) {\n        html.push('target=\"',\n                  target,\n                  '\" ');\n      }\n      html.push('href=\"',\n                url.replace(/\"/g, '&quot;'),\n                '\">');\n      addText(text);\n      html.push('</a>');\n    }\n  };\n}]);\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/angular/angular.js",
    "content": "/**\n * @license AngularJS v1.3.13\n * (c) 2010-2014 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, document, undefined) {'use strict';\n\n/**\n * @description\n *\n * This object provides a utility for producing rich Error messages within\n * Angular. It can be called as follows:\n *\n * var exampleMinErr = minErr('example');\n * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);\n *\n * The above creates an instance of minErr in the example namespace. The\n * resulting error will have a namespaced error code of example.one.  The\n * resulting error will replace {0} with the value of foo, and {1} with the\n * value of bar. The object is not restricted in the number of arguments it can\n * take.\n *\n * If fewer arguments are specified than necessary for interpolation, the extra\n * interpolation markers will be preserved in the final string.\n *\n * Since data will be parsed statically during a build step, some restrictions\n * are applied with respect to how minErr instances are created and called.\n * Instances should have names of the form namespaceMinErr for a minErr created\n * using minErr('namespace') . Error codes, namespaces and template strings\n * should all be static strings, not variables or general expressions.\n *\n * @param {string} module The namespace to use for the new minErr instance.\n * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning\n *   error from returned function, for cases when a particular type of error is useful.\n * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance\n */\n\nfunction minErr(module, ErrorConstructor) {\n  ErrorConstructor = ErrorConstructor || Error;\n  return function() {\n    var code = arguments[0],\n      prefix = '[' + (module ? module + ':' : '') + code + '] ',\n      template = arguments[1],\n      templateArgs = arguments,\n\n      message, i;\n\n    message = prefix + template.replace(/\\{\\d+\\}/g, function(match) {\n      var index = +match.slice(1, -1), arg;\n\n      if (index + 2 < templateArgs.length) {\n        return toDebugString(templateArgs[index + 2]);\n      }\n      return match;\n    });\n\n    message = message + '\\nhttp://errors.angularjs.org/1.3.13/' +\n      (module ? module + '/' : '') + code;\n    for (i = 2; i < arguments.length; i++) {\n      message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' +\n        encodeURIComponent(toDebugString(arguments[i]));\n    }\n    return new ErrorConstructor(message);\n  };\n}\n\n/* We need to tell jshint what variables are being exported */\n/* global angular: true,\n  msie: true,\n  jqLite: true,\n  jQuery: true,\n  slice: true,\n  splice: true,\n  push: true,\n  toString: true,\n  ngMinErr: true,\n  angularModule: true,\n  uid: true,\n  REGEX_STRING_REGEXP: true,\n  VALIDITY_STATE_PROPERTY: true,\n\n  lowercase: true,\n  uppercase: true,\n  manualLowercase: true,\n  manualUppercase: true,\n  nodeName_: true,\n  isArrayLike: true,\n  forEach: true,\n  sortedKeys: true,\n  forEachSorted: true,\n  reverseParams: true,\n  nextUid: true,\n  setHashKey: true,\n  extend: true,\n  int: true,\n  inherit: true,\n  noop: true,\n  identity: true,\n  valueFn: true,\n  isUndefined: true,\n  isDefined: true,\n  isObject: true,\n  isString: true,\n  isNumber: true,\n  isDate: true,\n  isArray: true,\n  isFunction: true,\n  isRegExp: true,\n  isWindow: true,\n  isScope: true,\n  isFile: true,\n  isFormData: true,\n  isBlob: true,\n  isBoolean: true,\n  isPromiseLike: true,\n  trim: true,\n  escapeForRegexp: true,\n  isElement: true,\n  makeMap: true,\n  includes: true,\n  arrayRemove: true,\n  copy: true,\n  shallowCopy: true,\n  equals: true,\n  csp: true,\n  concat: true,\n  sliceArgs: true,\n  bind: true,\n  toJsonReplacer: true,\n  toJson: true,\n  fromJson: true,\n  startingTag: true,\n  tryDecodeURIComponent: true,\n  parseKeyValue: true,\n  toKeyValue: true,\n  encodeUriSegment: true,\n  encodeUriQuery: true,\n  angularInit: true,\n  bootstrap: true,\n  getTestability: true,\n  snake_case: true,\n  bindJQuery: true,\n  assertArg: true,\n  assertArgFn: true,\n  assertNotHasOwnProperty: true,\n  getter: true,\n  getBlockNodes: true,\n  hasOwnProperty: true,\n  createMap: true,\n\n  NODE_TYPE_ELEMENT: true,\n  NODE_TYPE_TEXT: true,\n  NODE_TYPE_COMMENT: true,\n  NODE_TYPE_DOCUMENT: true,\n  NODE_TYPE_DOCUMENT_FRAGMENT: true,\n*/\n\n////////////////////////////////////\n\n/**\n * @ngdoc module\n * @name ng\n * @module ng\n * @description\n *\n * # ng (core module)\n * The ng module is loaded by default when an AngularJS application is started. The module itself\n * contains the essential components for an AngularJS application to function. The table below\n * lists a high level breakdown of each of the services/factories, filters, directives and testing\n * components available within this core module.\n *\n * <div doc-module-components=\"ng\"></div>\n */\n\nvar REGEX_STRING_REGEXP = /^\\/(.+)\\/([a-z]*)$/;\n\n// The name of a form control's ValidityState property.\n// This is used so that it's possible for internal tests to create mock ValidityStates.\nvar VALIDITY_STATE_PROPERTY = 'validity';\n\n/**\n * @ngdoc function\n * @name angular.lowercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to lowercase.\n * @param {string} string String to be converted to lowercase.\n * @returns {string} Lowercased string.\n */\nvar lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * @ngdoc function\n * @name angular.uppercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to uppercase.\n * @param {string} string String to be converted to uppercase.\n * @returns {string} Uppercased string.\n */\nvar uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};\n\n\nvar manualLowercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})\n      : s;\n};\nvar manualUppercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})\n      : s;\n};\n\n\n// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish\n// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods\n// with correct but slower alternatives.\nif ('i' !== 'I'.toLowerCase()) {\n  lowercase = manualLowercase;\n  uppercase = manualUppercase;\n}\n\n\nvar\n    msie,             // holds major version number for IE, or NaN if UA is not IE.\n    jqLite,           // delay binding since jQuery could be loaded after us.\n    jQuery,           // delay binding\n    slice             = [].slice,\n    splice            = [].splice,\n    push              = [].push,\n    toString          = Object.prototype.toString,\n    ngMinErr          = minErr('ng'),\n\n    /** @name angular */\n    angular           = window.angular || (window.angular = {}),\n    angularModule,\n    uid               = 0;\n\n/**\n * documentMode is an IE-only property\n * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx\n */\nmsie = document.documentMode;\n\n\n/**\n * @private\n * @param {*} obj\n * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,\n *                   String ...)\n */\nfunction isArrayLike(obj) {\n  if (obj == null || isWindow(obj)) {\n    return false;\n  }\n\n  var length = obj.length;\n\n  if (obj.nodeType === NODE_TYPE_ELEMENT && length) {\n    return true;\n  }\n\n  return isString(obj) || isArray(obj) || length === 0 ||\n         typeof length === 'number' && length > 0 && (length - 1) in obj;\n}\n\n/**\n * @ngdoc function\n * @name angular.forEach\n * @module ng\n * @kind function\n *\n * @description\n * Invokes the `iterator` function once for each item in `obj` collection, which can be either an\n * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`\n * is the value of an object property or an array element, `key` is the object property key or\n * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.\n *\n * It is worth noting that `.forEach` does not iterate over inherited properties because it filters\n * using the `hasOwnProperty` method.\n *\n * Unlike ES262's\n * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),\n * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just\n * return the value provided.\n *\n   ```js\n     var values = {name: 'misko', gender: 'male'};\n     var log = [];\n     angular.forEach(values, function(value, key) {\n       this.push(key + ': ' + value);\n     }, log);\n     expect(log).toEqual(['name: misko', 'gender: male']);\n   ```\n *\n * @param {Object|Array} obj Object to iterate over.\n * @param {Function} iterator Iterator function.\n * @param {Object=} context Object to become context (`this`) for the iterator function.\n * @returns {Object|Array} Reference to `obj`.\n */\n\nfunction forEach(obj, iterator, context) {\n  var key, length;\n  if (obj) {\n    if (isFunction(obj)) {\n      for (key in obj) {\n        // Need to check if hasOwnProperty exists,\n        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function\n        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (isArray(obj) || isArrayLike(obj)) {\n      var isPrimitive = typeof obj !== 'object';\n      for (key = 0, length = obj.length; key < length; key++) {\n        if (isPrimitive || key in obj) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (obj.forEach && obj.forEach !== forEach) {\n        obj.forEach(iterator, context, obj);\n    } else {\n      for (key in obj) {\n        if (obj.hasOwnProperty(key)) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nfunction sortedKeys(obj) {\n  return Object.keys(obj).sort();\n}\n\nfunction forEachSorted(obj, iterator, context) {\n  var keys = sortedKeys(obj);\n  for (var i = 0; i < keys.length; i++) {\n    iterator.call(context, obj[keys[i]], keys[i]);\n  }\n  return keys;\n}\n\n\n/**\n * when using forEach the params are value, key, but it is often useful to have key, value.\n * @param {function(string, *)} iteratorFn\n * @returns {function(*, string)}\n */\nfunction reverseParams(iteratorFn) {\n  return function(value, key) { iteratorFn(key, value); };\n}\n\n/**\n * A consistent way of creating unique IDs in angular.\n *\n * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before\n * we hit number precision issues in JavaScript.\n *\n * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M\n *\n * @returns {number} an unique alpha-numeric string\n */\nfunction nextUid() {\n  return ++uid;\n}\n\n\n/**\n * Set or clear the hashkey for an object.\n * @param obj object\n * @param h the hashkey (!truthy to delete the hashkey)\n */\nfunction setHashKey(obj, h) {\n  if (h) {\n    obj.$$hashKey = h;\n  } else {\n    delete obj.$$hashKey;\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.extend\n * @module ng\n * @kind function\n *\n * @description\n * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.\n * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).\n *\n * @param {Object} dst Destination object.\n * @param {...Object} src Source object(s).\n * @returns {Object} Reference to `dst`.\n */\nfunction extend(dst) {\n  var h = dst.$$hashKey;\n\n  for (var i = 1, ii = arguments.length; i < ii; i++) {\n    var obj = arguments[i];\n    if (obj) {\n      var keys = Object.keys(obj);\n      for (var j = 0, jj = keys.length; j < jj; j++) {\n        var key = keys[j];\n        dst[key] = obj[key];\n      }\n    }\n  }\n\n  setHashKey(dst, h);\n  return dst;\n}\n\nfunction int(str) {\n  return parseInt(str, 10);\n}\n\n\nfunction inherit(parent, extra) {\n  return extend(Object.create(parent), extra);\n}\n\n/**\n * @ngdoc function\n * @name angular.noop\n * @module ng\n * @kind function\n *\n * @description\n * A function that performs no operations. This function can be useful when writing code in the\n * functional style.\n   ```js\n     function foo(callback) {\n       var result = calculateResult();\n       (callback || angular.noop)(result);\n     }\n   ```\n */\nfunction noop() {}\nnoop.$inject = [];\n\n\n/**\n * @ngdoc function\n * @name angular.identity\n * @module ng\n * @kind function\n *\n * @description\n * A function that returns its first argument. This function is useful when writing code in the\n * functional style.\n *\n   ```js\n     function transformer(transformationFn, value) {\n       return (transformationFn || angular.identity)(value);\n     };\n   ```\n  * @param {*} value to be returned.\n  * @returns {*} the value passed in.\n */\nfunction identity($) {return $;}\nidentity.$inject = [];\n\n\nfunction valueFn(value) {return function() {return value;};}\n\n/**\n * @ngdoc function\n * @name angular.isUndefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is undefined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is undefined.\n */\nfunction isUndefined(value) {return typeof value === 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is defined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is defined.\n */\nfunction isDefined(value) {return typeof value !== 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isObject\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not\n * considered to be objects. Note that JavaScript arrays are objects.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Object` but not `null`.\n */\nfunction isObject(value) {\n  // http://jsperf.com/isobject4\n  return value !== null && typeof value === 'object';\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isString\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `String`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `String`.\n */\nfunction isString(value) {return typeof value === 'string';}\n\n\n/**\n * @ngdoc function\n * @name angular.isNumber\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Number`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Number`.\n */\nfunction isNumber(value) {return typeof value === 'number';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDate\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a value is a date.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Date`.\n */\nfunction isDate(value) {\n  return toString.call(value) === '[object Date]';\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isArray\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Array`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Array`.\n */\nvar isArray = Array.isArray;\n\n/**\n * @ngdoc function\n * @name angular.isFunction\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Function`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Function`.\n */\nfunction isFunction(value) {return typeof value === 'function';}\n\n\n/**\n * Determines if a value is a regular expression object.\n *\n * @private\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `RegExp`.\n */\nfunction isRegExp(value) {\n  return toString.call(value) === '[object RegExp]';\n}\n\n\n/**\n * Checks if `obj` is a window object.\n *\n * @private\n * @param {*} obj Object to check\n * @returns {boolean} True if `obj` is a window obj.\n */\nfunction isWindow(obj) {\n  return obj && obj.window === obj;\n}\n\n\nfunction isScope(obj) {\n  return obj && obj.$evalAsync && obj.$watch;\n}\n\n\nfunction isFile(obj) {\n  return toString.call(obj) === '[object File]';\n}\n\n\nfunction isFormData(obj) {\n  return toString.call(obj) === '[object FormData]';\n}\n\n\nfunction isBlob(obj) {\n  return toString.call(obj) === '[object Blob]';\n}\n\n\nfunction isBoolean(value) {\n  return typeof value === 'boolean';\n}\n\n\nfunction isPromiseLike(obj) {\n  return obj && isFunction(obj.then);\n}\n\n\nvar trim = function(value) {\n  return isString(value) ? value.trim() : value;\n};\n\n// Copied from:\n// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021\n// Prereq: s is a string.\nvar escapeForRegexp = function(s) {\n  return s.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1').\n           replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * @ngdoc function\n * @name angular.isElement\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a DOM element (or wrapped jQuery element).\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).\n */\nfunction isElement(node) {\n  return !!(node &&\n    (node.nodeName  // we are a direct element\n    || (node.prop && node.attr && node.find)));  // we have an on and find method part of jQuery API\n}\n\n/**\n * @param str 'key1,key2,...'\n * @returns {object} in the form of {key1:true, key2:true, ...}\n */\nfunction makeMap(str) {\n  var obj = {}, items = str.split(\",\"), i;\n  for (i = 0; i < items.length; i++)\n    obj[items[i]] = true;\n  return obj;\n}\n\n\nfunction nodeName_(element) {\n  return lowercase(element.nodeName || (element[0] && element[0].nodeName));\n}\n\nfunction includes(array, obj) {\n  return Array.prototype.indexOf.call(array, obj) != -1;\n}\n\nfunction arrayRemove(array, value) {\n  var index = array.indexOf(value);\n  if (index >= 0)\n    array.splice(index, 1);\n  return value;\n}\n\n/**\n * @ngdoc function\n * @name angular.copy\n * @module ng\n * @kind function\n *\n * @description\n * Creates a deep copy of `source`, which should be an object or an array.\n *\n * * If no destination is supplied, a copy of the object or array is created.\n * * If a destination is provided, all of its elements (for arrays) or properties (for objects)\n *   are deleted and then all elements/properties from the source are copied to it.\n * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.\n * * If `source` is identical to 'destination' an exception will be thrown.\n *\n * @param {*} source The source that will be used to make a copy.\n *                   Can be any type, including primitives, `null`, and `undefined`.\n * @param {(Object|Array)=} destination Destination into which the source is copied. If\n *     provided, must be of the same type as `source`.\n * @returns {*} The copy or updated `destination`, if `destination` was specified.\n *\n * @example\n <example module=\"copyExample\">\n <file name=\"index.html\">\n <div ng-controller=\"ExampleController\">\n <form novalidate class=\"simple-form\">\n Name: <input type=\"text\" ng-model=\"user.name\" /><br />\n E-mail: <input type=\"email\" ng-model=\"user.email\" /><br />\n Gender: <input type=\"radio\" ng-model=\"user.gender\" value=\"male\" />male\n <input type=\"radio\" ng-model=\"user.gender\" value=\"female\" />female<br />\n <button ng-click=\"reset()\">RESET</button>\n <button ng-click=\"update(user)\">SAVE</button>\n </form>\n <pre>form = {{user | json}}</pre>\n <pre>master = {{master | json}}</pre>\n </div>\n\n <script>\n  angular.module('copyExample', [])\n    .controller('ExampleController', ['$scope', function($scope) {\n      $scope.master= {};\n\n      $scope.update = function(user) {\n        // Example with 1 argument\n        $scope.master= angular.copy(user);\n      };\n\n      $scope.reset = function() {\n        // Example with 2 arguments\n        angular.copy($scope.master, $scope.user);\n      };\n\n      $scope.reset();\n    }]);\n </script>\n </file>\n </example>\n */\nfunction copy(source, destination, stackSource, stackDest) {\n  if (isWindow(source) || isScope(source)) {\n    throw ngMinErr('cpws',\n      \"Can't copy! Making copies of Window or Scope instances is not supported.\");\n  }\n\n  if (!destination) {\n    destination = source;\n    if (source) {\n      if (isArray(source)) {\n        destination = copy(source, [], stackSource, stackDest);\n      } else if (isDate(source)) {\n        destination = new Date(source.getTime());\n      } else if (isRegExp(source)) {\n        destination = new RegExp(source.source, source.toString().match(/[^\\/]*$/)[0]);\n        destination.lastIndex = source.lastIndex;\n      } else if (isObject(source)) {\n        var emptyObject = Object.create(Object.getPrototypeOf(source));\n        destination = copy(source, emptyObject, stackSource, stackDest);\n      }\n    }\n  } else {\n    if (source === destination) throw ngMinErr('cpi',\n      \"Can't copy! Source and destination are identical.\");\n\n    stackSource = stackSource || [];\n    stackDest = stackDest || [];\n\n    if (isObject(source)) {\n      var index = stackSource.indexOf(source);\n      if (index !== -1) return stackDest[index];\n\n      stackSource.push(source);\n      stackDest.push(destination);\n    }\n\n    var result;\n    if (isArray(source)) {\n      destination.length = 0;\n      for (var i = 0; i < source.length; i++) {\n        result = copy(source[i], null, stackSource, stackDest);\n        if (isObject(source[i])) {\n          stackSource.push(source[i]);\n          stackDest.push(result);\n        }\n        destination.push(result);\n      }\n    } else {\n      var h = destination.$$hashKey;\n      if (isArray(destination)) {\n        destination.length = 0;\n      } else {\n        forEach(destination, function(value, key) {\n          delete destination[key];\n        });\n      }\n      for (var key in source) {\n        if (source.hasOwnProperty(key)) {\n          result = copy(source[key], null, stackSource, stackDest);\n          if (isObject(source[key])) {\n            stackSource.push(source[key]);\n            stackDest.push(result);\n          }\n          destination[key] = result;\n        }\n      }\n      setHashKey(destination,h);\n    }\n\n  }\n  return destination;\n}\n\n/**\n * Creates a shallow copy of an object, an array or a primitive.\n *\n * Assumes that there are no proto properties for objects.\n */\nfunction shallowCopy(src, dst) {\n  if (isArray(src)) {\n    dst = dst || [];\n\n    for (var i = 0, ii = src.length; i < ii; i++) {\n      dst[i] = src[i];\n    }\n  } else if (isObject(src)) {\n    dst = dst || {};\n\n    for (var key in src) {\n      if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n        dst[key] = src[key];\n      }\n    }\n  }\n\n  return dst || src;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.equals\n * @module ng\n * @kind function\n *\n * @description\n * Determines if two objects or two values are equivalent. Supports value types, regular\n * expressions, arrays and objects.\n *\n * Two objects or values are considered equivalent if at least one of the following is true:\n *\n * * Both objects or values pass `===` comparison.\n * * Both objects or values are of the same type and all of their properties are equal by\n *   comparing them with `angular.equals`.\n * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)\n * * Both values represent the same regular expression (In JavaScript,\n *   /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual\n *   representation matches).\n *\n * During a property comparison, properties of `function` type and properties with names\n * that begin with `$` are ignored.\n *\n * Scope and DOMWindow objects are being compared only by identify (`===`).\n *\n * @param {*} o1 Object or value to compare.\n * @param {*} o2 Object or value to compare.\n * @returns {boolean} True if arguments are equal.\n */\nfunction equals(o1, o2) {\n  if (o1 === o2) return true;\n  if (o1 === null || o2 === null) return false;\n  if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n  var t1 = typeof o1, t2 = typeof o2, length, key, keySet;\n  if (t1 == t2) {\n    if (t1 == 'object') {\n      if (isArray(o1)) {\n        if (!isArray(o2)) return false;\n        if ((length = o1.length) == o2.length) {\n          for (key = 0; key < length; key++) {\n            if (!equals(o1[key], o2[key])) return false;\n          }\n          return true;\n        }\n      } else if (isDate(o1)) {\n        if (!isDate(o2)) return false;\n        return equals(o1.getTime(), o2.getTime());\n      } else if (isRegExp(o1) && isRegExp(o2)) {\n        return o1.toString() == o2.toString();\n      } else {\n        if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;\n        keySet = {};\n        for (key in o1) {\n          if (key.charAt(0) === '$' || isFunction(o1[key])) continue;\n          if (!equals(o1[key], o2[key])) return false;\n          keySet[key] = true;\n        }\n        for (key in o2) {\n          if (!keySet.hasOwnProperty(key) &&\n              key.charAt(0) !== '$' &&\n              o2[key] !== undefined &&\n              !isFunction(o2[key])) return false;\n        }\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nvar csp = function() {\n  if (isDefined(csp.isActive_)) return csp.isActive_;\n\n  var active = !!(document.querySelector('[ng-csp]') ||\n                  document.querySelector('[data-ng-csp]'));\n\n  if (!active) {\n    try {\n      /* jshint -W031, -W054 */\n      new Function('');\n      /* jshint +W031, +W054 */\n    } catch (e) {\n      active = true;\n    }\n  }\n\n  return (csp.isActive_ = active);\n};\n\n\n\nfunction concat(array1, array2, index) {\n  return array1.concat(slice.call(array2, index));\n}\n\nfunction sliceArgs(args, startIndex) {\n  return slice.call(args, startIndex || 0);\n}\n\n\n/* jshint -W101 */\n/**\n * @ngdoc function\n * @name angular.bind\n * @module ng\n * @kind function\n *\n * @description\n * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for\n * `fn`). You can supply optional `args` that are prebound to the function. This feature is also\n * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as\n * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).\n *\n * @param {Object} self Context which `fn` should be evaluated in.\n * @param {function()} fn Function to be bound.\n * @param {...*} args Optional arguments to be prebound to the `fn` function call.\n * @returns {function()} Function that wraps the `fn` with all the specified bindings.\n */\n/* jshint +W101 */\nfunction bind(self, fn) {\n  var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\n  if (isFunction(fn) && !(fn instanceof RegExp)) {\n    return curryArgs.length\n      ? function() {\n          return arguments.length\n            ? fn.apply(self, concat(curryArgs, arguments, 0))\n            : fn.apply(self, curryArgs);\n        }\n      : function() {\n          return arguments.length\n            ? fn.apply(self, arguments)\n            : fn.call(self);\n        };\n  } else {\n    // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)\n    return fn;\n  }\n}\n\n\nfunction toJsonReplacer(key, value) {\n  var val = value;\n\n  if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {\n    val = undefined;\n  } else if (isWindow(value)) {\n    val = '$WINDOW';\n  } else if (value &&  document === value) {\n    val = '$DOCUMENT';\n  } else if (isScope(value)) {\n    val = '$SCOPE';\n  }\n\n  return val;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.toJson\n * @module ng\n * @kind function\n *\n * @description\n * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be\n * stripped since angular uses this notation internally.\n *\n * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.\n * @param {boolean|number=} pretty If set to true, the JSON output will contain newlines and whitespace.\n *    If set to an integer, the JSON output will contain that many spaces per indentation (the default is 2).\n * @returns {string|undefined} JSON-ified string representing `obj`.\n */\nfunction toJson(obj, pretty) {\n  if (typeof obj === 'undefined') return undefined;\n  if (!isNumber(pretty)) {\n    pretty = pretty ? 2 : null;\n  }\n  return JSON.stringify(obj, toJsonReplacer, pretty);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.fromJson\n * @module ng\n * @kind function\n *\n * @description\n * Deserializes a JSON string.\n *\n * @param {string} json JSON string to deserialize.\n * @returns {Object|Array|string|number} Deserialized JSON string.\n */\nfunction fromJson(json) {\n  return isString(json)\n      ? JSON.parse(json)\n      : json;\n}\n\n\n/**\n * @returns {string} Returns the string representation of the element.\n */\nfunction startingTag(element) {\n  element = jqLite(element).clone();\n  try {\n    // turns out IE does not let you set .html() on elements which\n    // are not allowed to have children. So we just ignore it.\n    element.empty();\n  } catch (e) {}\n  var elemHtml = jqLite('<div>').append(element).html();\n  try {\n    return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :\n        elemHtml.\n          match(/^(<[^>]+>)/)[1].\n          replace(/^<([\\w\\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });\n  } catch (e) {\n    return lowercase(elemHtml);\n  }\n\n}\n\n\n/////////////////////////////////////////////////\n\n/**\n * Tries to decode the URI component without throwing an exception.\n *\n * @private\n * @param str value potential URI component to check.\n * @returns {boolean} True if `value` can be decoded\n * with the decodeURIComponent function.\n */\nfunction tryDecodeURIComponent(value) {\n  try {\n    return decodeURIComponent(value);\n  } catch (e) {\n    // Ignore any invalid uri component\n  }\n}\n\n\n/**\n * Parses an escaped url query string into key-value pairs.\n * @returns {Object.<string,boolean|Array>}\n */\nfunction parseKeyValue(/**string*/keyValue) {\n  var obj = {}, key_value, key;\n  forEach((keyValue || \"\").split('&'), function(keyValue) {\n    if (keyValue) {\n      key_value = keyValue.replace(/\\+/g,'%20').split('=');\n      key = tryDecodeURIComponent(key_value[0]);\n      if (isDefined(key)) {\n        var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;\n        if (!hasOwnProperty.call(obj, key)) {\n          obj[key] = val;\n        } else if (isArray(obj[key])) {\n          obj[key].push(val);\n        } else {\n          obj[key] = [obj[key],val];\n        }\n      }\n    }\n  });\n  return obj;\n}\n\nfunction toKeyValue(obj) {\n  var parts = [];\n  forEach(obj, function(value, key) {\n    if (isArray(value)) {\n      forEach(value, function(arrayValue) {\n        parts.push(encodeUriQuery(key, true) +\n                   (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));\n      });\n    } else {\n    parts.push(encodeUriQuery(key, true) +\n               (value === true ? '' : '=' + encodeUriQuery(value, true)));\n    }\n  });\n  return parts.length ? parts.join('&') : '';\n}\n\n\n/**\n * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path\n * segments:\n *    segment       = *pchar\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriSegment(val) {\n  return encodeUriQuery(val, true).\n             replace(/%26/gi, '&').\n             replace(/%3D/gi, '=').\n             replace(/%2B/gi, '+');\n}\n\n\n/**\n * This method is intended for encoding *key* or *value* parts of query component. We need a custom\n * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be\n * encoded per http://tools.ietf.org/html/rfc3986:\n *    query       = *( pchar / \"/\" / \"?\" )\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriQuery(val, pctEncodeSpaces) {\n  return encodeURIComponent(val).\n             replace(/%40/gi, '@').\n             replace(/%3A/gi, ':').\n             replace(/%24/g, '$').\n             replace(/%2C/gi, ',').\n             replace(/%3B/gi, ';').\n             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n}\n\nvar ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];\n\nfunction getNgAttribute(element, ngAttr) {\n  var attr, i, ii = ngAttrPrefixes.length;\n  element = jqLite(element);\n  for (i = 0; i < ii; ++i) {\n    attr = ngAttrPrefixes[i] + ngAttr;\n    if (isString(attr = element.attr(attr))) {\n      return attr;\n    }\n  }\n  return null;\n}\n\n/**\n * @ngdoc directive\n * @name ngApp\n * @module ng\n *\n * @element ANY\n * @param {angular.Module} ngApp an optional application\n *   {@link angular.module module} name to load.\n * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be\n *   created in \"strict-di\" mode. This means that the application will fail to invoke functions which\n *   do not use explicit function annotation (and are thus unsuitable for minification), as described\n *   in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in\n *   tracking down the root of these bugs.\n *\n * @description\n *\n * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive\n * designates the **root element** of the application and is typically placed near the root element\n * of the page - e.g. on the `<body>` or `<html>` tags.\n *\n * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`\n * found in the document will be used to define the root element to auto-bootstrap as an\n * application. To run multiple applications in an HTML document you must manually bootstrap them using\n * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.\n *\n * You can specify an **AngularJS module** to be used as the root module for the application.  This\n * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It\n * should contain the application code needed or have dependencies on other modules that will\n * contain the code. See {@link angular.module} for more information.\n *\n * In the example below if the `ngApp` directive were not placed on the `html` element then the\n * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`\n * would not be resolved to `3`.\n *\n * `ngApp` is the easiest, and most common way to bootstrap an application.\n *\n <example module=\"ngAppDemo\">\n   <file name=\"index.html\">\n   <div ng-controller=\"ngAppDemoController\">\n     I can add: {{a}} + {{b}} =  {{ a+b }}\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {\n     $scope.a = 1;\n     $scope.b = 2;\n   });\n   </file>\n </example>\n *\n * Using `ngStrictDi`, you would see something like this:\n *\n <example ng-app-included=\"true\">\n   <file name=\"index.html\">\n   <div ng-app=\"ngAppStrictDemo\" ng-strict-di>\n       <div ng-controller=\"GoodController1\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style (see\n              script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"GoodController2\">\n           Name: <input ng-model=\"name\"><br />\n           Hello, {{name}}!\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style\n              (see script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"BadController\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>The controller could not be instantiated, due to relying\n              on automatic function annotations (which are disabled in\n              strict mode). As such, the content of this section is not\n              interpolated, and there should be an error in your web console.\n           </p>\n       </div>\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppStrictDemo', [])\n     // BadController will fail to instantiate, due to relying on automatic function annotation,\n     // rather than an explicit annotation\n     .controller('BadController', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     })\n     // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,\n     // due to using explicit annotations using the array style and $inject property, respectively.\n     .controller('GoodController1', ['$scope', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     }])\n     .controller('GoodController2', GoodController2);\n     function GoodController2($scope) {\n       $scope.name = \"World\";\n     }\n     GoodController2.$inject = ['$scope'];\n   </file>\n   <file name=\"style.css\">\n   div[ng-controller] {\n       margin-bottom: 1em;\n       -webkit-border-radius: 4px;\n       border-radius: 4px;\n       border: 1px solid;\n       padding: .5em;\n   }\n   div[ng-controller^=Good] {\n       border-color: #d6e9c6;\n       background-color: #dff0d8;\n       color: #3c763d;\n   }\n   div[ng-controller^=Bad] {\n       border-color: #ebccd1;\n       background-color: #f2dede;\n       color: #a94442;\n       margin-bottom: 0;\n   }\n   </file>\n </example>\n */\nfunction angularInit(element, bootstrap) {\n  var appElement,\n      module,\n      config = {};\n\n  // The element `element` has priority over any other element\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n\n    if (!appElement && element.hasAttribute && element.hasAttribute(name)) {\n      appElement = element;\n      module = element.getAttribute(name);\n    }\n  });\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n    var candidate;\n\n    if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\\\:') + ']'))) {\n      appElement = candidate;\n      module = candidate.getAttribute(name);\n    }\n  });\n  if (appElement) {\n    config.strictDi = getNgAttribute(appElement, \"strict-di\") !== null;\n    bootstrap(appElement, module ? [module] : [], config);\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.bootstrap\n * @module ng\n * @description\n * Use this function to manually start up angular application.\n *\n * See: {@link guide/bootstrap Bootstrap}\n *\n * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.\n * They must use {@link ng.directive:ngApp ngApp}.\n *\n * Angular will detect if it has been loaded into the browser more than once and only allow the\n * first loaded script to be bootstrapped and will report a warning to the browser console for\n * each of the subsequent scripts. This prevents strange results in applications, where otherwise\n * multiple instances of Angular try to work on the DOM.\n *\n * ```html\n * <!doctype html>\n * <html>\n * <body>\n * <div ng-controller=\"WelcomeController\">\n *   {{greeting}}\n * </div>\n *\n * <script src=\"angular.js\"></script>\n * <script>\n *   var app = angular.module('demo', [])\n *   .controller('WelcomeController', function($scope) {\n *       $scope.greeting = 'Welcome!';\n *   });\n *   angular.bootstrap(document, ['demo']);\n * </script>\n * </body>\n * </html>\n * ```\n *\n * @param {DOMElement} element DOM element which is the root of angular application.\n * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.\n *     Each item in the array should be the name of a predefined module or a (DI annotated)\n *     function that will be invoked by the injector as a `config` block.\n *     See: {@link angular.module modules}\n * @param {Object=} config an object for defining configuration options for the application. The\n *     following keys are supported:\n *\n * * `strictDi` - disable automatic function annotation for the application. This is meant to\n *   assist in finding bugs which break minified code. Defaults to `false`.\n *\n * @returns {auto.$injector} Returns the newly created injector for this app.\n */\nfunction bootstrap(element, modules, config) {\n  if (!isObject(config)) config = {};\n  var defaultConfig = {\n    strictDi: false\n  };\n  config = extend(defaultConfig, config);\n  var doBootstrap = function() {\n    element = jqLite(element);\n\n    if (element.injector()) {\n      var tag = (element[0] === document) ? 'document' : startingTag(element);\n      //Encode angle brackets to prevent input from being sanitized to empty string #8683\n      throw ngMinErr(\n          'btstrpd',\n          \"App Already Bootstrapped with this Element '{0}'\",\n          tag.replace(/</,'&lt;').replace(/>/,'&gt;'));\n    }\n\n    modules = modules || [];\n    modules.unshift(['$provide', function($provide) {\n      $provide.value('$rootElement', element);\n    }]);\n\n    if (config.debugInfoEnabled) {\n      // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.\n      modules.push(['$compileProvider', function($compileProvider) {\n        $compileProvider.debugInfoEnabled(true);\n      }]);\n    }\n\n    modules.unshift('ng');\n    var injector = createInjector(modules, config.strictDi);\n    injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',\n       function bootstrapApply(scope, element, compile, injector) {\n        scope.$apply(function() {\n          element.data('$injector', injector);\n          compile(element)(scope);\n        });\n      }]\n    );\n    return injector;\n  };\n\n  var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;\n  var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;\n\n  if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {\n    config.debugInfoEnabled = true;\n    window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');\n  }\n\n  if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {\n    return doBootstrap();\n  }\n\n  window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');\n  angular.resumeBootstrap = function(extraModules) {\n    forEach(extraModules, function(module) {\n      modules.push(module);\n    });\n    return doBootstrap();\n  };\n\n  if (isFunction(angular.resumeDeferredBootstrap)) {\n    angular.resumeDeferredBootstrap();\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.reloadWithDebugInfo\n * @module ng\n * @description\n * Use this function to reload the current application with debug information turned on.\n * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.\n *\n * See {@link ng.$compileProvider#debugInfoEnabled} for more.\n */\nfunction reloadWithDebugInfo() {\n  window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\n  window.location.reload();\n}\n\n/**\n * @name angular.getTestability\n * @module ng\n * @description\n * Get the testability service for the instance of Angular on the given\n * element.\n * @param {DOMElement} element DOM element which is the root of angular application.\n */\nfunction getTestability(rootElement) {\n  var injector = angular.element(rootElement).injector();\n  if (!injector) {\n    throw ngMinErr('test',\n      'no injector found for element argument to getTestability');\n  }\n  return injector.get('$$testability');\n}\n\nvar SNAKE_CASE_REGEXP = /[A-Z]/g;\nfunction snake_case(name, separator) {\n  separator = separator || '_';\n  return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n    return (pos ? separator : '') + letter.toLowerCase();\n  });\n}\n\nvar bindJQueryFired = false;\nvar skipDestroyOnNextJQueryCleanData;\nfunction bindJQuery() {\n  var originalCleanData;\n\n  if (bindJQueryFired) {\n    return;\n  }\n\n  // bind to jQuery if present;\n  jQuery = window.jQuery;\n  // Use jQuery if it exists with proper functionality, otherwise default to us.\n  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.\n  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older\n  // versions. It will not work for sure with jQuery <1.7, though.\n  if (jQuery && jQuery.fn.on) {\n    jqLite = jQuery;\n    extend(jQuery.fn, {\n      scope: JQLitePrototype.scope,\n      isolateScope: JQLitePrototype.isolateScope,\n      controller: JQLitePrototype.controller,\n      injector: JQLitePrototype.injector,\n      inheritedData: JQLitePrototype.inheritedData\n    });\n\n    // All nodes removed from the DOM via various jQuery APIs like .remove()\n    // are passed through jQuery.cleanData. Monkey-patch this method to fire\n    // the $destroy event on all removed nodes.\n    originalCleanData = jQuery.cleanData;\n    jQuery.cleanData = function(elems) {\n      var events;\n      if (!skipDestroyOnNextJQueryCleanData) {\n        for (var i = 0, elem; (elem = elems[i]) != null; i++) {\n          events = jQuery._data(elem, \"events\");\n          if (events && events.$destroy) {\n            jQuery(elem).triggerHandler('$destroy');\n          }\n        }\n      } else {\n        skipDestroyOnNextJQueryCleanData = false;\n      }\n      originalCleanData(elems);\n    };\n  } else {\n    jqLite = JQLite;\n  }\n\n  angular.element = jqLite;\n\n  // Prevent double-proxying.\n  bindJQueryFired = true;\n}\n\n/**\n * throw error if the argument is falsy.\n */\nfunction assertArg(arg, name, reason) {\n  if (!arg) {\n    throw ngMinErr('areq', \"Argument '{0}' is {1}\", (name || '?'), (reason || \"required\"));\n  }\n  return arg;\n}\n\nfunction assertArgFn(arg, name, acceptArrayAnnotation) {\n  if (acceptArrayAnnotation && isArray(arg)) {\n      arg = arg[arg.length - 1];\n  }\n\n  assertArg(isFunction(arg), name, 'not a function, got ' +\n      (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));\n  return arg;\n}\n\n/**\n * throw error if the name given is hasOwnProperty\n * @param  {String} name    the name to test\n * @param  {String} context the context in which the name is used, such as module or directive\n */\nfunction assertNotHasOwnProperty(name, context) {\n  if (name === 'hasOwnProperty') {\n    throw ngMinErr('badname', \"hasOwnProperty is not a valid {0} name\", context);\n  }\n}\n\n/**\n * Return the value accessible from the object by path. Any undefined traversals are ignored\n * @param {Object} obj starting object\n * @param {String} path path to traverse\n * @param {boolean} [bindFnToScope=true]\n * @returns {Object} value as accessible by path\n */\n//TODO(misko): this function needs to be removed\nfunction getter(obj, path, bindFnToScope) {\n  if (!path) return obj;\n  var keys = path.split('.');\n  var key;\n  var lastInstance = obj;\n  var len = keys.length;\n\n  for (var i = 0; i < len; i++) {\n    key = keys[i];\n    if (obj) {\n      obj = (lastInstance = obj)[key];\n    }\n  }\n  if (!bindFnToScope && isFunction(obj)) {\n    return bind(lastInstance, obj);\n  }\n  return obj;\n}\n\n/**\n * Return the DOM siblings between the first and last node in the given array.\n * @param {Array} array like object\n * @returns {jqLite} jqLite collection containing the nodes\n */\nfunction getBlockNodes(nodes) {\n  // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original\n  //             collection, otherwise update the original collection.\n  var node = nodes[0];\n  var endNode = nodes[nodes.length - 1];\n  var blockNodes = [node];\n\n  do {\n    node = node.nextSibling;\n    if (!node) break;\n    blockNodes.push(node);\n  } while (node !== endNode);\n\n  return jqLite(blockNodes);\n}\n\n\n/**\n * Creates a new object without a prototype. This object is useful for lookup without having to\n * guard against prototypically inherited properties via hasOwnProperty.\n *\n * Related micro-benchmarks:\n * - http://jsperf.com/object-create2\n * - http://jsperf.com/proto-map-lookup/2\n * - http://jsperf.com/for-in-vs-object-keys2\n *\n * @returns {Object}\n */\nfunction createMap() {\n  return Object.create(null);\n}\n\nvar NODE_TYPE_ELEMENT = 1;\nvar NODE_TYPE_TEXT = 3;\nvar NODE_TYPE_COMMENT = 8;\nvar NODE_TYPE_DOCUMENT = 9;\nvar NODE_TYPE_DOCUMENT_FRAGMENT = 11;\n\n/**\n * @ngdoc type\n * @name angular.Module\n * @module ng\n * @description\n *\n * Interface for configuring angular {@link angular.module modules}.\n */\n\nfunction setupModuleLoader(window) {\n\n  var $injectorMinErr = minErr('$injector');\n  var ngMinErr = minErr('ng');\n\n  function ensure(obj, name, factory) {\n    return obj[name] || (obj[name] = factory());\n  }\n\n  var angular = ensure(window, 'angular', Object);\n\n  // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap\n  angular.$$minErr = angular.$$minErr || minErr;\n\n  return ensure(angular, 'module', function() {\n    /** @type {Object.<string, angular.Module>} */\n    var modules = {};\n\n    /**\n     * @ngdoc function\n     * @name angular.module\n     * @module ng\n     * @description\n     *\n     * The `angular.module` is a global place for creating, registering and retrieving Angular\n     * modules.\n     * All modules (angular core or 3rd party) that should be available to an application must be\n     * registered using this mechanism.\n     *\n     * When passed two or more arguments, a new module is created.  If passed only one argument, an\n     * existing module (the name passed as the first argument to `module`) is retrieved.\n     *\n     *\n     * # Module\n     *\n     * A module is a collection of services, directives, controllers, filters, and configuration information.\n     * `angular.module` is used to configure the {@link auto.$injector $injector}.\n     *\n     * ```js\n     * // Create a new module\n     * var myModule = angular.module('myModule', []);\n     *\n     * // register a new service\n     * myModule.value('appName', 'MyCoolApp');\n     *\n     * // configure existing services inside initialization blocks.\n     * myModule.config(['$locationProvider', function($locationProvider) {\n     *   // Configure existing providers\n     *   $locationProvider.hashPrefix('!');\n     * }]);\n     * ```\n     *\n     * Then you can create an injector and load your modules like this:\n     *\n     * ```js\n     * var injector = angular.injector(['ng', 'myModule'])\n     * ```\n     *\n     * However it's more likely that you'll just use\n     * {@link ng.directive:ngApp ngApp} or\n     * {@link angular.bootstrap} to simplify this process for you.\n     *\n     * @param {!string} name The name of the module to create or retrieve.\n     * @param {!Array.<string>=} requires If specified then new module is being created. If\n     *        unspecified then the module is being retrieved for further configuration.\n     * @param {Function=} configFn Optional configuration function for the module. Same as\n     *        {@link angular.Module#config Module#config()}.\n     * @returns {module} new module with the {@link angular.Module} api.\n     */\n    return function module(name, requires, configFn) {\n      var assertNotHasOwnProperty = function(name, context) {\n        if (name === 'hasOwnProperty') {\n          throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n        }\n      };\n\n      assertNotHasOwnProperty(name, 'module');\n      if (requires && modules.hasOwnProperty(name)) {\n        modules[name] = null;\n      }\n      return ensure(modules, name, function() {\n        if (!requires) {\n          throw $injectorMinErr('nomod', \"Module '{0}' is not available! You either misspelled \" +\n             \"the module name or forgot to load it. If registering a module ensure that you \" +\n             \"specify the dependencies as the second argument.\", name);\n        }\n\n        /** @type {!Array.<Array.<*>>} */\n        var invokeQueue = [];\n\n        /** @type {!Array.<Function>} */\n        var configBlocks = [];\n\n        /** @type {!Array.<Function>} */\n        var runBlocks = [];\n\n        var config = invokeLater('$injector', 'invoke', 'push', configBlocks);\n\n        /** @type {angular.Module} */\n        var moduleInstance = {\n          // Private state\n          _invokeQueue: invokeQueue,\n          _configBlocks: configBlocks,\n          _runBlocks: runBlocks,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#requires\n           * @module ng\n           *\n           * @description\n           * Holds the list of modules which the injector will load before the current module is\n           * loaded.\n           */\n          requires: requires,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#name\n           * @module ng\n           *\n           * @description\n           * Name of the module.\n           */\n          name: name,\n\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#provider\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerType Construction function for creating new instance of the\n           *                                service.\n           * @description\n           * See {@link auto.$provide#provider $provide.provider()}.\n           */\n          provider: invokeLater('$provide', 'provider'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#factory\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerFunction Function for creating new instance of the service.\n           * @description\n           * See {@link auto.$provide#factory $provide.factory()}.\n           */\n          factory: invokeLater('$provide', 'factory'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#service\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} constructor A constructor function that will be instantiated.\n           * @description\n           * See {@link auto.$provide#service $provide.service()}.\n           */\n          service: invokeLater('$provide', 'service'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#value\n           * @module ng\n           * @param {string} name service name\n           * @param {*} object Service instance object.\n           * @description\n           * See {@link auto.$provide#value $provide.value()}.\n           */\n          value: invokeLater('$provide', 'value'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#constant\n           * @module ng\n           * @param {string} name constant name\n           * @param {*} object Constant value.\n           * @description\n           * Because the constant are fixed, they get applied before other provide methods.\n           * See {@link auto.$provide#constant $provide.constant()}.\n           */\n          constant: invokeLater('$provide', 'constant', 'unshift'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#animation\n           * @module ng\n           * @param {string} name animation name\n           * @param {Function} animationFactory Factory function for creating new instance of an\n           *                                    animation.\n           * @description\n           *\n           * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.\n           *\n           *\n           * Defines an animation hook that can be later used with\n           * {@link ngAnimate.$animate $animate} service and directives that use this service.\n           *\n           * ```js\n           * module.animation('.animation-name', function($inject1, $inject2) {\n           *   return {\n           *     eventName : function(element, done) {\n           *       //code to run the animation\n           *       //once complete, then run done()\n           *       return function cancellationFunction(element) {\n           *         //code to cancel the animation\n           *       }\n           *     }\n           *   }\n           * })\n           * ```\n           *\n           * See {@link ng.$animateProvider#register $animateProvider.register()} and\n           * {@link ngAnimate ngAnimate module} for more information.\n           */\n          animation: invokeLater('$animateProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#filter\n           * @module ng\n           * @param {string} name Filter name.\n           * @param {Function} filterFactory Factory function for creating new instance of filter.\n           * @description\n           * See {@link ng.$filterProvider#register $filterProvider.register()}.\n           */\n          filter: invokeLater('$filterProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#controller\n           * @module ng\n           * @param {string|Object} name Controller name, or an object map of controllers where the\n           *    keys are the names and the values are the constructors.\n           * @param {Function} constructor Controller constructor function.\n           * @description\n           * See {@link ng.$controllerProvider#register $controllerProvider.register()}.\n           */\n          controller: invokeLater('$controllerProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#directive\n           * @module ng\n           * @param {string|Object} name Directive name, or an object map of directives where the\n           *    keys are the names and the values are the factories.\n           * @param {Function} directiveFactory Factory function for creating new instance of\n           * directives.\n           * @description\n           * See {@link ng.$compileProvider#directive $compileProvider.directive()}.\n           */\n          directive: invokeLater('$compileProvider', 'directive'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#config\n           * @module ng\n           * @param {Function} configFn Execute this function on module load. Useful for service\n           *    configuration.\n           * @description\n           * Use this method to register work which needs to be performed on module loading.\n           * For more about how to configure services, see\n           * {@link providers#provider-recipe Provider Recipe}.\n           */\n          config: config,\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#run\n           * @module ng\n           * @param {Function} initializationFn Execute this function after injector creation.\n           *    Useful for application initialization.\n           * @description\n           * Use this method to register work which should be performed when the injector is done\n           * loading all modules.\n           */\n          run: function(block) {\n            runBlocks.push(block);\n            return this;\n          }\n        };\n\n        if (configFn) {\n          config(configFn);\n        }\n\n        return moduleInstance;\n\n        /**\n         * @param {string} provider\n         * @param {string} method\n         * @param {String=} insertMethod\n         * @returns {angular.Module}\n         */\n        function invokeLater(provider, method, insertMethod, queue) {\n          if (!queue) queue = invokeQueue;\n          return function() {\n            queue[insertMethod || 'push']([provider, method, arguments]);\n            return moduleInstance;\n          };\n        }\n      });\n    };\n  });\n\n}\n\n/* global: toDebugString: true */\n\nfunction serializeObject(obj) {\n  var seen = [];\n\n  return JSON.stringify(obj, function(key, val) {\n    val = toJsonReplacer(key, val);\n    if (isObject(val)) {\n\n      if (seen.indexOf(val) >= 0) return '<<already seen>>';\n\n      seen.push(val);\n    }\n    return val;\n  });\n}\n\nfunction toDebugString(obj) {\n  if (typeof obj === 'function') {\n    return obj.toString().replace(/ \\{[\\s\\S]*$/, '');\n  } else if (typeof obj === 'undefined') {\n    return 'undefined';\n  } else if (typeof obj !== 'string') {\n    return serializeObject(obj);\n  }\n  return obj;\n}\n\n/* global angularModule: true,\n  version: true,\n\n  $LocaleProvider,\n  $CompileProvider,\n\n  htmlAnchorDirective,\n  inputDirective,\n  inputDirective,\n  formDirective,\n  scriptDirective,\n  selectDirective,\n  styleDirective,\n  optionDirective,\n  ngBindDirective,\n  ngBindHtmlDirective,\n  ngBindTemplateDirective,\n  ngClassDirective,\n  ngClassEvenDirective,\n  ngClassOddDirective,\n  ngCspDirective,\n  ngCloakDirective,\n  ngControllerDirective,\n  ngFormDirective,\n  ngHideDirective,\n  ngIfDirective,\n  ngIncludeDirective,\n  ngIncludeFillContentDirective,\n  ngInitDirective,\n  ngNonBindableDirective,\n  ngPluralizeDirective,\n  ngRepeatDirective,\n  ngShowDirective,\n  ngStyleDirective,\n  ngSwitchDirective,\n  ngSwitchWhenDirective,\n  ngSwitchDefaultDirective,\n  ngOptionsDirective,\n  ngTranscludeDirective,\n  ngModelDirective,\n  ngListDirective,\n  ngChangeDirective,\n  patternDirective,\n  patternDirective,\n  requiredDirective,\n  requiredDirective,\n  minlengthDirective,\n  minlengthDirective,\n  maxlengthDirective,\n  maxlengthDirective,\n  ngValueDirective,\n  ngModelOptionsDirective,\n  ngAttributeAliasDirectives,\n  ngEventDirectives,\n\n  $AnchorScrollProvider,\n  $AnimateProvider,\n  $BrowserProvider,\n  $CacheFactoryProvider,\n  $ControllerProvider,\n  $DocumentProvider,\n  $ExceptionHandlerProvider,\n  $FilterProvider,\n  $InterpolateProvider,\n  $IntervalProvider,\n  $HttpProvider,\n  $HttpBackendProvider,\n  $LocationProvider,\n  $LogProvider,\n  $ParseProvider,\n  $RootScopeProvider,\n  $QProvider,\n  $$QProvider,\n  $$SanitizeUriProvider,\n  $SceProvider,\n  $SceDelegateProvider,\n  $SnifferProvider,\n  $TemplateCacheProvider,\n  $TemplateRequestProvider,\n  $$TestabilityProvider,\n  $TimeoutProvider,\n  $$RAFProvider,\n  $$AsyncCallbackProvider,\n  $WindowProvider,\n  $$jqLiteProvider\n*/\n\n\n/**\n * @ngdoc object\n * @name angular.version\n * @module ng\n * @description\n * An object that contains information about the current AngularJS version. This object has the\n * following properties:\n *\n * - `full` – `{string}` – Full version string, such as \"0.9.18\".\n * - `major` – `{number}` – Major version number, such as \"0\".\n * - `minor` – `{number}` – Minor version number, such as \"9\".\n * - `dot` – `{number}` – Dot version number, such as \"18\".\n * - `codeName` – `{string}` – Code name of the release, such as \"jiggling-armfat\".\n */\nvar version = {\n  full: '1.3.13',    // all of these placeholder strings will be replaced by grunt's\n  major: 1,    // package task\n  minor: 3,\n  dot: 13,\n  codeName: 'meticulous-riffleshuffle'\n};\n\n\nfunction publishExternalAPI(angular) {\n  extend(angular, {\n    'bootstrap': bootstrap,\n    'copy': copy,\n    'extend': extend,\n    'equals': equals,\n    'element': jqLite,\n    'forEach': forEach,\n    'injector': createInjector,\n    'noop': noop,\n    'bind': bind,\n    'toJson': toJson,\n    'fromJson': fromJson,\n    'identity': identity,\n    'isUndefined': isUndefined,\n    'isDefined': isDefined,\n    'isString': isString,\n    'isFunction': isFunction,\n    'isObject': isObject,\n    'isNumber': isNumber,\n    'isElement': isElement,\n    'isArray': isArray,\n    'version': version,\n    'isDate': isDate,\n    'lowercase': lowercase,\n    'uppercase': uppercase,\n    'callbacks': {counter: 0},\n    'getTestability': getTestability,\n    '$$minErr': minErr,\n    '$$csp': csp,\n    'reloadWithDebugInfo': reloadWithDebugInfo\n  });\n\n  angularModule = setupModuleLoader(window);\n  try {\n    angularModule('ngLocale');\n  } catch (e) {\n    angularModule('ngLocale', []).provider('$locale', $LocaleProvider);\n  }\n\n  angularModule('ng', ['ngLocale'], ['$provide',\n    function ngModule($provide) {\n      // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.\n      $provide.provider({\n        $$sanitizeUri: $$SanitizeUriProvider\n      });\n      $provide.provider('$compile', $CompileProvider).\n        directive({\n            a: htmlAnchorDirective,\n            input: inputDirective,\n            textarea: inputDirective,\n            form: formDirective,\n            script: scriptDirective,\n            select: selectDirective,\n            style: styleDirective,\n            option: optionDirective,\n            ngBind: ngBindDirective,\n            ngBindHtml: ngBindHtmlDirective,\n            ngBindTemplate: ngBindTemplateDirective,\n            ngClass: ngClassDirective,\n            ngClassEven: ngClassEvenDirective,\n            ngClassOdd: ngClassOddDirective,\n            ngCloak: ngCloakDirective,\n            ngController: ngControllerDirective,\n            ngForm: ngFormDirective,\n            ngHide: ngHideDirective,\n            ngIf: ngIfDirective,\n            ngInclude: ngIncludeDirective,\n            ngInit: ngInitDirective,\n            ngNonBindable: ngNonBindableDirective,\n            ngPluralize: ngPluralizeDirective,\n            ngRepeat: ngRepeatDirective,\n            ngShow: ngShowDirective,\n            ngStyle: ngStyleDirective,\n            ngSwitch: ngSwitchDirective,\n            ngSwitchWhen: ngSwitchWhenDirective,\n            ngSwitchDefault: ngSwitchDefaultDirective,\n            ngOptions: ngOptionsDirective,\n            ngTransclude: ngTranscludeDirective,\n            ngModel: ngModelDirective,\n            ngList: ngListDirective,\n            ngChange: ngChangeDirective,\n            pattern: patternDirective,\n            ngPattern: patternDirective,\n            required: requiredDirective,\n            ngRequired: requiredDirective,\n            minlength: minlengthDirective,\n            ngMinlength: minlengthDirective,\n            maxlength: maxlengthDirective,\n            ngMaxlength: maxlengthDirective,\n            ngValue: ngValueDirective,\n            ngModelOptions: ngModelOptionsDirective\n        }).\n        directive({\n          ngInclude: ngIncludeFillContentDirective\n        }).\n        directive(ngAttributeAliasDirectives).\n        directive(ngEventDirectives);\n      $provide.provider({\n        $anchorScroll: $AnchorScrollProvider,\n        $animate: $AnimateProvider,\n        $browser: $BrowserProvider,\n        $cacheFactory: $CacheFactoryProvider,\n        $controller: $ControllerProvider,\n        $document: $DocumentProvider,\n        $exceptionHandler: $ExceptionHandlerProvider,\n        $filter: $FilterProvider,\n        $interpolate: $InterpolateProvider,\n        $interval: $IntervalProvider,\n        $http: $HttpProvider,\n        $httpBackend: $HttpBackendProvider,\n        $location: $LocationProvider,\n        $log: $LogProvider,\n        $parse: $ParseProvider,\n        $rootScope: $RootScopeProvider,\n        $q: $QProvider,\n        $$q: $$QProvider,\n        $sce: $SceProvider,\n        $sceDelegate: $SceDelegateProvider,\n        $sniffer: $SnifferProvider,\n        $templateCache: $TemplateCacheProvider,\n        $templateRequest: $TemplateRequestProvider,\n        $$testability: $$TestabilityProvider,\n        $timeout: $TimeoutProvider,\n        $window: $WindowProvider,\n        $$rAF: $$RAFProvider,\n        $$asyncCallback: $$AsyncCallbackProvider,\n        $$jqLite: $$jqLiteProvider\n      });\n    }\n  ]);\n}\n\n/* global JQLitePrototype: true,\n  addEventListenerFn: true,\n  removeEventListenerFn: true,\n  BOOLEAN_ATTR: true,\n  ALIASED_ATTR: true,\n*/\n\n//////////////////////////////////\n//JQLite\n//////////////////////////////////\n\n/**\n * @ngdoc function\n * @name angular.element\n * @module ng\n * @kind function\n *\n * @description\n * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.\n *\n * If jQuery is available, `angular.element` is an alias for the\n * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`\n * delegates to Angular's built-in subset of jQuery, called \"jQuery lite\" or \"jqLite.\"\n *\n * <div class=\"alert alert-success\">jqLite is a tiny, API-compatible subset of jQuery that allows\n * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most\n * commonly needed functionality with the goal of having a very small footprint.</div>\n *\n * To use jQuery, simply load it before `DOMContentLoaded` event fired.\n *\n * <div class=\"alert\">**Note:** all element references in Angular are always wrapped with jQuery or\n * jqLite; they are never raw DOM references.</div>\n *\n * ## Angular's jqLite\n * jqLite provides only the following jQuery methods:\n *\n * - [`addClass()`](http://api.jquery.com/addClass/)\n * - [`after()`](http://api.jquery.com/after/)\n * - [`append()`](http://api.jquery.com/append/)\n * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters\n * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData\n * - [`children()`](http://api.jquery.com/children/) - Does not support selectors\n * - [`clone()`](http://api.jquery.com/clone/)\n * - [`contents()`](http://api.jquery.com/contents/)\n * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`\n * - [`data()`](http://api.jquery.com/data/)\n * - [`detach()`](http://api.jquery.com/detach/)\n * - [`empty()`](http://api.jquery.com/empty/)\n * - [`eq()`](http://api.jquery.com/eq/)\n * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name\n * - [`hasClass()`](http://api.jquery.com/hasClass/)\n * - [`html()`](http://api.jquery.com/html/)\n * - [`next()`](http://api.jquery.com/next/) - Does not support selectors\n * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData\n * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors\n * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors\n * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors\n * - [`prepend()`](http://api.jquery.com/prepend/)\n * - [`prop()`](http://api.jquery.com/prop/)\n * - [`ready()`](http://api.jquery.com/ready/)\n * - [`remove()`](http://api.jquery.com/remove/)\n * - [`removeAttr()`](http://api.jquery.com/removeAttr/)\n * - [`removeClass()`](http://api.jquery.com/removeClass/)\n * - [`removeData()`](http://api.jquery.com/removeData/)\n * - [`replaceWith()`](http://api.jquery.com/replaceWith/)\n * - [`text()`](http://api.jquery.com/text/)\n * - [`toggleClass()`](http://api.jquery.com/toggleClass/)\n * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.\n * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces\n * - [`val()`](http://api.jquery.com/val/)\n * - [`wrap()`](http://api.jquery.com/wrap/)\n *\n * ## jQuery/jqLite Extras\n * Angular also provides the following additional methods and events to both jQuery and jqLite:\n *\n * ### Events\n * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event\n *    on all DOM nodes being removed.  This can be used to clean up any 3rd party bindings to the DOM\n *    element before it is removed.\n *\n * ### Methods\n * - `controller(name)` - retrieves the controller of the current element or its parent. By default\n *   retrieves controller associated with the `ngController` directive. If `name` is provided as\n *   camelCase directive name, then the controller for this directive will be retrieved (e.g.\n *   `'ngModel'`).\n * - `injector()` - retrieves the injector of the current element or its parent.\n * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current\n *   element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to\n *   be enabled.\n * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the\n *   current element. This getter should be used only on elements that contain a directive which starts a new isolate\n *   scope. Calling `scope()` on this element always returns the original non-isolate scope.\n *   Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.\n * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top\n *   parent element is reached.\n *\n * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.\n * @returns {Object} jQuery object.\n */\n\nJQLite.expando = 'ng339';\n\nvar jqCache = JQLite.cache = {},\n    jqId = 1,\n    addEventListenerFn = function(element, type, fn) {\n      element.addEventListener(type, fn, false);\n    },\n    removeEventListenerFn = function(element, type, fn) {\n      element.removeEventListener(type, fn, false);\n    };\n\n/*\n * !!! This is an undocumented \"private\" function !!!\n */\nJQLite._data = function(node) {\n  //jQuery always returns an object on cache miss\n  return this.cache[node[this.expando]] || {};\n};\n\nfunction jqNextId() { return ++jqId; }\n\n\nvar SPECIAL_CHARS_REGEXP = /([\\:\\-\\_]+(.))/g;\nvar MOZ_HACK_REGEXP = /^moz([A-Z])/;\nvar MOUSE_EVENT_MAP= { mouseleave: \"mouseout\", mouseenter: \"mouseover\"};\nvar jqLiteMinErr = minErr('jqLite');\n\n/**\n * Converts snake_case to camelCase.\n * Also there is special case for Moz prefix starting with upper case letter.\n * @param name Name to normalize\n */\nfunction camelCase(name) {\n  return name.\n    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {\n      return offset ? letter.toUpperCase() : letter;\n    }).\n    replace(MOZ_HACK_REGEXP, 'Moz$1');\n}\n\nvar SINGLE_TAG_REGEXP = /^<(\\w+)\\s*\\/?>(?:<\\/\\1>|)$/;\nvar HTML_REGEXP = /<|&#?\\w+;/;\nvar TAG_NAME_REGEXP = /<([\\w:]+)/;\nvar XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:]+)[^>]*)\\/>/gi;\n\nvar wrapMap = {\n  'option': [1, '<select multiple=\"multiple\">', '</select>'],\n\n  'thead': [1, '<table>', '</table>'],\n  'col': [2, '<table><colgroup>', '</colgroup></table>'],\n  'tr': [2, '<table><tbody>', '</tbody></table>'],\n  'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],\n  '_default': [0, \"\", \"\"]\n};\n\nwrapMap.optgroup = wrapMap.option;\nwrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;\nwrapMap.th = wrapMap.td;\n\n\nfunction jqLiteIsTextNode(html) {\n  return !HTML_REGEXP.test(html);\n}\n\nfunction jqLiteAcceptsData(node) {\n  // The window object can accept data but has no nodeType\n  // Otherwise we are only interested in elements (1) and documents (9)\n  var nodeType = node.nodeType;\n  return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;\n}\n\nfunction jqLiteBuildFragment(html, context) {\n  var tmp, tag, wrap,\n      fragment = context.createDocumentFragment(),\n      nodes = [], i;\n\n  if (jqLiteIsTextNode(html)) {\n    // Convert non-html into a text node\n    nodes.push(context.createTextNode(html));\n  } else {\n    // Convert html into DOM nodes\n    tmp = tmp || fragment.appendChild(context.createElement(\"div\"));\n    tag = (TAG_NAME_REGEXP.exec(html) || [\"\", \"\"])[1].toLowerCase();\n    wrap = wrapMap[tag] || wrapMap._default;\n    tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, \"<$1></$2>\") + wrap[2];\n\n    // Descend through wrappers to the right content\n    i = wrap[0];\n    while (i--) {\n      tmp = tmp.lastChild;\n    }\n\n    nodes = concat(nodes, tmp.childNodes);\n\n    tmp = fragment.firstChild;\n    tmp.textContent = \"\";\n  }\n\n  // Remove wrapper from fragment\n  fragment.textContent = \"\";\n  fragment.innerHTML = \"\"; // Clear inner HTML\n  forEach(nodes, function(node) {\n    fragment.appendChild(node);\n  });\n\n  return fragment;\n}\n\nfunction jqLiteParseHTML(html, context) {\n  context = context || document;\n  var parsed;\n\n  if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {\n    return [context.createElement(parsed[1])];\n  }\n\n  if ((parsed = jqLiteBuildFragment(html, context))) {\n    return parsed.childNodes;\n  }\n\n  return [];\n}\n\n/////////////////////////////////////////////\nfunction JQLite(element) {\n  if (element instanceof JQLite) {\n    return element;\n  }\n\n  var argIsString;\n\n  if (isString(element)) {\n    element = trim(element);\n    argIsString = true;\n  }\n  if (!(this instanceof JQLite)) {\n    if (argIsString && element.charAt(0) != '<') {\n      throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');\n    }\n    return new JQLite(element);\n  }\n\n  if (argIsString) {\n    jqLiteAddNodes(this, jqLiteParseHTML(element));\n  } else {\n    jqLiteAddNodes(this, element);\n  }\n}\n\nfunction jqLiteClone(element) {\n  return element.cloneNode(true);\n}\n\nfunction jqLiteDealoc(element, onlyDescendants) {\n  if (!onlyDescendants) jqLiteRemoveData(element);\n\n  if (element.querySelectorAll) {\n    var descendants = element.querySelectorAll('*');\n    for (var i = 0, l = descendants.length; i < l; i++) {\n      jqLiteRemoveData(descendants[i]);\n    }\n  }\n}\n\nfunction jqLiteOff(element, type, fn, unsupported) {\n  if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');\n\n  var expandoStore = jqLiteExpandoStore(element);\n  var events = expandoStore && expandoStore.events;\n  var handle = expandoStore && expandoStore.handle;\n\n  if (!handle) return; //no listeners registered\n\n  if (!type) {\n    for (type in events) {\n      if (type !== '$destroy') {\n        removeEventListenerFn(element, type, handle);\n      }\n      delete events[type];\n    }\n  } else {\n    forEach(type.split(' '), function(type) {\n      if (isDefined(fn)) {\n        var listenerFns = events[type];\n        arrayRemove(listenerFns || [], fn);\n        if (listenerFns && listenerFns.length > 0) {\n          return;\n        }\n      }\n\n      removeEventListenerFn(element, type, handle);\n      delete events[type];\n    });\n  }\n}\n\nfunction jqLiteRemoveData(element, name) {\n  var expandoId = element.ng339;\n  var expandoStore = expandoId && jqCache[expandoId];\n\n  if (expandoStore) {\n    if (name) {\n      delete expandoStore.data[name];\n      return;\n    }\n\n    if (expandoStore.handle) {\n      if (expandoStore.events.$destroy) {\n        expandoStore.handle({}, '$destroy');\n      }\n      jqLiteOff(element);\n    }\n    delete jqCache[expandoId];\n    element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it\n  }\n}\n\n\nfunction jqLiteExpandoStore(element, createIfNecessary) {\n  var expandoId = element.ng339,\n      expandoStore = expandoId && jqCache[expandoId];\n\n  if (createIfNecessary && !expandoStore) {\n    element.ng339 = expandoId = jqNextId();\n    expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};\n  }\n\n  return expandoStore;\n}\n\n\nfunction jqLiteData(element, key, value) {\n  if (jqLiteAcceptsData(element)) {\n\n    var isSimpleSetter = isDefined(value);\n    var isSimpleGetter = !isSimpleSetter && key && !isObject(key);\n    var massGetter = !key;\n    var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);\n    var data = expandoStore && expandoStore.data;\n\n    if (isSimpleSetter) { // data('key', value)\n      data[key] = value;\n    } else {\n      if (massGetter) {  // data()\n        return data;\n      } else {\n        if (isSimpleGetter) { // data('key')\n          // don't force creation of expandoStore if it doesn't exist yet\n          return data && data[key];\n        } else { // mass-setter: data({key1: val1, key2: val2})\n          extend(data, key);\n        }\n      }\n    }\n  }\n}\n\nfunction jqLiteHasClass(element, selector) {\n  if (!element.getAttribute) return false;\n  return ((\" \" + (element.getAttribute('class') || '') + \" \").replace(/[\\n\\t]/g, \" \").\n      indexOf(\" \" + selector + \" \") > -1);\n}\n\nfunction jqLiteRemoveClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    forEach(cssClasses.split(' '), function(cssClass) {\n      element.setAttribute('class', trim(\n          (\" \" + (element.getAttribute('class') || '') + \" \")\n          .replace(/[\\n\\t]/g, \" \")\n          .replace(\" \" + trim(cssClass) + \" \", \" \"))\n      );\n    });\n  }\n}\n\nfunction jqLiteAddClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\n                            .replace(/[\\n\\t]/g, \" \");\n\n    forEach(cssClasses.split(' '), function(cssClass) {\n      cssClass = trim(cssClass);\n      if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\n        existingClasses += cssClass + ' ';\n      }\n    });\n\n    element.setAttribute('class', trim(existingClasses));\n  }\n}\n\n\nfunction jqLiteAddNodes(root, elements) {\n  // THIS CODE IS VERY HOT. Don't make changes without benchmarking.\n\n  if (elements) {\n\n    // if a Node (the most common case)\n    if (elements.nodeType) {\n      root[root.length++] = elements;\n    } else {\n      var length = elements.length;\n\n      // if an Array or NodeList and not a Window\n      if (typeof length === 'number' && elements.window !== elements) {\n        if (length) {\n          for (var i = 0; i < length; i++) {\n            root[root.length++] = elements[i];\n          }\n        }\n      } else {\n        root[root.length++] = elements;\n      }\n    }\n  }\n}\n\n\nfunction jqLiteController(element, name) {\n  return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');\n}\n\nfunction jqLiteInheritedData(element, name, value) {\n  // if element is the document object work with the html element instead\n  // this makes $(document).scope() possible\n  if (element.nodeType == NODE_TYPE_DOCUMENT) {\n    element = element.documentElement;\n  }\n  var names = isArray(name) ? name : [name];\n\n  while (element) {\n    for (var i = 0, ii = names.length; i < ii; i++) {\n      if ((value = jqLite.data(element, names[i])) !== undefined) return value;\n    }\n\n    // If dealing with a document fragment node with a host element, and no parent, use the host\n    // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM\n    // to lookup parent controllers.\n    element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);\n  }\n}\n\nfunction jqLiteEmpty(element) {\n  jqLiteDealoc(element, true);\n  while (element.firstChild) {\n    element.removeChild(element.firstChild);\n  }\n}\n\nfunction jqLiteRemove(element, keepData) {\n  if (!keepData) jqLiteDealoc(element);\n  var parent = element.parentNode;\n  if (parent) parent.removeChild(element);\n}\n\n\nfunction jqLiteDocumentLoaded(action, win) {\n  win = win || window;\n  if (win.document.readyState === 'complete') {\n    // Force the action to be run async for consistent behaviour\n    // from the action's point of view\n    // i.e. it will definitely not be in a $apply\n    win.setTimeout(action);\n  } else {\n    // No need to unbind this handler as load is only ever called once\n    jqLite(win).on('load', action);\n  }\n}\n\n//////////////////////////////////////////\n// Functions which are declared directly.\n//////////////////////////////////////////\nvar JQLitePrototype = JQLite.prototype = {\n  ready: function(fn) {\n    var fired = false;\n\n    function trigger() {\n      if (fired) return;\n      fired = true;\n      fn();\n    }\n\n    // check if document is already loaded\n    if (document.readyState === 'complete') {\n      setTimeout(trigger);\n    } else {\n      this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9\n      // we can not use jqLite since we are not done loading and jQuery could be loaded later.\n      // jshint -W064\n      JQLite(window).on('load', trigger); // fallback to window.onload for others\n      // jshint +W064\n    }\n  },\n  toString: function() {\n    var value = [];\n    forEach(this, function(e) { value.push('' + e);});\n    return '[' + value.join(', ') + ']';\n  },\n\n  eq: function(index) {\n      return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);\n  },\n\n  length: 0,\n  push: push,\n  sort: [].sort,\n  splice: [].splice\n};\n\n//////////////////////////////////////////\n// Functions iterating getter/setters.\n// these functions return self on setter and\n// value on get.\n//////////////////////////////////////////\nvar BOOLEAN_ATTR = {};\nforEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {\n  BOOLEAN_ATTR[lowercase(value)] = value;\n});\nvar BOOLEAN_ELEMENTS = {};\nforEach('input,select,option,textarea,button,form,details'.split(','), function(value) {\n  BOOLEAN_ELEMENTS[value] = true;\n});\nvar ALIASED_ATTR = {\n  'ngMinlength': 'minlength',\n  'ngMaxlength': 'maxlength',\n  'ngMin': 'min',\n  'ngMax': 'max',\n  'ngPattern': 'pattern'\n};\n\nfunction getBooleanAttrName(element, name) {\n  // check dom last since we will most likely fail on name\n  var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];\n\n  // booleanAttr is here twice to minimize DOM access\n  return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;\n}\n\nfunction getAliasedAttrName(element, name) {\n  var nodeName = element.nodeName;\n  return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];\n}\n\nforEach({\n  data: jqLiteData,\n  removeData: jqLiteRemoveData\n}, function(fn, name) {\n  JQLite[name] = fn;\n});\n\nforEach({\n  data: jqLiteData,\n  inheritedData: jqLiteInheritedData,\n\n  scope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);\n  },\n\n  isolateScope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');\n  },\n\n  controller: jqLiteController,\n\n  injector: function(element) {\n    return jqLiteInheritedData(element, '$injector');\n  },\n\n  removeAttr: function(element, name) {\n    element.removeAttribute(name);\n  },\n\n  hasClass: jqLiteHasClass,\n\n  css: function(element, name, value) {\n    name = camelCase(name);\n\n    if (isDefined(value)) {\n      element.style[name] = value;\n    } else {\n      return element.style[name];\n    }\n  },\n\n  attr: function(element, name, value) {\n    var lowercasedName = lowercase(name);\n    if (BOOLEAN_ATTR[lowercasedName]) {\n      if (isDefined(value)) {\n        if (!!value) {\n          element[name] = true;\n          element.setAttribute(name, lowercasedName);\n        } else {\n          element[name] = false;\n          element.removeAttribute(lowercasedName);\n        }\n      } else {\n        return (element[name] ||\n                 (element.attributes.getNamedItem(name) || noop).specified)\n               ? lowercasedName\n               : undefined;\n      }\n    } else if (isDefined(value)) {\n      element.setAttribute(name, value);\n    } else if (element.getAttribute) {\n      // the extra argument \"2\" is to get the right thing for a.href in IE, see jQuery code\n      // some elements (e.g. Document) don't have get attribute, so return undefined\n      var ret = element.getAttribute(name, 2);\n      // normalize non-existing attributes to undefined (as jQuery)\n      return ret === null ? undefined : ret;\n    }\n  },\n\n  prop: function(element, name, value) {\n    if (isDefined(value)) {\n      element[name] = value;\n    } else {\n      return element[name];\n    }\n  },\n\n  text: (function() {\n    getText.$dv = '';\n    return getText;\n\n    function getText(element, value) {\n      if (isUndefined(value)) {\n        var nodeType = element.nodeType;\n        return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';\n      }\n      element.textContent = value;\n    }\n  })(),\n\n  val: function(element, value) {\n    if (isUndefined(value)) {\n      if (element.multiple && nodeName_(element) === 'select') {\n        var result = [];\n        forEach(element.options, function(option) {\n          if (option.selected) {\n            result.push(option.value || option.text);\n          }\n        });\n        return result.length === 0 ? null : result;\n      }\n      return element.value;\n    }\n    element.value = value;\n  },\n\n  html: function(element, value) {\n    if (isUndefined(value)) {\n      return element.innerHTML;\n    }\n    jqLiteDealoc(element, true);\n    element.innerHTML = value;\n  },\n\n  empty: jqLiteEmpty\n}, function(fn, name) {\n  /**\n   * Properties: writes return selection, reads return first value\n   */\n  JQLite.prototype[name] = function(arg1, arg2) {\n    var i, key;\n    var nodeCount = this.length;\n\n    // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it\n    // in a way that survives minification.\n    // jqLiteEmpty takes no arguments but is a setter.\n    if (fn !== jqLiteEmpty &&\n        (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {\n      if (isObject(arg1)) {\n\n        // we are a write, but the object properties are the key/values\n        for (i = 0; i < nodeCount; i++) {\n          if (fn === jqLiteData) {\n            // data() takes the whole object in jQuery\n            fn(this[i], arg1);\n          } else {\n            for (key in arg1) {\n              fn(this[i], key, arg1[key]);\n            }\n          }\n        }\n        // return self for chaining\n        return this;\n      } else {\n        // we are a read, so read the first child.\n        // TODO: do we still need this?\n        var value = fn.$dv;\n        // Only if we have $dv do we iterate over all, otherwise it is just the first element.\n        var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;\n        for (var j = 0; j < jj; j++) {\n          var nodeValue = fn(this[j], arg1, arg2);\n          value = value ? value + nodeValue : nodeValue;\n        }\n        return value;\n      }\n    } else {\n      // we are a write, so apply to all children\n      for (i = 0; i < nodeCount; i++) {\n        fn(this[i], arg1, arg2);\n      }\n      // return self for chaining\n      return this;\n    }\n  };\n});\n\nfunction createEventHandler(element, events) {\n  var eventHandler = function(event, type) {\n    // jQuery specific api\n    event.isDefaultPrevented = function() {\n      return event.defaultPrevented;\n    };\n\n    var eventFns = events[type || event.type];\n    var eventFnsLength = eventFns ? eventFns.length : 0;\n\n    if (!eventFnsLength) return;\n\n    if (isUndefined(event.immediatePropagationStopped)) {\n      var originalStopImmediatePropagation = event.stopImmediatePropagation;\n      event.stopImmediatePropagation = function() {\n        event.immediatePropagationStopped = true;\n\n        if (event.stopPropagation) {\n          event.stopPropagation();\n        }\n\n        if (originalStopImmediatePropagation) {\n          originalStopImmediatePropagation.call(event);\n        }\n      };\n    }\n\n    event.isImmediatePropagationStopped = function() {\n      return event.immediatePropagationStopped === true;\n    };\n\n    // Copy event handlers in case event handlers array is modified during execution.\n    if ((eventFnsLength > 1)) {\n      eventFns = shallowCopy(eventFns);\n    }\n\n    for (var i = 0; i < eventFnsLength; i++) {\n      if (!event.isImmediatePropagationStopped()) {\n        eventFns[i].call(element, event);\n      }\n    }\n  };\n\n  // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all\n  //       events on `element`\n  eventHandler.elem = element;\n  return eventHandler;\n}\n\n//////////////////////////////////////////\n// Functions iterating traversal.\n// These functions chain results into a single\n// selector.\n//////////////////////////////////////////\nforEach({\n  removeData: jqLiteRemoveData,\n\n  on: function jqLiteOn(element, type, fn, unsupported) {\n    if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');\n\n    // Do not add event handlers to non-elements because they will not be cleaned up.\n    if (!jqLiteAcceptsData(element)) {\n      return;\n    }\n\n    var expandoStore = jqLiteExpandoStore(element, true);\n    var events = expandoStore.events;\n    var handle = expandoStore.handle;\n\n    if (!handle) {\n      handle = expandoStore.handle = createEventHandler(element, events);\n    }\n\n    // http://jsperf.com/string-indexof-vs-split\n    var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];\n    var i = types.length;\n\n    while (i--) {\n      type = types[i];\n      var eventFns = events[type];\n\n      if (!eventFns) {\n        events[type] = [];\n\n        if (type === 'mouseenter' || type === 'mouseleave') {\n          // Refer to jQuery's implementation of mouseenter & mouseleave\n          // Read about mouseenter and mouseleave:\n          // http://www.quirksmode.org/js/events_mouse.html#link8\n\n          jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {\n            var target = this, related = event.relatedTarget;\n            // For mousenter/leave call the handler if related is outside the target.\n            // NB: No relatedTarget if the mouse left/entered the browser window\n            if (!related || (related !== target && !target.contains(related))) {\n              handle(event, type);\n            }\n          });\n\n        } else {\n          if (type !== '$destroy') {\n            addEventListenerFn(element, type, handle);\n          }\n        }\n        eventFns = events[type];\n      }\n      eventFns.push(fn);\n    }\n  },\n\n  off: jqLiteOff,\n\n  one: function(element, type, fn) {\n    element = jqLite(element);\n\n    //add the listener twice so that when it is called\n    //you can remove the original function and still be\n    //able to call element.off(ev, fn) normally\n    element.on(type, function onFn() {\n      element.off(type, fn);\n      element.off(type, onFn);\n    });\n    element.on(type, fn);\n  },\n\n  replaceWith: function(element, replaceNode) {\n    var index, parent = element.parentNode;\n    jqLiteDealoc(element);\n    forEach(new JQLite(replaceNode), function(node) {\n      if (index) {\n        parent.insertBefore(node, index.nextSibling);\n      } else {\n        parent.replaceChild(node, element);\n      }\n      index = node;\n    });\n  },\n\n  children: function(element) {\n    var children = [];\n    forEach(element.childNodes, function(element) {\n      if (element.nodeType === NODE_TYPE_ELEMENT)\n        children.push(element);\n    });\n    return children;\n  },\n\n  contents: function(element) {\n    return element.contentDocument || element.childNodes || [];\n  },\n\n  append: function(element, node) {\n    var nodeType = element.nodeType;\n    if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;\n\n    node = new JQLite(node);\n\n    for (var i = 0, ii = node.length; i < ii; i++) {\n      var child = node[i];\n      element.appendChild(child);\n    }\n  },\n\n  prepend: function(element, node) {\n    if (element.nodeType === NODE_TYPE_ELEMENT) {\n      var index = element.firstChild;\n      forEach(new JQLite(node), function(child) {\n        element.insertBefore(child, index);\n      });\n    }\n  },\n\n  wrap: function(element, wrapNode) {\n    wrapNode = jqLite(wrapNode).eq(0).clone()[0];\n    var parent = element.parentNode;\n    if (parent) {\n      parent.replaceChild(wrapNode, element);\n    }\n    wrapNode.appendChild(element);\n  },\n\n  remove: jqLiteRemove,\n\n  detach: function(element) {\n    jqLiteRemove(element, true);\n  },\n\n  after: function(element, newElement) {\n    var index = element, parent = element.parentNode;\n    newElement = new JQLite(newElement);\n\n    for (var i = 0, ii = newElement.length; i < ii; i++) {\n      var node = newElement[i];\n      parent.insertBefore(node, index.nextSibling);\n      index = node;\n    }\n  },\n\n  addClass: jqLiteAddClass,\n  removeClass: jqLiteRemoveClass,\n\n  toggleClass: function(element, selector, condition) {\n    if (selector) {\n      forEach(selector.split(' '), function(className) {\n        var classCondition = condition;\n        if (isUndefined(classCondition)) {\n          classCondition = !jqLiteHasClass(element, className);\n        }\n        (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);\n      });\n    }\n  },\n\n  parent: function(element) {\n    var parent = element.parentNode;\n    return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;\n  },\n\n  next: function(element) {\n    return element.nextElementSibling;\n  },\n\n  find: function(element, selector) {\n    if (element.getElementsByTagName) {\n      return element.getElementsByTagName(selector);\n    } else {\n      return [];\n    }\n  },\n\n  clone: jqLiteClone,\n\n  triggerHandler: function(element, event, extraParameters) {\n\n    var dummyEvent, eventFnsCopy, handlerArgs;\n    var eventName = event.type || event;\n    var expandoStore = jqLiteExpandoStore(element);\n    var events = expandoStore && expandoStore.events;\n    var eventFns = events && events[eventName];\n\n    if (eventFns) {\n      // Create a dummy event to pass to the handlers\n      dummyEvent = {\n        preventDefault: function() { this.defaultPrevented = true; },\n        isDefaultPrevented: function() { return this.defaultPrevented === true; },\n        stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },\n        isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },\n        stopPropagation: noop,\n        type: eventName,\n        target: element\n      };\n\n      // If a custom event was provided then extend our dummy event with it\n      if (event.type) {\n        dummyEvent = extend(dummyEvent, event);\n      }\n\n      // Copy event handlers in case event handlers array is modified during execution.\n      eventFnsCopy = shallowCopy(eventFns);\n      handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];\n\n      forEach(eventFnsCopy, function(fn) {\n        if (!dummyEvent.isImmediatePropagationStopped()) {\n          fn.apply(element, handlerArgs);\n        }\n      });\n    }\n  }\n}, function(fn, name) {\n  /**\n   * chaining functions\n   */\n  JQLite.prototype[name] = function(arg1, arg2, arg3) {\n    var value;\n\n    for (var i = 0, ii = this.length; i < ii; i++) {\n      if (isUndefined(value)) {\n        value = fn(this[i], arg1, arg2, arg3);\n        if (isDefined(value)) {\n          // any function which returns a value needs to be wrapped\n          value = jqLite(value);\n        }\n      } else {\n        jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));\n      }\n    }\n    return isDefined(value) ? value : this;\n  };\n\n  // bind legacy bind/unbind to on/off\n  JQLite.prototype.bind = JQLite.prototype.on;\n  JQLite.prototype.unbind = JQLite.prototype.off;\n});\n\n\n// Provider for private $$jqLite service\nfunction $$jqLiteProvider() {\n  this.$get = function $$jqLite() {\n    return extend(JQLite, {\n      hasClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteHasClass(node, classes);\n      },\n      addClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteAddClass(node, classes);\n      },\n      removeClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteRemoveClass(node, classes);\n      }\n    });\n  };\n}\n\n/**\n * Computes a hash of an 'obj'.\n * Hash of a:\n *  string is string\n *  number is number as string\n *  object is either result of calling $$hashKey function on the object or uniquely generated id,\n *         that is also assigned to the $$hashKey property of the object.\n *\n * @param obj\n * @returns {string} hash string such that the same input will have the same hash string.\n *         The resulting string key is in 'type:hashKey' format.\n */\nfunction hashKey(obj, nextUidFn) {\n  var key = obj && obj.$$hashKey;\n\n  if (key) {\n    if (typeof key === 'function') {\n      key = obj.$$hashKey();\n    }\n    return key;\n  }\n\n  var objType = typeof obj;\n  if (objType == 'function' || (objType == 'object' && obj !== null)) {\n    key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();\n  } else {\n    key = objType + ':' + obj;\n  }\n\n  return key;\n}\n\n/**\n * HashMap which can use objects as keys\n */\nfunction HashMap(array, isolatedUid) {\n  if (isolatedUid) {\n    var uid = 0;\n    this.nextUid = function() {\n      return ++uid;\n    };\n  }\n  forEach(array, this.put, this);\n}\nHashMap.prototype = {\n  /**\n   * Store key value pair\n   * @param key key to store can be any type\n   * @param value value to store can be any type\n   */\n  put: function(key, value) {\n    this[hashKey(key, this.nextUid)] = value;\n  },\n\n  /**\n   * @param key\n   * @returns {Object} the value for the key\n   */\n  get: function(key) {\n    return this[hashKey(key, this.nextUid)];\n  },\n\n  /**\n   * Remove the key/value pair\n   * @param key\n   */\n  remove: function(key) {\n    var value = this[key = hashKey(key, this.nextUid)];\n    delete this[key];\n    return value;\n  }\n};\n\n/**\n * @ngdoc function\n * @module ng\n * @name angular.injector\n * @kind function\n *\n * @description\n * Creates an injector object that can be used for retrieving services as well as for\n * dependency injection (see {@link guide/di dependency injection}).\n *\n * @param {Array.<string|Function>} modules A list of module functions or their aliases. See\n *     {@link angular.module}. The `ng` module must be explicitly added.\n * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which\n *     disallows argument name annotation inference.\n * @returns {injector} Injector object. See {@link auto.$injector $injector}.\n *\n * @example\n * Typical usage\n * ```js\n *   // create an injector\n *   var $injector = angular.injector(['ng']);\n *\n *   // use the injector to kick off your application\n *   // use the type inference to auto inject arguments, or use implicit injection\n *   $injector.invoke(function($rootScope, $compile, $document) {\n *     $compile($document)($rootScope);\n *     $rootScope.$digest();\n *   });\n * ```\n *\n * Sometimes you want to get access to the injector of a currently running Angular app\n * from outside Angular. Perhaps, you want to inject and compile some markup after the\n * application has been bootstrapped. You can do this using the extra `injector()` added\n * to JQuery/jqLite elements. See {@link angular.element}.\n *\n * *This is fairly rare but could be the case if a third party library is injecting the\n * markup.*\n *\n * In the following example a new block of HTML containing a `ng-controller`\n * directive is added to the end of the document body by JQuery. We then compile and link\n * it into the current AngularJS scope.\n *\n * ```js\n * var $div = $('<div ng-controller=\"MyCtrl\">{{content.label}}</div>');\n * $(document.body).append($div);\n *\n * angular.element(document).injector().invoke(function($compile) {\n *   var scope = angular.element($div).scope();\n *   $compile($div)(scope);\n * });\n * ```\n */\n\n\n/**\n * @ngdoc module\n * @name auto\n * @description\n *\n * Implicit module which gets automatically added to each {@link auto.$injector $injector}.\n */\n\nvar FN_ARGS = /^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nvar $injectorMinErr = minErr('$injector');\n\nfunction anonFn(fn) {\n  // For anonymous functions, showing at the very least the function signature can help in\n  // debugging.\n  var fnText = fn.toString().replace(STRIP_COMMENTS, ''),\n      args = fnText.match(FN_ARGS);\n  if (args) {\n    return 'function(' + (args[1] || '').replace(/[\\s\\r\\n]+/, ' ') + ')';\n  }\n  return 'fn';\n}\n\nfunction annotate(fn, strictDi, name) {\n  var $inject,\n      fnText,\n      argDecl,\n      last;\n\n  if (typeof fn === 'function') {\n    if (!($inject = fn.$inject)) {\n      $inject = [];\n      if (fn.length) {\n        if (strictDi) {\n          if (!isString(name) || !name) {\n            name = fn.name || anonFn(fn);\n          }\n          throw $injectorMinErr('strictdi',\n            '{0} is not using explicit annotation and cannot be invoked in strict mode', name);\n        }\n        fnText = fn.toString().replace(STRIP_COMMENTS, '');\n        argDecl = fnText.match(FN_ARGS);\n        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n          arg.replace(FN_ARG, function(all, underscore, name) {\n            $inject.push(name);\n          });\n        });\n      }\n      fn.$inject = $inject;\n    }\n  } else if (isArray(fn)) {\n    last = fn.length - 1;\n    assertArgFn(fn[last], 'fn');\n    $inject = fn.slice(0, last);\n  } else {\n    assertArgFn(fn, 'fn', true);\n  }\n  return $inject;\n}\n\n///////////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $injector\n *\n * @description\n *\n * `$injector` is used to retrieve object instances as defined by\n * {@link auto.$provide provider}, instantiate types, invoke methods,\n * and load modules.\n *\n * The following always holds true:\n *\n * ```js\n *   var $injector = angular.injector();\n *   expect($injector.get('$injector')).toBe($injector);\n *   expect($injector.invoke(function($injector) {\n *     return $injector;\n *   })).toBe($injector);\n * ```\n *\n * # Injection Function Annotation\n *\n * JavaScript does not have annotations, and annotations are needed for dependency injection. The\n * following are all valid ways of annotating function with injection arguments and are equivalent.\n *\n * ```js\n *   // inferred (only works if code not minified/obfuscated)\n *   $injector.invoke(function(serviceA){});\n *\n *   // annotated\n *   function explicit(serviceA) {};\n *   explicit.$inject = ['serviceA'];\n *   $injector.invoke(explicit);\n *\n *   // inline\n *   $injector.invoke(['serviceA', function(serviceA){}]);\n * ```\n *\n * ## Inference\n *\n * In JavaScript calling `toString()` on a function returns the function definition. The definition\n * can then be parsed and the function arguments can be extracted. This method of discovering\n * annotations is disallowed when the injector is in strict mode.\n * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the\n * argument names.\n *\n * ## `$inject` Annotation\n * By adding an `$inject` property onto a function the injection parameters can be specified.\n *\n * ## Inline\n * As an array of injection names, where the last item in the array is the function to call.\n */\n\n/**\n * @ngdoc method\n * @name $injector#get\n *\n * @description\n * Return an instance of the service.\n *\n * @param {string} name The name of the instance to retrieve.\n * @param {string} caller An optional string to provide the origin of the function call for error messages.\n * @return {*} The instance.\n */\n\n/**\n * @ngdoc method\n * @name $injector#invoke\n *\n * @description\n * Invoke the method and supply the method arguments from the `$injector`.\n *\n * @param {!Function} fn The function to invoke. Function parameters are injected according to the\n *   {@link guide/di $inject Annotation} rules.\n * @param {Object=} self The `this` for the invoked method.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n *                         object first, before the `$injector` is consulted.\n * @returns {*} the value returned by the invoked `fn` function.\n */\n\n/**\n * @ngdoc method\n * @name $injector#has\n *\n * @description\n * Allows the user to query if the particular service exists.\n *\n * @param {string} name Name of the service to query.\n * @returns {boolean} `true` if injector has given service.\n */\n\n/**\n * @ngdoc method\n * @name $injector#instantiate\n * @description\n * Create a new instance of JS type. The method takes a constructor function, invokes the new\n * operator, and supplies all of the arguments to the constructor function as specified by the\n * constructor annotation.\n *\n * @param {Function} Type Annotated constructor function.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {Object} new instance of `Type`.\n */\n\n/**\n * @ngdoc method\n * @name $injector#annotate\n *\n * @description\n * Returns an array of service names which the function is requesting for injection. This API is\n * used by the injector to determine which services need to be injected into the function when the\n * function is invoked. There are three ways in which the function can be annotated with the needed\n * dependencies.\n *\n * # Argument names\n *\n * The simplest form is to extract the dependencies from the arguments of the function. This is done\n * by converting the function into a string using `toString()` method and extracting the argument\n * names.\n * ```js\n *   // Given\n *   function MyController($scope, $route) {\n *     // ...\n *   }\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * You can disallow this method by using strict injection mode.\n *\n * This method does not work with code minification / obfuscation. For this reason the following\n * annotation strategies are supported.\n *\n * # The `$inject` property\n *\n * If a function has an `$inject` property and its value is an array of strings, then the strings\n * represent names of services to be injected into the function.\n * ```js\n *   // Given\n *   var MyController = function(obfuscatedScope, obfuscatedRoute) {\n *     // ...\n *   }\n *   // Define function dependencies\n *   MyController['$inject'] = ['$scope', '$route'];\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * # The array notation\n *\n * It is often desirable to inline Injected functions and that's when setting the `$inject` property\n * is very inconvenient. In these situations using the array notation to specify the dependencies in\n * a way that survives minification is a better choice:\n *\n * ```js\n *   // We wish to write this (not minification / obfuscation safe)\n *   injector.invoke(function($compile, $rootScope) {\n *     // ...\n *   });\n *\n *   // We are forced to write break inlining\n *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {\n *     // ...\n *   };\n *   tmpFn.$inject = ['$compile', '$rootScope'];\n *   injector.invoke(tmpFn);\n *\n *   // To better support inline function the inline annotation is supported\n *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {\n *     // ...\n *   }]);\n *\n *   // Therefore\n *   expect(injector.annotate(\n *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])\n *    ).toEqual(['$compile', '$rootScope']);\n * ```\n *\n * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to\n * be retrieved as described above.\n *\n * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.\n *\n * @returns {Array.<string>} The names of the services which the function requires.\n */\n\n\n\n\n/**\n * @ngdoc service\n * @name $provide\n *\n * @description\n *\n * The {@link auto.$provide $provide} service has a number of methods for registering components\n * with the {@link auto.$injector $injector}. Many of these functions are also exposed on\n * {@link angular.Module}.\n *\n * An Angular **service** is a singleton object created by a **service factory**.  These **service\n * factories** are functions which, in turn, are created by a **service provider**.\n * The **service providers** are constructor functions. When instantiated they must contain a\n * property called `$get`, which holds the **service factory** function.\n *\n * When you request a service, the {@link auto.$injector $injector} is responsible for finding the\n * correct **service provider**, instantiating it and then calling its `$get` **service factory**\n * function to get the instance of the **service**.\n *\n * Often services have no configuration options and there is no need to add methods to the service\n * provider.  The provider will be no more than a constructor function with a `$get` property. For\n * these cases the {@link auto.$provide $provide} service has additional helper methods to register\n * services without specifying a provider.\n *\n * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the\n *     {@link auto.$injector $injector}\n * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by\n *     providers and services.\n * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by\n *     services, not providers.\n * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,\n *     that will be wrapped in a **service provider** object, whose `$get` property will contain the\n *     given factory function.\n * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`\n *     that will be wrapped in a **service provider** object, whose `$get` property will instantiate\n *      a new object using the given constructor function.\n *\n * See the individual methods for more information and examples.\n */\n\n/**\n * @ngdoc method\n * @name $provide#provider\n * @description\n *\n * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions\n * are constructor functions, whose instances are responsible for \"providing\" a factory for a\n * service.\n *\n * Service provider names start with the name of the service they provide followed by `Provider`.\n * For example, the {@link ng.$log $log} service has a provider called\n * {@link ng.$logProvider $logProvider}.\n *\n * Service provider objects can have additional methods which allow configuration of the provider\n * and its service. Importantly, you can configure what kind of service is created by the `$get`\n * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a\n * method {@link ng.$logProvider#debugEnabled debugEnabled}\n * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the\n * console or not.\n *\n * @param {string} name The name of the instance. NOTE: the provider will be available under `name +\n                        'Provider'` key.\n * @param {(Object|function())} provider If the provider is:\n *\n *   - `Object`: then it should have a `$get` method. The `$get` method will be invoked using\n *     {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.\n *   - `Constructor`: a new instance of the provider will be created using\n *     {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.\n *\n * @returns {Object} registered provider instance\n\n * @example\n *\n * The following example shows how to create a simple event tracking service and register it using\n * {@link auto.$provide#provider $provide.provider()}.\n *\n * ```js\n *  // Define the eventTracker provider\n *  function EventTrackerProvider() {\n *    var trackingUrl = '/track';\n *\n *    // A provider method for configuring where the tracked events should been saved\n *    this.setTrackingUrl = function(url) {\n *      trackingUrl = url;\n *    };\n *\n *    // The service factory function\n *    this.$get = ['$http', function($http) {\n *      var trackedEvents = {};\n *      return {\n *        // Call this to track an event\n *        event: function(event) {\n *          var count = trackedEvents[event] || 0;\n *          count += 1;\n *          trackedEvents[event] = count;\n *          return count;\n *        },\n *        // Call this to save the tracked events to the trackingUrl\n *        save: function() {\n *          $http.post(trackingUrl, trackedEvents);\n *        }\n *      };\n *    }];\n *  }\n *\n *  describe('eventTracker', function() {\n *    var postSpy;\n *\n *    beforeEach(module(function($provide) {\n *      // Register the eventTracker provider\n *      $provide.provider('eventTracker', EventTrackerProvider);\n *    }));\n *\n *    beforeEach(module(function(eventTrackerProvider) {\n *      // Configure eventTracker provider\n *      eventTrackerProvider.setTrackingUrl('/custom-track');\n *    }));\n *\n *    it('tracks events', inject(function(eventTracker) {\n *      expect(eventTracker.event('login')).toEqual(1);\n *      expect(eventTracker.event('login')).toEqual(2);\n *    }));\n *\n *    it('saves to the tracking url', inject(function(eventTracker, $http) {\n *      postSpy = spyOn($http, 'post');\n *      eventTracker.event('login');\n *      eventTracker.save();\n *      expect(postSpy).toHaveBeenCalled();\n *      expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');\n *      expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');\n *      expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });\n *    }));\n *  });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $provide#factory\n * @description\n *\n * Register a **service factory**, which will be called to return the service instance.\n * This is short for registering a service where its provider consists of only a `$get` property,\n * which is the given service factory function.\n * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to\n * configure your service in a provider.\n *\n * @param {string} name The name of the instance.\n * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand\n *                            for `$provide.provider(name, {$get: $getFn})`.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service\n * ```js\n *   $provide.factory('ping', ['$http', function($http) {\n *     return function ping() {\n *       return $http.send('/ping');\n *     };\n *   }]);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#service\n * @description\n *\n * Register a **service constructor**, which will be invoked with `new` to create the service\n * instance.\n * This is short for registering a service where its provider's `$get` property is the service\n * constructor function that will be used to instantiate the service instance.\n *\n * You should use {@link auto.$provide#service $provide.service(class)} if you define your service\n * as a type/class.\n *\n * @param {string} name The name of the instance.\n * @param {Function} constructor A class (constructor function) that will be instantiated.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service using\n * {@link auto.$provide#service $provide.service(class)}.\n * ```js\n *   var Ping = function($http) {\n *     this.$http = $http;\n *   };\n *\n *   Ping.$inject = ['$http'];\n *\n *   Ping.prototype.send = function() {\n *     return this.$http.get('/ping');\n *   };\n *   $provide.service('ping', Ping);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping.send();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#value\n * @description\n *\n * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a\n * number, an array, an object or a function.  This is short for registering a service where its\n * provider's `$get` property is a factory function that takes no arguments and returns the **value\n * service**.\n *\n * Value services are similar to constant services, except that they cannot be injected into a\n * module configuration function (see {@link angular.Module#config}) but they can be overridden by\n * an Angular\n * {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the instance.\n * @param {*} value The value.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here are some examples of creating value services.\n * ```js\n *   $provide.value('ADMIN_USER', 'admin');\n *\n *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });\n *\n *   $provide.value('halfOf', function(value) {\n *     return value / 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#constant\n * @description\n *\n * Register a **constant service**, such as a string, a number, an array, an object or a function,\n * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be\n * injected into a module configuration function (see {@link angular.Module#config}) and it cannot\n * be overridden by an Angular {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the constant.\n * @param {*} value The constant value.\n * @returns {Object} registered instance\n *\n * @example\n * Here a some examples of creating constants:\n * ```js\n *   $provide.constant('SHARD_HEIGHT', 306);\n *\n *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);\n *\n *   $provide.constant('double', function(value) {\n *     return value * 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#decorator\n * @description\n *\n * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator\n * intercepts the creation of a service, allowing it to override or modify the behaviour of the\n * service. The object returned by the decorator may be the original service, or a new service\n * object which replaces or wraps and delegates to the original service.\n *\n * @param {string} name The name of the service to decorate.\n * @param {function()} decorator This function will be invoked when the service needs to be\n *    instantiated and should return the decorated service instance. The function is called using\n *    the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.\n *    Local injection arguments:\n *\n *    * `$delegate` - The original service instance, which can be monkey patched, configured,\n *      decorated or delegated to.\n *\n * @example\n * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting\n * calls to {@link ng.$log#error $log.warn()}.\n * ```js\n *   $provide.decorator('$log', ['$delegate', function($delegate) {\n *     $delegate.warn = $delegate.error;\n *     return $delegate;\n *   }]);\n * ```\n */\n\n\nfunction createInjector(modulesToLoad, strictDi) {\n  strictDi = (strictDi === true);\n  var INSTANTIATING = {},\n      providerSuffix = 'Provider',\n      path = [],\n      loadedModules = new HashMap([], true),\n      providerCache = {\n        $provide: {\n            provider: supportObject(provider),\n            factory: supportObject(factory),\n            service: supportObject(service),\n            value: supportObject(value),\n            constant: supportObject(constant),\n            decorator: decorator\n          }\n      },\n      providerInjector = (providerCache.$injector =\n          createInternalInjector(providerCache, function(serviceName, caller) {\n            if (angular.isString(caller)) {\n              path.push(caller);\n            }\n            throw $injectorMinErr('unpr', \"Unknown provider: {0}\", path.join(' <- '));\n          })),\n      instanceCache = {},\n      instanceInjector = (instanceCache.$injector =\n          createInternalInjector(instanceCache, function(serviceName, caller) {\n            var provider = providerInjector.get(serviceName + providerSuffix, caller);\n            return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);\n          }));\n\n\n  forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });\n\n  return instanceInjector;\n\n  ////////////////////////////////////\n  // $provider\n  ////////////////////////////////////\n\n  function supportObject(delegate) {\n    return function(key, value) {\n      if (isObject(key)) {\n        forEach(key, reverseParams(delegate));\n      } else {\n        return delegate(key, value);\n      }\n    };\n  }\n\n  function provider(name, provider_) {\n    assertNotHasOwnProperty(name, 'service');\n    if (isFunction(provider_) || isArray(provider_)) {\n      provider_ = providerInjector.instantiate(provider_);\n    }\n    if (!provider_.$get) {\n      throw $injectorMinErr('pget', \"Provider '{0}' must define $get factory method.\", name);\n    }\n    return providerCache[name + providerSuffix] = provider_;\n  }\n\n  function enforceReturnValue(name, factory) {\n    return function enforcedReturnValue() {\n      var result = instanceInjector.invoke(factory, this);\n      if (isUndefined(result)) {\n        throw $injectorMinErr('undef', \"Provider '{0}' must return a value from $get factory method.\", name);\n      }\n      return result;\n    };\n  }\n\n  function factory(name, factoryFn, enforce) {\n    return provider(name, {\n      $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn\n    });\n  }\n\n  function service(name, constructor) {\n    return factory(name, ['$injector', function($injector) {\n      return $injector.instantiate(constructor);\n    }]);\n  }\n\n  function value(name, val) { return factory(name, valueFn(val), false); }\n\n  function constant(name, value) {\n    assertNotHasOwnProperty(name, 'constant');\n    providerCache[name] = value;\n    instanceCache[name] = value;\n  }\n\n  function decorator(serviceName, decorFn) {\n    var origProvider = providerInjector.get(serviceName + providerSuffix),\n        orig$get = origProvider.$get;\n\n    origProvider.$get = function() {\n      var origInstance = instanceInjector.invoke(orig$get, origProvider);\n      return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});\n    };\n  }\n\n  ////////////////////////////////////\n  // Module Loading\n  ////////////////////////////////////\n  function loadModules(modulesToLoad) {\n    var runBlocks = [], moduleFn;\n    forEach(modulesToLoad, function(module) {\n      if (loadedModules.get(module)) return;\n      loadedModules.put(module, true);\n\n      function runInvokeQueue(queue) {\n        var i, ii;\n        for (i = 0, ii = queue.length; i < ii; i++) {\n          var invokeArgs = queue[i],\n              provider = providerInjector.get(invokeArgs[0]);\n\n          provider[invokeArgs[1]].apply(provider, invokeArgs[2]);\n        }\n      }\n\n      try {\n        if (isString(module)) {\n          moduleFn = angularModule(module);\n          runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);\n          runInvokeQueue(moduleFn._invokeQueue);\n          runInvokeQueue(moduleFn._configBlocks);\n        } else if (isFunction(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else if (isArray(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else {\n          assertArgFn(module, 'module');\n        }\n      } catch (e) {\n        if (isArray(module)) {\n          module = module[module.length - 1];\n        }\n        if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {\n          // Safari & FF's stack traces don't contain error.message content\n          // unlike those of Chrome and IE\n          // So if stack doesn't contain message, we create a new string that contains both.\n          // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.\n          /* jshint -W022 */\n          e = e.message + '\\n' + e.stack;\n        }\n        throw $injectorMinErr('modulerr', \"Failed to instantiate module {0} due to:\\n{1}\",\n                  module, e.stack || e.message || e);\n      }\n    });\n    return runBlocks;\n  }\n\n  ////////////////////////////////////\n  // internal Injector\n  ////////////////////////////////////\n\n  function createInternalInjector(cache, factory) {\n\n    function getService(serviceName, caller) {\n      if (cache.hasOwnProperty(serviceName)) {\n        if (cache[serviceName] === INSTANTIATING) {\n          throw $injectorMinErr('cdep', 'Circular dependency found: {0}',\n                    serviceName + ' <- ' + path.join(' <- '));\n        }\n        return cache[serviceName];\n      } else {\n        try {\n          path.unshift(serviceName);\n          cache[serviceName] = INSTANTIATING;\n          return cache[serviceName] = factory(serviceName, caller);\n        } catch (err) {\n          if (cache[serviceName] === INSTANTIATING) {\n            delete cache[serviceName];\n          }\n          throw err;\n        } finally {\n          path.shift();\n        }\n      }\n    }\n\n    function invoke(fn, self, locals, serviceName) {\n      if (typeof locals === 'string') {\n        serviceName = locals;\n        locals = null;\n      }\n\n      var args = [],\n          $inject = createInjector.$$annotate(fn, strictDi, serviceName),\n          length, i,\n          key;\n\n      for (i = 0, length = $inject.length; i < length; i++) {\n        key = $inject[i];\n        if (typeof key !== 'string') {\n          throw $injectorMinErr('itkn',\n                  'Incorrect injection token! Expected service name as string, got {0}', key);\n        }\n        args.push(\n          locals && locals.hasOwnProperty(key)\n          ? locals[key]\n          : getService(key, serviceName)\n        );\n      }\n      if (isArray(fn)) {\n        fn = fn[length];\n      }\n\n      // http://jsperf.com/angularjs-invoke-apply-vs-switch\n      // #5388\n      return fn.apply(self, args);\n    }\n\n    function instantiate(Type, locals, serviceName) {\n      // Check if Type is annotated and use just the given function at n-1 as parameter\n      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);\n      // Object creation: http://jsperf.com/create-constructor/2\n      var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);\n      var returnedValue = invoke(Type, instance, locals, serviceName);\n\n      return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;\n    }\n\n    return {\n      invoke: invoke,\n      instantiate: instantiate,\n      get: getService,\n      annotate: createInjector.$$annotate,\n      has: function(name) {\n        return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);\n      }\n    };\n  }\n}\n\ncreateInjector.$$annotate = annotate;\n\n/**\n * @ngdoc provider\n * @name $anchorScrollProvider\n *\n * @description\n * Use `$anchorScrollProvider` to disable automatic scrolling whenever\n * {@link ng.$location#hash $location.hash()} changes.\n */\nfunction $AnchorScrollProvider() {\n\n  var autoScrollingEnabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $anchorScrollProvider#disableAutoScrolling\n   *\n   * @description\n   * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to\n   * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />\n   * Use this method to disable automatic scrolling.\n   *\n   * If automatic scrolling is disabled, one must explicitly call\n   * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the\n   * current hash.\n   */\n  this.disableAutoScrolling = function() {\n    autoScrollingEnabled = false;\n  };\n\n  /**\n   * @ngdoc service\n   * @name $anchorScroll\n   * @kind function\n   * @requires $window\n   * @requires $location\n   * @requires $rootScope\n   *\n   * @description\n   * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and\n   * scrolls to the related element, according to the rules specified in the\n   * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).\n   *\n   * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to\n   * match any anchor whenever it changes. This can be disabled by calling\n   * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.\n   *\n   * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a\n   * vertical scroll-offset (either fixed or dynamic).\n   *\n   * @property {(number|function|jqLite)} yOffset\n   * If set, specifies a vertical scroll-offset. This is often useful when there are fixed\n   * positioned elements at the top of the page, such as navbars, headers etc.\n   *\n   * `yOffset` can be specified in various ways:\n   * - **number**: A fixed number of pixels to be used as offset.<br /><br />\n   * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return\n   *   a number representing the offset (in pixels).<br /><br />\n   * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from\n   *   the top of the page to the element's bottom will be used as offset.<br />\n   *   **Note**: The element will be taken into account only as long as its `position` is set to\n   *   `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust\n   *   their height and/or positioning according to the viewport's size.\n   *\n   * <br />\n   * <div class=\"alert alert-warning\">\n   * In order for `yOffset` to work properly, scrolling should take place on the document's root and\n   * not some child element.\n   * </div>\n   *\n   * @example\n     <example module=\"anchorScrollExample\">\n       <file name=\"index.html\">\n         <div id=\"scrollArea\" ng-controller=\"ScrollController\">\n           <a ng-click=\"gotoBottom()\">Go to bottom</a>\n           <a id=\"bottom\"></a> You're at the bottom!\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollExample', [])\n           .controller('ScrollController', ['$scope', '$location', '$anchorScroll',\n             function ($scope, $location, $anchorScroll) {\n               $scope.gotoBottom = function() {\n                 // set the location.hash to the id of\n                 // the element you wish to scroll to.\n                 $location.hash('bottom');\n\n                 // call $anchorScroll()\n                 $anchorScroll();\n               };\n             }]);\n       </file>\n       <file name=\"style.css\">\n         #scrollArea {\n           height: 280px;\n           overflow: auto;\n         }\n\n         #bottom {\n           display: block;\n           margin-top: 2000px;\n         }\n       </file>\n     </example>\n   *\n   * <hr />\n   * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).\n   * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.\n   *\n   * @example\n     <example module=\"anchorScrollOffsetExample\">\n       <file name=\"index.html\">\n         <div class=\"fixed-header\" ng-controller=\"headerCtrl\">\n           <a href=\"\" ng-click=\"gotoAnchor(x)\" ng-repeat=\"x in [1,2,3,4,5]\">\n             Go to anchor {{x}}\n           </a>\n         </div>\n         <div id=\"anchor{{x}}\" class=\"anchor\" ng-repeat=\"x in [1,2,3,4,5]\">\n           Anchor {{x}} of 5\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollOffsetExample', [])\n           .run(['$anchorScroll', function($anchorScroll) {\n             $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels\n           }])\n           .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',\n             function ($anchorScroll, $location, $scope) {\n               $scope.gotoAnchor = function(x) {\n                 var newHash = 'anchor' + x;\n                 if ($location.hash() !== newHash) {\n                   // set the $location.hash to `newHash` and\n                   // $anchorScroll will automatically scroll to it\n                   $location.hash('anchor' + x);\n                 } else {\n                   // call $anchorScroll() explicitly,\n                   // since $location.hash hasn't changed\n                   $anchorScroll();\n                 }\n               };\n             }\n           ]);\n       </file>\n       <file name=\"style.css\">\n         body {\n           padding-top: 50px;\n         }\n\n         .anchor {\n           border: 2px dashed DarkOrchid;\n           padding: 10px 10px 200px 10px;\n         }\n\n         .fixed-header {\n           background-color: rgba(0, 0, 0, 0.2);\n           height: 50px;\n           position: fixed;\n           top: 0; left: 0; right: 0;\n         }\n\n         .fixed-header > a {\n           display: inline-block;\n           margin: 5px 15px;\n         }\n       </file>\n     </example>\n   */\n  this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {\n    var document = $window.document;\n\n    // Helper function to get first anchor from a NodeList\n    // (using `Array#some()` instead of `angular#forEach()` since it's more performant\n    //  and working in all supported browsers.)\n    function getFirstAnchor(list) {\n      var result = null;\n      Array.prototype.some.call(list, function(element) {\n        if (nodeName_(element) === 'a') {\n          result = element;\n          return true;\n        }\n      });\n      return result;\n    }\n\n    function getYOffset() {\n\n      var offset = scroll.yOffset;\n\n      if (isFunction(offset)) {\n        offset = offset();\n      } else if (isElement(offset)) {\n        var elem = offset[0];\n        var style = $window.getComputedStyle(elem);\n        if (style.position !== 'fixed') {\n          offset = 0;\n        } else {\n          offset = elem.getBoundingClientRect().bottom;\n        }\n      } else if (!isNumber(offset)) {\n        offset = 0;\n      }\n\n      return offset;\n    }\n\n    function scrollTo(elem) {\n      if (elem) {\n        elem.scrollIntoView();\n\n        var offset = getYOffset();\n\n        if (offset) {\n          // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.\n          // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the\n          // top of the viewport.\n          //\n          // IF the number of pixels from the top of `elem` to the end of the page's content is less\n          // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some\n          // way down the page.\n          //\n          // This is often the case for elements near the bottom of the page.\n          //\n          // In such cases we do not need to scroll the whole `offset` up, just the difference between\n          // the top of the element and the offset, which is enough to align the top of `elem` at the\n          // desired position.\n          var elemTop = elem.getBoundingClientRect().top;\n          $window.scrollBy(0, elemTop - offset);\n        }\n      } else {\n        $window.scrollTo(0, 0);\n      }\n    }\n\n    function scroll() {\n      var hash = $location.hash(), elm;\n\n      // empty hash, scroll to the top of the page\n      if (!hash) scrollTo(null);\n\n      // element with given id\n      else if ((elm = document.getElementById(hash))) scrollTo(elm);\n\n      // first anchor with given name :-D\n      else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);\n\n      // no element and hash == 'top', scroll to the top of the page\n      else if (hash === 'top') scrollTo(null);\n    }\n\n    // does not scroll when user clicks on anchor link that is currently on\n    // (no url change, no $location.hash() change), browser native does scroll\n    if (autoScrollingEnabled) {\n      $rootScope.$watch(function autoScrollWatch() {return $location.hash();},\n        function autoScrollWatchAction(newVal, oldVal) {\n          // skip the initial scroll if $location.hash is empty\n          if (newVal === oldVal && newVal === '') return;\n\n          jqLiteDocumentLoaded(function() {\n            $rootScope.$evalAsync(scroll);\n          });\n        });\n    }\n\n    return scroll;\n  }];\n}\n\nvar $animateMinErr = minErr('$animate');\n\n/**\n * @ngdoc provider\n * @name $animateProvider\n *\n * @description\n * Default implementation of $animate that doesn't perform any animations, instead just\n * synchronously performs DOM\n * updates and calls done() callbacks.\n *\n * In order to enable animations the ngAnimate module has to be loaded.\n *\n * To see the functional implementation check out src/ngAnimate/animate.js\n */\nvar $AnimateProvider = ['$provide', function($provide) {\n\n\n  this.$$selectors = {};\n\n\n  /**\n   * @ngdoc method\n   * @name $animateProvider#register\n   *\n   * @description\n   * Registers a new injectable animation factory function. The factory function produces the\n   * animation object which contains callback functions for each event that is expected to be\n   * animated.\n   *\n   *   * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`\n   *   must be called once the element animation is complete. If a function is returned then the\n   *   animation service will use this function to cancel the animation whenever a cancel event is\n   *   triggered.\n   *\n   *\n   * ```js\n   *   return {\n     *     eventFn : function(element, done) {\n     *       //code to run the animation\n     *       //once complete, then run done()\n     *       return function cancellationFunction() {\n     *         //code to cancel the animation\n     *       }\n     *     }\n     *   }\n   * ```\n   *\n   * @param {string} name The name of the animation.\n   * @param {Function} factory The factory function that will be executed to return the animation\n   *                           object.\n   */\n  this.register = function(name, factory) {\n    var key = name + '-animation';\n    if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',\n        \"Expecting class selector starting with '.' got '{0}'.\", name);\n    this.$$selectors[name.substr(1)] = key;\n    $provide.factory(key, factory);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $animateProvider#classNameFilter\n   *\n   * @description\n   * Sets and/or returns the CSS class regular expression that is checked when performing\n   * an animation. Upon bootstrap the classNameFilter value is not set at all and will\n   * therefore enable $animate to attempt to perform an animation on any element.\n   * When setting the classNameFilter value, animations will only be performed on elements\n   * that successfully match the filter expression. This in turn can boost performance\n   * for low-powered devices as well as applications containing a lot of structural operations.\n   * @param {RegExp=} expression The className expression which will be checked against all animations\n   * @return {RegExp} The current CSS className expression value. If null then there is no expression value\n   */\n  this.classNameFilter = function(expression) {\n    if (arguments.length === 1) {\n      this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;\n    }\n    return this.$$classNameFilter;\n  };\n\n  this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {\n\n    var currentDefer;\n\n    function runAnimationPostDigest(fn) {\n      var cancelFn, defer = $$q.defer();\n      defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {\n        cancelFn && cancelFn();\n      };\n\n      $rootScope.$$postDigest(function ngAnimatePostDigest() {\n        cancelFn = fn(function ngAnimateNotifyComplete() {\n          defer.resolve();\n        });\n      });\n\n      return defer.promise;\n    }\n\n    function resolveElementClasses(element, classes) {\n      var toAdd = [], toRemove = [];\n\n      var hasClasses = createMap();\n      forEach((element.attr('class') || '').split(/\\s+/), function(className) {\n        hasClasses[className] = true;\n      });\n\n      forEach(classes, function(status, className) {\n        var hasClass = hasClasses[className];\n\n        // If the most recent class manipulation (via $animate) was to remove the class, and the\n        // element currently has the class, the class is scheduled for removal. Otherwise, if\n        // the most recent class manipulation (via $animate) was to add the class, and the\n        // element does not currently have the class, the class is scheduled to be added.\n        if (status === false && hasClass) {\n          toRemove.push(className);\n        } else if (status === true && !hasClass) {\n          toAdd.push(className);\n        }\n      });\n\n      return (toAdd.length + toRemove.length) > 0 &&\n        [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];\n    }\n\n    function cachedClassManipulation(cache, classes, op) {\n      for (var i=0, ii = classes.length; i < ii; ++i) {\n        var className = classes[i];\n        cache[className] = op;\n      }\n    }\n\n    function asyncPromise() {\n      // only serve one instance of a promise in order to save CPU cycles\n      if (!currentDefer) {\n        currentDefer = $$q.defer();\n        $$asyncCallback(function() {\n          currentDefer.resolve();\n          currentDefer = null;\n        });\n      }\n      return currentDefer.promise;\n    }\n\n    function applyStyles(element, options) {\n      if (angular.isObject(options)) {\n        var styles = extend(options.from || {}, options.to || {});\n        element.css(styles);\n      }\n    }\n\n    /**\n     *\n     * @ngdoc service\n     * @name $animate\n     * @description The $animate service provides rudimentary DOM manipulation functions to\n     * insert, remove and move elements within the DOM, as well as adding and removing classes.\n     * This service is the core service used by the ngAnimate $animator service which provides\n     * high-level animation hooks for CSS and JavaScript.\n     *\n     * $animate is available in the AngularJS core, however, the ngAnimate module must be included\n     * to enable full out animation support. Otherwise, $animate will only perform simple DOM\n     * manipulation operations.\n     *\n     * To learn more about enabling animation support, click here to visit the {@link ngAnimate\n     * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service\n     * page}.\n     */\n    return {\n      animate: function(element, from, to) {\n        applyStyles(element, { from: from, to: to });\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#enter\n       * @kind function\n       * @description Inserts the element into the DOM either after the `after` element or\n       * as the first child within the `parent` element. When the function is called a promise\n       * is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will be inserted into the DOM\n       * @param {DOMElement} parent the parent element which will append the element as\n       *   a child (if the after element is not present)\n       * @param {DOMElement} after the sibling element which will append the element\n       *   after itself\n       * @param {object=} options an optional collection of styles that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      enter: function(element, parent, after, options) {\n        applyStyles(element, options);\n        after ? after.after(element)\n              : parent.prepend(element);\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#leave\n       * @kind function\n       * @description Removes the element from the DOM. When the function is called a promise\n       * is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will be removed from the DOM\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      leave: function(element, options) {\n        element.remove();\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#move\n       * @kind function\n       * @description Moves the position of the provided element within the DOM to be placed\n       * either after the `after` element or inside of the `parent` element. When the function\n       * is called a promise is returned that will be resolved at a later time.\n       *\n       * @param {DOMElement} element the element which will be moved around within the\n       *   DOM\n       * @param {DOMElement} parent the parent element where the element will be\n       *   inserted into (if the after element is not present)\n       * @param {DOMElement} after the sibling element where the element will be\n       *   positioned next to\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      move: function(element, parent, after, options) {\n        // Do not remove element before insert. Removing will cause data associated with the\n        // element to be dropped. Insert will implicitly do the remove.\n        return this.enter(element, parent, after, options);\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#addClass\n       * @kind function\n       * @description Adds the provided className CSS class value to the provided element.\n       * When the function is called a promise is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will have the className value\n       *   added to it\n       * @param {string} className the CSS class which will be added to the element\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      addClass: function(element, className, options) {\n        return this.setClass(element, className, [], options);\n      },\n\n      $$addClassImmediately: function(element, className, options) {\n        element = jqLite(element);\n        className = !isString(className)\n                        ? (isArray(className) ? className.join(' ') : '')\n                        : className;\n        forEach(element, function(element) {\n          jqLiteAddClass(element, className);\n        });\n        applyStyles(element, options);\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#removeClass\n       * @kind function\n       * @description Removes the provided className CSS class value from the provided element.\n       * When the function is called a promise is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will have the className value\n       *   removed from it\n       * @param {string} className the CSS class which will be removed from the element\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      removeClass: function(element, className, options) {\n        return this.setClass(element, [], className, options);\n      },\n\n      $$removeClassImmediately: function(element, className, options) {\n        element = jqLite(element);\n        className = !isString(className)\n                        ? (isArray(className) ? className.join(' ') : '')\n                        : className;\n        forEach(element, function(element) {\n          jqLiteRemoveClass(element, className);\n        });\n        applyStyles(element, options);\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#setClass\n       * @kind function\n       * @description Adds and/or removes the given CSS classes to and from the element.\n       * When the function is called a promise is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will have its CSS classes changed\n       *   removed from it\n       * @param {string} add the CSS classes which will be added to the element\n       * @param {string} remove the CSS class which will be removed from the element\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      setClass: function(element, add, remove, options) {\n        var self = this;\n        var STORAGE_KEY = '$$animateClasses';\n        var createdCache = false;\n        element = jqLite(element);\n\n        var cache = element.data(STORAGE_KEY);\n        if (!cache) {\n          cache = {\n            classes: {},\n            options: options\n          };\n          createdCache = true;\n        } else if (options && cache.options) {\n          cache.options = angular.extend(cache.options || {}, options);\n        }\n\n        var classes = cache.classes;\n\n        add = isArray(add) ? add : add.split(' ');\n        remove = isArray(remove) ? remove : remove.split(' ');\n        cachedClassManipulation(classes, add, true);\n        cachedClassManipulation(classes, remove, false);\n\n        if (createdCache) {\n          cache.promise = runAnimationPostDigest(function(done) {\n            var cache = element.data(STORAGE_KEY);\n            element.removeData(STORAGE_KEY);\n\n            // in the event that the element is removed before postDigest\n            // is run then the cache will be undefined and there will be\n            // no need anymore to add or remove and of the element classes\n            if (cache) {\n              var classes = resolveElementClasses(element, cache.classes);\n              if (classes) {\n                self.$$setClassImmediately(element, classes[0], classes[1], cache.options);\n              }\n            }\n\n            done();\n          });\n          element.data(STORAGE_KEY, cache);\n        }\n\n        return cache.promise;\n      },\n\n      $$setClassImmediately: function(element, add, remove, options) {\n        add && this.$$addClassImmediately(element, add);\n        remove && this.$$removeClassImmediately(element, remove);\n        applyStyles(element, options);\n        return asyncPromise();\n      },\n\n      enabled: noop,\n      cancel: noop\n    };\n  }];\n}];\n\nfunction $$AsyncCallbackProvider() {\n  this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {\n    return $$rAF.supported\n      ? function(fn) { return $$rAF(fn); }\n      : function(fn) {\n        return $timeout(fn, 0, false);\n      };\n  }];\n}\n\n/* global stripHash: true */\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n * @requires $log\n * @description\n * This object has two goals:\n *\n * - hide all the global state in the browser caused by the window object\n * - abstract away all the browser specific features and inconsistencies\n *\n * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`\n * service, which can be used for convenient testing of the application without the interaction with\n * the real browser apis.\n */\n/**\n * @param {object} window The global window object.\n * @param {object} document jQuery wrapped document.\n * @param {object} $log window.console or an object with the same interface.\n * @param {object} $sniffer $sniffer service\n */\nfunction Browser(window, document, $log, $sniffer) {\n  var self = this,\n      rawDocument = document[0],\n      location = window.location,\n      history = window.history,\n      setTimeout = window.setTimeout,\n      clearTimeout = window.clearTimeout,\n      pendingDeferIds = {};\n\n  self.isMock = false;\n\n  var outstandingRequestCount = 0;\n  var outstandingRequestCallbacks = [];\n\n  // TODO(vojta): remove this temporary api\n  self.$$completeOutstandingRequest = completeOutstandingRequest;\n  self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };\n\n  /**\n   * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`\n   * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.\n   */\n  function completeOutstandingRequest(fn) {\n    try {\n      fn.apply(null, sliceArgs(arguments, 1));\n    } finally {\n      outstandingRequestCount--;\n      if (outstandingRequestCount === 0) {\n        while (outstandingRequestCallbacks.length) {\n          try {\n            outstandingRequestCallbacks.pop()();\n          } catch (e) {\n            $log.error(e);\n          }\n        }\n      }\n    }\n  }\n\n  function getHash(url) {\n    var index = url.indexOf('#');\n    return index === -1 ? '' : url.substr(index + 1);\n  }\n\n  /**\n   * @private\n   * Note: this method is used only by scenario runner\n   * TODO(vojta): prefix this method with $$ ?\n   * @param {function()} callback Function that will be called when no outstanding request\n   */\n  self.notifyWhenNoOutstandingRequests = function(callback) {\n    // force browser to execute all pollFns - this is needed so that cookies and other pollers fire\n    // at some deterministic time in respect to the test runner's actions. Leaving things up to the\n    // regular poller would result in flaky tests.\n    forEach(pollFns, function(pollFn) { pollFn(); });\n\n    if (outstandingRequestCount === 0) {\n      callback();\n    } else {\n      outstandingRequestCallbacks.push(callback);\n    }\n  };\n\n  //////////////////////////////////////////////////////////////\n  // Poll Watcher API\n  //////////////////////////////////////////////////////////////\n  var pollFns = [],\n      pollTimeout;\n\n  /**\n   * @name $browser#addPollFn\n   *\n   * @param {function()} fn Poll function to add\n   *\n   * @description\n   * Adds a function to the list of functions that poller periodically executes,\n   * and starts polling if not started yet.\n   *\n   * @returns {function()} the added function\n   */\n  self.addPollFn = function(fn) {\n    if (isUndefined(pollTimeout)) startPoller(100, setTimeout);\n    pollFns.push(fn);\n    return fn;\n  };\n\n  /**\n   * @param {number} interval How often should browser call poll functions (ms)\n   * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.\n   *\n   * @description\n   * Configures the poller to run in the specified intervals, using the specified\n   * setTimeout fn and kicks it off.\n   */\n  function startPoller(interval, setTimeout) {\n    (function check() {\n      forEach(pollFns, function(pollFn) { pollFn(); });\n      pollTimeout = setTimeout(check, interval);\n    })();\n  }\n\n  //////////////////////////////////////////////////////////////\n  // URL API\n  //////////////////////////////////////////////////////////////\n\n  var cachedState, lastHistoryState,\n      lastBrowserUrl = location.href,\n      baseElement = document.find('base'),\n      reloadLocation = null;\n\n  cacheState();\n  lastHistoryState = cachedState;\n\n  /**\n   * @name $browser#url\n   *\n   * @description\n   * GETTER:\n   * Without any argument, this method just returns current value of location.href.\n   *\n   * SETTER:\n   * With at least one argument, this method sets url to new value.\n   * If html5 history api supported, pushState/replaceState is used, otherwise\n   * location.href/location.replace is used.\n   * Returns its own instance to allow chaining\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to change url.\n   *\n   * @param {string} url New url (when used as setter)\n   * @param {boolean=} replace Should new url replace current history record?\n   * @param {object=} state object to use with pushState/replaceState\n   */\n  self.url = function(url, replace, state) {\n    // In modern browsers `history.state` is `null` by default; treating it separately\n    // from `undefined` would cause `$browser.url('/foo')` to change `history.state`\n    // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.\n    if (isUndefined(state)) {\n      state = null;\n    }\n\n    // Android Browser BFCache causes location, history reference to become stale.\n    if (location !== window.location) location = window.location;\n    if (history !== window.history) history = window.history;\n\n    // setter\n    if (url) {\n      var sameState = lastHistoryState === state;\n\n      // Don't change anything if previous and current URLs and states match. This also prevents\n      // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.\n      // See https://github.com/angular/angular.js/commit/ffb2701\n      if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {\n        return self;\n      }\n      var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);\n      lastBrowserUrl = url;\n      lastHistoryState = state;\n      // Don't use history API if only the hash changed\n      // due to a bug in IE10/IE11 which leads\n      // to not firing a `hashchange` nor `popstate` event\n      // in some cases (see #9143).\n      if ($sniffer.history && (!sameBase || !sameState)) {\n        history[replace ? 'replaceState' : 'pushState'](state, '', url);\n        cacheState();\n        // Do the assignment again so that those two variables are referentially identical.\n        lastHistoryState = cachedState;\n      } else {\n        if (!sameBase) {\n          reloadLocation = url;\n        }\n        if (replace) {\n          location.replace(url);\n        } else if (!sameBase) {\n          location.href = url;\n        } else {\n          location.hash = getHash(url);\n        }\n      }\n      return self;\n    // getter\n    } else {\n      // - reloadLocation is needed as browsers don't allow to read out\n      //   the new location.href if a reload happened.\n      // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172\n      return reloadLocation || location.href.replace(/%27/g,\"'\");\n    }\n  };\n\n  /**\n   * @name $browser#state\n   *\n   * @description\n   * This method is a getter.\n   *\n   * Return history.state or null if history.state is undefined.\n   *\n   * @returns {object} state\n   */\n  self.state = function() {\n    return cachedState;\n  };\n\n  var urlChangeListeners = [],\n      urlChangeInit = false;\n\n  function cacheStateAndFireUrlChange() {\n    cacheState();\n    fireUrlChange();\n  }\n\n  // This variable should be used *only* inside the cacheState function.\n  var lastCachedState = null;\n  function cacheState() {\n    // This should be the only place in $browser where `history.state` is read.\n    cachedState = window.history.state;\n    cachedState = isUndefined(cachedState) ? null : cachedState;\n\n    // Prevent callbacks fo fire twice if both hashchange & popstate were fired.\n    if (equals(cachedState, lastCachedState)) {\n      cachedState = lastCachedState;\n    }\n    lastCachedState = cachedState;\n  }\n\n  function fireUrlChange() {\n    if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {\n      return;\n    }\n\n    lastBrowserUrl = self.url();\n    lastHistoryState = cachedState;\n    forEach(urlChangeListeners, function(listener) {\n      listener(self.url(), cachedState);\n    });\n  }\n\n  /**\n   * @name $browser#onUrlChange\n   *\n   * @description\n   * Register callback function that will be called, when url changes.\n   *\n   * It's only called when the url is changed from outside of angular:\n   * - user types different url into address bar\n   * - user clicks on history (forward/back) button\n   * - user clicks on a link\n   *\n   * It's not called when url is changed by $browser.url() method\n   *\n   * The listener gets called with new url as parameter.\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to monitor url changes in angular apps.\n   *\n   * @param {function(string)} listener Listener function to be called when url changes.\n   * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\n   */\n  self.onUrlChange = function(callback) {\n    // TODO(vojta): refactor to use node's syntax for events\n    if (!urlChangeInit) {\n      // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)\n      // don't fire popstate when user change the address bar and don't fire hashchange when url\n      // changed by push/replaceState\n\n      // html5 history api - popstate event\n      if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);\n      // hashchange event\n      jqLite(window).on('hashchange', cacheStateAndFireUrlChange);\n\n      urlChangeInit = true;\n    }\n\n    urlChangeListeners.push(callback);\n    return callback;\n  };\n\n  /**\n   * Checks whether the url has changed outside of Angular.\n   * Needs to be exported to be able to check for changes that have been done in sync,\n   * as hashchange/popstate events fire in async.\n   */\n  self.$$checkUrlChange = fireUrlChange;\n\n  //////////////////////////////////////////////////////////////\n  // Misc API\n  //////////////////////////////////////////////////////////////\n\n  /**\n   * @name $browser#baseHref\n   *\n   * @description\n   * Returns current <base href>\n   * (always relative - without domain)\n   *\n   * @returns {string} The current base href\n   */\n  self.baseHref = function() {\n    var href = baseElement.attr('href');\n    return href ? href.replace(/^(https?\\:)?\\/\\/[^\\/]*/, '') : '';\n  };\n\n  //////////////////////////////////////////////////////////////\n  // Cookies API\n  //////////////////////////////////////////////////////////////\n  var lastCookies = {};\n  var lastCookieString = '';\n  var cookiePath = self.baseHref();\n\n  function safeDecodeURIComponent(str) {\n    try {\n      return decodeURIComponent(str);\n    } catch (e) {\n      return str;\n    }\n  }\n\n  /**\n   * @name $browser#cookies\n   *\n   * @param {string=} name Cookie name\n   * @param {string=} value Cookie value\n   *\n   * @description\n   * The cookies method provides a 'private' low level access to browser cookies.\n   * It is not meant to be used directly, use the $cookie service instead.\n   *\n   * The return values vary depending on the arguments that the method was called with as follows:\n   *\n   * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify\n   *   it\n   * - cookies(name, value) -> set name to value, if value is undefined delete the cookie\n   * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that\n   *   way)\n   *\n   * @returns {Object} Hash of all cookies (if called without any parameter)\n   */\n  self.cookies = function(name, value) {\n    var cookieLength, cookieArray, cookie, i, index;\n\n    if (name) {\n      if (value === undefined) {\n        rawDocument.cookie = encodeURIComponent(name) + \"=;path=\" + cookiePath +\n                                \";expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n      } else {\n        if (isString(value)) {\n          cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +\n                                ';path=' + cookiePath).length + 1;\n\n          // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:\n          // - 300 cookies\n          // - 20 cookies per unique domain\n          // - 4096 bytes per cookie\n          if (cookieLength > 4096) {\n            $log.warn(\"Cookie '\" + name +\n              \"' possibly not set or overflowed because it was too large (\" +\n              cookieLength + \" > 4096 bytes)!\");\n          }\n        }\n      }\n    } else {\n      if (rawDocument.cookie !== lastCookieString) {\n        lastCookieString = rawDocument.cookie;\n        cookieArray = lastCookieString.split(\"; \");\n        lastCookies = {};\n\n        for (i = 0; i < cookieArray.length; i++) {\n          cookie = cookieArray[i];\n          index = cookie.indexOf('=');\n          if (index > 0) { //ignore nameless cookies\n            name = safeDecodeURIComponent(cookie.substring(0, index));\n            // the first value that is seen for a cookie is the most\n            // specific one.  values for the same cookie name that\n            // follow are for less specific paths.\n            if (lastCookies[name] === undefined) {\n              lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));\n            }\n          }\n        }\n      }\n      return lastCookies;\n    }\n  };\n\n\n  /**\n   * @name $browser#defer\n   * @param {function()} fn A function, who's execution should be deferred.\n   * @param {number=} [delay=0] of milliseconds to defer the function execution.\n   * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\n   *\n   * @description\n   * Executes a fn asynchronously via `setTimeout(fn, delay)`.\n   *\n   * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\n   * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\n   * via `$browser.defer.flush()`.\n   *\n   */\n  self.defer = function(fn, delay) {\n    var timeoutId;\n    outstandingRequestCount++;\n    timeoutId = setTimeout(function() {\n      delete pendingDeferIds[timeoutId];\n      completeOutstandingRequest(fn);\n    }, delay || 0);\n    pendingDeferIds[timeoutId] = true;\n    return timeoutId;\n  };\n\n\n  /**\n   * @name $browser#defer.cancel\n   *\n   * @description\n   * Cancels a deferred task identified with `deferId`.\n   *\n   * @param {*} deferId Token returned by the `$browser.defer` function.\n   * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n   *                    canceled.\n   */\n  self.defer.cancel = function(deferId) {\n    if (pendingDeferIds[deferId]) {\n      delete pendingDeferIds[deferId];\n      clearTimeout(deferId);\n      completeOutstandingRequest(noop);\n      return true;\n    }\n    return false;\n  };\n\n}\n\nfunction $BrowserProvider() {\n  this.$get = ['$window', '$log', '$sniffer', '$document',\n      function($window, $log, $sniffer, $document) {\n        return new Browser($window, $document, $log, $sniffer);\n      }];\n}\n\n/**\n * @ngdoc service\n * @name $cacheFactory\n *\n * @description\n * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to\n * them.\n *\n * ```js\n *\n *  var cache = $cacheFactory('cacheId');\n *  expect($cacheFactory.get('cacheId')).toBe(cache);\n *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();\n *\n *  cache.put(\"key\", \"value\");\n *  cache.put(\"another key\", \"another value\");\n *\n *  // We've specified no options on creation\n *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});\n *\n * ```\n *\n *\n * @param {string} cacheId Name or id of the newly created cache.\n * @param {object=} options Options object that specifies the cache behavior. Properties:\n *\n *   - `{number=}` `capacity` — turns the cache into LRU cache.\n *\n * @returns {object} Newly created cache object with the following set of methods:\n *\n * - `{object}` `info()` — Returns id, size, and options of cache.\n * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns\n *   it.\n * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.\n * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.\n * - `{void}` `removeAll()` — Removes all cached values.\n * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.\n *\n * @example\n   <example module=\"cacheExampleApp\">\n     <file name=\"index.html\">\n       <div ng-controller=\"CacheController\">\n         <input ng-model=\"newCacheKey\" placeholder=\"Key\">\n         <input ng-model=\"newCacheValue\" placeholder=\"Value\">\n         <button ng-click=\"put(newCacheKey, newCacheValue)\">Cache</button>\n\n         <p ng-if=\"keys.length\">Cached Values</p>\n         <div ng-repeat=\"key in keys\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"cache.get(key)\"></b>\n         </div>\n\n         <p>Cache Info</p>\n         <div ng-repeat=\"(key, value) in cache.info()\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"value\"></b>\n         </div>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('cacheExampleApp', []).\n         controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {\n           $scope.keys = [];\n           $scope.cache = $cacheFactory('cacheId');\n           $scope.put = function(key, value) {\n             if ($scope.cache.get(key) === undefined) {\n               $scope.keys.push(key);\n             }\n             $scope.cache.put(key, value === undefined ? null : value);\n           };\n         }]);\n     </file>\n     <file name=\"style.css\">\n       p {\n         margin: 10px 0 3px;\n       }\n     </file>\n   </example>\n */\nfunction $CacheFactoryProvider() {\n\n  this.$get = function() {\n    var caches = {};\n\n    function cacheFactory(cacheId, options) {\n      if (cacheId in caches) {\n        throw minErr('$cacheFactory')('iid', \"CacheId '{0}' is already taken!\", cacheId);\n      }\n\n      var size = 0,\n          stats = extend({}, options, {id: cacheId}),\n          data = {},\n          capacity = (options && options.capacity) || Number.MAX_VALUE,\n          lruHash = {},\n          freshEnd = null,\n          staleEnd = null;\n\n      /**\n       * @ngdoc type\n       * @name $cacheFactory.Cache\n       *\n       * @description\n       * A cache object used to store and retrieve data, primarily used by\n       * {@link $http $http} and the {@link ng.directive:script script} directive to cache\n       * templates and other data.\n       *\n       * ```js\n       *  angular.module('superCache')\n       *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {\n       *      return $cacheFactory('super-cache');\n       *    }]);\n       * ```\n       *\n       * Example test:\n       *\n       * ```js\n       *  it('should behave like a cache', inject(function(superCache) {\n       *    superCache.put('key', 'value');\n       *    superCache.put('another key', 'another value');\n       *\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 2\n       *    });\n       *\n       *    superCache.remove('another key');\n       *    expect(superCache.get('another key')).toBeUndefined();\n       *\n       *    superCache.removeAll();\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 0\n       *    });\n       *  }));\n       * ```\n       */\n      return caches[cacheId] = {\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#put\n         * @kind function\n         *\n         * @description\n         * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be\n         * retrieved later, and incrementing the size of the cache if the key was not already\n         * present in the cache. If behaving like an LRU cache, it will also remove stale\n         * entries from the set.\n         *\n         * It will not insert undefined values into the cache.\n         *\n         * @param {string} key the key under which the cached data is stored.\n         * @param {*} value the value to store alongside the key. If it is undefined, the key\n         *    will not be stored.\n         * @returns {*} the value stored.\n         */\n        put: function(key, value) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key] || (lruHash[key] = {key: key});\n\n            refresh(lruEntry);\n          }\n\n          if (isUndefined(value)) return;\n          if (!(key in data)) size++;\n          data[key] = value;\n\n          if (size > capacity) {\n            this.remove(staleEnd.key);\n          }\n\n          return value;\n        },\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#get\n         * @kind function\n         *\n         * @description\n         * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the data to be retrieved\n         * @returns {*} the value stored.\n         */\n        get: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            refresh(lruEntry);\n          }\n\n          return data[key];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#remove\n         * @kind function\n         *\n         * @description\n         * Removes an entry from the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the entry to be removed\n         */\n        remove: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            if (lruEntry == freshEnd) freshEnd = lruEntry.p;\n            if (lruEntry == staleEnd) staleEnd = lruEntry.n;\n            link(lruEntry.n,lruEntry.p);\n\n            delete lruHash[key];\n          }\n\n          delete data[key];\n          size--;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#removeAll\n         * @kind function\n         *\n         * @description\n         * Clears the cache object of any entries.\n         */\n        removeAll: function() {\n          data = {};\n          size = 0;\n          lruHash = {};\n          freshEnd = staleEnd = null;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#destroy\n         * @kind function\n         *\n         * @description\n         * Destroys the {@link $cacheFactory.Cache Cache} object entirely,\n         * removing it from the {@link $cacheFactory $cacheFactory} set.\n         */\n        destroy: function() {\n          data = null;\n          stats = null;\n          lruHash = null;\n          delete caches[cacheId];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#info\n         * @kind function\n         *\n         * @description\n         * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.\n         *\n         * @returns {object} an object with the following properties:\n         *   <ul>\n         *     <li>**id**: the id of the cache instance</li>\n         *     <li>**size**: the number of entries kept in the cache instance</li>\n         *     <li>**...**: any additional properties from the options object when creating the\n         *       cache.</li>\n         *   </ul>\n         */\n        info: function() {\n          return extend({}, stats, {size: size});\n        }\n      };\n\n\n      /**\n       * makes the `entry` the freshEnd of the LRU linked list\n       */\n      function refresh(entry) {\n        if (entry != freshEnd) {\n          if (!staleEnd) {\n            staleEnd = entry;\n          } else if (staleEnd == entry) {\n            staleEnd = entry.n;\n          }\n\n          link(entry.n, entry.p);\n          link(entry, freshEnd);\n          freshEnd = entry;\n          freshEnd.n = null;\n        }\n      }\n\n\n      /**\n       * bidirectionally links two entries of the LRU linked list\n       */\n      function link(nextEntry, prevEntry) {\n        if (nextEntry != prevEntry) {\n          if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify\n          if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify\n        }\n      }\n    }\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#info\n   *\n   * @description\n   * Get information about all the caches that have been created\n   *\n   * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`\n   */\n    cacheFactory.info = function() {\n      var info = {};\n      forEach(caches, function(cache, cacheId) {\n        info[cacheId] = cache.info();\n      });\n      return info;\n    };\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#get\n   *\n   * @description\n   * Get access to a cache object by the `cacheId` used when it was created.\n   *\n   * @param {string} cacheId Name or id of a cache to access.\n   * @returns {object} Cache object identified by the cacheId or undefined if no such cache.\n   */\n    cacheFactory.get = function(cacheId) {\n      return caches[cacheId];\n    };\n\n\n    return cacheFactory;\n  };\n}\n\n/**\n * @ngdoc service\n * @name $templateCache\n *\n * @description\n * The first time a template is used, it is loaded in the template cache for quick retrieval. You\n * can load templates directly into the cache in a `script` tag, or by consuming the\n * `$templateCache` service directly.\n *\n * Adding via the `script` tag:\n *\n * ```html\n *   <script type=\"text/ng-template\" id=\"templateId.html\">\n *     <p>This is the content of the template</p>\n *   </script>\n * ```\n *\n * **Note:** the `script` tag containing the template does not need to be included in the `head` of\n * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,\n * element with ng-app attribute), otherwise the template will be ignored.\n *\n * Adding via the $templateCache service:\n *\n * ```js\n * var myApp = angular.module('myApp', []);\n * myApp.run(function($templateCache) {\n *   $templateCache.put('templateId.html', 'This is the content of the template');\n * });\n * ```\n *\n * To retrieve the template later, simply use it in your HTML:\n * ```html\n * <div ng-include=\" 'templateId.html' \"></div>\n * ```\n *\n * or get it via Javascript:\n * ```js\n * $templateCache.get('templateId.html')\n * ```\n *\n * See {@link ng.$cacheFactory $cacheFactory}.\n *\n */\nfunction $TemplateCacheProvider() {\n  this.$get = ['$cacheFactory', function($cacheFactory) {\n    return $cacheFactory('templates');\n  }];\n}\n\n/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!\n *\n * DOM-related variables:\n *\n * - \"node\" - DOM Node\n * - \"element\" - DOM Element or Node\n * - \"$node\" or \"$element\" - jqLite-wrapped node or element\n *\n *\n * Compiler related stuff:\n *\n * - \"linkFn\" - linking fn of a single directive\n * - \"nodeLinkFn\" - function that aggregates all linking fns for a particular node\n * - \"childLinkFn\" -  function that aggregates all linking fns for child nodes of a particular node\n * - \"compositeLinkFn\" - function that aggregates all linking fns for a compilation root (nodeList)\n */\n\n\n/**\n * @ngdoc service\n * @name $compile\n * @kind function\n *\n * @description\n * Compiles an HTML string or DOM into a template and produces a template function, which\n * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.\n *\n * The compilation is a process of walking the DOM tree and matching DOM elements to\n * {@link ng.$compileProvider#directive directives}.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** This document is an in-depth reference of all directive options.\n * For a gentle introduction to directives with examples of common use cases,\n * see the {@link guide/directive directive guide}.\n * </div>\n *\n * ## Comprehensive Directive API\n *\n * There are many different options for a directive.\n *\n * The difference resides in the return value of the factory function.\n * You can either return a \"Directive Definition Object\" (see below) that defines the directive properties,\n * or just the `postLink` function (all other properties will have the default values).\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's recommended to use the \"directive definition object\" form.\n * </div>\n *\n * Here's an example directive declared with a Directive Definition Object:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       priority: 0,\n *       template: '<div></div>', // or // function(tElement, tAttrs) { ... },\n *       // or\n *       // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },\n *       transclude: false,\n *       restrict: 'A',\n *       templateNamespace: 'html',\n *       scope: false,\n *       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },\n *       controllerAs: 'stringAlias',\n *       require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],\n *       compile: function compile(tElement, tAttrs, transclude) {\n *         return {\n *           pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *           post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *         }\n *         // or\n *         // return function postLink( ... ) { ... }\n *       },\n *       // or\n *       // link: {\n *       //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *       //  post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *       // }\n *       // or\n *       // link: function postLink( ... ) { ... }\n *     };\n *     return directiveDefinitionObject;\n *   });\n * ```\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Any unspecified options will use the default value. You can see the default values below.\n * </div>\n *\n * Therefore the above can be simplified as:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       link: function postLink(scope, iElement, iAttrs) { ... }\n *     };\n *     return directiveDefinitionObject;\n *     // or\n *     // return function postLink(scope, iElement, iAttrs) { ... }\n *   });\n * ```\n *\n *\n *\n * ### Directive Definition Object\n *\n * The directive definition object provides instructions to the {@link ng.$compile\n * compiler}. The attributes are:\n *\n * #### `multiElement`\n * When this property is set to true, the HTML compiler will collect DOM nodes between\n * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them\n * together as the directive elements. It is recommended that this feature be used on directives\n * which are not strictly behavioural (such as {@link ngClick}), and which\n * do not manipulate or replace child nodes (such as {@link ngInclude}).\n *\n * #### `priority`\n * When there are multiple directives defined on a single DOM element, sometimes it\n * is necessary to specify the order in which the directives are applied. The `priority` is used\n * to sort the directives before their `compile` functions get called. Priority is defined as a\n * number. Directives with greater numerical `priority` are compiled first. Pre-link functions\n * are also run in priority order, but post-link functions are run in reverse order. The order\n * of directives with the same priority is undefined. The default priority is `0`.\n *\n * #### `terminal`\n * If set to true then the current `priority` will be the last set of directives\n * which will execute (any directives at the current priority will still execute\n * as the order of execution on same `priority` is undefined). Note that expressions\n * and other directives used in the directive's template will also be excluded from execution.\n *\n * #### `scope`\n * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the\n * same element request a new scope, only one new scope is created. The new scope rule does not\n * apply for the root of the template since the root of the template always gets a new scope.\n *\n * **If set to `{}` (object hash),** then a new \"isolate\" scope is created. The 'isolate' scope differs from\n * normal scope in that it does not prototypically inherit from the parent scope. This is useful\n * when creating reusable components, which should not accidentally read or modify data in the\n * parent scope.\n *\n * The 'isolate' scope takes an object hash which defines a set of local scope properties\n * derived from the parent scope. These local properties are useful for aliasing values for\n * templates. Locals definition is a hash of local scope property to its source:\n *\n * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is\n *   always a string since DOM attributes are strings. If no `attr` name is specified  then the\n *   attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"hello {{name}}\">` and widget definition\n *   of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect\n *   the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the\n *   `localName` property on the widget scope. The `name` is read from the parent scope (not\n *   component scope).\n *\n * * `=` or `=attr` - set up bi-directional binding between a local scope property and the\n *   parent scope property of name defined via the value of the `attr` attribute. If no `attr`\n *   name is specified then the attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"parentModel\">` and widget definition of\n *   `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the\n *   value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected\n *   in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent\n *   scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You\n *   can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If\n *   you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use\n *   `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).\n *\n * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.\n *   If no `attr` name is specified then the attribute name is assumed to be the same as the\n *   local name. Given `<widget my-attr=\"count = count + value\">` and widget definition of\n *   `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to\n *   a function wrapper for the `count = count + value` expression. Often it's desirable to\n *   pass data from the isolated scope via an expression to the parent scope, this can be\n *   done by passing a map of local variable names and values into the expression wrapper fn.\n *   For example, if the expression is `increment(amount)` then we can specify the amount value\n *   by calling the `localFn` as `localFn({amount: 22})`.\n *\n *\n * #### `bindToController`\n * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will\n * allow a component to have its properties bound to the controller, rather than to scope. When the controller\n * is instantiated, the initial values of the isolate scope bindings are already available.\n *\n * #### `controller`\n * Controller constructor function. The controller is instantiated before the\n * pre-linking phase and it is shared with other directives (see\n * `require` attribute). This allows the directives to communicate with each other and augment\n * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:\n *\n * * `$scope` - Current scope associated with the element\n * * `$element` - Current element\n * * `$attrs` - Current attributes object for the element\n * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:\n *   `function([scope], cloneLinkingFn, futureParentElement)`.\n *    * `scope`: optional argument to override the scope.\n *    * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.\n *    * `futureParentElement`:\n *        * defines the parent to which the `cloneLinkingFn` will add the cloned elements.\n *        * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.\n *        * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)\n *          and when the `cloneLinkinFn` is passed,\n *          as those elements need to created and cloned in a special way when they are defined outside their\n *          usual containers (e.g. like `<svg>`).\n *        * See also the `directive.templateNamespace` property.\n *\n *\n * #### `require`\n * Require another directive and inject its controller as the fourth argument to the linking function. The\n * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the\n * injected argument will be an array in corresponding order. If no such directive can be\n * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:\n *\n * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.\n * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.\n * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.\n * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.\n * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass\n *   `null` to the `link` fn if not found.\n * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass\n *   `null` to the `link` fn if not found.\n *\n *\n * #### `controllerAs`\n * Controller alias at the directive scope. An alias for the controller so it\n * can be referenced at the directive template. The directive needs to define a scope for this\n * configuration to be used. Useful in the case when directive is used as component.\n *\n *\n * #### `restrict`\n * String of subset of `EACM` which restricts the directive to a specific directive\n * declaration style. If omitted, the defaults (elements and attributes) are used.\n *\n * * `E` - Element name (default): `<my-directive></my-directive>`\n * * `A` - Attribute (default): `<div my-directive=\"exp\"></div>`\n * * `C` - Class: `<div class=\"my-directive: exp;\"></div>`\n * * `M` - Comment: `<!-- directive: my-directive exp -->`\n *\n *\n * #### `templateNamespace`\n * String representing the document type used by the markup in the template.\n * AngularJS needs this information as those elements need to be created and cloned\n * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.\n *\n * * `html` - All root nodes in the template are HTML. Root nodes may also be\n *   top-level elements such as `<svg>` or `<math>`.\n * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).\n * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).\n *\n * If no `templateNamespace` is specified, then the namespace is considered to be `html`.\n *\n * #### `template`\n * HTML markup that may:\n * * Replace the contents of the directive's element (default).\n * * Replace the directive's element itself (if `replace` is true - DEPRECATED).\n * * Wrap the contents of the directive's element (if `transclude` is true).\n *\n * Value may be:\n *\n * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.\n * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`\n *   function api below) and returns a string value.\n *\n *\n * #### `templateUrl`\n * This is similar to `template` but the template is loaded from the specified URL, asynchronously.\n *\n * Because template loading is asynchronous the compiler will suspend compilation of directives on that element\n * for later when the template has been resolved.  In the meantime it will continue to compile and link\n * sibling and parent elements as though this element had not contained any directives.\n *\n * The compiler does not suspend the entire compilation to wait for templates to be loaded because this\n * would result in the whole app \"stalling\" until all templates are loaded asynchronously - even in the\n * case when only one deeply nested directive has `templateUrl`.\n *\n * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}\n *\n * You can specify `templateUrl` as a string representing the URL or as a function which takes two\n * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns\n * a string value representing the url.  In either case, the template URL is passed through {@link\n * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.\n *\n *\n * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)\n * specify what the template should replace. Defaults to `false`.\n *\n * * `true` - the template will replace the directive's element.\n * * `false` - the template will replace the contents of the directive's element.\n *\n * The replacement process migrates all of the attributes / classes from the old element to the new\n * one. See the {@link guide/directive#template-expanding-directive\n * Directives Guide} for an example.\n *\n * There are very few scenarios where element replacement is required for the application function,\n * the main one being reusable custom components that are used within SVG contexts\n * (because SVG doesn't work with custom elements in the DOM tree).\n *\n * #### `transclude`\n * Extract the contents of the element where the directive appears and make it available to the directive.\n * The contents are compiled and provided to the directive as a **transclusion function**. See the\n * {@link $compile#transclusion Transclusion} section below.\n *\n * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the\n * directive's element or the entire element:\n *\n * * `true` - transclude the content (i.e. the child nodes) of the directive's element.\n * * `'element'` - transclude the whole of the directive's element including any directives on this\n *   element that defined at a lower priority than this directive. When used, the `template`\n *   property is ignored.\n *\n *\n * #### `compile`\n *\n * ```js\n *   function compile(tElement, tAttrs, transclude) { ... }\n * ```\n *\n * The compile function deals with transforming the template DOM. Since most directives do not do\n * template transformation, it is not used often. The compile function takes the following arguments:\n *\n *   * `tElement` - template element - The element where the directive has been declared. It is\n *     safe to do template transformation on the element and child elements only.\n *\n *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared\n *     between all directive compile functions.\n *\n *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`\n *\n * <div class=\"alert alert-warning\">\n * **Note:** The template instance and the link instance may be different objects if the template has\n * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that\n * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration\n * should be done in a linking function rather than in a compile function.\n * </div>\n\n * <div class=\"alert alert-warning\">\n * **Note:** The compile function cannot handle directives that recursively use themselves in their\n * own templates or compile functions. Compiling these directives results in an infinite loop and a\n * stack overflow errors.\n *\n * This can be avoided by manually using $compile in the postLink function to imperatively compile\n * a directive's template instead of relying on automatic template compilation via `template` or\n * `templateUrl` declaration or manual compilation inside the compile function.\n * </div>\n *\n * <div class=\"alert alert-error\">\n * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it\n *   e.g. does not know about the right outer scope. Please use the transclude function that is passed\n *   to the link function instead.\n * </div>\n\n * A compile function can have a return value which can be either a function or an object.\n *\n * * returning a (post-link) function - is equivalent to registering the linking function via the\n *   `link` property of the config object when the compile function is empty.\n *\n * * returning an object with function(s) registered via `pre` and `post` properties - allows you to\n *   control when a linking function should be called during the linking phase. See info about\n *   pre-linking and post-linking functions below.\n *\n *\n * #### `link`\n * This property is used only if the `compile` property is not defined.\n *\n * ```js\n *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }\n * ```\n *\n * The link function is responsible for registering DOM listeners as well as updating the DOM. It is\n * executed after the template has been cloned. This is where most of the directive logic will be\n * put.\n *\n *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the\n *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.\n *\n *   * `iElement` - instance element - The element where the directive is to be used. It is safe to\n *     manipulate the children of the element only in `postLink` function since the children have\n *     already been linked.\n *\n *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared\n *     between all directive linking functions.\n *\n *   * `controller` - a controller instance - A controller instance if at least one directive on the\n *     element defines a controller. The controller is shared among all the directives, which allows\n *     the directives to use the controllers as a communication channel.\n *\n *   * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.\n *     This is the same as the `$transclude`\n *     parameter of directive controllers, see there for details.\n *     `function([scope], cloneLinkingFn, futureParentElement)`.\n *\n * #### Pre-linking function\n *\n * Executed before the child elements are linked. Not safe to do DOM transformation since the\n * compiler linking function will fail to locate the correct elements for linking.\n *\n * #### Post-linking function\n *\n * Executed after the child elements are linked.\n *\n * Note that child elements that contain `templateUrl` directives will not have been compiled\n * and linked since they are waiting for their template to load asynchronously and their own\n * compilation and linking has been suspended until that occurs.\n *\n * It is safe to do DOM transformation in the post-linking function on elements that are not waiting\n * for their async templates to be resolved.\n *\n *\n * ### Transclusion\n *\n * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and\n * copying them to another part of the DOM, while maintaining their connection to the original AngularJS\n * scope from where they were taken.\n *\n * Transclusion is used (often with {@link ngTransclude}) to insert the\n * original contents of a directive's element into a specified place in the template of the directive.\n * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded\n * content has access to the properties on the scope from which it was taken, even if the directive\n * has isolated scope.\n * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.\n *\n * This makes it possible for the widget to have private state for its template, while the transcluded\n * content has access to its originating scope.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** When testing an element transclude directive you must not place the directive at the root of the\n * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives\n * Testing Transclusion Directives}.\n * </div>\n *\n * #### Transclusion Functions\n *\n * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion\n * function** to the directive's `link` function and `controller`. This transclusion function is a special\n * **linking function** that will return the compiled contents linked to a new transclusion scope.\n *\n * <div class=\"alert alert-info\">\n * If you are just using {@link ngTransclude} then you don't need to worry about this function, since\n * ngTransclude will deal with it for us.\n * </div>\n *\n * If you want to manually control the insertion and removal of the transcluded content in your directive\n * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery\n * object that contains the compiled DOM, which is linked to the correct transclusion scope.\n *\n * When you call a transclusion function you can pass in a **clone attach function**. This function accepts\n * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded\n * content and the `scope` is the newly created transclusion scope, to which the clone is bound.\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function\n * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.\n * </div>\n *\n * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone\n * attach function**:\n *\n * ```js\n * var transcludedContent, transclusionScope;\n *\n * $transclude(function(clone, scope) {\n *   element.append(clone);\n *   transcludedContent = clone;\n *   transclusionScope = scope;\n * });\n * ```\n *\n * Later, if you want to remove the transcluded content from your DOM then you should also destroy the\n * associated transclusion scope:\n *\n * ```js\n * transcludedContent.remove();\n * transclusionScope.$destroy();\n * ```\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: if you intend to add and remove transcluded content manually in your directive\n * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),\n * then you are also responsible for calling `$destroy` on the transclusion scope.\n * </div>\n *\n * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}\n * automatically destroy their transluded clones as necessary so you do not need to worry about this if\n * you are simply using {@link ngTransclude} to inject the transclusion into your directive.\n *\n *\n * #### Transclusion Scopes\n *\n * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion\n * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed\n * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it\n * was taken.\n *\n * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look\n * like this:\n *\n * ```html\n * <div ng-app>\n *   <div isolate>\n *     <div transclusion>\n *     </div>\n *   </div>\n * </div>\n * ```\n *\n * The `$parent` scope hierarchy will look like this:\n *\n * ```\n * - $rootScope\n *   - isolate\n *     - transclusion\n * ```\n *\n * but the scopes will inherit prototypically from different scopes to their `$parent`.\n *\n * ```\n * - $rootScope\n *   - transclusion\n * - isolate\n * ```\n *\n *\n * ### Attributes\n *\n * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the\n * `link()` or `compile()` functions. It has a variety of uses.\n *\n * accessing *Normalized attribute names:*\n * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.\n * the attributes object allows for normalized access to\n *   the attributes.\n *\n * * *Directive inter-communication:* All directives share the same instance of the attributes\n *   object which allows the directives to use the attributes object as inter directive\n *   communication.\n *\n * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object\n *   allowing other directives to read the interpolated value.\n *\n * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes\n *   that contain interpolation (e.g. `src=\"{{bar}}\"`). Not only is this very efficient but it's also\n *   the only way to easily get the actual value because during the linking phase the interpolation\n *   hasn't been evaluated yet and so the value is at this time set to `undefined`.\n *\n * ```js\n * function linkingFn(scope, elm, attrs, ctrl) {\n *   // get the attribute value\n *   console.log(attrs.ngModel);\n *\n *   // change the attribute\n *   attrs.$set('ngModel', 'new value');\n *\n *   // observe changes to interpolated attribute\n *   attrs.$observe('ngModel', function(value) {\n *     console.log('ngModel has changed value to ' + value);\n *   });\n * }\n * ```\n *\n * ## Example\n *\n * <div class=\"alert alert-warning\">\n * **Note**: Typically directives are registered with `module.directive`. The example below is\n * to illustrate how `$compile` works.\n * </div>\n *\n <example module=\"compileExample\">\n   <file name=\"index.html\">\n    <script>\n      angular.module('compileExample', [], function($compileProvider) {\n        // configure new 'compile' directive by passing a directive\n        // factory function. The factory function injects the '$compile'\n        $compileProvider.directive('compile', function($compile) {\n          // directive factory creates a link function\n          return function(scope, element, attrs) {\n            scope.$watch(\n              function(scope) {\n                 // watch the 'compile' expression for changes\n                return scope.$eval(attrs.compile);\n              },\n              function(value) {\n                // when the 'compile' expression changes\n                // assign it into the current DOM\n                element.html(value);\n\n                // compile the new DOM and link it to the current\n                // scope.\n                // NOTE: we only compile .childNodes so that\n                // we don't get into infinite loop compiling ourselves\n                $compile(element.contents())(scope);\n              }\n            );\n          };\n        });\n      })\n      .controller('GreeterController', ['$scope', function($scope) {\n        $scope.name = 'Angular';\n        $scope.html = 'Hello {{name}}';\n      }]);\n    </script>\n    <div ng-controller=\"GreeterController\">\n      <input ng-model=\"name\"> <br>\n      <textarea ng-model=\"html\"></textarea> <br>\n      <div compile=\"html\"></div>\n    </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should auto compile', function() {\n       var textarea = $('textarea');\n       var output = $('div[compile]');\n       // The initial state reads 'Hello Angular'.\n       expect(output.getText()).toBe('Hello Angular');\n       textarea.clear();\n       textarea.sendKeys('{{name}}!');\n       expect(output.getText()).toBe('Angular!');\n     });\n   </file>\n </example>\n\n *\n *\n * @param {string|DOMElement} element Element or HTML string to compile into a template function.\n * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.\n *\n * <div class=\"alert alert-error\">\n * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it\n *   e.g. will not use the right outer scope. Please pass the transclude function as a\n *   `parentBoundTranscludeFn` to the link function instead.\n * </div>\n *\n * @param {number} maxPriority only apply directives lower than given priority (Only effects the\n *                 root element(s), not their children)\n * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template\n * (a DOM element/tree) to a scope. Where:\n *\n *  * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.\n *  * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the\n *  `template` and call the `cloneAttachFn` function allowing the caller to attach the\n *  cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is\n *  called as: <br> `cloneAttachFn(clonedElement, scope)` where:\n *\n *      * `clonedElement` - is a clone of the original `element` passed into the compiler.\n *      * `scope` - is the current scope with which the linking function is working with.\n *\n *  * `options` - An optional object hash with linking options. If `options` is provided, then the following\n *  keys may be used to control linking behavior:\n *\n *      * `parentBoundTranscludeFn` - the transclude function made available to\n *        directives; if given, it will be passed through to the link functions of\n *        directives found in `element` during compilation.\n *      * `transcludeControllers` - an object hash with keys that map controller names\n *        to controller instances; if given, it will make the controllers\n *        available to directives.\n *      * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add\n *        the cloned elements; only needed for transcludes that are allowed to contain non html\n *        elements (e.g. SVG elements). See also the directive.controller property.\n *\n * Calling the linking function returns the element of the template. It is either the original\n * element passed in, or the clone of the element if the `cloneAttachFn` is provided.\n *\n * After linking the view is not updated until after a call to $digest which typically is done by\n * Angular automatically.\n *\n * If you need access to the bound view, there are two ways to do it:\n *\n * - If you are not asking the linking function to clone the template, create the DOM element(s)\n *   before you send them to the compiler and keep this reference around.\n *   ```js\n *     var element = $compile('<p>{{total}}</p>')(scope);\n *   ```\n *\n * - if on the other hand, you need the element to be cloned, the view reference from the original\n *   example would not point to the clone, but rather to the original template that was cloned. In\n *   this case, you can access the clone via the cloneAttachFn:\n *   ```js\n *     var templateElement = angular.element('<p>{{total}}</p>'),\n *         scope = ....;\n *\n *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {\n *       //attach the clone to DOM document at the right place\n *     });\n *\n *     //now we have reference to the cloned DOM via `clonedElement`\n *   ```\n *\n *\n * For information on how the compiler works, see the\n * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.\n */\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc provider\n * @name $compileProvider\n *\n * @description\n */\n$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];\nfunction $CompileProvider($provide, $$sanitizeUriProvider) {\n  var hasDirectives = {},\n      Suffix = 'Directive',\n      COMMENT_DIRECTIVE_REGEXP = /^\\s*directive\\:\\s*([\\w\\-]+)\\s+(.*)$/,\n      CLASS_DIRECTIVE_REGEXP = /(([\\w\\-]+)(?:\\:([^;]+))?;?)/,\n      ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),\n      REQUIRE_PREFIX_REGEXP = /^(?:(\\^\\^?)?(\\?)?(\\^\\^?)?)?/;\n\n  // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes\n  // The assumption is that future DOM event attribute names will begin with\n  // 'on' and be composed of only English letters.\n  var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;\n\n  function parseIsolateBindings(scope, directiveName) {\n    var LOCAL_REGEXP = /^\\s*([@&]|=(\\*?))(\\??)\\s*(\\w*)\\s*$/;\n\n    var bindings = {};\n\n    forEach(scope, function(definition, scopeName) {\n      var match = definition.match(LOCAL_REGEXP);\n\n      if (!match) {\n        throw $compileMinErr('iscp',\n            \"Invalid isolate scope definition for directive '{0}'.\" +\n            \" Definition: {... {1}: '{2}' ...}\",\n            directiveName, scopeName, definition);\n      }\n\n      bindings[scopeName] = {\n        mode: match[1][0],\n        collection: match[2] === '*',\n        optional: match[3] === '?',\n        attrName: match[4] || scopeName\n      };\n    });\n\n    return bindings;\n  }\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#directive\n   * @kind function\n   *\n   * @description\n   * Register a new directive with the compiler.\n   *\n   * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which\n   *    will match as <code>ng-bind</code>), or an object map of directives where the keys are the\n   *    names and the values are the factories.\n   * @param {Function|Array} directiveFactory An injectable directive factory function. See\n   *    {@link guide/directive} for more info.\n   * @returns {ng.$compileProvider} Self for chaining.\n   */\n   this.directive = function registerDirective(name, directiveFactory) {\n    assertNotHasOwnProperty(name, 'directive');\n    if (isString(name)) {\n      assertArg(directiveFactory, 'directiveFactory');\n      if (!hasDirectives.hasOwnProperty(name)) {\n        hasDirectives[name] = [];\n        $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',\n          function($injector, $exceptionHandler) {\n            var directives = [];\n            forEach(hasDirectives[name], function(directiveFactory, index) {\n              try {\n                var directive = $injector.invoke(directiveFactory);\n                if (isFunction(directive)) {\n                  directive = { compile: valueFn(directive) };\n                } else if (!directive.compile && directive.link) {\n                  directive.compile = valueFn(directive.link);\n                }\n                directive.priority = directive.priority || 0;\n                directive.index = index;\n                directive.name = directive.name || name;\n                directive.require = directive.require || (directive.controller && directive.name);\n                directive.restrict = directive.restrict || 'EA';\n                if (isObject(directive.scope)) {\n                  directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);\n                }\n                directives.push(directive);\n              } catch (e) {\n                $exceptionHandler(e);\n              }\n            });\n            return directives;\n          }]);\n      }\n      hasDirectives[name].push(directiveFactory);\n    } else {\n      forEach(name, reverseParams(registerDirective));\n    }\n    return this;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#aHrefSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at preventing XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.aHrefSanitizationWhitelist();\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#imgSrcSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name  $compileProvider#debugInfoEnabled\n   *\n   * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the\n   * current debugInfoEnabled state\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   *\n   * @kind function\n   *\n   * @description\n   * Call this method to enable/disable various debug runtime information in the compiler such as adding\n   * binding information and a reference to the current scope on to DOM elements.\n   * If enabled, the compiler will add the following to DOM elements that have been bound to the scope\n   * * `ng-binding` CSS class\n   * * `$binding` data property containing an array of the binding expressions\n   *\n   * You may want to disable this in production for a significant performance boost. See\n   * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.\n   *\n   * The default value is true.\n   */\n  var debugInfoEnabled = true;\n  this.debugInfoEnabled = function(enabled) {\n    if (isDefined(enabled)) {\n      debugInfoEnabled = enabled;\n      return this;\n    }\n    return debugInfoEnabled;\n  };\n\n  this.$get = [\n            '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',\n            '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',\n    function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,\n             $controller,   $rootScope,   $document,   $sce,   $animate,   $$sanitizeUri) {\n\n    var Attributes = function(element, attributesToCopy) {\n      if (attributesToCopy) {\n        var keys = Object.keys(attributesToCopy);\n        var i, l, key;\n\n        for (i = 0, l = keys.length; i < l; i++) {\n          key = keys[i];\n          this[key] = attributesToCopy[key];\n        }\n      } else {\n        this.$attr = {};\n      }\n\n      this.$$element = element;\n    };\n\n    Attributes.prototype = {\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$normalize\n       * @kind function\n       *\n       * @description\n       * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or\n       * `data-`) to its normalized, camelCase form.\n       *\n       * Also there is special case for Moz prefix starting with upper case letter.\n       *\n       * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\n       *\n       * @param {string} name Name to normalize\n       */\n      $normalize: directiveNormalize,\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$addClass\n       * @kind function\n       *\n       * @description\n       * Adds the CSS class value specified by the classVal parameter to the element. If animations\n       * are enabled then an animation will be triggered for the class addition.\n       *\n       * @param {string} classVal The className value that will be added to the element\n       */\n      $addClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.addClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$removeClass\n       * @kind function\n       *\n       * @description\n       * Removes the CSS class value specified by the classVal parameter from the element. If\n       * animations are enabled then an animation will be triggered for the class removal.\n       *\n       * @param {string} classVal The className value that will be removed from the element\n       */\n      $removeClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.removeClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$updateClass\n       * @kind function\n       *\n       * @description\n       * Adds and removes the appropriate CSS class values to the element based on the difference\n       * between the new and old CSS class values (specified as newClasses and oldClasses).\n       *\n       * @param {string} newClasses The current CSS className value\n       * @param {string} oldClasses The former CSS className value\n       */\n      $updateClass: function(newClasses, oldClasses) {\n        var toAdd = tokenDifference(newClasses, oldClasses);\n        if (toAdd && toAdd.length) {\n          $animate.addClass(this.$$element, toAdd);\n        }\n\n        var toRemove = tokenDifference(oldClasses, newClasses);\n        if (toRemove && toRemove.length) {\n          $animate.removeClass(this.$$element, toRemove);\n        }\n      },\n\n      /**\n       * Set a normalized attribute on the element in a way such that all directives\n       * can share the attribute. This function properly handles boolean attributes.\n       * @param {string} key Normalized key. (ie ngAttribute)\n       * @param {string|boolean} value The value to set. If `null` attribute will be deleted.\n       * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.\n       *     Defaults to true.\n       * @param {string=} attrName Optional none normalized name. Defaults to key.\n       */\n      $set: function(key, value, writeAttr, attrName) {\n        // TODO: decide whether or not to throw an error if \"class\"\n        //is set through this function since it may cause $updateClass to\n        //become unstable.\n\n        var node = this.$$element[0],\n            booleanKey = getBooleanAttrName(node, key),\n            aliasedKey = getAliasedAttrName(node, key),\n            observer = key,\n            nodeName;\n\n        if (booleanKey) {\n          this.$$element.prop(key, value);\n          attrName = booleanKey;\n        } else if (aliasedKey) {\n          this[aliasedKey] = value;\n          observer = aliasedKey;\n        }\n\n        this[key] = value;\n\n        // translate normalized key to actual key\n        if (attrName) {\n          this.$attr[key] = attrName;\n        } else {\n          attrName = this.$attr[key];\n          if (!attrName) {\n            this.$attr[key] = attrName = snake_case(key, '-');\n          }\n        }\n\n        nodeName = nodeName_(this.$$element);\n\n        if ((nodeName === 'a' && key === 'href') ||\n            (nodeName === 'img' && key === 'src')) {\n          // sanitize a[href] and img[src] values\n          this[key] = value = $$sanitizeUri(value, key === 'src');\n        } else if (nodeName === 'img' && key === 'srcset') {\n          // sanitize img[srcset] values\n          var result = \"\";\n\n          // first check if there are spaces because it's not the same pattern\n          var trimmedSrcset = trim(value);\n          //                (   999x   ,|   999w   ,|   ,|,   )\n          var srcPattern = /(\\s+\\d+x\\s*,|\\s+\\d+w\\s*,|\\s+,|,\\s+)/;\n          var pattern = /\\s/.test(trimmedSrcset) ? srcPattern : /(,)/;\n\n          // split srcset into tuple of uri and descriptor except for the last item\n          var rawUris = trimmedSrcset.split(pattern);\n\n          // for each tuples\n          var nbrUrisWith2parts = Math.floor(rawUris.length / 2);\n          for (var i = 0; i < nbrUrisWith2parts; i++) {\n            var innerIdx = i * 2;\n            // sanitize the uri\n            result += $$sanitizeUri(trim(rawUris[innerIdx]), true);\n            // add the descriptor\n            result += (\" \" + trim(rawUris[innerIdx + 1]));\n          }\n\n          // split the last item into uri and descriptor\n          var lastTuple = trim(rawUris[i * 2]).split(/\\s/);\n\n          // sanitize the last uri\n          result += $$sanitizeUri(trim(lastTuple[0]), true);\n\n          // and add the last descriptor if any\n          if (lastTuple.length === 2) {\n            result += (\" \" + trim(lastTuple[1]));\n          }\n          this[key] = value = result;\n        }\n\n        if (writeAttr !== false) {\n          if (value === null || value === undefined) {\n            this.$$element.removeAttr(attrName);\n          } else {\n            this.$$element.attr(attrName, value);\n          }\n        }\n\n        // fire observers\n        var $$observers = this.$$observers;\n        $$observers && forEach($$observers[observer], function(fn) {\n          try {\n            fn(value);\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        });\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$observe\n       * @kind function\n       *\n       * @description\n       * Observes an interpolated attribute.\n       *\n       * The observer function will be invoked once during the next `$digest` following\n       * compilation. The observer is then invoked whenever the interpolated value\n       * changes.\n       *\n       * @param {string} key Normalized key. (ie ngAttribute) .\n       * @param {function(interpolatedValue)} fn Function that will be called whenever\n                the interpolated value of the attribute changes.\n       *        See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.\n       * @returns {function()} Returns a deregistration function for this observer.\n       */\n      $observe: function(key, fn) {\n        var attrs = this,\n            $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),\n            listeners = ($$observers[key] || ($$observers[key] = []));\n\n        listeners.push(fn);\n        $rootScope.$evalAsync(function() {\n          if (!listeners.$$inter && attrs.hasOwnProperty(key)) {\n            // no one registered attribute interpolation function, so lets call it manually\n            fn(attrs[key]);\n          }\n        });\n\n        return function() {\n          arrayRemove(listeners, fn);\n        };\n      }\n    };\n\n\n    function safeAddClass($element, className) {\n      try {\n        $element.addClass(className);\n      } catch (e) {\n        // ignore, since it means that we are trying to set class on\n        // SVG element, where class name is read-only.\n      }\n    }\n\n\n    var startSymbol = $interpolate.startSymbol(),\n        endSymbol = $interpolate.endSymbol(),\n        denormalizeTemplate = (startSymbol == '{{' || endSymbol  == '}}')\n            ? identity\n            : function denormalizeTemplate(template) {\n              return template.replace(/\\{\\{/g, startSymbol).replace(/}}/g, endSymbol);\n        },\n        NG_ATTR_BINDING = /^ngAttr[A-Z]/;\n\n    compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {\n      var bindings = $element.data('$binding') || [];\n\n      if (isArray(binding)) {\n        bindings = bindings.concat(binding);\n      } else {\n        bindings.push(binding);\n      }\n\n      $element.data('$binding', bindings);\n    } : noop;\n\n    compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {\n      safeAddClass($element, 'ng-binding');\n    } : noop;\n\n    compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {\n      var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n      $element.data(dataName, scope);\n    } : noop;\n\n    compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {\n      safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');\n    } : noop;\n\n    return compile;\n\n    //================================\n\n    function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,\n                        previousCompileContext) {\n      if (!($compileNodes instanceof jqLite)) {\n        // jquery always rewraps, whereas we need to preserve the original selector so that we can\n        // modify it.\n        $compileNodes = jqLite($compileNodes);\n      }\n      // We can not compile top level text elements since text nodes can be merged and we will\n      // not be able to attach scope data to them, so we will wrap them in <span>\n      forEach($compileNodes, function(node, index) {\n        if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\\S+/) /* non-empty */ ) {\n          $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];\n        }\n      });\n      var compositeLinkFn =\n              compileNodes($compileNodes, transcludeFn, $compileNodes,\n                           maxPriority, ignoreDirective, previousCompileContext);\n      compile.$$addScopeClass($compileNodes);\n      var namespace = null;\n      return function publicLinkFn(scope, cloneConnectFn, options) {\n        assertArg(scope, 'scope');\n\n        options = options || {};\n        var parentBoundTranscludeFn = options.parentBoundTranscludeFn,\n          transcludeControllers = options.transcludeControllers,\n          futureParentElement = options.futureParentElement;\n\n        // When `parentBoundTranscludeFn` is passed, it is a\n        // `controllersBoundTransclude` function (it was previously passed\n        // as `transclude` to directive.link) so we must unwrap it to get\n        // its `boundTranscludeFn`\n        if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {\n          parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;\n        }\n\n        if (!namespace) {\n          namespace = detectNamespaceForChildElements(futureParentElement);\n        }\n        var $linkNode;\n        if (namespace !== 'html') {\n          // When using a directive with replace:true and templateUrl the $compileNodes\n          // (or a child element inside of them)\n          // might change, so we need to recreate the namespace adapted compileNodes\n          // for call to the link function.\n          // Note: This will already clone the nodes...\n          $linkNode = jqLite(\n            wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())\n          );\n        } else if (cloneConnectFn) {\n          // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart\n          // and sometimes changes the structure of the DOM.\n          $linkNode = JQLitePrototype.clone.call($compileNodes);\n        } else {\n          $linkNode = $compileNodes;\n        }\n\n        if (transcludeControllers) {\n          for (var controllerName in transcludeControllers) {\n            $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);\n          }\n        }\n\n        compile.$$addScopeInfo($linkNode, scope);\n\n        if (cloneConnectFn) cloneConnectFn($linkNode, scope);\n        if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);\n        return $linkNode;\n      };\n    }\n\n    function detectNamespaceForChildElements(parentElement) {\n      // TODO: Make this detect MathML as well...\n      var node = parentElement && parentElement[0];\n      if (!node) {\n        return 'html';\n      } else {\n        return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';\n      }\n    }\n\n    /**\n     * Compile function matches each node in nodeList against the directives. Once all directives\n     * for a particular node are collected their compile functions are executed. The compile\n     * functions return values - the linking functions - are combined into a composite linking\n     * function, which is the a linking function for the node.\n     *\n     * @param {NodeList} nodeList an array of nodes or NodeList to compile\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *        scope argument is auto-generated to the new child of the transcluded parent scope.\n     * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then\n     *        the rootElement must be set the jqLite collection of the compile root. This is\n     *        needed so that the jqLite collection items can be replaced with widgets.\n     * @param {number=} maxPriority Max directive priority.\n     * @returns {Function} A composite linking function of all of the matched directives or null.\n     */\n    function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,\n                            previousCompileContext) {\n      var linkFns = [],\n          attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;\n\n      for (var i = 0; i < nodeList.length; i++) {\n        attrs = new Attributes();\n\n        // we must always refer to nodeList[i] since the nodes can be replaced underneath us.\n        directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,\n                                        ignoreDirective);\n\n        nodeLinkFn = (directives.length)\n            ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,\n                                      null, [], [], previousCompileContext)\n            : null;\n\n        if (nodeLinkFn && nodeLinkFn.scope) {\n          compile.$$addScopeClass(attrs.$$element);\n        }\n\n        childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||\n                      !(childNodes = nodeList[i].childNodes) ||\n                      !childNodes.length)\n            ? null\n            : compileNodes(childNodes,\n                 nodeLinkFn ? (\n                  (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)\n                     && nodeLinkFn.transclude) : transcludeFn);\n\n        if (nodeLinkFn || childLinkFn) {\n          linkFns.push(i, nodeLinkFn, childLinkFn);\n          linkFnFound = true;\n          nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;\n        }\n\n        //use the previous context only for the first element in the virtual group\n        previousCompileContext = null;\n      }\n\n      // return a linking function if we have found anything, null otherwise\n      return linkFnFound ? compositeLinkFn : null;\n\n      function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {\n        var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;\n        var stableNodeList;\n\n\n        if (nodeLinkFnFound) {\n          // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our\n          // offsets don't get screwed up\n          var nodeListLength = nodeList.length;\n          stableNodeList = new Array(nodeListLength);\n\n          // create a sparse array by only copying the elements which have a linkFn\n          for (i = 0; i < linkFns.length; i+=3) {\n            idx = linkFns[i];\n            stableNodeList[idx] = nodeList[idx];\n          }\n        } else {\n          stableNodeList = nodeList;\n        }\n\n        for (i = 0, ii = linkFns.length; i < ii;) {\n          node = stableNodeList[linkFns[i++]];\n          nodeLinkFn = linkFns[i++];\n          childLinkFn = linkFns[i++];\n\n          if (nodeLinkFn) {\n            if (nodeLinkFn.scope) {\n              childScope = scope.$new();\n              compile.$$addScopeInfo(jqLite(node), childScope);\n            } else {\n              childScope = scope;\n            }\n\n            if (nodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(\n                  scope, nodeLinkFn.transclude, parentBoundTranscludeFn,\n                  nodeLinkFn.elementTranscludeOnThisElement);\n\n            } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {\n              childBoundTranscludeFn = parentBoundTranscludeFn;\n\n            } else if (!parentBoundTranscludeFn && transcludeFn) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);\n\n            } else {\n              childBoundTranscludeFn = null;\n            }\n\n            nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);\n\n          } else if (childLinkFn) {\n            childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);\n          }\n        }\n      }\n    }\n\n    function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {\n\n      var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {\n\n        if (!transcludedScope) {\n          transcludedScope = scope.$new(false, containingScope);\n          transcludedScope.$$transcluded = true;\n        }\n\n        return transcludeFn(transcludedScope, cloneFn, {\n          parentBoundTranscludeFn: previousBoundTranscludeFn,\n          transcludeControllers: controllers,\n          futureParentElement: futureParentElement\n        });\n      };\n\n      return boundTranscludeFn;\n    }\n\n    /**\n     * Looks for directives on the given node and adds them to the directive collection which is\n     * sorted.\n     *\n     * @param node Node to search.\n     * @param directives An array to which the directives are added to. This array is sorted before\n     *        the function returns.\n     * @param attrs The shared attrs object which is used to populate the normalized attributes.\n     * @param {number=} maxPriority Max directive priority.\n     */\n    function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n      var nodeType = node.nodeType,\n          attrsMap = attrs.$attr,\n          match,\n          className;\n\n      switch (nodeType) {\n        case NODE_TYPE_ELEMENT: /* Element */\n          // use the node name: <directive>\n          addDirective(directives,\n              directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);\n\n          // iterate over the attributes\n          for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,\n                   j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {\n            var attrStartName = false;\n            var attrEndName = false;\n\n            attr = nAttrs[j];\n            name = attr.name;\n            value = trim(attr.value);\n\n            // support ngAttr attribute binding\n            ngAttrName = directiveNormalize(name);\n            if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {\n              name = name.replace(PREFIX_REGEXP, '')\n                .substr(8).replace(/_(.)/g, function(match, letter) {\n                  return letter.toUpperCase();\n                });\n            }\n\n            var directiveNName = ngAttrName.replace(/(Start|End)$/, '');\n            if (directiveIsMultiElement(directiveNName)) {\n              if (ngAttrName === directiveNName + 'Start') {\n                attrStartName = name;\n                attrEndName = name.substr(0, name.length - 5) + 'end';\n                name = name.substr(0, name.length - 6);\n              }\n            }\n\n            nName = directiveNormalize(name.toLowerCase());\n            attrsMap[nName] = name;\n            if (isNgAttr || !attrs.hasOwnProperty(nName)) {\n                attrs[nName] = value;\n                if (getBooleanAttrName(node, nName)) {\n                  attrs[nName] = true; // presence means true\n                }\n            }\n            addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);\n            addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,\n                          attrEndName);\n          }\n\n          // use class as directive\n          className = node.className;\n          if (isObject(className)) {\n              // Maybe SVGAnimatedString\n              className = className.animVal;\n          }\n          if (isString(className) && className !== '') {\n            while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {\n              nName = directiveNormalize(match[2]);\n              if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[3]);\n              }\n              className = className.substr(match.index + match[0].length);\n            }\n          }\n          break;\n        case NODE_TYPE_TEXT: /* Text Node */\n          addTextInterpolateDirective(directives, node.nodeValue);\n          break;\n        case NODE_TYPE_COMMENT: /* Comment */\n          try {\n            match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);\n            if (match) {\n              nName = directiveNormalize(match[1]);\n              if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[2]);\n              }\n            }\n          } catch (e) {\n            // turns out that under some circumstances IE9 throws errors when one attempts to read\n            // comment's node value.\n            // Just ignore it and continue. (Can't seem to reproduce in test case.)\n          }\n          break;\n      }\n\n      directives.sort(byPriority);\n      return directives;\n    }\n\n    /**\n     * Given a node with an directive-start it collects all of the siblings until it finds\n     * directive-end.\n     * @param node\n     * @param attrStart\n     * @param attrEnd\n     * @returns {*}\n     */\n    function groupScan(node, attrStart, attrEnd) {\n      var nodes = [];\n      var depth = 0;\n      if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {\n        do {\n          if (!node) {\n            throw $compileMinErr('uterdir',\n                      \"Unterminated attribute, found '{0}' but no matching '{1}' found.\",\n                      attrStart, attrEnd);\n          }\n          if (node.nodeType == NODE_TYPE_ELEMENT) {\n            if (node.hasAttribute(attrStart)) depth++;\n            if (node.hasAttribute(attrEnd)) depth--;\n          }\n          nodes.push(node);\n          node = node.nextSibling;\n        } while (depth > 0);\n      } else {\n        nodes.push(node);\n      }\n\n      return jqLite(nodes);\n    }\n\n    /**\n     * Wrapper for linking function which converts normal linking function into a grouped\n     * linking function.\n     * @param linkFn\n     * @param attrStart\n     * @param attrEnd\n     * @returns {Function}\n     */\n    function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {\n      return function(scope, element, attrs, controllers, transcludeFn) {\n        element = groupScan(element[0], attrStart, attrEnd);\n        return linkFn(scope, element, attrs, controllers, transcludeFn);\n      };\n    }\n\n    /**\n     * Once the directives have been collected, their compile functions are executed. This method\n     * is responsible for inlining directive templates as well as terminating the application\n     * of the directives if the terminal directive has been reached.\n     *\n     * @param {Array} directives Array of collected directives to execute their compile function.\n     *        this needs to be pre-sorted by priority order.\n     * @param {Node} compileNode The raw DOM node to apply the compile functions to\n     * @param {Object} templateAttrs The shared attribute function\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *                                                  scope argument is auto-generated to the new\n     *                                                  child of the transcluded parent scope.\n     * @param {JQLite} jqCollection If we are working on the root of the compile tree then this\n     *                              argument has the root jqLite array so that we can replace nodes\n     *                              on it.\n     * @param {Object=} originalReplaceDirective An optional directive that will be ignored when\n     *                                           compiling the transclusion.\n     * @param {Array.<Function>} preLinkFns\n     * @param {Array.<Function>} postLinkFns\n     * @param {Object} previousCompileContext Context used for previous compilation of the current\n     *                                        node\n     * @returns {Function} linkFn\n     */\n    function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,\n                                   jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,\n                                   previousCompileContext) {\n      previousCompileContext = previousCompileContext || {};\n\n      var terminalPriority = -Number.MAX_VALUE,\n          newScopeDirective,\n          controllerDirectives = previousCompileContext.controllerDirectives,\n          controllers,\n          newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,\n          templateDirective = previousCompileContext.templateDirective,\n          nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,\n          hasTranscludeDirective = false,\n          hasTemplate = false,\n          hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,\n          $compileNode = templateAttrs.$$element = jqLite(compileNode),\n          directive,\n          directiveName,\n          $template,\n          replaceDirective = originalReplaceDirective,\n          childTranscludeFn = transcludeFn,\n          linkFn,\n          directiveValue;\n\n      // executes all directives on the current element\n      for (var i = 0, ii = directives.length; i < ii; i++) {\n        directive = directives[i];\n        var attrStart = directive.$$start;\n        var attrEnd = directive.$$end;\n\n        // collect multiblock sections\n        if (attrStart) {\n          $compileNode = groupScan(compileNode, attrStart, attrEnd);\n        }\n        $template = undefined;\n\n        if (terminalPriority > directive.priority) {\n          break; // prevent further processing of directives\n        }\n\n        if (directiveValue = directive.scope) {\n\n          // skip the check for directives with async templates, we'll check the derived sync\n          // directive when the template arrives\n          if (!directive.templateUrl) {\n            if (isObject(directiveValue)) {\n              // This directive is trying to add an isolated scope.\n              // Check that there is no scope of any kind already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,\n                                directive, $compileNode);\n              newIsolateScopeDirective = directive;\n            } else {\n              // This directive is trying to add a child scope.\n              // Check that there is no isolated scope already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,\n                                $compileNode);\n            }\n          }\n\n          newScopeDirective = newScopeDirective || directive;\n        }\n\n        directiveName = directive.name;\n\n        if (!directive.templateUrl && directive.controller) {\n          directiveValue = directive.controller;\n          controllerDirectives = controllerDirectives || {};\n          assertNoDuplicate(\"'\" + directiveName + \"' controller\",\n              controllerDirectives[directiveName], directive, $compileNode);\n          controllerDirectives[directiveName] = directive;\n        }\n\n        if (directiveValue = directive.transclude) {\n          hasTranscludeDirective = true;\n\n          // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.\n          // This option should only be used by directives that know how to safely handle element transclusion,\n          // where the transcluded nodes are added or replaced after linking.\n          if (!directive.$$tlb) {\n            assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);\n            nonTlbTranscludeDirective = directive;\n          }\n\n          if (directiveValue == 'element') {\n            hasElementTranscludeDirective = true;\n            terminalPriority = directive.priority;\n            $template = $compileNode;\n            $compileNode = templateAttrs.$$element =\n                jqLite(document.createComment(' ' + directiveName + ': ' +\n                                              templateAttrs[directiveName] + ' '));\n            compileNode = $compileNode[0];\n            replaceWith(jqCollection, sliceArgs($template), compileNode);\n\n            childTranscludeFn = compile($template, transcludeFn, terminalPriority,\n                                        replaceDirective && replaceDirective.name, {\n                                          // Don't pass in:\n                                          // - controllerDirectives - otherwise we'll create duplicates controllers\n                                          // - newIsolateScopeDirective or templateDirective - combining templates with\n                                          //   element transclusion doesn't make sense.\n                                          //\n                                          // We need only nonTlbTranscludeDirective so that we prevent putting transclusion\n                                          // on the same element more than once.\n                                          nonTlbTranscludeDirective: nonTlbTranscludeDirective\n                                        });\n          } else {\n            $template = jqLite(jqLiteClone(compileNode)).contents();\n            $compileNode.empty(); // clear contents\n            childTranscludeFn = compile($template, transcludeFn);\n          }\n        }\n\n        if (directive.template) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          directiveValue = (isFunction(directive.template))\n              ? directive.template($compileNode, templateAttrs)\n              : directive.template;\n\n          directiveValue = denormalizeTemplate(directiveValue);\n\n          if (directive.replace) {\n            replaceDirective = directive;\n            if (jqLiteIsTextNode(directiveValue)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  directiveName, '');\n            }\n\n            replaceWith(jqCollection, $compileNode, compileNode);\n\n            var newTemplateAttrs = {$attr: {}};\n\n            // combine directives from the original node and from the template:\n            // - take the array of directives for this element\n            // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)\n            // - collect directives from the template and sort them by priority\n            // - combine directives as: processed + template + unprocessed\n            var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);\n            var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));\n\n            if (newIsolateScopeDirective) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = directives.concat(templateDirectives).concat(unprocessedDirectives);\n            mergeTemplateAttributes(templateAttrs, newTemplateAttrs);\n\n            ii = directives.length;\n          } else {\n            $compileNode.html(directiveValue);\n          }\n        }\n\n        if (directive.templateUrl) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          if (directive.replace) {\n            replaceDirective = directive;\n          }\n\n          nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,\n              templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {\n                controllerDirectives: controllerDirectives,\n                newIsolateScopeDirective: newIsolateScopeDirective,\n                templateDirective: templateDirective,\n                nonTlbTranscludeDirective: nonTlbTranscludeDirective\n              });\n          ii = directives.length;\n        } else if (directive.compile) {\n          try {\n            linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);\n            if (isFunction(linkFn)) {\n              addLinkFns(null, linkFn, attrStart, attrEnd);\n            } else if (linkFn) {\n              addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);\n            }\n          } catch (e) {\n            $exceptionHandler(e, startingTag($compileNode));\n          }\n        }\n\n        if (directive.terminal) {\n          nodeLinkFn.terminal = true;\n          terminalPriority = Math.max(terminalPriority, directive.priority);\n        }\n\n      }\n\n      nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;\n      nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;\n      nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;\n      nodeLinkFn.templateOnThisElement = hasTemplate;\n      nodeLinkFn.transclude = childTranscludeFn;\n\n      previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;\n\n      // might be normal or delayed nodeLinkFn depending on if templateUrl is present\n      return nodeLinkFn;\n\n      ////////////////////\n\n      function addLinkFns(pre, post, attrStart, attrEnd) {\n        if (pre) {\n          if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);\n          pre.require = directive.require;\n          pre.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            pre = cloneAndAnnotateFn(pre, {isolateScope: true});\n          }\n          preLinkFns.push(pre);\n        }\n        if (post) {\n          if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);\n          post.require = directive.require;\n          post.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            post = cloneAndAnnotateFn(post, {isolateScope: true});\n          }\n          postLinkFns.push(post);\n        }\n      }\n\n\n      function getControllers(directiveName, require, $element, elementControllers) {\n        var value, retrievalMethod = 'data', optional = false;\n        var $searchElement = $element;\n        var match;\n        if (isString(require)) {\n          match = require.match(REQUIRE_PREFIX_REGEXP);\n          require = require.substring(match[0].length);\n\n          if (match[3]) {\n            if (match[1]) match[3] = null;\n            else match[1] = match[3];\n          }\n          if (match[1] === '^') {\n            retrievalMethod = 'inheritedData';\n          } else if (match[1] === '^^') {\n            retrievalMethod = 'inheritedData';\n            $searchElement = $element.parent();\n          }\n          if (match[2] === '?') {\n            optional = true;\n          }\n\n          value = null;\n\n          if (elementControllers && retrievalMethod === 'data') {\n            if (value = elementControllers[require]) {\n              value = value.instance;\n            }\n          }\n          value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');\n\n          if (!value && !optional) {\n            throw $compileMinErr('ctreq',\n                \"Controller '{0}', required by directive '{1}', can't be found!\",\n                require, directiveName);\n          }\n          return value || null;\n        } else if (isArray(require)) {\n          value = [];\n          forEach(require, function(require) {\n            value.push(getControllers(directiveName, require, $element, elementControllers));\n          });\n        }\n        return value;\n      }\n\n\n      function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {\n        var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,\n            attrs;\n\n        if (compileNode === linkNode) {\n          attrs = templateAttrs;\n          $element = templateAttrs.$$element;\n        } else {\n          $element = jqLite(linkNode);\n          attrs = new Attributes($element, templateAttrs);\n        }\n\n        if (newIsolateScopeDirective) {\n          isolateScope = scope.$new(true);\n        }\n\n        if (boundTranscludeFn) {\n          // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`\n          // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`\n          transcludeFn = controllersBoundTransclude;\n          transcludeFn.$$boundTransclude = boundTranscludeFn;\n        }\n\n        if (controllerDirectives) {\n          // TODO: merge `controllers` and `elementControllers` into single object.\n          controllers = {};\n          elementControllers = {};\n          forEach(controllerDirectives, function(directive) {\n            var locals = {\n              $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,\n              $element: $element,\n              $attrs: attrs,\n              $transclude: transcludeFn\n            }, controllerInstance;\n\n            controller = directive.controller;\n            if (controller == '@') {\n              controller = attrs[directive.name];\n            }\n\n            controllerInstance = $controller(controller, locals, true, directive.controllerAs);\n\n            // For directives with element transclusion the element is a comment,\n            // but jQuery .data doesn't support attaching data to comment nodes as it's hard to\n            // clean up (http://bugs.jquery.com/ticket/8335).\n            // Instead, we save the controllers for the element in a local hash and attach to .data\n            // later, once we have the actual element.\n            elementControllers[directive.name] = controllerInstance;\n            if (!hasElementTranscludeDirective) {\n              $element.data('$' + directive.name + 'Controller', controllerInstance.instance);\n            }\n\n            controllers[directive.name] = controllerInstance;\n          });\n        }\n\n        if (newIsolateScopeDirective) {\n          compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||\n              templateDirective === newIsolateScopeDirective.$$originalDirective)));\n          compile.$$addScopeClass($element, true);\n\n          var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];\n          var isolateBindingContext = isolateScope;\n          if (isolateScopeController && isolateScopeController.identifier &&\n              newIsolateScopeDirective.bindToController === true) {\n            isolateBindingContext = isolateScopeController.instance;\n          }\n\n          forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {\n            var attrName = definition.attrName,\n                optional = definition.optional,\n                mode = definition.mode, // @, =, or &\n                lastValue,\n                parentGet, parentSet, compare;\n\n            switch (mode) {\n\n              case '@':\n                attrs.$observe(attrName, function(value) {\n                  isolateBindingContext[scopeName] = value;\n                });\n                attrs.$$observers[attrName].$$scope = scope;\n                if (attrs[attrName]) {\n                  // If the attribute has been provided then we trigger an interpolation to ensure\n                  // the value is there for use in the link fn\n                  isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);\n                }\n                break;\n\n              case '=':\n                if (optional && !attrs[attrName]) {\n                  return;\n                }\n                parentGet = $parse(attrs[attrName]);\n                if (parentGet.literal) {\n                  compare = equals;\n                } else {\n                  compare = function(a, b) { return a === b || (a !== a && b !== b); };\n                }\n                parentSet = parentGet.assign || function() {\n                  // reset the change, or we will throw this exception on every $digest\n                  lastValue = isolateBindingContext[scopeName] = parentGet(scope);\n                  throw $compileMinErr('nonassign',\n                      \"Expression '{0}' used with directive '{1}' is non-assignable!\",\n                      attrs[attrName], newIsolateScopeDirective.name);\n                };\n                lastValue = isolateBindingContext[scopeName] = parentGet(scope);\n                var parentValueWatch = function parentValueWatch(parentValue) {\n                  if (!compare(parentValue, isolateBindingContext[scopeName])) {\n                    // we are out of sync and need to copy\n                    if (!compare(parentValue, lastValue)) {\n                      // parent changed and it has precedence\n                      isolateBindingContext[scopeName] = parentValue;\n                    } else {\n                      // if the parent can be assigned then do so\n                      parentSet(scope, parentValue = isolateBindingContext[scopeName]);\n                    }\n                  }\n                  return lastValue = parentValue;\n                };\n                parentValueWatch.$stateful = true;\n                var unwatch;\n                if (definition.collection) {\n                  unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);\n                } else {\n                  unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);\n                }\n                isolateScope.$on('$destroy', unwatch);\n                break;\n\n              case '&':\n                parentGet = $parse(attrs[attrName]);\n                isolateBindingContext[scopeName] = function(locals) {\n                  return parentGet(scope, locals);\n                };\n                break;\n            }\n          });\n        }\n        if (controllers) {\n          forEach(controllers, function(controller) {\n            controller();\n          });\n          controllers = null;\n        }\n\n        // PRELINKING\n        for (i = 0, ii = preLinkFns.length; i < ii; i++) {\n          linkFn = preLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // RECURSION\n        // We only pass the isolate scope, if the isolate directive has a template,\n        // otherwise the child elements do not belong to the isolate directive.\n        var scopeToChild = scope;\n        if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {\n          scopeToChild = isolateScope;\n        }\n        childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);\n\n        // POSTLINKING\n        for (i = postLinkFns.length - 1; i >= 0; i--) {\n          linkFn = postLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // This is the function that is injected as `$transclude`.\n        // Note: all arguments are optional!\n        function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {\n          var transcludeControllers;\n\n          // No scope passed in:\n          if (!isScope(scope)) {\n            futureParentElement = cloneAttachFn;\n            cloneAttachFn = scope;\n            scope = undefined;\n          }\n\n          if (hasElementTranscludeDirective) {\n            transcludeControllers = elementControllers;\n          }\n          if (!futureParentElement) {\n            futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;\n          }\n          return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n        }\n      }\n    }\n\n    function markDirectivesAsIsolate(directives) {\n      // mark all directives as needing isolate scope.\n      for (var j = 0, jj = directives.length; j < jj; j++) {\n        directives[j] = inherit(directives[j], {$$isolateScope: true});\n      }\n    }\n\n    /**\n     * looks up the directive and decorates it with exception handling and proper parameters. We\n     * call this the boundDirective.\n     *\n     * @param {string} name name of the directive to look up.\n     * @param {string} location The directive must be found in specific format.\n     *   String containing any of theses characters:\n     *\n     *   * `E`: element name\n     *   * `A': attribute\n     *   * `C`: class\n     *   * `M`: comment\n     * @returns {boolean} true if directive was added.\n     */\n    function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,\n                          endAttrName) {\n      if (name === ignoreDirective) return null;\n      var match = null;\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          try {\n            directive = directives[i];\n            if ((maxPriority === undefined || maxPriority > directive.priority) &&\n                 directive.restrict.indexOf(location) != -1) {\n              if (startAttrName) {\n                directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});\n              }\n              tDirectives.push(directive);\n              match = directive;\n            }\n          } catch (e) { $exceptionHandler(e); }\n        }\n      }\n      return match;\n    }\n\n\n    /**\n     * looks up the directive and returns true if it is a multi-element directive,\n     * and therefore requires DOM nodes between -start and -end markers to be grouped\n     * together.\n     *\n     * @param {string} name name of the directive to look up.\n     * @returns true if directive was registered as multi-element.\n     */\n    function directiveIsMultiElement(name) {\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          directive = directives[i];\n          if (directive.multiElement) {\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n\n    /**\n     * When the element is replaced with HTML template then the new attributes\n     * on the template need to be merged with the existing attributes in the DOM.\n     * The desired effect is to have both of the attributes present.\n     *\n     * @param {object} dst destination attributes (original DOM)\n     * @param {object} src source attributes (from the directive template)\n     */\n    function mergeTemplateAttributes(dst, src) {\n      var srcAttr = src.$attr,\n          dstAttr = dst.$attr,\n          $element = dst.$$element;\n\n      // reapply the old attributes to the new element\n      forEach(dst, function(value, key) {\n        if (key.charAt(0) != '$') {\n          if (src[key] && src[key] !== value) {\n            value += (key === 'style' ? ';' : ' ') + src[key];\n          }\n          dst.$set(key, value, true, srcAttr[key]);\n        }\n      });\n\n      // copy the new attributes on the old attrs object\n      forEach(src, function(value, key) {\n        if (key == 'class') {\n          safeAddClass($element, value);\n          dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;\n        } else if (key == 'style') {\n          $element.attr('style', $element.attr('style') + ';' + value);\n          dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;\n          // `dst` will never contain hasOwnProperty as DOM parser won't let it.\n          // You will get an \"InvalidCharacterError: DOM Exception 5\" error if you\n          // have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.\n        } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {\n          dst[key] = value;\n          dstAttr[key] = srcAttr[key];\n        }\n      });\n    }\n\n\n    function compileTemplateUrl(directives, $compileNode, tAttrs,\n        $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {\n      var linkQueue = [],\n          afterTemplateNodeLinkFn,\n          afterTemplateChildLinkFn,\n          beforeTemplateCompileNode = $compileNode[0],\n          origAsyncDirective = directives.shift(),\n          derivedSyncDirective = inherit(origAsyncDirective, {\n            templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective\n          }),\n          templateUrl = (isFunction(origAsyncDirective.templateUrl))\n              ? origAsyncDirective.templateUrl($compileNode, tAttrs)\n              : origAsyncDirective.templateUrl,\n          templateNamespace = origAsyncDirective.templateNamespace;\n\n      $compileNode.empty();\n\n      $templateRequest($sce.getTrustedResourceUrl(templateUrl))\n        .then(function(content) {\n          var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;\n\n          content = denormalizeTemplate(content);\n\n          if (origAsyncDirective.replace) {\n            if (jqLiteIsTextNode(content)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(templateNamespace, trim(content)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  origAsyncDirective.name, templateUrl);\n            }\n\n            tempTemplateAttrs = {$attr: {}};\n            replaceWith($rootElement, $compileNode, compileNode);\n            var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);\n\n            if (isObject(origAsyncDirective.scope)) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = templateDirectives.concat(directives);\n            mergeTemplateAttributes(tAttrs, tempTemplateAttrs);\n          } else {\n            compileNode = beforeTemplateCompileNode;\n            $compileNode.html(content);\n          }\n\n          directives.unshift(derivedSyncDirective);\n\n          afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,\n              childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,\n              previousCompileContext);\n          forEach($rootElement, function(node, i) {\n            if (node == compileNode) {\n              $rootElement[i] = $compileNode[0];\n            }\n          });\n          afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);\n\n          while (linkQueue.length) {\n            var scope = linkQueue.shift(),\n                beforeTemplateLinkNode = linkQueue.shift(),\n                linkRootElement = linkQueue.shift(),\n                boundTranscludeFn = linkQueue.shift(),\n                linkNode = $compileNode[0];\n\n            if (scope.$$destroyed) continue;\n\n            if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {\n              var oldClasses = beforeTemplateLinkNode.className;\n\n              if (!(previousCompileContext.hasElementTranscludeDirective &&\n                  origAsyncDirective.replace)) {\n                // it was cloned therefore we have to clone as well.\n                linkNode = jqLiteClone(compileNode);\n              }\n              replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);\n\n              // Copy in CSS classes from original node\n              safeAddClass(jqLite(linkNode), oldClasses);\n            }\n            if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n            } else {\n              childBoundTranscludeFn = boundTranscludeFn;\n            }\n            afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,\n              childBoundTranscludeFn);\n          }\n          linkQueue = null;\n        });\n\n      return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {\n        var childBoundTranscludeFn = boundTranscludeFn;\n        if (scope.$$destroyed) return;\n        if (linkQueue) {\n          linkQueue.push(scope,\n                         node,\n                         rootElement,\n                         childBoundTranscludeFn);\n        } else {\n          if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n            childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n          }\n          afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);\n        }\n      };\n    }\n\n\n    /**\n     * Sorting function for bound directives.\n     */\n    function byPriority(a, b) {\n      var diff = b.priority - a.priority;\n      if (diff !== 0) return diff;\n      if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;\n      return a.index - b.index;\n    }\n\n\n    function assertNoDuplicate(what, previousDirective, directive, element) {\n      if (previousDirective) {\n        throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',\n            previousDirective.name, directive.name, what, startingTag(element));\n      }\n    }\n\n\n    function addTextInterpolateDirective(directives, text) {\n      var interpolateFn = $interpolate(text, true);\n      if (interpolateFn) {\n        directives.push({\n          priority: 0,\n          compile: function textInterpolateCompileFn(templateNode) {\n            var templateNodeParent = templateNode.parent(),\n                hasCompileParent = !!templateNodeParent.length;\n\n            // When transcluding a template that has bindings in the root\n            // we don't have a parent and thus need to add the class during linking fn.\n            if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);\n\n            return function textInterpolateLinkFn(scope, node) {\n              var parent = node.parent();\n              if (!hasCompileParent) compile.$$addBindingClass(parent);\n              compile.$$addBindingInfo(parent, interpolateFn.expressions);\n              scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {\n                node[0].nodeValue = value;\n              });\n            };\n          }\n        });\n      }\n    }\n\n\n    function wrapTemplate(type, template) {\n      type = lowercase(type || 'html');\n      switch (type) {\n      case 'svg':\n      case 'math':\n        var wrapper = document.createElement('div');\n        wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';\n        return wrapper.childNodes[0].childNodes;\n      default:\n        return template;\n      }\n    }\n\n\n    function getTrustedContext(node, attrNormalizedName) {\n      if (attrNormalizedName == \"srcdoc\") {\n        return $sce.HTML;\n      }\n      var tag = nodeName_(node);\n      // maction[xlink:href] can source SVG.  It's not limited to <maction>.\n      if (attrNormalizedName == \"xlinkHref\" ||\n          (tag == \"form\" && attrNormalizedName == \"action\") ||\n          (tag != \"img\" && (attrNormalizedName == \"src\" ||\n                            attrNormalizedName == \"ngSrc\"))) {\n        return $sce.RESOURCE_URL;\n      }\n    }\n\n\n    function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {\n      var trustedContext = getTrustedContext(node, name);\n      allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;\n\n      var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);\n\n      // no interpolation found -> ignore\n      if (!interpolateFn) return;\n\n\n      if (name === \"multiple\" && nodeName_(node) === \"select\") {\n        throw $compileMinErr(\"selmulti\",\n            \"Binding to the 'multiple' attribute is not supported. Element: {0}\",\n            startingTag(node));\n      }\n\n      directives.push({\n        priority: 100,\n        compile: function() {\n            return {\n              pre: function attrInterpolatePreLinkFn(scope, element, attr) {\n                var $$observers = (attr.$$observers || (attr.$$observers = {}));\n\n                if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {\n                  throw $compileMinErr('nodomevents',\n                      \"Interpolations for HTML DOM event attributes are disallowed.  Please use the \" +\n                          \"ng- versions (such as ng-click instead of onclick) instead.\");\n                }\n\n                // If the attribute has changed since last $interpolate()ed\n                var newValue = attr[name];\n                if (newValue !== value) {\n                  // we need to interpolate again since the attribute value has been updated\n                  // (e.g. by another directive's compile function)\n                  // ensure unset/empty values make interpolateFn falsy\n                  interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);\n                  value = newValue;\n                }\n\n                // if attribute was updated so that there is no interpolation going on we don't want to\n                // register any observers\n                if (!interpolateFn) return;\n\n                // initialize attr object so that it's ready in case we need the value for isolate\n                // scope initialization, otherwise the value would not be available from isolate\n                // directive's linking fn during linking phase\n                attr[name] = interpolateFn(scope);\n\n                ($$observers[name] || ($$observers[name] = [])).$$inter = true;\n                (attr.$$observers && attr.$$observers[name].$$scope || scope).\n                  $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {\n                    //special case for class attribute addition + removal\n                    //so that class changes can tap into the animation\n                    //hooks provided by the $animate service. Be sure to\n                    //skip animations when the first digest occurs (when\n                    //both the new and the old values are the same) since\n                    //the CSS classes are the non-interpolated values\n                    if (name === 'class' && newValue != oldValue) {\n                      attr.$updateClass(newValue, oldValue);\n                    } else {\n                      attr.$set(name, newValue);\n                    }\n                  });\n              }\n            };\n          }\n      });\n    }\n\n\n    /**\n     * This is a special jqLite.replaceWith, which can replace items which\n     * have no parents, provided that the containing jqLite collection is provided.\n     *\n     * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes\n     *                               in the root of the tree.\n     * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep\n     *                                  the shell, but replace its DOM node reference.\n     * @param {Node} newNode The new DOM node.\n     */\n    function replaceWith($rootElement, elementsToRemove, newNode) {\n      var firstElementToRemove = elementsToRemove[0],\n          removeCount = elementsToRemove.length,\n          parent = firstElementToRemove.parentNode,\n          i, ii;\n\n      if ($rootElement) {\n        for (i = 0, ii = $rootElement.length; i < ii; i++) {\n          if ($rootElement[i] == firstElementToRemove) {\n            $rootElement[i++] = newNode;\n            for (var j = i, j2 = j + removeCount - 1,\n                     jj = $rootElement.length;\n                 j < jj; j++, j2++) {\n              if (j2 < jj) {\n                $rootElement[j] = $rootElement[j2];\n              } else {\n                delete $rootElement[j];\n              }\n            }\n            $rootElement.length -= removeCount - 1;\n\n            // If the replaced element is also the jQuery .context then replace it\n            // .context is a deprecated jQuery api, so we should set it only when jQuery set it\n            // http://api.jquery.com/context/\n            if ($rootElement.context === firstElementToRemove) {\n              $rootElement.context = newNode;\n            }\n            break;\n          }\n        }\n      }\n\n      if (parent) {\n        parent.replaceChild(newNode, firstElementToRemove);\n      }\n\n      // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?\n      var fragment = document.createDocumentFragment();\n      fragment.appendChild(firstElementToRemove);\n\n      // Copy over user data (that includes Angular's $scope etc.). Don't copy private\n      // data here because there's no public interface in jQuery to do that and copying over\n      // event listeners (which is the main use of private data) wouldn't work anyway.\n      jqLite(newNode).data(jqLite(firstElementToRemove).data());\n\n      // Remove data of the replaced element. We cannot just call .remove()\n      // on the element it since that would deallocate scope that is needed\n      // for the new node. Instead, remove the data \"manually\".\n      if (!jQuery) {\n        delete jqLite.cache[firstElementToRemove[jqLite.expando]];\n      } else {\n        // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after\n        // the replaced element. The cleanData version monkey-patched by Angular would cause\n        // the scope to be trashed and we do need the very same scope to work with the new\n        // element. However, we cannot just cache the non-patched version and use it here as\n        // that would break if another library patches the method after Angular does (one\n        // example is jQuery UI). Instead, set a flag indicating scope destroying should be\n        // skipped this one time.\n        skipDestroyOnNextJQueryCleanData = true;\n        jQuery.cleanData([firstElementToRemove]);\n      }\n\n      for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {\n        var element = elementsToRemove[k];\n        jqLite(element).remove(); // must do this way to clean up expando\n        fragment.appendChild(element);\n        delete elementsToRemove[k];\n      }\n\n      elementsToRemove[0] = newNode;\n      elementsToRemove.length = 1;\n    }\n\n\n    function cloneAndAnnotateFn(fn, annotation) {\n      return extend(function() { return fn.apply(null, arguments); }, fn, annotation);\n    }\n\n\n    function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {\n      try {\n        linkFn(scope, $element, attrs, controllers, transcludeFn);\n      } catch (e) {\n        $exceptionHandler(e, startingTag($element));\n      }\n    }\n  }];\n}\n\nvar PREFIX_REGEXP = /^((?:x|data)[\\:\\-_])/i;\n/**\n * Converts all accepted directives format into proper directive name.\n * @param name Name to normalize\n */\nfunction directiveNormalize(name) {\n  return camelCase(name.replace(PREFIX_REGEXP, ''));\n}\n\n/**\n * @ngdoc type\n * @name $compile.directive.Attributes\n *\n * @description\n * A shared object between directive compile / linking functions which contains normalized DOM\n * element attributes. The values reflect current binding state `{{ }}`. The normalization is\n * needed since all of these are treated as equivalent in Angular:\n *\n * ```\n *    <span ng:bind=\"a\" ng-bind=\"a\" data-ng-bind=\"a\" x-ng-bind=\"a\">\n * ```\n */\n\n/**\n * @ngdoc property\n * @name $compile.directive.Attributes#$attr\n *\n * @description\n * A map of DOM element attribute names to the normalized name. This is\n * needed to do reverse lookup from normalized name back to actual name.\n */\n\n\n/**\n * @ngdoc method\n * @name $compile.directive.Attributes#$set\n * @kind function\n *\n * @description\n * Set DOM element attribute value.\n *\n *\n * @param {string} name Normalized element attribute name of the property to modify. The name is\n *          reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}\n *          property to the original name.\n * @param {string} value Value to set the attribute to. The value can be an interpolated string.\n */\n\n\n\n/**\n * Closure compiler type information\n */\n\nfunction nodesetLinkingFn(\n  /* angular.Scope */ scope,\n  /* NodeList */ nodeList,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction directiveLinkingFn(\n  /* nodesetLinkingFn */ nodesetLinkingFn,\n  /* angular.Scope */ scope,\n  /* Node */ node,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction tokenDifference(str1, str2) {\n  var values = '',\n      tokens1 = str1.split(/\\s+/),\n      tokens2 = str2.split(/\\s+/);\n\n  outer:\n  for (var i = 0; i < tokens1.length; i++) {\n    var token = tokens1[i];\n    for (var j = 0; j < tokens2.length; j++) {\n      if (token == tokens2[j]) continue outer;\n    }\n    values += (values.length > 0 ? ' ' : '') + token;\n  }\n  return values;\n}\n\nfunction removeComments(jqNodes) {\n  jqNodes = jqLite(jqNodes);\n  var i = jqNodes.length;\n\n  if (i <= 1) {\n    return jqNodes;\n  }\n\n  while (i--) {\n    var node = jqNodes[i];\n    if (node.nodeType === NODE_TYPE_COMMENT) {\n      splice.call(jqNodes, i, 1);\n    }\n  }\n  return jqNodes;\n}\n\nvar $controllerMinErr = minErr('$controller');\n\n/**\n * @ngdoc provider\n * @name $controllerProvider\n * @description\n * The {@link ng.$controller $controller service} is used by Angular to create new\n * controllers.\n *\n * This provider allows controller registration via the\n * {@link ng.$controllerProvider#register register} method.\n */\nfunction $ControllerProvider() {\n  var controllers = {},\n      globals = false,\n      CNTRL_REG = /^(\\S+)(\\s+as\\s+(\\w+))?$/;\n\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#register\n   * @param {string|Object} name Controller name, or an object map of controllers where the keys are\n   *    the names and the values are the constructors.\n   * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\n   *    annotations in the array notation).\n   */\n  this.register = function(name, constructor) {\n    assertNotHasOwnProperty(name, 'controller');\n    if (isObject(name)) {\n      extend(controllers, name);\n    } else {\n      controllers[name] = constructor;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#allowGlobals\n   * @description If called, allows `$controller` to find controller constructors on `window`\n   */\n  this.allowGlobals = function() {\n    globals = true;\n  };\n\n\n  this.$get = ['$injector', '$window', function($injector, $window) {\n\n    /**\n     * @ngdoc service\n     * @name $controller\n     * @requires $injector\n     *\n     * @param {Function|string} constructor If called with a function then it's considered to be the\n     *    controller constructor function. Otherwise it's considered to be a string which is used\n     *    to retrieve the controller constructor using the following steps:\n     *\n     *    * check if a controller with given name is registered via `$controllerProvider`\n     *    * check if evaluating the string on the current scope returns a constructor\n     *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\n     *      `window` object (not recommended)\n     *\n     *    The string can use the `controller as property` syntax, where the controller instance is published\n     *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n     *    to work correctly.\n     *\n     * @param {Object} locals Injection locals for Controller.\n     * @return {Object} Instance of given controller.\n     *\n     * @description\n     * `$controller` service is responsible for instantiating controllers.\n     *\n     * It's just a simple call to {@link auto.$injector $injector}, but extracted into\n     * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).\n     */\n    return function(expression, locals, later, ident) {\n      // PRIVATE API:\n      //   param `later` --- indicates that the controller's constructor is invoked at a later time.\n      //                     If true, $controller will allocate the object with the correct\n      //                     prototype chain, but will not invoke the controller until a returned\n      //                     callback is invoked.\n      //   param `ident` --- An optional label which overrides the label parsed from the controller\n      //                     expression, if any.\n      var instance, match, constructor, identifier;\n      later = later === true;\n      if (ident && isString(ident)) {\n        identifier = ident;\n      }\n\n      if (isString(expression)) {\n        match = expression.match(CNTRL_REG);\n        if (!match) {\n          throw $controllerMinErr('ctrlfmt',\n            \"Badly formed controller string '{0}'. \" +\n            \"Must match `__name__ as __id__` or `__name__`.\", expression);\n        }\n        constructor = match[1],\n        identifier = identifier || match[3];\n        expression = controllers.hasOwnProperty(constructor)\n            ? controllers[constructor]\n            : getter(locals.$scope, constructor, true) ||\n                (globals ? getter($window, constructor, true) : undefined);\n\n        assertArgFn(expression, constructor, true);\n      }\n\n      if (later) {\n        // Instantiate controller later:\n        // This machinery is used to create an instance of the object before calling the\n        // controller's constructor itself.\n        //\n        // This allows properties to be added to the controller before the constructor is\n        // invoked. Primarily, this is used for isolate scope bindings in $compile.\n        //\n        // This feature is not intended for use by applications, and is thus not documented\n        // publicly.\n        // Object creation: http://jsperf.com/create-constructor/2\n        var controllerPrototype = (isArray(expression) ?\n          expression[expression.length - 1] : expression).prototype;\n        instance = Object.create(controllerPrototype || null);\n\n        if (identifier) {\n          addIdentifier(locals, identifier, instance, constructor || expression.name);\n        }\n\n        return extend(function() {\n          $injector.invoke(expression, instance, locals, constructor);\n          return instance;\n        }, {\n          instance: instance,\n          identifier: identifier\n        });\n      }\n\n      instance = $injector.instantiate(expression, locals, constructor);\n\n      if (identifier) {\n        addIdentifier(locals, identifier, instance, constructor || expression.name);\n      }\n\n      return instance;\n    };\n\n    function addIdentifier(locals, identifier, instance, name) {\n      if (!(locals && isObject(locals.$scope))) {\n        throw minErr('$controller')('noscp',\n          \"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.\",\n          name, identifier);\n      }\n\n      locals.$scope[identifier] = instance;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $document\n * @requires $window\n *\n * @description\n * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.\n *\n * @example\n   <example module=\"documentExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <p>$document title: <b ng-bind=\"title\"></b></p>\n         <p>window.document title: <b ng-bind=\"windowTitle\"></b></p>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('documentExample', [])\n         .controller('ExampleController', ['$scope', '$document', function($scope, $document) {\n           $scope.title = $document[0].title;\n           $scope.windowTitle = angular.element(window.document)[0].title;\n         }]);\n     </file>\n   </example>\n */\nfunction $DocumentProvider() {\n  this.$get = ['$window', function(window) {\n    return jqLite(window.document);\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n * @requires ng.$log\n *\n * @description\n * Any uncaught exception in angular expressions is delegated to this service.\n * The default implementation simply delegates to `$log.error` which logs it into\n * the browser console.\n *\n * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by\n * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.\n *\n * ## Example:\n *\n * ```js\n *   angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {\n *     return function(exception, cause) {\n *       exception.message += ' (caused by \"' + cause + '\")';\n *       throw exception;\n *     };\n *   });\n * ```\n *\n * This example will override the normal action of `$exceptionHandler`, to make angular\n * exceptions fail hard when they happen, instead of just logging to the console.\n *\n * <hr />\n * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`\n * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}\n * (unless executed during a digest).\n *\n * If you wish, you can manually delegate exceptions, e.g.\n * `try { ... } catch(e) { $exceptionHandler(e); }`\n *\n * @param {Error} exception Exception associated with the error.\n * @param {string=} cause optional information about the context in which\n *       the error was thrown.\n *\n */\nfunction $ExceptionHandlerProvider() {\n  this.$get = ['$log', function($log) {\n    return function(exception, cause) {\n      $log.error.apply($log, arguments);\n    };\n  }];\n}\n\nvar APPLICATION_JSON = 'application/json';\nvar CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};\nvar JSON_START = /^\\[|^\\{(?!\\{)/;\nvar JSON_ENDS = {\n  '[': /]$/,\n  '{': /}$/\n};\nvar JSON_PROTECTION_PREFIX = /^\\)\\]\\}',?\\n/;\n\nfunction defaultHttpResponseTransform(data, headers) {\n  if (isString(data)) {\n    // Strip json vulnerability protection prefix and trim whitespace\n    var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();\n\n    if (tempData) {\n      var contentType = headers('Content-Type');\n      if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {\n        data = fromJson(tempData);\n      }\n    }\n  }\n\n  return data;\n}\n\nfunction isJsonLike(str) {\n    var jsonStart = str.match(JSON_START);\n    return jsonStart && JSON_ENDS[jsonStart[0]].test(str);\n}\n\n/**\n * Parse headers into key value object\n *\n * @param {string} headers Raw headers as a string\n * @returns {Object} Parsed headers as key value object\n */\nfunction parseHeaders(headers) {\n  var parsed = createMap(), key, val, i;\n\n  if (!headers) return parsed;\n\n  forEach(headers.split('\\n'), function(line) {\n    i = line.indexOf(':');\n    key = lowercase(trim(line.substr(0, i)));\n    val = trim(line.substr(i + 1));\n\n    if (key) {\n      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n    }\n  });\n\n  return parsed;\n}\n\n\n/**\n * Returns a function that provides access to parsed headers.\n *\n * Headers are lazy parsed when first requested.\n * @see parseHeaders\n *\n * @param {(string|Object)} headers Headers to provide access to.\n * @returns {function(string=)} Returns a getter function which if called with:\n *\n *   - if called with single an argument returns a single header value or null\n *   - if called with no arguments returns an object containing all headers.\n */\nfunction headersGetter(headers) {\n  var headersObj = isObject(headers) ? headers : undefined;\n\n  return function(name) {\n    if (!headersObj) headersObj =  parseHeaders(headers);\n\n    if (name) {\n      var value = headersObj[lowercase(name)];\n      if (value === void 0) {\n        value = null;\n      }\n      return value;\n    }\n\n    return headersObj;\n  };\n}\n\n\n/**\n * Chain all given functions\n *\n * This function is used for both request and response transforming\n *\n * @param {*} data Data to transform.\n * @param {function(string=)} headers HTTP headers getter fn.\n * @param {number} status HTTP status code of the response.\n * @param {(Function|Array.<Function>)} fns Function or an array of functions.\n * @returns {*} Transformed data.\n */\nfunction transformData(data, headers, status, fns) {\n  if (isFunction(fns))\n    return fns(data, headers, status);\n\n  forEach(fns, function(fn) {\n    data = fn(data, headers, status);\n  });\n\n  return data;\n}\n\n\nfunction isSuccess(status) {\n  return 200 <= status && status < 300;\n}\n\n\n/**\n * @ngdoc provider\n * @name $httpProvider\n * @description\n * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.\n * */\nfunction $HttpProvider() {\n  /**\n   * @ngdoc property\n   * @name $httpProvider#defaults\n   * @description\n   *\n   * Object containing default values for all {@link ng.$http $http} requests.\n   *\n   * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}\n   * that will provide the cache for all requests who set their `cache` property to `true`.\n   * If you set the `default.cache = false` then only requests that specify their own custom\n   * cache object will be cached. See {@link $http#caching $http Caching} for more information.\n   *\n   * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.\n   * Defaults value is `'XSRF-TOKEN'`.\n   *\n   * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the\n   * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.\n   *\n   * - **`defaults.headers`** - {Object} - Default headers for all $http requests.\n   * Refer to {@link ng.$http#setting-http-headers $http} for documentation on\n   * setting default headers.\n   *     - **`defaults.headers.common`**\n   *     - **`defaults.headers.post`**\n   *     - **`defaults.headers.put`**\n   *     - **`defaults.headers.patch`**\n   *\n   **/\n  var defaults = this.defaults = {\n    // transform incoming response data\n    transformResponse: [defaultHttpResponseTransform],\n\n    // transform outgoing request data\n    transformRequest: [function(d) {\n      return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;\n    }],\n\n    // default headers\n    headers: {\n      common: {\n        'Accept': 'application/json, text/plain, */*'\n      },\n      post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)\n    },\n\n    xsrfCookieName: 'XSRF-TOKEN',\n    xsrfHeaderName: 'X-XSRF-TOKEN'\n  };\n\n  var useApplyAsync = false;\n  /**\n   * @ngdoc method\n   * @name $httpProvider#useApplyAsync\n   * @description\n   *\n   * Configure $http service to combine processing of multiple http responses received at around\n   * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in\n   * significant performance improvement for bigger applications that make many HTTP requests\n   * concurrently (common during application bootstrap).\n   *\n   * Defaults to false. If no value is specifed, returns the current configured value.\n   *\n   * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred\n   *    \"apply\" on the next tick, giving time for subsequent requests in a roughly ~10ms window\n   *    to load and share the same digest cycle.\n   *\n   * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n   *    otherwise, returns the current configured value.\n   **/\n  this.useApplyAsync = function(value) {\n    if (isDefined(value)) {\n      useApplyAsync = !!value;\n      return this;\n    }\n    return useApplyAsync;\n  };\n\n  /**\n   * @ngdoc property\n   * @name $httpProvider#interceptors\n   * @description\n   *\n   * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}\n   * pre-processing of request or postprocessing of responses.\n   *\n   * These service factories are ordered by request, i.e. they are applied in the same order as the\n   * array, on request, but reverse order, on response.\n   *\n   * {@link ng.$http#interceptors Interceptors detailed info}\n   **/\n  var interceptorFactories = this.interceptors = [];\n\n  this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',\n      function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {\n\n    var defaultCache = $cacheFactory('$http');\n\n    /**\n     * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\n     * The reversal is needed so that we can build up the interception chain around the\n     * server request.\n     */\n    var reversedInterceptors = [];\n\n    forEach(interceptorFactories, function(interceptorFactory) {\n      reversedInterceptors.unshift(isString(interceptorFactory)\n          ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\n    });\n\n    /**\n     * @ngdoc service\n     * @kind function\n     * @name $http\n     * @requires ng.$httpBackend\n     * @requires $cacheFactory\n     * @requires $rootScope\n     * @requires $q\n     * @requires $injector\n     *\n     * @description\n     * The `$http` service is a core Angular service that facilitates communication with the remote\n     * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)\n     * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).\n     *\n     * For unit testing applications that use `$http` service, see\n     * {@link ngMock.$httpBackend $httpBackend mock}.\n     *\n     * For a higher level of abstraction, please check out the {@link ngResource.$resource\n     * $resource} service.\n     *\n     * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by\n     * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage\n     * it is important to familiarize yourself with these APIs and the guarantees they provide.\n     *\n     *\n     * ## General usage\n     * The `$http` service is a function which takes a single argument — a configuration object —\n     * that is used to generate an HTTP request and returns  a {@link ng.$q promise}\n     * with two $http specific methods: `success` and `error`.\n     *\n     * ```js\n     *   // Simple GET request example :\n     *   $http.get('/someUrl').\n     *     success(function(data, status, headers, config) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }).\n     *     error(function(data, status, headers, config) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     * ```js\n     *   // Simple POST request example (passing data) :\n     *   $http.post('/someUrl', {msg:'hello word!'}).\n     *     success(function(data, status, headers, config) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }).\n     *     error(function(data, status, headers, config) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     *\n     * Since the returned value of calling the $http function is a `promise`, you can also use\n     * the `then` method to register callbacks, and these callbacks will receive a single argument –\n     * an object representing the response. See the API signature and type info below for more\n     * details.\n     *\n     * A response status code between 200 and 299 is considered a success status and\n     * will result in the success callback being called. Note that if the response is a redirect,\n     * XMLHttpRequest will transparently follow it, meaning that the error callback will not be\n     * called for such responses.\n     *\n     * ## Writing Unit Tests that use $http\n     * When unit testing (using {@link ngMock ngMock}), it is necessary to call\n     * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending\n     * request using trained responses.\n     *\n     * ```\n     * $httpBackend.expectGET(...);\n     * $http.get(...);\n     * $httpBackend.flush();\n     * ```\n     *\n     * ## Shortcut methods\n     *\n     * Shortcut methods are also available. All shortcut methods require passing in the URL, and\n     * request data must be passed in for POST/PUT requests.\n     *\n     * ```js\n     *   $http.get('/someUrl').success(successCallback);\n     *   $http.post('/someUrl', data).success(successCallback);\n     * ```\n     *\n     * Complete list of shortcut methods:\n     *\n     * - {@link ng.$http#get $http.get}\n     * - {@link ng.$http#head $http.head}\n     * - {@link ng.$http#post $http.post}\n     * - {@link ng.$http#put $http.put}\n     * - {@link ng.$http#delete $http.delete}\n     * - {@link ng.$http#jsonp $http.jsonp}\n     * - {@link ng.$http#patch $http.patch}\n     *\n     *\n     * ## Setting HTTP Headers\n     *\n     * The $http service will automatically add certain HTTP headers to all requests. These defaults\n     * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration\n     * object, which currently contains this default configuration:\n     *\n     * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):\n     *   - `Accept: application/json, text/plain, * / *`\n     * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)\n     *   - `Content-Type: application/json`\n     * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)\n     *   - `Content-Type: application/json`\n     *\n     * To add or overwrite these defaults, simply add or remove a property from these configuration\n     * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object\n     * with the lowercased HTTP method name as the key, e.g.\n     * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.\n     *\n     * The defaults can also be set at runtime via the `$http.defaults` object in the same\n     * fashion. For example:\n     *\n     * ```\n     * module.run(function($http) {\n     *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'\n     * });\n     * ```\n     *\n     * In addition, you can supply a `headers` property in the config object passed when\n     * calling `$http(config)`, which overrides the defaults without changing them globally.\n     *\n     * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,\n     * Use the `headers` property, setting the desired header to `undefined`. For example:\n     *\n     * ```js\n     * var req = {\n     *  method: 'POST',\n     *  url: 'http://example.com',\n     *  headers: {\n     *    'Content-Type': undefined\n     *  },\n     *  data: { test: 'test' },\n     * }\n     *\n     * $http(req).success(function(){...}).error(function(){...});\n     * ```\n     *\n     * ## Transforming Requests and Responses\n     *\n     * Both requests and responses can be transformed using transformation functions: `transformRequest`\n     * and `transformResponse`. These properties can be a single function that returns\n     * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,\n     * which allows you to `push` or `unshift` a new transformation function into the transformation chain.\n     *\n     * ### Default Transformations\n     *\n     * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and\n     * `defaults.transformResponse` properties. If a request does not provide its own transformations\n     * then these will be applied.\n     *\n     * You can augment or replace the default transformations by modifying these properties by adding to or\n     * replacing the array.\n     *\n     * Angular provides the following default transformations:\n     *\n     * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):\n     *\n     * - If the `data` property of the request configuration object contains an object, serialize it\n     *   into JSON format.\n     *\n     * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):\n     *\n     *  - If XSRF prefix is detected, strip it (see Security Considerations section below).\n     *  - If JSON response is detected, deserialize it using a JSON parser.\n     *\n     *\n     * ### Overriding the Default Transformations Per Request\n     *\n     * If you wish override the request/response transformations only for a single request then provide\n     * `transformRequest` and/or `transformResponse` properties on the configuration object passed\n     * into `$http`.\n     *\n     * Note that if you provide these properties on the config object the default transformations will be\n     * overwritten. If you wish to augment the default transformations then you must include them in your\n     * local transformation array.\n     *\n     * The following code demonstrates adding a new response transformation to be run after the default response\n     * transformations have been run.\n     *\n     * ```js\n     * function appendTransform(defaults, transform) {\n     *\n     *   // We can't guarantee that the default transformation is an array\n     *   defaults = angular.isArray(defaults) ? defaults : [defaults];\n     *\n     *   // Append the new transformation to the defaults\n     *   return defaults.concat(transform);\n     * }\n     *\n     * $http({\n     *   url: '...',\n     *   method: 'GET',\n     *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {\n     *     return doTransform(value);\n     *   })\n     * });\n     * ```\n     *\n     *\n     * ## Caching\n     *\n     * To enable caching, set the request configuration `cache` property to `true` (to use default\n     * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).\n     * When the cache is enabled, `$http` stores the response from the server in the specified\n     * cache. The next time the same request is made, the response is served from the cache without\n     * sending a request to the server.\n     *\n     * Note that even if the response is served from cache, delivery of the data is asynchronous in\n     * the same way that real requests are.\n     *\n     * If there are multiple GET requests for the same URL that should be cached using the same\n     * cache, but the cache is not populated yet, only one request to the server will be made and\n     * the remaining requests will be fulfilled using the response from the first request.\n     *\n     * You can change the default cache to a new object (built with\n     * {@link ng.$cacheFactory `$cacheFactory`}) by updating the\n     * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set\n     * their `cache` property to `true` will now use this cache object.\n     *\n     * If you set the default cache to `false` then only requests that specify their own custom\n     * cache object will be cached.\n     *\n     * ## Interceptors\n     *\n     * Before you start creating interceptors, be sure to understand the\n     * {@link ng.$q $q and deferred/promise APIs}.\n     *\n     * For purposes of global error handling, authentication, or any kind of synchronous or\n     * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be\n     * able to intercept requests before they are handed to the server and\n     * responses before they are handed over to the application code that\n     * initiated these requests. The interceptors leverage the {@link ng.$q\n     * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.\n     *\n     * The interceptors are service factories that are registered with the `$httpProvider` by\n     * adding them to the `$httpProvider.interceptors` array. The factory is called and\n     * injected with dependencies (if specified) and returns the interceptor.\n     *\n     * There are two kinds of interceptors (and two kinds of rejection interceptors):\n     *\n     *   * `request`: interceptors get called with a http `config` object. The function is free to\n     *     modify the `config` object or create a new one. The function needs to return the `config`\n     *     object directly, or a promise containing the `config` or a new `config` object.\n     *   * `requestError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *   * `response`: interceptors get called with http `response` object. The function is free to\n     *     modify the `response` object or create a new one. The function needs to return the `response`\n     *     object directly, or as a promise containing the `response` or a new `response` object.\n     *   * `responseError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *\n     *\n     * ```js\n     *   // register the interceptor as a service\n     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {\n     *     return {\n     *       // optional method\n     *       'request': function(config) {\n     *         // do something on success\n     *         return config;\n     *       },\n     *\n     *       // optional method\n     *      'requestError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       },\n     *\n     *\n     *\n     *       // optional method\n     *       'response': function(response) {\n     *         // do something on success\n     *         return response;\n     *       },\n     *\n     *       // optional method\n     *      'responseError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       }\n     *     };\n     *   });\n     *\n     *   $httpProvider.interceptors.push('myHttpInterceptor');\n     *\n     *\n     *   // alternatively, register the interceptor via an anonymous factory\n     *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {\n     *     return {\n     *      'request': function(config) {\n     *          // same as above\n     *       },\n     *\n     *       'response': function(response) {\n     *          // same as above\n     *       }\n     *     };\n     *   });\n     * ```\n     *\n     * ## Security Considerations\n     *\n     * When designing web applications, consider security threats from:\n     *\n     * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\n     *\n     * Both server and the client must cooperate in order to eliminate these threats. Angular comes\n     * pre-configured with strategies that address these issues, but for this to work backend server\n     * cooperation is required.\n     *\n     * ### JSON Vulnerability Protection\n     *\n     * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * allows third party website to turn your JSON resource URL into\n     * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To\n     * counter this your server can prefix all JSON requests with following string `\")]}',\\n\"`.\n     * Angular will automatically strip the prefix before processing it as JSON.\n     *\n     * For example if your server needs to return:\n     * ```js\n     * ['one','two']\n     * ```\n     *\n     * which is vulnerable to attack, your server can return:\n     * ```js\n     * )]}',\n     * ['one','two']\n     * ```\n     *\n     * Angular will strip the prefix, before processing the JSON.\n     *\n     *\n     * ### Cross Site Request Forgery (XSRF) Protection\n     *\n     * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which\n     * an unauthorized site can gain your user's private data. Angular provides a mechanism\n     * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie\n     * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only\n     * JavaScript that runs on your domain could read the cookie, your server can be assured that\n     * the XHR came from JavaScript running on your domain. The header will not be set for\n     * cross-domain requests.\n     *\n     * To take advantage of this, your server needs to set a token in a JavaScript readable session\n     * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the\n     * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure\n     * that only JavaScript running on your domain could have sent the request. The token must be\n     * unique for each user and must be verifiable by the server (to prevent the JavaScript from\n     * making up its own tokens). We recommend that the token is a digest of your site's\n     * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)\n     * for added security.\n     *\n     * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName\n     * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,\n     * or the per-request config object.\n     *\n     *\n     * @param {object} config Object describing the request to be made and how it should be\n     *    processed. The object has following properties:\n     *\n     *    - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)\n     *    - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.\n     *    - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned\n     *      to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be\n     *      JSONified.\n     *    - **data** – `{string|Object}` – Data to be sent as the request message data.\n     *    - **headers** – `{Object}` – Map of strings or functions which return strings representing\n     *      HTTP headers to send to the server. If the return value of a function is null, the\n     *      header will not be sent.\n     *    - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.\n     *    - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.\n     *    - **transformRequest** –\n     *      `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      request body and headers and returns its transformed (typically serialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default Transformations}\n     *    - **transformResponse** –\n     *      `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      response body, headers and status and returns its transformed (typically deserialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default Transformations}\n     *    - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\n     *      GET request, otherwise if a cache instance built with\n     *      {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\n     *      caching.\n     *    - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}\n     *      that should abort the request when resolved.\n     *    - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the\n     *      XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)\n     *      for more information.\n     *    - **responseType** - `{string}` - see\n     *      [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).\n     *\n     * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the\n     *   standard `then` method and two http specific methods: `success` and `error`. The `then`\n     *   method takes two arguments a success and an error callback which will be called with a\n     *   response object. The `success` and `error` methods take a single argument - a function that\n     *   will be called when the request succeeds or fails respectively. The arguments passed into\n     *   these functions are destructured representation of the response object passed into the\n     *   `then` method. The response object has these properties:\n     *\n     *   - **data** – `{string|Object}` – The response body transformed with the transform\n     *     functions.\n     *   - **status** – `{number}` – HTTP status code of the response.\n     *   - **headers** – `{function([headerName])}` – Header getter function.\n     *   - **config** – `{Object}` – The configuration object that was used to generate the request.\n     *   - **statusText** – `{string}` – HTTP status text of the response.\n     *\n     * @property {Array.<Object>} pendingRequests Array of config objects for currently pending\n     *   requests. This is primarily meant to be used for debugging purposes.\n     *\n     *\n     * @example\n<example module=\"httpExample\">\n<file name=\"index.html\">\n  <div ng-controller=\"FetchController\">\n    <select ng-model=\"method\">\n      <option>GET</option>\n      <option>JSONP</option>\n    </select>\n    <input type=\"text\" ng-model=\"url\" size=\"80\"/>\n    <button id=\"fetchbtn\" ng-click=\"fetch()\">fetch</button><br>\n    <button id=\"samplegetbtn\" ng-click=\"updateModel('GET', 'http-hello.html')\">Sample GET</button>\n    <button id=\"samplejsonpbtn\"\n      ng-click=\"updateModel('JSONP',\n                    'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')\">\n      Sample JSONP\n    </button>\n    <button id=\"invalidjsonpbtn\"\n      ng-click=\"updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')\">\n        Invalid JSONP\n      </button>\n    <pre>http status code: {{status}}</pre>\n    <pre>http response data: {{data}}</pre>\n  </div>\n</file>\n<file name=\"script.js\">\n  angular.module('httpExample', [])\n    .controller('FetchController', ['$scope', '$http', '$templateCache',\n      function($scope, $http, $templateCache) {\n        $scope.method = 'GET';\n        $scope.url = 'http-hello.html';\n\n        $scope.fetch = function() {\n          $scope.code = null;\n          $scope.response = null;\n\n          $http({method: $scope.method, url: $scope.url, cache: $templateCache}).\n            success(function(data, status) {\n              $scope.status = status;\n              $scope.data = data;\n            }).\n            error(function(data, status) {\n              $scope.data = data || \"Request failed\";\n              $scope.status = status;\n          });\n        };\n\n        $scope.updateModel = function(method, url) {\n          $scope.method = method;\n          $scope.url = url;\n        };\n      }]);\n</file>\n<file name=\"http-hello.html\">\n  Hello, $http!\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  var status = element(by.binding('status'));\n  var data = element(by.binding('data'));\n  var fetchBtn = element(by.id('fetchbtn'));\n  var sampleGetBtn = element(by.id('samplegetbtn'));\n  var sampleJsonpBtn = element(by.id('samplejsonpbtn'));\n  var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));\n\n  it('should make an xhr GET request', function() {\n    sampleGetBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('200');\n    expect(data.getText()).toMatch(/Hello, \\$http!/);\n  });\n\n// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185\n// it('should make a JSONP request to angularjs.org', function() {\n//   sampleJsonpBtn.click();\n//   fetchBtn.click();\n//   expect(status.getText()).toMatch('200');\n//   expect(data.getText()).toMatch(/Super Hero!/);\n// });\n\n  it('should make JSONP request to invalid URL and invoke the error handler',\n      function() {\n    invalidJsonpBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('0');\n    expect(data.getText()).toMatch('Request failed');\n  });\n</file>\n</example>\n     */\n    function $http(requestConfig) {\n\n      if (!angular.isObject(requestConfig)) {\n        throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);\n      }\n\n      var config = extend({\n        method: 'get',\n        transformRequest: defaults.transformRequest,\n        transformResponse: defaults.transformResponse\n      }, requestConfig);\n\n      config.headers = mergeHeaders(requestConfig);\n      config.method = uppercase(config.method);\n\n      var serverRequest = function(config) {\n        var headers = config.headers;\n        var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);\n\n        // strip content-type if data is undefined\n        if (isUndefined(reqData)) {\n          forEach(headers, function(value, header) {\n            if (lowercase(header) === 'content-type') {\n                delete headers[header];\n            }\n          });\n        }\n\n        if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {\n          config.withCredentials = defaults.withCredentials;\n        }\n\n        // send request\n        return sendReq(config, reqData).then(transformResponse, transformResponse);\n      };\n\n      var chain = [serverRequest, undefined];\n      var promise = $q.when(config);\n\n      // apply interceptors\n      forEach(reversedInterceptors, function(interceptor) {\n        if (interceptor.request || interceptor.requestError) {\n          chain.unshift(interceptor.request, interceptor.requestError);\n        }\n        if (interceptor.response || interceptor.responseError) {\n          chain.push(interceptor.response, interceptor.responseError);\n        }\n      });\n\n      while (chain.length) {\n        var thenFn = chain.shift();\n        var rejectFn = chain.shift();\n\n        promise = promise.then(thenFn, rejectFn);\n      }\n\n      promise.success = function(fn) {\n        promise.then(function(response) {\n          fn(response.data, response.status, response.headers, config);\n        });\n        return promise;\n      };\n\n      promise.error = function(fn) {\n        promise.then(null, function(response) {\n          fn(response.data, response.status, response.headers, config);\n        });\n        return promise;\n      };\n\n      return promise;\n\n      function transformResponse(response) {\n        // make a copy since the response must be cacheable\n        var resp = extend({}, response);\n        if (!response.data) {\n          resp.data = response.data;\n        } else {\n          resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);\n        }\n        return (isSuccess(response.status))\n          ? resp\n          : $q.reject(resp);\n      }\n\n      function executeHeaderFns(headers) {\n        var headerContent, processedHeaders = {};\n\n        forEach(headers, function(headerFn, header) {\n          if (isFunction(headerFn)) {\n            headerContent = headerFn();\n            if (headerContent != null) {\n              processedHeaders[header] = headerContent;\n            }\n          } else {\n            processedHeaders[header] = headerFn;\n          }\n        });\n\n        return processedHeaders;\n      }\n\n      function mergeHeaders(config) {\n        var defHeaders = defaults.headers,\n            reqHeaders = extend({}, config.headers),\n            defHeaderName, lowercaseDefHeaderName, reqHeaderName;\n\n        defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);\n\n        // using for-in instead of forEach to avoid unecessary iteration after header has been found\n        defaultHeadersIteration:\n        for (defHeaderName in defHeaders) {\n          lowercaseDefHeaderName = lowercase(defHeaderName);\n\n          for (reqHeaderName in reqHeaders) {\n            if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {\n              continue defaultHeadersIteration;\n            }\n          }\n\n          reqHeaders[defHeaderName] = defHeaders[defHeaderName];\n        }\n\n        // execute if header value is a function for merged headers\n        return executeHeaderFns(reqHeaders);\n      }\n    }\n\n    $http.pendingRequests = [];\n\n    /**\n     * @ngdoc method\n     * @name $http#get\n     *\n     * @description\n     * Shortcut method to perform `GET` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#delete\n     *\n     * @description\n     * Shortcut method to perform `DELETE` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#head\n     *\n     * @description\n     * Shortcut method to perform `HEAD` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#jsonp\n     *\n     * @description\n     * Shortcut method to perform `JSONP` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request.\n     *                     The name of the callback should be the string `JSON_CALLBACK`.\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n    createShortMethods('get', 'delete', 'head', 'jsonp');\n\n    /**\n     * @ngdoc method\n     * @name $http#post\n     *\n     * @description\n     * Shortcut method to perform `POST` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#put\n     *\n     * @description\n     * Shortcut method to perform `PUT` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n     /**\n      * @ngdoc method\n      * @name $http#patch\n      *\n      * @description\n      * Shortcut method to perform `PATCH` request.\n      *\n      * @param {string} url Relative or absolute URL specifying the destination of the request\n      * @param {*} data Request content\n      * @param {Object=} config Optional configuration object\n      * @returns {HttpPromise} Future object\n      */\n    createShortMethodsWithData('post', 'put', 'patch');\n\n        /**\n         * @ngdoc property\n         * @name $http#defaults\n         *\n         * @description\n         * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of\n         * default headers, withCredentials as well as request and response transformations.\n         *\n         * See \"Setting HTTP Headers\" and \"Transforming Requests and Responses\" sections above.\n         */\n    $http.defaults = defaults;\n\n\n    return $http;\n\n\n    function createShortMethods(names) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, config) {\n          return $http(extend(config || {}, {\n            method: name,\n            url: url\n          }));\n        };\n      });\n    }\n\n\n    function createShortMethodsWithData(name) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, data, config) {\n          return $http(extend(config || {}, {\n            method: name,\n            url: url,\n            data: data\n          }));\n        };\n      });\n    }\n\n\n    /**\n     * Makes the request.\n     *\n     * !!! ACCESSES CLOSURE VARS:\n     * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests\n     */\n    function sendReq(config, reqData) {\n      var deferred = $q.defer(),\n          promise = deferred.promise,\n          cache,\n          cachedResp,\n          reqHeaders = config.headers,\n          url = buildUrl(config.url, config.params);\n\n      $http.pendingRequests.push(config);\n      promise.then(removePendingReq, removePendingReq);\n\n\n      if ((config.cache || defaults.cache) && config.cache !== false &&\n          (config.method === 'GET' || config.method === 'JSONP')) {\n        cache = isObject(config.cache) ? config.cache\n              : isObject(defaults.cache) ? defaults.cache\n              : defaultCache;\n      }\n\n      if (cache) {\n        cachedResp = cache.get(url);\n        if (isDefined(cachedResp)) {\n          if (isPromiseLike(cachedResp)) {\n            // cached request has already been sent, but there is no response yet\n            cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);\n          } else {\n            // serving from cache\n            if (isArray(cachedResp)) {\n              resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);\n            } else {\n              resolvePromise(cachedResp, 200, {}, 'OK');\n            }\n          }\n        } else {\n          // put the promise for the non-transformed response into cache as a placeholder\n          cache.put(url, promise);\n        }\n      }\n\n\n      // if we won't have the response in cache, set the xsrf headers and\n      // send the request to the backend\n      if (isUndefined(cachedResp)) {\n        var xsrfValue = urlIsSameOrigin(config.url)\n            ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]\n            : undefined;\n        if (xsrfValue) {\n          reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;\n        }\n\n        $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,\n            config.withCredentials, config.responseType);\n      }\n\n      return promise;\n\n\n      /**\n       * Callback registered to $httpBackend():\n       *  - caches the response if desired\n       *  - resolves the raw $http promise\n       *  - calls $apply\n       */\n      function done(status, response, headersString, statusText) {\n        if (cache) {\n          if (isSuccess(status)) {\n            cache.put(url, [status, response, parseHeaders(headersString), statusText]);\n          } else {\n            // remove promise from the cache\n            cache.remove(url);\n          }\n        }\n\n        function resolveHttpPromise() {\n          resolvePromise(response, status, headersString, statusText);\n        }\n\n        if (useApplyAsync) {\n          $rootScope.$applyAsync(resolveHttpPromise);\n        } else {\n          resolveHttpPromise();\n          if (!$rootScope.$$phase) $rootScope.$apply();\n        }\n      }\n\n\n      /**\n       * Resolves the raw $http promise.\n       */\n      function resolvePromise(response, status, headers, statusText) {\n        // normalize internal statuses to 0\n        status = Math.max(status, 0);\n\n        (isSuccess(status) ? deferred.resolve : deferred.reject)({\n          data: response,\n          status: status,\n          headers: headersGetter(headers),\n          config: config,\n          statusText: statusText\n        });\n      }\n\n      function resolvePromiseWithResult(result) {\n        resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);\n      }\n\n      function removePendingReq() {\n        var idx = $http.pendingRequests.indexOf(config);\n        if (idx !== -1) $http.pendingRequests.splice(idx, 1);\n      }\n    }\n\n\n    function buildUrl(url, params) {\n      if (!params) return url;\n      var parts = [];\n      forEachSorted(params, function(value, key) {\n        if (value === null || isUndefined(value)) return;\n        if (!isArray(value)) value = [value];\n\n        forEach(value, function(v) {\n          if (isObject(v)) {\n            if (isDate(v)) {\n              v = v.toISOString();\n            } else {\n              v = toJson(v);\n            }\n          }\n          parts.push(encodeUriQuery(key) + '=' +\n                     encodeUriQuery(v));\n        });\n      });\n      if (parts.length > 0) {\n        url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');\n      }\n      return url;\n    }\n  }];\n}\n\nfunction createXhr() {\n    return new window.XMLHttpRequest();\n}\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @requires $window\n * @requires $document\n *\n * @description\n * HTTP backend used by the {@link ng.$http service} that delegates to\n * XMLHttpRequest object or JSONP and deals with browser incompatibilities.\n *\n * You should never need to use this service directly, instead use the higher-level abstractions:\n * {@link ng.$http $http} or {@link ngResource.$resource $resource}.\n *\n * During testing this implementation is swapped with {@link ngMock.$httpBackend mock\n * $httpBackend} which can be trained with responses.\n */\nfunction $HttpBackendProvider() {\n  this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {\n    return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);\n  }];\n}\n\nfunction createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {\n  // TODO(vojta): fix the signature\n  return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {\n    $browser.$$incOutstandingRequestCount();\n    url = url || $browser.url();\n\n    if (lowercase(method) == 'jsonp') {\n      var callbackId = '_' + (callbacks.counter++).toString(36);\n      callbacks[callbackId] = function(data) {\n        callbacks[callbackId].data = data;\n        callbacks[callbackId].called = true;\n      };\n\n      var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),\n          callbackId, function(status, text) {\n        completeRequest(callback, status, callbacks[callbackId].data, \"\", text);\n        callbacks[callbackId] = noop;\n      });\n    } else {\n\n      var xhr = createXhr();\n\n      xhr.open(method, url, true);\n      forEach(headers, function(value, key) {\n        if (isDefined(value)) {\n            xhr.setRequestHeader(key, value);\n        }\n      });\n\n      xhr.onload = function requestLoaded() {\n        var statusText = xhr.statusText || '';\n\n        // responseText is the old-school way of retrieving response (supported by IE8 & 9)\n        // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)\n        var response = ('response' in xhr) ? xhr.response : xhr.responseText;\n\n        // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)\n        var status = xhr.status === 1223 ? 204 : xhr.status;\n\n        // fix status code when it is 0 (0 status is undocumented).\n        // Occurs when accessing file resources or on Android 4.1 stock browser\n        // while retrieving files from application cache.\n        if (status === 0) {\n          status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;\n        }\n\n        completeRequest(callback,\n            status,\n            response,\n            xhr.getAllResponseHeaders(),\n            statusText);\n      };\n\n      var requestError = function() {\n        // The response is always empty\n        // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\n        completeRequest(callback, -1, null, null, '');\n      };\n\n      xhr.onerror = requestError;\n      xhr.onabort = requestError;\n\n      if (withCredentials) {\n        xhr.withCredentials = true;\n      }\n\n      if (responseType) {\n        try {\n          xhr.responseType = responseType;\n        } catch (e) {\n          // WebKit added support for the json responseType value on 09/03/2013\n          // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are\n          // known to throw when setting the value \"json\" as the response type. Other older\n          // browsers implementing the responseType\n          //\n          // The json response type can be ignored if not supported, because JSON payloads are\n          // parsed on the client-side regardless.\n          if (responseType !== 'json') {\n            throw e;\n          }\n        }\n      }\n\n      xhr.send(post || null);\n    }\n\n    if (timeout > 0) {\n      var timeoutId = $browserDefer(timeoutRequest, timeout);\n    } else if (isPromiseLike(timeout)) {\n      timeout.then(timeoutRequest);\n    }\n\n\n    function timeoutRequest() {\n      jsonpDone && jsonpDone();\n      xhr && xhr.abort();\n    }\n\n    function completeRequest(callback, status, response, headersString, statusText) {\n      // cancel timeout and subsequent timeout promise resolution\n      if (timeoutId !== undefined) {\n        $browserDefer.cancel(timeoutId);\n      }\n      jsonpDone = xhr = null;\n\n      callback(status, response, headersString, statusText);\n      $browser.$$completeOutstandingRequest(noop);\n    }\n  };\n\n  function jsonpReq(url, callbackId, done) {\n    // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:\n    // - fetches local scripts via XHR and evals them\n    // - adds and immediately removes script elements from the document\n    var script = rawDocument.createElement('script'), callback = null;\n    script.type = \"text/javascript\";\n    script.src = url;\n    script.async = true;\n\n    callback = function(event) {\n      removeEventListenerFn(script, \"load\", callback);\n      removeEventListenerFn(script, \"error\", callback);\n      rawDocument.body.removeChild(script);\n      script = null;\n      var status = -1;\n      var text = \"unknown\";\n\n      if (event) {\n        if (event.type === \"load\" && !callbacks[callbackId].called) {\n          event = { type: \"error\" };\n        }\n        text = event.type;\n        status = event.type === \"error\" ? 404 : 200;\n      }\n\n      if (done) {\n        done(status, text);\n      }\n    };\n\n    addEventListenerFn(script, \"load\", callback);\n    addEventListenerFn(script, \"error\", callback);\n    rawDocument.body.appendChild(script);\n    return callback;\n  }\n}\n\nvar $interpolateMinErr = minErr('$interpolate');\n\n/**\n * @ngdoc provider\n * @name $interpolateProvider\n *\n * @description\n *\n * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.\n *\n * @example\n<example module=\"customInterpolationApp\">\n<file name=\"index.html\">\n<script>\n  var customInterpolationApp = angular.module('customInterpolationApp', []);\n\n  customInterpolationApp.config(function($interpolateProvider) {\n    $interpolateProvider.startSymbol('//');\n    $interpolateProvider.endSymbol('//');\n  });\n\n\n  customInterpolationApp.controller('DemoController', function() {\n      this.label = \"This binding is brought you by // interpolation symbols.\";\n  });\n</script>\n<div ng-app=\"App\" ng-controller=\"DemoController as demo\">\n    //demo.label//\n</div>\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  it('should interpolate binding with custom symbols', function() {\n    expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');\n  });\n</file>\n</example>\n */\nfunction $InterpolateProvider() {\n  var startSymbol = '{{';\n  var endSymbol = '}}';\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#startSymbol\n   * @description\n   * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.\n   *\n   * @param {string=} value new value to set the starting symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.startSymbol = function(value) {\n    if (value) {\n      startSymbol = value;\n      return this;\n    } else {\n      return startSymbol;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#endSymbol\n   * @description\n   * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n   *\n   * @param {string=} value new value to set the ending symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.endSymbol = function(value) {\n    if (value) {\n      endSymbol = value;\n      return this;\n    } else {\n      return endSymbol;\n    }\n  };\n\n\n  this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {\n    var startSymbolLength = startSymbol.length,\n        endSymbolLength = endSymbol.length,\n        escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),\n        escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');\n\n    function escape(ch) {\n      return '\\\\\\\\\\\\' + ch;\n    }\n\n    /**\n     * @ngdoc service\n     * @name $interpolate\n     * @kind function\n     *\n     * @requires $parse\n     * @requires $sce\n     *\n     * @description\n     *\n     * Compiles a string with markup into an interpolation function. This service is used by the\n     * HTML {@link ng.$compile $compile} service for data binding. See\n     * {@link ng.$interpolateProvider $interpolateProvider} for configuring the\n     * interpolation markup.\n     *\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var exp = $interpolate('Hello {{name | uppercase}}!');\n     *   expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');\n     * ```\n     *\n     * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is\n     * `true`, the interpolation function will return `undefined` unless all embedded expressions\n     * evaluate to a value other than `undefined`.\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var context = {greeting: 'Hello', name: undefined };\n     *\n     *   // default \"forgiving\" mode\n     *   var exp = $interpolate('{{greeting}} {{name}}!');\n     *   expect(exp(context)).toEqual('Hello !');\n     *\n     *   // \"allOrNothing\" mode\n     *   exp = $interpolate('{{greeting}} {{name}}!', false, null, true);\n     *   expect(exp(context)).toBeUndefined();\n     *   context.name = 'Angular';\n     *   expect(exp(context)).toEqual('Hello Angular!');\n     * ```\n     *\n     * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.\n     *\n     * ####Escaped Interpolation\n     * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers\n     * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).\n     * It will be rendered as a regular start/end marker, and will not be interpreted as an expression\n     * or binding.\n     *\n     * This enables web-servers to prevent script injection attacks and defacing attacks, to some\n     * degree, while also enabling code examples to work without relying on the\n     * {@link ng.directive:ngNonBindable ngNonBindable} directive.\n     *\n     * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,\n     * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all\n     * interpolation start/end markers with their escaped counterparts.**\n     *\n     * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered\n     * output when the $interpolate service processes the text. So, for HTML elements interpolated\n     * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter\n     * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,\n     * this is typically useful only when user-data is used in rendering a template from the server, or\n     * when otherwise untrusted data is used by a directive.\n     *\n     * <example>\n     *  <file name=\"index.html\">\n     *    <div ng-init=\"username='A user'\">\n     *      <p ng-init=\"apptitle='Escaping demo'\">{{apptitle}}: \\{\\{ username = \"defaced value\"; \\}\\}\n     *        </p>\n     *      <p><strong>{{username}}</strong> attempts to inject code which will deface the\n     *        application, but fails to accomplish their task, because the server has correctly\n     *        escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)\n     *        characters.</p>\n     *      <p>Instead, the result of the attempted script injection is visible, and can be removed\n     *        from the database by an administrator.</p>\n     *    </div>\n     *  </file>\n     * </example>\n     *\n     * @param {string} text The text with markup to interpolate.\n     * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have\n     *    embedded expression in order to return an interpolation function. Strings with no\n     *    embedded expression will return null for the interpolation function.\n     * @param {string=} trustedContext when provided, the returned function passes the interpolated\n     *    result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,\n     *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that\n     *    provides Strict Contextual Escaping for details.\n     * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined\n     *    unless all embedded expressions evaluate to a value other than `undefined`.\n     * @returns {function(context)} an interpolation function which is used to compute the\n     *    interpolated string. The function has these parameters:\n     *\n     * - `context`: evaluation context for all expressions embedded in the interpolated text\n     */\n    function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {\n      allOrNothing = !!allOrNothing;\n      var startIndex,\n          endIndex,\n          index = 0,\n          expressions = [],\n          parseFns = [],\n          textLength = text.length,\n          exp,\n          concat = [],\n          expressionPositions = [];\n\n      while (index < textLength) {\n        if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&\n             ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {\n          if (index !== startIndex) {\n            concat.push(unescapeText(text.substring(index, startIndex)));\n          }\n          exp = text.substring(startIndex + startSymbolLength, endIndex);\n          expressions.push(exp);\n          parseFns.push($parse(exp, parseStringifyInterceptor));\n          index = endIndex + endSymbolLength;\n          expressionPositions.push(concat.length);\n          concat.push('');\n        } else {\n          // we did not find an interpolation, so we have to add the remainder to the separators array\n          if (index !== textLength) {\n            concat.push(unescapeText(text.substring(index)));\n          }\n          break;\n        }\n      }\n\n      // Concatenating expressions makes it hard to reason about whether some combination of\n      // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a\n      // single expression be used for iframe[src], object[src], etc., we ensure that the value\n      // that's used is assigned or constructed by some JS code somewhere that is more testable or\n      // make it obvious that you bound the value to some user controlled value.  This helps reduce\n      // the load when auditing for XSS issues.\n      if (trustedContext && concat.length > 1) {\n          throw $interpolateMinErr('noconcat',\n              \"Error while interpolating: {0}\\nStrict Contextual Escaping disallows \" +\n              \"interpolations that concatenate multiple expressions when a trusted value is \" +\n              \"required.  See http://docs.angularjs.org/api/ng.$sce\", text);\n      }\n\n      if (!mustHaveExpression || expressions.length) {\n        var compute = function(values) {\n          for (var i = 0, ii = expressions.length; i < ii; i++) {\n            if (allOrNothing && isUndefined(values[i])) return;\n            concat[expressionPositions[i]] = values[i];\n          }\n          return concat.join('');\n        };\n\n        var getValue = function(value) {\n          return trustedContext ?\n            $sce.getTrusted(trustedContext, value) :\n            $sce.valueOf(value);\n        };\n\n        var stringify = function(value) {\n          if (value == null) { // null || undefined\n            return '';\n          }\n          switch (typeof value) {\n            case 'string':\n              break;\n            case 'number':\n              value = '' + value;\n              break;\n            default:\n              value = toJson(value);\n          }\n\n          return value;\n        };\n\n        return extend(function interpolationFn(context) {\n            var i = 0;\n            var ii = expressions.length;\n            var values = new Array(ii);\n\n            try {\n              for (; i < ii; i++) {\n                values[i] = parseFns[i](context);\n              }\n\n              return compute(values);\n            } catch (err) {\n              var newErr = $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text,\n                  err.toString());\n              $exceptionHandler(newErr);\n            }\n\n          }, {\n          // all of these properties are undocumented for now\n          exp: text, //just for compatibility with regular watchers created via $watch\n          expressions: expressions,\n          $$watchDelegate: function(scope, listener, objectEquality) {\n            var lastValue;\n            return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {\n              var currValue = compute(values);\n              if (isFunction(listener)) {\n                listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);\n              }\n              lastValue = currValue;\n            }, objectEquality);\n          }\n        });\n      }\n\n      function unescapeText(text) {\n        return text.replace(escapedStartRegexp, startSymbol).\n          replace(escapedEndRegexp, endSymbol);\n      }\n\n      function parseStringifyInterceptor(value) {\n        try {\n          value = getValue(value);\n          return allOrNothing && !isDefined(value) ? value : stringify(value);\n        } catch (err) {\n          var newErr = $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text,\n            err.toString());\n          $exceptionHandler(newErr);\n        }\n      }\n    }\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#startSymbol\n     * @description\n     * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.\n     *\n     * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} start symbol.\n     */\n    $interpolate.startSymbol = function() {\n      return startSymbol;\n    };\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#endSymbol\n     * @description\n     * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n     *\n     * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} end symbol.\n     */\n    $interpolate.endSymbol = function() {\n      return endSymbol;\n    };\n\n    return $interpolate;\n  }];\n}\n\nfunction $IntervalProvider() {\n  this.$get = ['$rootScope', '$window', '$q', '$$q',\n       function($rootScope,   $window,   $q,   $$q) {\n    var intervals = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $interval\n      *\n      * @description\n      * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`\n      * milliseconds.\n      *\n      * The return value of registering an interval function is a promise. This promise will be\n      * notified upon each tick of the interval, and will be resolved after `count` iterations, or\n      * run indefinitely if `count` is not defined. The value of the notification will be the\n      * number of iterations that have run.\n      * To cancel an interval, call `$interval.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n      * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n      * time.\n      *\n      * <div class=\"alert alert-warning\">\n      * **Note**: Intervals created by this service must be explicitly destroyed when you are finished\n      * with them.  In particular they are not automatically destroyed when a controller's scope or a\n      * directive's element are destroyed.\n      * You should take this into consideration and make sure to always cancel the interval at the\n      * appropriate moment.  See the example below for more details on how and when to do this.\n      * </div>\n      *\n      * @param {function()} fn A function that should be called repeatedly.\n      * @param {number} delay Number of milliseconds between each function call.\n      * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n      *   indefinitely.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @returns {promise} A promise which will be notified on each iteration.\n      *\n      * @example\n      * <example module=\"intervalExample\">\n      * <file name=\"index.html\">\n      *   <script>\n      *     angular.module('intervalExample', [])\n      *       .controller('ExampleController', ['$scope', '$interval',\n      *         function($scope, $interval) {\n      *           $scope.format = 'M/d/yy h:mm:ss a';\n      *           $scope.blood_1 = 100;\n      *           $scope.blood_2 = 120;\n      *\n      *           var stop;\n      *           $scope.fight = function() {\n      *             // Don't start a new fight if we are already fighting\n      *             if ( angular.isDefined(stop) ) return;\n      *\n      *             stop = $interval(function() {\n      *               if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {\n      *                 $scope.blood_1 = $scope.blood_1 - 3;\n      *                 $scope.blood_2 = $scope.blood_2 - 4;\n      *               } else {\n      *                 $scope.stopFight();\n      *               }\n      *             }, 100);\n      *           };\n      *\n      *           $scope.stopFight = function() {\n      *             if (angular.isDefined(stop)) {\n      *               $interval.cancel(stop);\n      *               stop = undefined;\n      *             }\n      *           };\n      *\n      *           $scope.resetFight = function() {\n      *             $scope.blood_1 = 100;\n      *             $scope.blood_2 = 120;\n      *           };\n      *\n      *           $scope.$on('$destroy', function() {\n      *             // Make sure that the interval is destroyed too\n      *             $scope.stopFight();\n      *           });\n      *         }])\n      *       // Register the 'myCurrentTime' directive factory method.\n      *       // We inject $interval and dateFilter service since the factory method is DI.\n      *       .directive('myCurrentTime', ['$interval', 'dateFilter',\n      *         function($interval, dateFilter) {\n      *           // return the directive link function. (compile function not needed)\n      *           return function(scope, element, attrs) {\n      *             var format,  // date format\n      *                 stopTime; // so that we can cancel the time updates\n      *\n      *             // used to update the UI\n      *             function updateTime() {\n      *               element.text(dateFilter(new Date(), format));\n      *             }\n      *\n      *             // watch the expression, and update the UI on change.\n      *             scope.$watch(attrs.myCurrentTime, function(value) {\n      *               format = value;\n      *               updateTime();\n      *             });\n      *\n      *             stopTime = $interval(updateTime, 1000);\n      *\n      *             // listen on DOM destroy (removal) event, and cancel the next UI update\n      *             // to prevent updating time after the DOM element was removed.\n      *             element.on('$destroy', function() {\n      *               $interval.cancel(stopTime);\n      *             });\n      *           }\n      *         }]);\n      *   </script>\n      *\n      *   <div>\n      *     <div ng-controller=\"ExampleController\">\n      *       Date format: <input ng-model=\"format\"> <hr/>\n      *       Current time is: <span my-current-time=\"format\"></span>\n      *       <hr/>\n      *       Blood 1 : <font color='red'>{{blood_1}}</font>\n      *       Blood 2 : <font color='red'>{{blood_2}}</font>\n      *       <button type=\"button\" data-ng-click=\"fight()\">Fight</button>\n      *       <button type=\"button\" data-ng-click=\"stopFight()\">StopFight</button>\n      *       <button type=\"button\" data-ng-click=\"resetFight()\">resetFight</button>\n      *     </div>\n      *   </div>\n      *\n      * </file>\n      * </example>\n      */\n    function interval(fn, delay, count, invokeApply) {\n      var setInterval = $window.setInterval,\n          clearInterval = $window.clearInterval,\n          iteration = 0,\n          skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise;\n\n      count = isDefined(count) ? count : 0;\n\n      promise.then(null, null, fn);\n\n      promise.$$intervalId = setInterval(function tick() {\n        deferred.notify(iteration++);\n\n        if (count > 0 && iteration >= count) {\n          deferred.resolve(iteration);\n          clearInterval(promise.$$intervalId);\n          delete intervals[promise.$$intervalId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n\n      }, delay);\n\n      intervals[promise.$$intervalId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $interval#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`.\n      *\n      * @param {promise} promise returned by the `$interval` function.\n      * @returns {boolean} Returns `true` if the task was successfully canceled.\n      */\n    interval.cancel = function(promise) {\n      if (promise && promise.$$intervalId in intervals) {\n        intervals[promise.$$intervalId].reject('canceled');\n        $window.clearInterval(promise.$$intervalId);\n        delete intervals[promise.$$intervalId];\n        return true;\n      }\n      return false;\n    };\n\n    return interval;\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $locale\n *\n * @description\n * $locale service provides localization rules for various Angular components. As of right now the\n * only public api is:\n *\n * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)\n */\nfunction $LocaleProvider() {\n  this.$get = function() {\n    return {\n      id: 'en-us',\n\n      NUMBER_FORMATS: {\n        DECIMAL_SEP: '.',\n        GROUP_SEP: ',',\n        PATTERNS: [\n          { // Decimal Pattern\n            minInt: 1,\n            minFrac: 0,\n            maxFrac: 3,\n            posPre: '',\n            posSuf: '',\n            negPre: '-',\n            negSuf: '',\n            gSize: 3,\n            lgSize: 3\n          },{ //Currency Pattern\n            minInt: 1,\n            minFrac: 2,\n            maxFrac: 2,\n            posPre: '\\u00A4',\n            posSuf: '',\n            negPre: '(\\u00A4',\n            negSuf: ')',\n            gSize: 3,\n            lgSize: 3\n          }\n        ],\n        CURRENCY_SYM: '$'\n      },\n\n      DATETIME_FORMATS: {\n        MONTH:\n            'January,February,March,April,May,June,July,August,September,October,November,December'\n            .split(','),\n        SHORTMONTH:  'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),\n        DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),\n        SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),\n        AMPMS: ['AM','PM'],\n        medium: 'MMM d, y h:mm:ss a',\n        'short': 'M/d/yy h:mm a',\n        fullDate: 'EEEE, MMMM d, y',\n        longDate: 'MMMM d, y',\n        mediumDate: 'MMM d, y',\n        shortDate: 'M/d/yy',\n        mediumTime: 'h:mm:ss a',\n        shortTime: 'h:mm a'\n      },\n\n      pluralCat: function(num) {\n        if (num === 1) {\n          return 'one';\n        }\n        return 'other';\n      }\n    };\n  };\n}\n\nvar PATH_MATCH = /^([^\\?#]*)(\\?([^#]*))?(#(.*))?$/,\n    DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};\nvar $locationMinErr = minErr('$location');\n\n\n/**\n * Encode path using encodeUriSegment, ignoring forward slashes\n *\n * @param {string} path Path to encode\n * @returns {string}\n */\nfunction encodePath(path) {\n  var segments = path.split('/'),\n      i = segments.length;\n\n  while (i--) {\n    segments[i] = encodeUriSegment(segments[i]);\n  }\n\n  return segments.join('/');\n}\n\nfunction parseAbsoluteUrl(absoluteUrl, locationObj) {\n  var parsedUrl = urlResolve(absoluteUrl);\n\n  locationObj.$$protocol = parsedUrl.protocol;\n  locationObj.$$host = parsedUrl.hostname;\n  locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;\n}\n\n\nfunction parseAppUrl(relativeUrl, locationObj) {\n  var prefixed = (relativeUrl.charAt(0) !== '/');\n  if (prefixed) {\n    relativeUrl = '/' + relativeUrl;\n  }\n  var match = urlResolve(relativeUrl);\n  locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?\n      match.pathname.substring(1) : match.pathname);\n  locationObj.$$search = parseKeyValue(match.search);\n  locationObj.$$hash = decodeURIComponent(match.hash);\n\n  // make sure path starts with '/';\n  if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {\n    locationObj.$$path = '/' + locationObj.$$path;\n  }\n}\n\n\n/**\n *\n * @param {string} begin\n * @param {string} whole\n * @returns {string} returns text from whole after begin or undefined if it does not begin with\n *                   expected string.\n */\nfunction beginsWith(begin, whole) {\n  if (whole.indexOf(begin) === 0) {\n    return whole.substr(begin.length);\n  }\n}\n\n\nfunction stripHash(url) {\n  var index = url.indexOf('#');\n  return index == -1 ? url : url.substr(0, index);\n}\n\nfunction trimEmptyHash(url) {\n  return url.replace(/(#.+)|#$/, '$1');\n}\n\n\nfunction stripFile(url) {\n  return url.substr(0, stripHash(url).lastIndexOf('/') + 1);\n}\n\n/* return the server only (scheme://host:port) */\nfunction serverBase(url) {\n  return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));\n}\n\n\n/**\n * LocationHtml5Url represents an url\n * This object is exposed as $location service when HTML5 mode is enabled and supported\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} basePrefix url path prefix\n */\nfunction LocationHtml5Url(appBase, basePrefix) {\n  this.$$html5 = true;\n  basePrefix = basePrefix || '';\n  var appBaseNoFile = stripFile(appBase);\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given html5 (regular) url string into properties\n   * @param {string} url HTML5 url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var pathUrl = beginsWith(appBaseNoFile, url);\n    if (!isString(pathUrl)) {\n      throw $locationMinErr('ipthprfx', 'Invalid url \"{0}\", missing path prefix \"{1}\".', url,\n          appBaseNoFile);\n    }\n\n    parseAppUrl(pathUrl, this);\n\n    if (!this.$$path) {\n      this.$$path = '/';\n    }\n\n    this.$$compose();\n  };\n\n  /**\n   * Compose url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n    var appUrl, prevAppUrl;\n    var rewrittenUrl;\n\n    if ((appUrl = beginsWith(appBase, url)) !== undefined) {\n      prevAppUrl = appUrl;\n      if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {\n        rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);\n      } else {\n        rewrittenUrl = appBase + prevAppUrl;\n      }\n    } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {\n      rewrittenUrl = appBaseNoFile + appUrl;\n    } else if (appBaseNoFile == url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when developer doesn't opt into html5 mode.\n * It also serves as the base class for html5 mode fallback on legacy browsers.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangUrl(appBase, hashPrefix) {\n  var appBaseNoFile = stripFile(appBase);\n\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given hashbang url into properties\n   * @param {string} url Hashbang url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);\n    var withoutHashUrl;\n\n    if (withoutBaseUrl.charAt(0) === '#') {\n\n      // The rest of the url starts with a hash so we have\n      // got either a hashbang path or a plain hash fragment\n      withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);\n      if (isUndefined(withoutHashUrl)) {\n        // There was no hashbang prefix so we just have a hash fragment\n        withoutHashUrl = withoutBaseUrl;\n      }\n\n    } else {\n      // There was no hashbang path nor hash fragment:\n      // If we are in HTML5 mode we use what is left as the path;\n      // Otherwise we ignore what is left\n      withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';\n    }\n\n    parseAppUrl(withoutHashUrl, this);\n\n    this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);\n\n    this.$$compose();\n\n    /*\n     * In Windows, on an anchor node on documents loaded from\n     * the filesystem, the browser will return a pathname\n     * prefixed with the drive name ('/C:/path') when a\n     * pathname without a drive is set:\n     *  * a.setAttribute('href', '/foo')\n     *   * a.pathname === '/C:/foo' //true\n     *\n     * Inside of Angular, we're always using pathnames that\n     * do not include drive names for routing.\n     */\n    function removeWindowsDriveName(path, url, base) {\n      /*\n      Matches paths for file protocol on windows,\n      such as /C:/foo/bar, and captures only /foo/bar.\n      */\n      var windowsFilePathExp = /^\\/[A-Z]:(\\/.*)/;\n\n      var firstPathSegmentMatch;\n\n      //Get the relative path from the input URL.\n      if (url.indexOf(base) === 0) {\n        url = url.replace(base, '');\n      }\n\n      // The input URL intentionally contains a first path segment that ends with a colon.\n      if (windowsFilePathExp.exec(url)) {\n        return path;\n      }\n\n      firstPathSegmentMatch = windowsFilePathExp.exec(path);\n      return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;\n    }\n  };\n\n  /**\n   * Compose hashbang url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (stripHash(appBase) == stripHash(url)) {\n      this.$$parse(url);\n      return true;\n    }\n    return false;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when html5 history api is enabled but the browser\n * does not support it.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangInHtml5Url(appBase, hashPrefix) {\n  this.$$html5 = true;\n  LocationHashbangUrl.apply(this, arguments);\n\n  var appBaseNoFile = stripFile(appBase);\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n\n    var rewrittenUrl;\n    var appUrl;\n\n    if (appBase == stripHash(url)) {\n      rewrittenUrl = url;\n    } else if ((appUrl = beginsWith(appBaseNoFile, url))) {\n      rewrittenUrl = appBase + hashPrefix + appUrl;\n    } else if (appBaseNoFile === url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'\n    this.$$absUrl = appBase + hashPrefix + this.$$url;\n  };\n\n}\n\n\nvar locationPrototype = {\n\n  /**\n   * Are we in html5 mode?\n   * @private\n   */\n  $$html5: false,\n\n  /**\n   * Has any change been replacing?\n   * @private\n   */\n  $$replace: false,\n\n  /**\n   * @ngdoc method\n   * @name $location#absUrl\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return full url representation with all segments encoded according to rules specified in\n   * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var absUrl = $location.absUrl();\n   * // => \"http://example.com/#/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @return {string} full url\n   */\n  absUrl: locationGetter('$$absUrl'),\n\n  /**\n   * @ngdoc method\n   * @name $location#url\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return url (e.g. `/path?a=b#hash`) when called without any parameter.\n   *\n   * Change path, search and hash, when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var url = $location.url();\n   * // => \"/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)\n   * @return {string} url\n   */\n  url: function(url) {\n    if (isUndefined(url))\n      return this.$$url;\n\n    var match = PATH_MATCH.exec(url);\n    if (match[1] || url === '') this.path(decodeURIComponent(match[1]));\n    if (match[2] || match[1] || url === '') this.search(match[3] || '');\n    this.hash(match[5] || '');\n\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#protocol\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return protocol of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var protocol = $location.protocol();\n   * // => \"http\"\n   * ```\n   *\n   * @return {string} protocol of current url\n   */\n  protocol: locationGetter('$$protocol'),\n\n  /**\n   * @ngdoc method\n   * @name $location#host\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return host of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var host = $location.host();\n   * // => \"example.com\"\n   * ```\n   *\n   * @return {string} host of current url.\n   */\n  host: locationGetter('$$host'),\n\n  /**\n   * @ngdoc method\n   * @name $location#port\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return port of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var port = $location.port();\n   * // => 80\n   * ```\n   *\n   * @return {Number} port\n   */\n  port: locationGetter('$$port'),\n\n  /**\n   * @ngdoc method\n   * @name $location#path\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return path of current url when called without any parameter.\n   *\n   * Change path when called with parameter and return `$location`.\n   *\n   * Note: Path should always begin with forward slash (/), this method will add the forward slash\n   * if it is missing.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var path = $location.path();\n   * // => \"/some/path\"\n   * ```\n   *\n   * @param {(string|number)=} path New path\n   * @return {string} path\n   */\n  path: locationGetterSetter('$$path', function(path) {\n    path = path !== null ? path.toString() : '';\n    return path.charAt(0) == '/' ? path : '/' + path;\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#search\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return search part (as object) of current url when called without any parameter.\n   *\n   * Change search part when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var searchObject = $location.search();\n   * // => {foo: 'bar', baz: 'xoxo'}\n   *\n   * // set foo to 'yipee'\n   * $location.search('foo', 'yipee');\n   * // $location.search() => {foo: 'yipee', baz: 'xoxo'}\n   * ```\n   *\n   * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or\n   * hash object.\n   *\n   * When called with a single argument the method acts as a setter, setting the `search` component\n   * of `$location` to the specified value.\n   *\n   * If the argument is a hash object containing an array of values, these values will be encoded\n   * as duplicate search parameters in the url.\n   *\n   * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`\n   * will override only a single search property.\n   *\n   * If `paramValue` is an array, it will override the property of the `search` component of\n   * `$location` specified via the first argument.\n   *\n   * If `paramValue` is `null`, the property specified via the first argument will be deleted.\n   *\n   * If `paramValue` is `true`, the property specified via the first argument will be added with no\n   * value nor trailing equal sign.\n   *\n   * @return {Object} If called with no arguments returns the parsed `search` object. If called with\n   * one or more arguments returns `$location` object itself.\n   */\n  search: function(search, paramValue) {\n    switch (arguments.length) {\n      case 0:\n        return this.$$search;\n      case 1:\n        if (isString(search) || isNumber(search)) {\n          search = search.toString();\n          this.$$search = parseKeyValue(search);\n        } else if (isObject(search)) {\n          search = copy(search, {});\n          // remove object undefined or null properties\n          forEach(search, function(value, key) {\n            if (value == null) delete search[key];\n          });\n\n          this.$$search = search;\n        } else {\n          throw $locationMinErr('isrcharg',\n              'The first argument of the `$location#search()` call must be a string or an object.');\n        }\n        break;\n      default:\n        if (isUndefined(paramValue) || paramValue === null) {\n          delete this.$$search[search];\n        } else {\n          this.$$search[search] = paramValue;\n        }\n    }\n\n    this.$$compose();\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#hash\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return hash fragment when called without any parameter.\n   *\n   * Change hash fragment when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue\n   * var hash = $location.hash();\n   * // => \"hashValue\"\n   * ```\n   *\n   * @param {(string|number)=} hash New hash fragment\n   * @return {string} hash\n   */\n  hash: locationGetterSetter('$$hash', function(hash) {\n    return hash !== null ? hash.toString() : '';\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#replace\n   *\n   * @description\n   * If called, all changes to $location during current `$digest` will be replacing current history\n   * record, instead of adding new one.\n   */\n  replace: function() {\n    this.$$replace = true;\n    return this;\n  }\n};\n\nforEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {\n  Location.prototype = Object.create(locationPrototype);\n\n  /**\n   * @ngdoc method\n   * @name $location#state\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return the history state object when called without any parameter.\n   *\n   * Change the history state object when called with one parameter and return `$location`.\n   * The state object is later passed to `pushState` or `replaceState`.\n   *\n   * NOTE: This method is supported only in HTML5 mode and only in browsers supporting\n   * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support\n   * older browsers (like IE9 or Android < 4.0), don't use this method.\n   *\n   * @param {object=} state State object for pushState or replaceState\n   * @return {object} state\n   */\n  Location.prototype.state = function(state) {\n    if (!arguments.length)\n      return this.$$state;\n\n    if (Location !== LocationHtml5Url || !this.$$html5) {\n      throw $locationMinErr('nostate', 'History API state support is available only ' +\n        'in HTML5 mode and only in browsers supporting HTML5 History API');\n    }\n    // The user might modify `stateObject` after invoking `$location.state(stateObject)`\n    // but we're changing the $$state reference to $browser.state() during the $digest\n    // so the modification window is narrow.\n    this.$$state = isUndefined(state) ? null : state;\n\n    return this;\n  };\n});\n\n\nfunction locationGetter(property) {\n  return function() {\n    return this[property];\n  };\n}\n\n\nfunction locationGetterSetter(property, preprocess) {\n  return function(value) {\n    if (isUndefined(value))\n      return this[property];\n\n    this[property] = preprocess(value);\n    this.$$compose();\n\n    return this;\n  };\n}\n\n\n/**\n * @ngdoc service\n * @name $location\n *\n * @requires $rootElement\n *\n * @description\n * The $location service parses the URL in the browser address bar (based on the\n * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL\n * available to your application. Changes to the URL in the address bar are reflected into\n * $location service and changes to $location are reflected into the browser address bar.\n *\n * **The $location service:**\n *\n * - Exposes the current URL in the browser address bar, so you can\n *   - Watch and observe the URL.\n *   - Change the URL.\n * - Synchronizes the URL with the browser when the user\n *   - Changes the address bar.\n *   - Clicks the back or forward button (or clicks a History link).\n *   - Clicks on a link.\n * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).\n *\n * For more information see {@link guide/$location Developer Guide: Using $location}\n */\n\n/**\n * @ngdoc provider\n * @name $locationProvider\n * @description\n * Use the `$locationProvider` to configure how the application deep linking paths are stored.\n */\nfunction $LocationProvider() {\n  var hashPrefix = '',\n      html5Mode = {\n        enabled: false,\n        requireBase: true,\n        rewriteLinks: true\n      };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#hashPrefix\n   * @description\n   * @param {string=} prefix Prefix for hash part (containing path and search)\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.hashPrefix = function(prefix) {\n    if (isDefined(prefix)) {\n      hashPrefix = prefix;\n      return this;\n    } else {\n      return hashPrefix;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#html5Mode\n   * @description\n   * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.\n   *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported\n   *   properties:\n   *   - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to\n   *     change urls where supported. Will fall back to hash-prefixed paths in browsers that do not\n   *     support `pushState`.\n   *   - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies\n   *     whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are\n   *     true, and a base tag is not present, an error will be thrown when `$location` is injected.\n   *     See the {@link guide/$location $location guide for more information}\n   *   - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,\n   *     enables/disables url rewriting for relative links.\n   *\n   * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter\n   */\n  this.html5Mode = function(mode) {\n    if (isBoolean(mode)) {\n      html5Mode.enabled = mode;\n      return this;\n    } else if (isObject(mode)) {\n\n      if (isBoolean(mode.enabled)) {\n        html5Mode.enabled = mode.enabled;\n      }\n\n      if (isBoolean(mode.requireBase)) {\n        html5Mode.requireBase = mode.requireBase;\n      }\n\n      if (isBoolean(mode.rewriteLinks)) {\n        html5Mode.rewriteLinks = mode.rewriteLinks;\n      }\n\n      return this;\n    } else {\n      return html5Mode;\n    }\n  };\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeStart\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted before a URL will change.\n   *\n   * This change can be prevented by calling\n   * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more\n   * details about event object. Upon successful change\n   * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeSuccess\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted after a URL was changed.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',\n      function($rootScope, $browser, $sniffer, $rootElement, $window) {\n    var $location,\n        LocationMode,\n        baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''\n        initialUrl = $browser.url(),\n        appBase;\n\n    if (html5Mode.enabled) {\n      if (!baseHref && html5Mode.requireBase) {\n        throw $locationMinErr('nobase',\n          \"$location in HTML5 mode requires a <base> tag to be present!\");\n      }\n      appBase = serverBase(initialUrl) + (baseHref || '/');\n      LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;\n    } else {\n      appBase = stripHash(initialUrl);\n      LocationMode = LocationHashbangUrl;\n    }\n    $location = new LocationMode(appBase, '#' + hashPrefix);\n    $location.$$parseLinkUrl(initialUrl, initialUrl);\n\n    $location.$$state = $browser.state();\n\n    var IGNORE_URI_REGEXP = /^\\s*(javascript|mailto):/i;\n\n    function setBrowserUrlWithFallback(url, replace, state) {\n      var oldUrl = $location.url();\n      var oldState = $location.$$state;\n      try {\n        $browser.url(url, replace, state);\n\n        // Make sure $location.state() returns referentially identical (not just deeply equal)\n        // state object; this makes possible quick checking if the state changed in the digest\n        // loop. Checking deep equality would be too expensive.\n        $location.$$state = $browser.state();\n      } catch (e) {\n        // Restore old values if pushState fails\n        $location.url(oldUrl);\n        $location.$$state = oldState;\n\n        throw e;\n      }\n    }\n\n    $rootElement.on('click', function(event) {\n      // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)\n      // currently we open nice url link and redirect then\n\n      if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;\n\n      var elm = jqLite(event.target);\n\n      // traverse the DOM up to find first A tag\n      while (nodeName_(elm[0]) !== 'a') {\n        // ignore rewriting if no A tag (reached root element, or no parent - removed from document)\n        if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;\n      }\n\n      var absHref = elm.prop('href');\n      // get the actual href attribute - see\n      // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx\n      var relHref = elm.attr('href') || elm.attr('xlink:href');\n\n      if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {\n        // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during\n        // an animation.\n        absHref = urlResolve(absHref.animVal).href;\n      }\n\n      // Ignore when url is started with javascript: or mailto:\n      if (IGNORE_URI_REGEXP.test(absHref)) return;\n\n      if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {\n        if ($location.$$parseLinkUrl(absHref, relHref)) {\n          // We do a preventDefault for all urls that are part of the angular application,\n          // in html5mode and also without, so that we are able to abort navigation without\n          // getting double entries in the location history.\n          event.preventDefault();\n          // update location manually\n          if ($location.absUrl() != $browser.url()) {\n            $rootScope.$apply();\n            // hack to work around FF6 bug 684208 when scenario runner clicks on links\n            $window.angular['ff-684208-preventDefault'] = true;\n          }\n        }\n      }\n    });\n\n\n    // rewrite hashbang url <> html5 url\n    if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {\n      $browser.url($location.absUrl(), true);\n    }\n\n    var initializing = true;\n\n    // update $location when $browser url changes\n    $browser.onUrlChange(function(newUrl, newState) {\n      $rootScope.$evalAsync(function() {\n        var oldUrl = $location.absUrl();\n        var oldState = $location.$$state;\n        var defaultPrevented;\n\n        $location.$$parse(newUrl);\n        $location.$$state = newState;\n\n        defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n            newState, oldState).defaultPrevented;\n\n        // if the location was changed by a `$locationChangeStart` handler then stop\n        // processing this location change\n        if ($location.absUrl() !== newUrl) return;\n\n        if (defaultPrevented) {\n          $location.$$parse(oldUrl);\n          $location.$$state = oldState;\n          setBrowserUrlWithFallback(oldUrl, false, oldState);\n        } else {\n          initializing = false;\n          afterLocationChange(oldUrl, oldState);\n        }\n      });\n      if (!$rootScope.$$phase) $rootScope.$digest();\n    });\n\n    // update browser\n    $rootScope.$watch(function $locationWatch() {\n      var oldUrl = trimEmptyHash($browser.url());\n      var newUrl = trimEmptyHash($location.absUrl());\n      var oldState = $browser.state();\n      var currentReplace = $location.$$replace;\n      var urlOrStateChanged = oldUrl !== newUrl ||\n        ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);\n\n      if (initializing || urlOrStateChanged) {\n        initializing = false;\n\n        $rootScope.$evalAsync(function() {\n          var newUrl = $location.absUrl();\n          var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n              $location.$$state, oldState).defaultPrevented;\n\n          // if the location was changed by a `$locationChangeStart` handler then stop\n          // processing this location change\n          if ($location.absUrl() !== newUrl) return;\n\n          if (defaultPrevented) {\n            $location.$$parse(oldUrl);\n            $location.$$state = oldState;\n          } else {\n            if (urlOrStateChanged) {\n              setBrowserUrlWithFallback(newUrl, currentReplace,\n                                        oldState === $location.$$state ? null : $location.$$state);\n            }\n            afterLocationChange(oldUrl, oldState);\n          }\n        });\n      }\n\n      $location.$$replace = false;\n\n      // we don't need to return anything because $evalAsync will make the digest loop dirty when\n      // there is a change\n    });\n\n    return $location;\n\n    function afterLocationChange(oldUrl, oldState) {\n      $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,\n        $location.$$state, oldState);\n    }\n}];\n}\n\n/**\n * @ngdoc service\n * @name $log\n * @requires $window\n *\n * @description\n * Simple service for logging. Default implementation safely writes the message\n * into the browser's console (if present).\n *\n * The main purpose of this service is to simplify debugging and troubleshooting.\n *\n * The default is to log `debug` messages. You can use\n * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.\n *\n * @example\n   <example module=\"logExample\">\n     <file name=\"script.js\">\n       angular.module('logExample', [])\n         .controller('LogController', ['$scope', '$log', function($scope, $log) {\n           $scope.$log = $log;\n           $scope.message = 'Hello World!';\n         }]);\n     </file>\n     <file name=\"index.html\">\n       <div ng-controller=\"LogController\">\n         <p>Reload this page with open console, enter text and hit the log button...</p>\n         Message:\n         <input type=\"text\" ng-model=\"message\"/>\n         <button ng-click=\"$log.log(message)\">log</button>\n         <button ng-click=\"$log.warn(message)\">warn</button>\n         <button ng-click=\"$log.info(message)\">info</button>\n         <button ng-click=\"$log.error(message)\">error</button>\n       </div>\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc provider\n * @name $logProvider\n * @description\n * Use the `$logProvider` to configure how the application logs messages\n */\nfunction $LogProvider() {\n  var debug = true,\n      self = this;\n\n  /**\n   * @ngdoc method\n   * @name $logProvider#debugEnabled\n   * @description\n   * @param {boolean=} flag enable or disable debug level messages\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.debugEnabled = function(flag) {\n    if (isDefined(flag)) {\n      debug = flag;\n    return this;\n    } else {\n      return debug;\n    }\n  };\n\n  this.$get = ['$window', function($window) {\n    return {\n      /**\n       * @ngdoc method\n       * @name $log#log\n       *\n       * @description\n       * Write a log message\n       */\n      log: consoleLog('log'),\n\n      /**\n       * @ngdoc method\n       * @name $log#info\n       *\n       * @description\n       * Write an information message\n       */\n      info: consoleLog('info'),\n\n      /**\n       * @ngdoc method\n       * @name $log#warn\n       *\n       * @description\n       * Write a warning message\n       */\n      warn: consoleLog('warn'),\n\n      /**\n       * @ngdoc method\n       * @name $log#error\n       *\n       * @description\n       * Write an error message\n       */\n      error: consoleLog('error'),\n\n      /**\n       * @ngdoc method\n       * @name $log#debug\n       *\n       * @description\n       * Write a debug message\n       */\n      debug: (function() {\n        var fn = consoleLog('debug');\n\n        return function() {\n          if (debug) {\n            fn.apply(self, arguments);\n          }\n        };\n      }())\n    };\n\n    function formatError(arg) {\n      if (arg instanceof Error) {\n        if (arg.stack) {\n          arg = (arg.message && arg.stack.indexOf(arg.message) === -1)\n              ? 'Error: ' + arg.message + '\\n' + arg.stack\n              : arg.stack;\n        } else if (arg.sourceURL) {\n          arg = arg.message + '\\n' + arg.sourceURL + ':' + arg.line;\n        }\n      }\n      return arg;\n    }\n\n    function consoleLog(type) {\n      var console = $window.console || {},\n          logFn = console[type] || console.log || noop,\n          hasApply = false;\n\n      // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.\n      // The reason behind this is that console.log has type \"object\" in IE8...\n      try {\n        hasApply = !!logFn.apply;\n      } catch (e) {}\n\n      if (hasApply) {\n        return function() {\n          var args = [];\n          forEach(arguments, function(arg) {\n            args.push(formatError(arg));\n          });\n          return logFn.apply(console, args);\n        };\n      }\n\n      // we are IE which either doesn't have window.console => this is noop and we do nothing,\n      // or we are IE where console.log doesn't have apply so we log at least first 2 args\n      return function(arg1, arg2) {\n        logFn(arg1, arg2 == null ? '' : arg2);\n      };\n    }\n  }];\n}\n\nvar $parseMinErr = minErr('$parse');\n\n// Sandboxing Angular Expressions\n// ------------------------------\n// Angular expressions are generally considered safe because these expressions only have direct\n// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by\n// obtaining a reference to native JS functions such as the Function constructor.\n//\n// As an example, consider the following Angular expression:\n//\n//   {}.toString.constructor('alert(\"evil JS code\")')\n//\n// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits\n// against the expression language, but not to prevent exploits that were enabled by exposing\n// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good\n// practice and therefore we are not even trying to protect against interaction with an object\n// explicitly exposed in this way.\n//\n// In general, it is not possible to access a Window object from an angular expression unless a\n// window or some DOM object that has a reference to window is published onto a Scope.\n// Similarly we prevent invocations of function known to be dangerous, as well as assignments to\n// native objects.\n//\n// See https://docs.angularjs.org/guide/security\n\n\nfunction ensureSafeMemberName(name, fullExpression) {\n  if (name === \"__defineGetter__\" || name === \"__defineSetter__\"\n      || name === \"__lookupGetter__\" || name === \"__lookupSetter__\"\n      || name === \"__proto__\") {\n    throw $parseMinErr('isecfld',\n        'Attempting to access a disallowed field in Angular expressions! '\n        + 'Expression: {0}', fullExpression);\n  }\n  return name;\n}\n\nfunction ensureSafeObject(obj, fullExpression) {\n  // nifty check if obj is Function that is fast and works across iframes and other contexts\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n          'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isWindow(obj)\n        obj.window === obj) {\n      throw $parseMinErr('isecwindow',\n          'Referencing the Window in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isElement(obj)\n        obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {\n      throw $parseMinErr('isecdom',\n          'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// block Object so that we can't get hold of dangerous Object.* methods\n        obj === Object) {\n      throw $parseMinErr('isecobj',\n          'Referencing Object in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    }\n  }\n  return obj;\n}\n\nvar CALL = Function.prototype.call;\nvar APPLY = Function.prototype.apply;\nvar BIND = Function.prototype.bind;\n\nfunction ensureSafeFunction(obj, fullExpression) {\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n        'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    } else if (obj === CALL || obj === APPLY || obj === BIND) {\n      throw $parseMinErr('isecff',\n        'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    }\n  }\n}\n\n//Keyword constants\nvar CONSTANTS = createMap();\nforEach({\n  'null': function() { return null; },\n  'true': function() { return true; },\n  'false': function() { return false; },\n  'undefined': function() {}\n}, function(constantGetter, name) {\n  constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;\n  CONSTANTS[name] = constantGetter;\n});\n\n//Not quite a constant, but can be lex/parsed the same\nCONSTANTS['this'] = function(self) { return self; };\nCONSTANTS['this'].sharedGetter = true;\n\n\n//Operators - will be wrapped by binaryFn/unaryFn/assignment/filter\nvar OPERATORS = extend(createMap(), {\n    '+':function(self, locals, a, b) {\n      a=a(self, locals); b=b(self, locals);\n      if (isDefined(a)) {\n        if (isDefined(b)) {\n          return a + b;\n        }\n        return a;\n      }\n      return isDefined(b) ? b : undefined;},\n    '-':function(self, locals, a, b) {\n          a=a(self, locals); b=b(self, locals);\n          return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);\n        },\n    '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},\n    '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},\n    '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},\n    '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},\n    '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},\n    '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},\n    '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},\n    '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},\n    '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},\n    '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},\n    '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},\n    '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},\n    '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},\n    '!':function(self, locals, a) {return !a(self, locals);},\n\n    //Tokenized as operators but parsed as assignment/filters\n    '=':true,\n    '|':true\n});\nvar ESCAPE = {\"n\":\"\\n\", \"f\":\"\\f\", \"r\":\"\\r\", \"t\":\"\\t\", \"v\":\"\\v\", \"'\":\"'\", '\"':'\"'};\n\n\n/////////////////////////////////////////\n\n\n/**\n * @constructor\n */\nvar Lexer = function(options) {\n  this.options = options;\n};\n\nLexer.prototype = {\n  constructor: Lexer,\n\n  lex: function(text) {\n    this.text = text;\n    this.index = 0;\n    this.tokens = [];\n\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (ch === '\"' || ch === \"'\") {\n        this.readString(ch);\n      } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\n        this.readNumber();\n      } else if (this.isIdent(ch)) {\n        this.readIdent();\n      } else if (this.is(ch, '(){}[].,;:?')) {\n        this.tokens.push({index: this.index, text: ch});\n        this.index++;\n      } else if (this.isWhitespace(ch)) {\n        this.index++;\n      } else {\n        var ch2 = ch + this.peek();\n        var ch3 = ch2 + this.peek(2);\n        var op1 = OPERATORS[ch];\n        var op2 = OPERATORS[ch2];\n        var op3 = OPERATORS[ch3];\n        if (op1 || op2 || op3) {\n          var token = op3 ? ch3 : (op2 ? ch2 : ch);\n          this.tokens.push({index: this.index, text: token, operator: true});\n          this.index += token.length;\n        } else {\n          this.throwError('Unexpected next character ', this.index, this.index + 1);\n        }\n      }\n    }\n    return this.tokens;\n  },\n\n  is: function(ch, chars) {\n    return chars.indexOf(ch) !== -1;\n  },\n\n  peek: function(i) {\n    var num = i || 1;\n    return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\n  },\n\n  isNumber: function(ch) {\n    return ('0' <= ch && ch <= '9') && typeof ch === \"string\";\n  },\n\n  isWhitespace: function(ch) {\n    // IE treats non-breaking space as \\u00A0\n    return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\n            ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\n  },\n\n  isIdent: function(ch) {\n    return ('a' <= ch && ch <= 'z' ||\n            'A' <= ch && ch <= 'Z' ||\n            '_' === ch || ch === '$');\n  },\n\n  isExpOperator: function(ch) {\n    return (ch === '-' || ch === '+' || this.isNumber(ch));\n  },\n\n  throwError: function(error, start, end) {\n    end = end || this.index;\n    var colStr = (isDefined(start)\n            ? 's ' + start +  '-' + this.index + ' [' + this.text.substring(start, end) + ']'\n            : ' ' + end);\n    throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\n        error, colStr, this.text);\n  },\n\n  readNumber: function() {\n    var number = '';\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = lowercase(this.text.charAt(this.index));\n      if (ch == '.' || this.isNumber(ch)) {\n        number += ch;\n      } else {\n        var peekCh = this.peek();\n        if (ch == 'e' && this.isExpOperator(peekCh)) {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            peekCh && this.isNumber(peekCh) &&\n            number.charAt(number.length - 1) == 'e') {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            (!peekCh || !this.isNumber(peekCh)) &&\n            number.charAt(number.length - 1) == 'e') {\n          this.throwError('Invalid exponent');\n        } else {\n          break;\n        }\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: number,\n      constant: true,\n      value: Number(number)\n    });\n  },\n\n  readIdent: function() {\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (!(this.isIdent(ch) || this.isNumber(ch))) {\n        break;\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: this.text.slice(start, this.index),\n      identifier: true\n    });\n  },\n\n  readString: function(quote) {\n    var start = this.index;\n    this.index++;\n    var string = '';\n    var rawString = quote;\n    var escape = false;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      rawString += ch;\n      if (escape) {\n        if (ch === 'u') {\n          var hex = this.text.substring(this.index + 1, this.index + 5);\n          if (!hex.match(/[\\da-f]{4}/i))\n            this.throwError('Invalid unicode escape [\\\\u' + hex + ']');\n          this.index += 4;\n          string += String.fromCharCode(parseInt(hex, 16));\n        } else {\n          var rep = ESCAPE[ch];\n          string = string + (rep || ch);\n        }\n        escape = false;\n      } else if (ch === '\\\\') {\n        escape = true;\n      } else if (ch === quote) {\n        this.index++;\n        this.tokens.push({\n          index: start,\n          text: rawString,\n          constant: true,\n          value: string\n        });\n        return;\n      } else {\n        string += ch;\n      }\n      this.index++;\n    }\n    this.throwError('Unterminated quote', start);\n  }\n};\n\n\nfunction isConstant(exp) {\n  return exp.constant;\n}\n\n/**\n * @constructor\n */\nvar Parser = function(lexer, $filter, options) {\n  this.lexer = lexer;\n  this.$filter = $filter;\n  this.options = options;\n};\n\nParser.ZERO = extend(function() {\n  return 0;\n}, {\n  sharedGetter: true,\n  constant: true\n});\n\nParser.prototype = {\n  constructor: Parser,\n\n  parse: function(text) {\n    this.text = text;\n    this.tokens = this.lexer.lex(text);\n\n    var value = this.statements();\n\n    if (this.tokens.length !== 0) {\n      this.throwError('is an unexpected token', this.tokens[0]);\n    }\n\n    value.literal = !!value.literal;\n    value.constant = !!value.constant;\n\n    return value;\n  },\n\n  primary: function() {\n    var primary;\n    if (this.expect('(')) {\n      primary = this.filterChain();\n      this.consume(')');\n    } else if (this.expect('[')) {\n      primary = this.arrayDeclaration();\n    } else if (this.expect('{')) {\n      primary = this.object();\n    } else if (this.peek().identifier && this.peek().text in CONSTANTS) {\n      primary = CONSTANTS[this.consume().text];\n    } else if (this.peek().identifier) {\n      primary = this.identifier();\n    } else if (this.peek().constant) {\n      primary = this.constant();\n    } else {\n      this.throwError('not a primary expression', this.peek());\n    }\n\n    var next, context;\n    while ((next = this.expect('(', '[', '.'))) {\n      if (next.text === '(') {\n        primary = this.functionCall(primary, context);\n        context = null;\n      } else if (next.text === '[') {\n        context = primary;\n        primary = this.objectIndex(primary);\n      } else if (next.text === '.') {\n        context = primary;\n        primary = this.fieldAccess(primary);\n      } else {\n        this.throwError('IMPOSSIBLE');\n      }\n    }\n    return primary;\n  },\n\n  throwError: function(msg, token) {\n    throw $parseMinErr('syntax',\n        'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\n          token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\n  },\n\n  peekToken: function() {\n    if (this.tokens.length === 0)\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    return this.tokens[0];\n  },\n\n  peek: function(e1, e2, e3, e4) {\n    return this.peekAhead(0, e1, e2, e3, e4);\n  },\n  peekAhead: function(i, e1, e2, e3, e4) {\n    if (this.tokens.length > i) {\n      var token = this.tokens[i];\n      var t = token.text;\n      if (t === e1 || t === e2 || t === e3 || t === e4 ||\n          (!e1 && !e2 && !e3 && !e4)) {\n        return token;\n      }\n    }\n    return false;\n  },\n\n  expect: function(e1, e2, e3, e4) {\n    var token = this.peek(e1, e2, e3, e4);\n    if (token) {\n      this.tokens.shift();\n      return token;\n    }\n    return false;\n  },\n\n  consume: function(e1) {\n    if (this.tokens.length === 0) {\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    }\n\n    var token = this.expect(e1);\n    if (!token) {\n      this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\n    }\n    return token;\n  },\n\n  unaryFn: function(op, right) {\n    var fn = OPERATORS[op];\n    return extend(function $parseUnaryFn(self, locals) {\n      return fn(self, locals, right);\n    }, {\n      constant:right.constant,\n      inputs: [right]\n    });\n  },\n\n  binaryFn: function(left, op, right, isBranching) {\n    var fn = OPERATORS[op];\n    return extend(function $parseBinaryFn(self, locals) {\n      return fn(self, locals, left, right);\n    }, {\n      constant: left.constant && right.constant,\n      inputs: !isBranching && [left, right]\n    });\n  },\n\n  identifier: function() {\n    var id = this.consume().text;\n\n    //Continue reading each `.identifier` unless it is a method invocation\n    while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {\n      id += this.consume().text + this.consume().text;\n    }\n\n    return getterFn(id, this.options, this.text);\n  },\n\n  constant: function() {\n    var value = this.consume().value;\n\n    return extend(function $parseConstant() {\n      return value;\n    }, {\n      constant: true,\n      literal: true\n    });\n  },\n\n  statements: function() {\n    var statements = [];\n    while (true) {\n      if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))\n        statements.push(this.filterChain());\n      if (!this.expect(';')) {\n        // optimize for the common case where there is only one statement.\n        // TODO(size): maybe we should not support multiple statements?\n        return (statements.length === 1)\n            ? statements[0]\n            : function $parseStatements(self, locals) {\n                var value;\n                for (var i = 0, ii = statements.length; i < ii; i++) {\n                  value = statements[i](self, locals);\n                }\n                return value;\n              };\n      }\n    }\n  },\n\n  filterChain: function() {\n    var left = this.expression();\n    var token;\n    while ((token = this.expect('|'))) {\n      left = this.filter(left);\n    }\n    return left;\n  },\n\n  filter: function(inputFn) {\n    var fn = this.$filter(this.consume().text);\n    var argsFn;\n    var args;\n\n    if (this.peek(':')) {\n      argsFn = [];\n      args = []; // we can safely reuse the array\n      while (this.expect(':')) {\n        argsFn.push(this.expression());\n      }\n    }\n\n    var inputs = [inputFn].concat(argsFn || []);\n\n    return extend(function $parseFilter(self, locals) {\n      var input = inputFn(self, locals);\n      if (args) {\n        args[0] = input;\n\n        var i = argsFn.length;\n        while (i--) {\n          args[i + 1] = argsFn[i](self, locals);\n        }\n\n        return fn.apply(undefined, args);\n      }\n\n      return fn(input);\n    }, {\n      constant: !fn.$stateful && inputs.every(isConstant),\n      inputs: !fn.$stateful && inputs\n    });\n  },\n\n  expression: function() {\n    return this.assignment();\n  },\n\n  assignment: function() {\n    var left = this.ternary();\n    var right;\n    var token;\n    if ((token = this.expect('='))) {\n      if (!left.assign) {\n        this.throwError('implies assignment but [' +\n            this.text.substring(0, token.index) + '] can not be assigned to', token);\n      }\n      right = this.ternary();\n      return extend(function $parseAssignment(scope, locals) {\n        return left.assign(scope, right(scope, locals), locals);\n      }, {\n        inputs: [left, right]\n      });\n    }\n    return left;\n  },\n\n  ternary: function() {\n    var left = this.logicalOR();\n    var middle;\n    var token;\n    if ((token = this.expect('?'))) {\n      middle = this.assignment();\n      if (this.consume(':')) {\n        var right = this.assignment();\n\n        return extend(function $parseTernary(self, locals) {\n          return left(self, locals) ? middle(self, locals) : right(self, locals);\n        }, {\n          constant: left.constant && middle.constant && right.constant\n        });\n      }\n    }\n\n    return left;\n  },\n\n  logicalOR: function() {\n    var left = this.logicalAND();\n    var token;\n    while ((token = this.expect('||'))) {\n      left = this.binaryFn(left, token.text, this.logicalAND(), true);\n    }\n    return left;\n  },\n\n  logicalAND: function() {\n    var left = this.equality();\n    var token;\n    while ((token = this.expect('&&'))) {\n      left = this.binaryFn(left, token.text, this.equality(), true);\n    }\n    return left;\n  },\n\n  equality: function() {\n    var left = this.relational();\n    var token;\n    while ((token = this.expect('==','!=','===','!=='))) {\n      left = this.binaryFn(left, token.text, this.relational());\n    }\n    return left;\n  },\n\n  relational: function() {\n    var left = this.additive();\n    var token;\n    while ((token = this.expect('<', '>', '<=', '>='))) {\n      left = this.binaryFn(left, token.text, this.additive());\n    }\n    return left;\n  },\n\n  additive: function() {\n    var left = this.multiplicative();\n    var token;\n    while ((token = this.expect('+','-'))) {\n      left = this.binaryFn(left, token.text, this.multiplicative());\n    }\n    return left;\n  },\n\n  multiplicative: function() {\n    var left = this.unary();\n    var token;\n    while ((token = this.expect('*','/','%'))) {\n      left = this.binaryFn(left, token.text, this.unary());\n    }\n    return left;\n  },\n\n  unary: function() {\n    var token;\n    if (this.expect('+')) {\n      return this.primary();\n    } else if ((token = this.expect('-'))) {\n      return this.binaryFn(Parser.ZERO, token.text, this.unary());\n    } else if ((token = this.expect('!'))) {\n      return this.unaryFn(token.text, this.unary());\n    } else {\n      return this.primary();\n    }\n  },\n\n  fieldAccess: function(object) {\n    var getter = this.identifier();\n\n    return extend(function $parseFieldAccess(scope, locals, self) {\n      var o = self || object(scope, locals);\n      return (o == null) ? undefined : getter(o);\n    }, {\n      assign: function(scope, value, locals) {\n        var o = object(scope, locals);\n        if (!o) object.assign(scope, o = {}, locals);\n        return getter.assign(o, value);\n      }\n    });\n  },\n\n  objectIndex: function(obj) {\n    var expression = this.text;\n\n    var indexFn = this.expression();\n    this.consume(']');\n\n    return extend(function $parseObjectIndex(self, locals) {\n      var o = obj(self, locals),\n          i = indexFn(self, locals),\n          v;\n\n      ensureSafeMemberName(i, expression);\n      if (!o) return undefined;\n      v = ensureSafeObject(o[i], expression);\n      return v;\n    }, {\n      assign: function(self, value, locals) {\n        var key = ensureSafeMemberName(indexFn(self, locals), expression);\n        // prevent overwriting of Function.constructor which would break ensureSafeObject check\n        var o = ensureSafeObject(obj(self, locals), expression);\n        if (!o) obj.assign(self, o = {}, locals);\n        return o[key] = value;\n      }\n    });\n  },\n\n  functionCall: function(fnGetter, contextGetter) {\n    var argsFn = [];\n    if (this.peekToken().text !== ')') {\n      do {\n        argsFn.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume(')');\n\n    var expressionText = this.text;\n    // we can safely reuse the array across invocations\n    var args = argsFn.length ? [] : null;\n\n    return function $parseFunctionCall(scope, locals) {\n      var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;\n      var fn = fnGetter(scope, locals, context) || noop;\n\n      if (args) {\n        var i = argsFn.length;\n        while (i--) {\n          args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);\n        }\n      }\n\n      ensureSafeObject(context, expressionText);\n      ensureSafeFunction(fn, expressionText);\n\n      // IE doesn't have apply for some native functions\n      var v = fn.apply\n            ? fn.apply(context, args)\n            : fn(args[0], args[1], args[2], args[3], args[4]);\n\n      if (args) {\n        // Free-up the memory (arguments of the last function call).\n        args.length = 0;\n      }\n\n      return ensureSafeObject(v, expressionText);\n      };\n  },\n\n  // This is used with json array declaration\n  arrayDeclaration: function() {\n    var elementFns = [];\n    if (this.peekToken().text !== ']') {\n      do {\n        if (this.peek(']')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        elementFns.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume(']');\n\n    return extend(function $parseArrayLiteral(self, locals) {\n      var array = [];\n      for (var i = 0, ii = elementFns.length; i < ii; i++) {\n        array.push(elementFns[i](self, locals));\n      }\n      return array;\n    }, {\n      literal: true,\n      constant: elementFns.every(isConstant),\n      inputs: elementFns\n    });\n  },\n\n  object: function() {\n    var keys = [], valueFns = [];\n    if (this.peekToken().text !== '}') {\n      do {\n        if (this.peek('}')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        var token = this.consume();\n        if (token.constant) {\n          keys.push(token.value);\n        } else if (token.identifier) {\n          keys.push(token.text);\n        } else {\n          this.throwError(\"invalid key\", token);\n        }\n        this.consume(':');\n        valueFns.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume('}');\n\n    return extend(function $parseObjectLiteral(self, locals) {\n      var object = {};\n      for (var i = 0, ii = valueFns.length; i < ii; i++) {\n        object[keys[i]] = valueFns[i](self, locals);\n      }\n      return object;\n    }, {\n      literal: true,\n      constant: valueFns.every(isConstant),\n      inputs: valueFns\n    });\n  }\n};\n\n\n//////////////////////////////////////////////////\n// Parser helper functions\n//////////////////////////////////////////////////\n\nfunction setter(obj, locals, path, setValue, fullExp) {\n  ensureSafeObject(obj, fullExp);\n  ensureSafeObject(locals, fullExp);\n\n  var element = path.split('.'), key;\n  for (var i = 0; element.length > 1; i++) {\n    key = ensureSafeMemberName(element.shift(), fullExp);\n    var propertyObj = (i === 0 && locals && locals[key]) || obj[key];\n    if (!propertyObj) {\n      propertyObj = {};\n      obj[key] = propertyObj;\n    }\n    obj = ensureSafeObject(propertyObj, fullExp);\n  }\n  key = ensureSafeMemberName(element.shift(), fullExp);\n  ensureSafeObject(obj[key], fullExp);\n  obj[key] = setValue;\n  return setValue;\n}\n\nvar getterFnCacheDefault = createMap();\nvar getterFnCacheExpensive = createMap();\n\nfunction isPossiblyDangerousMemberName(name) {\n  return name == 'constructor';\n}\n\n/**\n * Implementation of the \"Black Hole\" variant from:\n * - http://jsperf.com/angularjs-parse-getter/4\n * - http://jsperf.com/path-evaluation-simplified/7\n */\nfunction cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {\n  ensureSafeMemberName(key0, fullExp);\n  ensureSafeMemberName(key1, fullExp);\n  ensureSafeMemberName(key2, fullExp);\n  ensureSafeMemberName(key3, fullExp);\n  ensureSafeMemberName(key4, fullExp);\n  var eso = function(o) {\n    return ensureSafeObject(o, fullExp);\n  };\n  var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;\n  var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;\n  var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;\n  var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;\n  var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;\n\n  return function cspSafeGetter(scope, locals) {\n    var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;\n\n    if (pathVal == null) return pathVal;\n    pathVal = eso0(pathVal[key0]);\n\n    if (!key1) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso1(pathVal[key1]);\n\n    if (!key2) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso2(pathVal[key2]);\n\n    if (!key3) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso3(pathVal[key3]);\n\n    if (!key4) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso4(pathVal[key4]);\n\n    return pathVal;\n  };\n}\n\nfunction getterFnWithEnsureSafeObject(fn, fullExpression) {\n  return function(s, l) {\n    return fn(s, l, ensureSafeObject, fullExpression);\n  };\n}\n\nfunction getterFn(path, options, fullExp) {\n  var expensiveChecks = options.expensiveChecks;\n  var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);\n  var fn = getterFnCache[path];\n  if (fn) return fn;\n\n\n  var pathKeys = path.split('.'),\n      pathKeysLength = pathKeys.length;\n\n  // http://jsperf.com/angularjs-parse-getter/6\n  if (options.csp) {\n    if (pathKeysLength < 6) {\n      fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);\n    } else {\n      fn = function cspSafeGetter(scope, locals) {\n        var i = 0, val;\n        do {\n          val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],\n                                pathKeys[i++], fullExp, expensiveChecks)(scope, locals);\n\n          locals = undefined; // clear after first iteration\n          scope = val;\n        } while (i < pathKeysLength);\n        return val;\n      };\n    }\n  } else {\n    var code = '';\n    if (expensiveChecks) {\n      code += 's = eso(s, fe);\\nl = eso(l, fe);\\n';\n    }\n    var needsEnsureSafeObject = expensiveChecks;\n    forEach(pathKeys, function(key, index) {\n      ensureSafeMemberName(key, fullExp);\n      var lookupJs = (index\n                      // we simply dereference 's' on any .dot notation\n                      ? 's'\n                      // but if we are first then we check locals first, and if so read it first\n                      : '((l&&l.hasOwnProperty(\"' + key + '\"))?l:s)') + '.' + key;\n      if (expensiveChecks || isPossiblyDangerousMemberName(key)) {\n        lookupJs = 'eso(' + lookupJs + ', fe)';\n        needsEnsureSafeObject = true;\n      }\n      code += 'if(s == null) return undefined;\\n' +\n              's=' + lookupJs + ';\\n';\n    });\n    code += 'return s;';\n\n    /* jshint -W054 */\n    var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject\n    /* jshint +W054 */\n    evaledFnGetter.toString = valueFn(code);\n    if (needsEnsureSafeObject) {\n      evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);\n    }\n    fn = evaledFnGetter;\n  }\n\n  fn.sharedGetter = true;\n  fn.assign = function(self, value, locals) {\n    return setter(self, locals, path, value, path);\n  };\n  getterFnCache[path] = fn;\n  return fn;\n}\n\nvar objectValueOf = Object.prototype.valueOf;\n\nfunction getValueOf(value) {\n  return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);\n}\n\n///////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $parse\n * @kind function\n *\n * @description\n *\n * Converts Angular {@link guide/expression expression} into a function.\n *\n * ```js\n *   var getter = $parse('user.name');\n *   var setter = getter.assign;\n *   var context = {user:{name:'angular'}};\n *   var locals = {user:{name:'local'}};\n *\n *   expect(getter(context)).toEqual('angular');\n *   setter(context, 'newValue');\n *   expect(context.user.name).toEqual('newValue');\n *   expect(getter(context, locals)).toEqual('local');\n * ```\n *\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n *      are evaluated against (typically a scope object).\n *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n *      `context`.\n *\n *    The returned function also has the following properties:\n *      * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript\n *        literal.\n *      * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript\n *        constant literals.\n *      * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be\n *        set to a function to change its value on the given context.\n *\n */\n\n\n/**\n * @ngdoc provider\n * @name $parseProvider\n *\n * @description\n * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}\n *  service.\n */\nfunction $ParseProvider() {\n  var cacheDefault = createMap();\n  var cacheExpensive = createMap();\n\n\n\n  this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {\n    var $parseOptions = {\n          csp: $sniffer.csp,\n          expensiveChecks: false\n        },\n        $parseOptionsExpensive = {\n          csp: $sniffer.csp,\n          expensiveChecks: true\n        };\n\n    function wrapSharedExpression(exp) {\n      var wrapped = exp;\n\n      if (exp.sharedGetter) {\n        wrapped = function $parseWrapper(self, locals) {\n          return exp(self, locals);\n        };\n        wrapped.literal = exp.literal;\n        wrapped.constant = exp.constant;\n        wrapped.assign = exp.assign;\n      }\n\n      return wrapped;\n    }\n\n    return function $parse(exp, interceptorFn, expensiveChecks) {\n      var parsedExpression, oneTime, cacheKey;\n\n      switch (typeof exp) {\n        case 'string':\n          cacheKey = exp = exp.trim();\n\n          var cache = (expensiveChecks ? cacheExpensive : cacheDefault);\n          parsedExpression = cache[cacheKey];\n\n          if (!parsedExpression) {\n            if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {\n              oneTime = true;\n              exp = exp.substring(2);\n            }\n\n            var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;\n            var lexer = new Lexer(parseOptions);\n            var parser = new Parser(lexer, $filter, parseOptions);\n            parsedExpression = parser.parse(exp);\n\n            if (parsedExpression.constant) {\n              parsedExpression.$$watchDelegate = constantWatchDelegate;\n            } else if (oneTime) {\n              //oneTime is not part of the exp passed to the Parser so we may have to\n              //wrap the parsedExpression before adding a $$watchDelegate\n              parsedExpression = wrapSharedExpression(parsedExpression);\n              parsedExpression.$$watchDelegate = parsedExpression.literal ?\n                oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;\n            } else if (parsedExpression.inputs) {\n              parsedExpression.$$watchDelegate = inputsWatchDelegate;\n            }\n\n            cache[cacheKey] = parsedExpression;\n          }\n          return addInterceptor(parsedExpression, interceptorFn);\n\n        case 'function':\n          return addInterceptor(exp, interceptorFn);\n\n        default:\n          return addInterceptor(noop, interceptorFn);\n      }\n    };\n\n    function collectExpressionInputs(inputs, list) {\n      for (var i = 0, ii = inputs.length; i < ii; i++) {\n        var input = inputs[i];\n        if (!input.constant) {\n          if (input.inputs) {\n            collectExpressionInputs(input.inputs, list);\n          } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?\n            list.push(input);\n          }\n        }\n      }\n\n      return list;\n    }\n\n    function expressionInputDirtyCheck(newValue, oldValueOfValue) {\n\n      if (newValue == null || oldValueOfValue == null) { // null/undefined\n        return newValue === oldValueOfValue;\n      }\n\n      if (typeof newValue === 'object') {\n\n        // attempt to convert the value to a primitive type\n        // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can\n        //             be cheaply dirty-checked\n        newValue = getValueOf(newValue);\n\n        if (typeof newValue === 'object') {\n          // objects/arrays are not supported - deep-watching them would be too expensive\n          return false;\n        }\n\n        // fall-through to the primitive equality check\n      }\n\n      //Primitive or NaN\n      return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);\n    }\n\n    function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var inputExpressions = parsedExpression.$$inputs ||\n                    (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));\n\n      var lastResult;\n\n      if (inputExpressions.length === 1) {\n        var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails\n        inputExpressions = inputExpressions[0];\n        return scope.$watch(function expressionInputWatch(scope) {\n          var newInputValue = inputExpressions(scope);\n          if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {\n            lastResult = parsedExpression(scope);\n            oldInputValue = newInputValue && getValueOf(newInputValue);\n          }\n          return lastResult;\n        }, listener, objectEquality);\n      }\n\n      var oldInputValueOfValues = [];\n      for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n        oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails\n      }\n\n      return scope.$watch(function expressionInputsWatch(scope) {\n        var changed = false;\n\n        for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n          var newInputValue = inputExpressions[i](scope);\n          if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {\n            oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\n          }\n        }\n\n        if (changed) {\n          lastResult = parsedExpression(scope);\n        }\n\n        return lastResult;\n      }, listener, objectEquality);\n    }\n\n    function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        if (isDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isDefined(lastValue)) {\n              unwatch();\n            }\n          });\n        }\n      }, objectEquality);\n    }\n\n    function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.call(this, value, old, scope);\n        }\n        if (isAllDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isAllDefined(lastValue)) unwatch();\n          });\n        }\n      }, objectEquality);\n\n      function isAllDefined(value) {\n        var allDefined = true;\n        forEach(value, function(val) {\n          if (!isDefined(val)) allDefined = false;\n        });\n        return allDefined;\n      }\n    }\n\n    function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch;\n      return unwatch = scope.$watch(function constantWatch(scope) {\n        return parsedExpression(scope);\n      }, function constantListener(value, old, scope) {\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        unwatch();\n      }, objectEquality);\n    }\n\n    function addInterceptor(parsedExpression, interceptorFn) {\n      if (!interceptorFn) return parsedExpression;\n      var watchDelegate = parsedExpression.$$watchDelegate;\n\n      var regularWatch =\n          watchDelegate !== oneTimeLiteralWatchDelegate &&\n          watchDelegate !== oneTimeWatchDelegate;\n\n      var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {\n        var value = parsedExpression(scope, locals);\n        return interceptorFn(value, scope, locals);\n      } : function oneTimeInterceptedExpression(scope, locals) {\n        var value = parsedExpression(scope, locals);\n        var result = interceptorFn(value, scope, locals);\n        // we only return the interceptor's result if the\n        // initial value is defined (for bind-once)\n        return isDefined(value) ? result : value;\n      };\n\n      // Propagate $$watchDelegates other then inputsWatchDelegate\n      if (parsedExpression.$$watchDelegate &&\n          parsedExpression.$$watchDelegate !== inputsWatchDelegate) {\n        fn.$$watchDelegate = parsedExpression.$$watchDelegate;\n      } else if (!interceptorFn.$stateful) {\n        // If there is an interceptor, but no watchDelegate then treat the interceptor like\n        // we treat filters - it is assumed to be a pure function unless flagged with $stateful\n        fn.$$watchDelegate = inputsWatchDelegate;\n        fn.inputs = [parsedExpression];\n      }\n\n      return fn;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $q\n * @requires $rootScope\n *\n * @description\n * A service that helps you run functions asynchronously, and use their return values (or exceptions)\n * when they are done processing.\n *\n * This is an implementation of promises/deferred objects inspired by\n * [Kris Kowal's Q](https://github.com/kriskowal/q).\n *\n * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred\n * implementations, and the other which resembles ES6 promises to some degree.\n *\n * # $q constructor\n *\n * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`\n * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,\n * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n *\n * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are\n * available yet.\n *\n * It can be used like so:\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     // perform some asynchronous operation, resolve or reject the promise when appropriate.\n *     return $q(function(resolve, reject) {\n *       setTimeout(function() {\n *         if (okToGreet(name)) {\n *           resolve('Hello, ' + name + '!');\n *         } else {\n *           reject('Greeting ' + name + ' is not allowed.');\n *         }\n *       }, 1000);\n *     });\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   });\n * ```\n *\n * Note: progress/notify callbacks are not currently supported via the ES6-style interface.\n *\n * However, the more traditional CommonJS-style usage is still available, and documented below.\n *\n * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an\n * interface for interacting with an object that represents the result of an action that is\n * performed asynchronously, and may or may not be finished at any given point in time.\n *\n * From the perspective of dealing with error handling, deferred and promise APIs are to\n * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     var deferred = $q.defer();\n *\n *     setTimeout(function() {\n *       deferred.notify('About to greet ' + name + '.');\n *\n *       if (okToGreet(name)) {\n *         deferred.resolve('Hello, ' + name + '!');\n *       } else {\n *         deferred.reject('Greeting ' + name + ' is not allowed.');\n *       }\n *     }, 1000);\n *\n *     return deferred.promise;\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   }, function(update) {\n *     alert('Got notification: ' + update);\n *   });\n * ```\n *\n * At first it might not be obvious why this extra complexity is worth the trouble. The payoff\n * comes in the way of guarantees that promise and deferred APIs make, see\n * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.\n *\n * Additionally the promise api allows for composition that is very hard to do with the\n * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.\n * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the\n * section on serial or parallel joining of promises.\n *\n * # The Deferred API\n *\n * A new instance of deferred is constructed by calling `$q.defer()`.\n *\n * The purpose of the deferred object is to expose the associated Promise instance as well as APIs\n * that can be used for signaling the successful or unsuccessful completion, as well as the status\n * of the task.\n *\n * **Methods**\n *\n * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection\n *   constructed via `$q.reject`, the promise will be rejected instead.\n * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to\n *   resolving it with a rejection constructed via `$q.reject`.\n * - `notify(value)` - provides updates on the status of the promise's execution. This may be called\n *   multiple times before the promise is either resolved or rejected.\n *\n * **Properties**\n *\n * - promise – `{Promise}` – promise object associated with this deferred.\n *\n *\n * # The Promise API\n *\n * A new promise instance is created when a deferred instance is created and can be retrieved by\n * calling `deferred.promise`.\n *\n * The purpose of the promise object is to allow for interested parties to get access to the result\n * of the deferred task when it completes.\n *\n * **Methods**\n *\n * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or\n *   will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously\n *   as soon as the result is available. The callbacks are called with a single argument: the result\n *   or rejection reason. Additionally, the notify callback may be called zero or more times to\n *   provide a progress indication, before the promise is resolved or rejected.\n *\n *   This method *returns a new promise* which is resolved or rejected via the return value of the\n *   `successCallback`, `errorCallback`. It also notifies via the return value of the\n *   `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback\n *   method.\n *\n * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`\n *\n * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,\n *   but to do so without modifying the final value. This is useful to release resources or do some\n *   clean-up that needs to be done whether the promise was rejected or resolved. See the [full\n *   specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for\n *   more information.\n *\n * # Chaining promises\n *\n * Because calling the `then` method of a promise returns a new derived promise, it is easily\n * possible to create a chain of promises:\n *\n * ```js\n *   promiseB = promiseA.then(function(result) {\n *     return result + 1;\n *   });\n *\n *   // promiseB will be resolved immediately after promiseA is resolved and its value\n *   // will be the result of promiseA incremented by 1\n * ```\n *\n * It is possible to create chains of any length and since a promise can be resolved with another\n * promise (which will defer its resolution further), it is possible to pause/defer resolution of\n * the promises at any point in the chain. This makes it possible to implement powerful APIs like\n * $http's response interceptors.\n *\n *\n * # Differences between Kris Kowal's Q and $q\n *\n *  There are two main differences:\n *\n * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation\n *   mechanism in angular, which means faster propagation of resolution or rejection into your\n *   models and avoiding unnecessary browser repaints, which would result in flickering UI.\n * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains\n *   all the important functionality needed for common async tasks.\n *\n *  # Testing\n *\n *  ```js\n *    it('should simulate promise', inject(function($q, $rootScope) {\n *      var deferred = $q.defer();\n *      var promise = deferred.promise;\n *      var resolvedValue;\n *\n *      promise.then(function(value) { resolvedValue = value; });\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Simulate resolving of promise\n *      deferred.resolve(123);\n *      // Note that the 'then' function does not get called synchronously.\n *      // This is because we want the promise API to always be async, whether or not\n *      // it got called synchronously or asynchronously.\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Propagate promise resolution to 'then' functions using $apply().\n *      $rootScope.$apply();\n *      expect(resolvedValue).toEqual(123);\n *    }));\n *  ```\n *\n * @param {function(function, function)} resolver Function which is responsible for resolving or\n *   rejecting the newly created promise. The first parameter is a function which resolves the\n *   promise, the second parameter is a function which rejects the promise.\n *\n * @returns {Promise} The newly created promise.\n */\nfunction $QProvider() {\n\n  this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $rootScope.$evalAsync(callback);\n    }, $exceptionHandler);\n  }];\n}\n\nfunction $$QProvider() {\n  this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $browser.defer(callback);\n    }, $exceptionHandler);\n  }];\n}\n\n/**\n * Constructs a promise manager.\n *\n * @param {function(function)} nextTick Function for executing functions in the next turn.\n * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for\n *     debugging purposes.\n * @returns {object} Promise manager.\n */\nfunction qFactory(nextTick, exceptionHandler) {\n  var $qMinErr = minErr('$q', TypeError);\n  function callOnce(self, resolveFn, rejectFn) {\n    var called = false;\n    function wrap(fn) {\n      return function(value) {\n        if (called) return;\n        called = true;\n        fn.call(self, value);\n      };\n    }\n\n    return [wrap(resolveFn), wrap(rejectFn)];\n  }\n\n  /**\n   * @ngdoc method\n   * @name ng.$q#defer\n   * @kind function\n   *\n   * @description\n   * Creates a `Deferred` object which represents a task which will finish in the future.\n   *\n   * @returns {Deferred} Returns a new instance of deferred.\n   */\n  var defer = function() {\n    return new Deferred();\n  };\n\n  function Promise() {\n    this.$$state = { status: 0 };\n  }\n\n  Promise.prototype = {\n    then: function(onFulfilled, onRejected, progressBack) {\n      var result = new Deferred();\n\n      this.$$state.pending = this.$$state.pending || [];\n      this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);\n      if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);\n\n      return result.promise;\n    },\n\n    \"catch\": function(callback) {\n      return this.then(null, callback);\n    },\n\n    \"finally\": function(callback, progressBack) {\n      return this.then(function(value) {\n        return handleCallback(value, true, callback);\n      }, function(error) {\n        return handleCallback(error, false, callback);\n      }, progressBack);\n    }\n  };\n\n  //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native\n  function simpleBind(context, fn) {\n    return function(value) {\n      fn.call(context, value);\n    };\n  }\n\n  function processQueue(state) {\n    var fn, promise, pending;\n\n    pending = state.pending;\n    state.processScheduled = false;\n    state.pending = undefined;\n    for (var i = 0, ii = pending.length; i < ii; ++i) {\n      promise = pending[i][0];\n      fn = pending[i][state.status];\n      try {\n        if (isFunction(fn)) {\n          promise.resolve(fn(state.value));\n        } else if (state.status === 1) {\n          promise.resolve(state.value);\n        } else {\n          promise.reject(state.value);\n        }\n      } catch (e) {\n        promise.reject(e);\n        exceptionHandler(e);\n      }\n    }\n  }\n\n  function scheduleProcessQueue(state) {\n    if (state.processScheduled || !state.pending) return;\n    state.processScheduled = true;\n    nextTick(function() { processQueue(state); });\n  }\n\n  function Deferred() {\n    this.promise = new Promise();\n    //Necessary to support unbound execution :/\n    this.resolve = simpleBind(this, this.resolve);\n    this.reject = simpleBind(this, this.reject);\n    this.notify = simpleBind(this, this.notify);\n  }\n\n  Deferred.prototype = {\n    resolve: function(val) {\n      if (this.promise.$$state.status) return;\n      if (val === this.promise) {\n        this.$$reject($qMinErr(\n          'qcycle',\n          \"Expected promise to be resolved with value other than itself '{0}'\",\n          val));\n      } else {\n        this.$$resolve(val);\n      }\n\n    },\n\n    $$resolve: function(val) {\n      var then, fns;\n\n      fns = callOnce(this, this.$$resolve, this.$$reject);\n      try {\n        if ((isObject(val) || isFunction(val))) then = val && val.then;\n        if (isFunction(then)) {\n          this.promise.$$state.status = -1;\n          then.call(val, fns[0], fns[1], this.notify);\n        } else {\n          this.promise.$$state.value = val;\n          this.promise.$$state.status = 1;\n          scheduleProcessQueue(this.promise.$$state);\n        }\n      } catch (e) {\n        fns[1](e);\n        exceptionHandler(e);\n      }\n    },\n\n    reject: function(reason) {\n      if (this.promise.$$state.status) return;\n      this.$$reject(reason);\n    },\n\n    $$reject: function(reason) {\n      this.promise.$$state.value = reason;\n      this.promise.$$state.status = 2;\n      scheduleProcessQueue(this.promise.$$state);\n    },\n\n    notify: function(progress) {\n      var callbacks = this.promise.$$state.pending;\n\n      if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {\n        nextTick(function() {\n          var callback, result;\n          for (var i = 0, ii = callbacks.length; i < ii; i++) {\n            result = callbacks[i][0];\n            callback = callbacks[i][3];\n            try {\n              result.notify(isFunction(callback) ? callback(progress) : progress);\n            } catch (e) {\n              exceptionHandler(e);\n            }\n          }\n        });\n      }\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#reject\n   * @kind function\n   *\n   * @description\n   * Creates a promise that is resolved as rejected with the specified `reason`. This api should be\n   * used to forward rejection in a chain of promises. If you are dealing with the last promise in\n   * a promise chain, you don't need to worry about it.\n   *\n   * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of\n   * `reject` as the `throw` keyword in JavaScript. This also means that if you \"catch\" an error via\n   * a promise error callback and you want to forward the error to the promise derived from the\n   * current promise, you have to \"rethrow\" the error by returning a rejection constructed via\n   * `reject`.\n   *\n   * ```js\n   *   promiseB = promiseA.then(function(result) {\n   *     // success: do something and resolve promiseB\n   *     //          with the old or a new result\n   *     return result;\n   *   }, function(reason) {\n   *     // error: handle the error if possible and\n   *     //        resolve promiseB with newPromiseOrValue,\n   *     //        otherwise forward the rejection to promiseB\n   *     if (canHandle(reason)) {\n   *      // handle the error and recover\n   *      return newPromiseOrValue;\n   *     }\n   *     return $q.reject(reason);\n   *   });\n   * ```\n   *\n   * @param {*} reason Constant, message, exception or an object representing the rejection reason.\n   * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.\n   */\n  var reject = function(reason) {\n    var result = new Deferred();\n    result.reject(reason);\n    return result.promise;\n  };\n\n  var makePromise = function makePromise(value, resolved) {\n    var result = new Deferred();\n    if (resolved) {\n      result.resolve(value);\n    } else {\n      result.reject(value);\n    }\n    return result.promise;\n  };\n\n  var handleCallback = function handleCallback(value, isResolved, callback) {\n    var callbackOutput = null;\n    try {\n      if (isFunction(callback)) callbackOutput = callback();\n    } catch (e) {\n      return makePromise(e, false);\n    }\n    if (isPromiseLike(callbackOutput)) {\n      return callbackOutput.then(function() {\n        return makePromise(value, isResolved);\n      }, function(error) {\n        return makePromise(error, false);\n      });\n    } else {\n      return makePromise(value, isResolved);\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#when\n   * @kind function\n   *\n   * @description\n   * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.\n   * This is useful when you are dealing with an object that might or might not be a promise, or if\n   * the promise comes from a source that can't be trusted.\n   *\n   * @param {*} value Value or a promise\n   * @returns {Promise} Returns a promise of the passed value or promise\n   */\n\n\n  var when = function(value, callback, errback, progressBack) {\n    var result = new Deferred();\n    result.resolve(value);\n    return result.promise.then(callback, errback, progressBack);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#all\n   * @kind function\n   *\n   * @description\n   * Combines multiple promises into a single promise that is resolved when all of the input\n   * promises are resolved.\n   *\n   * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.\n   * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,\n   *   each value corresponding to the promise at the same index/key in the `promises` array/hash.\n   *   If any of the promises is resolved with a rejection, this resulting promise will be rejected\n   *   with the same rejection value.\n   */\n\n  function all(promises) {\n    var deferred = new Deferred(),\n        counter = 0,\n        results = isArray(promises) ? [] : {};\n\n    forEach(promises, function(promise, key) {\n      counter++;\n      when(promise).then(function(value) {\n        if (results.hasOwnProperty(key)) return;\n        results[key] = value;\n        if (!(--counter)) deferred.resolve(results);\n      }, function(reason) {\n        if (results.hasOwnProperty(key)) return;\n        deferred.reject(reason);\n      });\n    });\n\n    if (counter === 0) {\n      deferred.resolve(results);\n    }\n\n    return deferred.promise;\n  }\n\n  var $Q = function Q(resolver) {\n    if (!isFunction(resolver)) {\n      throw $qMinErr('norslvr', \"Expected resolverFn, got '{0}'\", resolver);\n    }\n\n    if (!(this instanceof Q)) {\n      // More useful when $Q is the Promise itself.\n      return new Q(resolver);\n    }\n\n    var deferred = new Deferred();\n\n    function resolveFn(value) {\n      deferred.resolve(value);\n    }\n\n    function rejectFn(reason) {\n      deferred.reject(reason);\n    }\n\n    resolver(resolveFn, rejectFn);\n\n    return deferred.promise;\n  };\n\n  $Q.defer = defer;\n  $Q.reject = reject;\n  $Q.when = when;\n  $Q.all = all;\n\n  return $Q;\n}\n\nfunction $$RAFProvider() { //rAF\n  this.$get = ['$window', '$timeout', function($window, $timeout) {\n    var requestAnimationFrame = $window.requestAnimationFrame ||\n                                $window.webkitRequestAnimationFrame;\n\n    var cancelAnimationFrame = $window.cancelAnimationFrame ||\n                               $window.webkitCancelAnimationFrame ||\n                               $window.webkitCancelRequestAnimationFrame;\n\n    var rafSupported = !!requestAnimationFrame;\n    var raf = rafSupported\n      ? function(fn) {\n          var id = requestAnimationFrame(fn);\n          return function() {\n            cancelAnimationFrame(id);\n          };\n        }\n      : function(fn) {\n          var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666\n          return function() {\n            $timeout.cancel(timer);\n          };\n        };\n\n    raf.supported = rafSupported;\n\n    return raf;\n  }];\n}\n\n/**\n * DESIGN NOTES\n *\n * The design decisions behind the scope are heavily favored for speed and memory consumption.\n *\n * The typical use of scope is to watch the expressions, which most of the time return the same\n * value as last time so we optimize the operation.\n *\n * Closures construction is expensive in terms of speed as well as memory:\n *   - No closures, instead use prototypical inheritance for API\n *   - Internal state needs to be stored on scope directly, which means that private state is\n *     exposed as $$____ properties\n *\n * Loop operations are optimized by using while(count--) { ... }\n *   - this means that in order to keep the same order of execution as addition we have to add\n *     items to the array at the beginning (unshift) instead of at the end (push)\n *\n * Child scopes are created and removed often\n *   - Using an array would be slow since inserts in middle are expensive so we use linked list\n *\n * There are few watches then a lot of observers. This is why you don't want the observer to be\n * implemented in the same way as watch. Watch requires return of initialization function which\n * are expensive to construct.\n */\n\n\n/**\n * @ngdoc provider\n * @name $rootScopeProvider\n * @description\n *\n * Provider for the $rootScope service.\n */\n\n/**\n * @ngdoc method\n * @name $rootScopeProvider#digestTtl\n * @description\n *\n * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that the dependencies between `$watch`s will result in\n * several digest iterations. However if an application needs more than the default 10 digest\n * iterations for its model to stabilize then you should investigate what is causing the model to\n * continuously change during the digest.\n *\n * Increasing the TTL could have performance implications, so you should not change it without\n * proper justification.\n *\n * @param {number} limit The number of digest iterations.\n */\n\n\n/**\n * @ngdoc service\n * @name $rootScope\n * @description\n *\n * Every application has a single root {@link ng.$rootScope.Scope scope}.\n * All other scopes are descendant scopes of the root scope. Scopes provide separation\n * between the model and the view, via a mechanism for watching the model for changes.\n * They also provide an event emission/broadcast and subscription facility. See the\n * {@link guide/scope developer guide on scopes}.\n */\nfunction $RootScopeProvider() {\n  var TTL = 10;\n  var $rootScopeMinErr = minErr('$rootScope');\n  var lastDirtyWatch = null;\n  var applyAsyncId = null;\n\n  this.digestTtl = function(value) {\n    if (arguments.length) {\n      TTL = value;\n    }\n    return TTL;\n  };\n\n  this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',\n      function($injector, $exceptionHandler, $parse, $browser) {\n\n    /**\n     * @ngdoc type\n     * @name $rootScope.Scope\n     *\n     * @description\n     * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the\n     * {@link auto.$injector $injector}. Child scopes are created using the\n     * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when\n     * compiled HTML template is executed.)\n     *\n     * Here is a simple scope snippet to show how you can interact with the scope.\n     * ```html\n     * <file src=\"./test/ng/rootScopeSpec.js\" tag=\"docs1\" />\n     * ```\n     *\n     * # Inheritance\n     * A scope can inherit from a parent scope, as in this example:\n     * ```js\n         var parent = $rootScope;\n         var child = parent.$new();\n\n         parent.salutation = \"Hello\";\n         expect(child.salutation).toEqual('Hello');\n\n         child.salutation = \"Welcome\";\n         expect(child.salutation).toEqual('Welcome');\n         expect(parent.salutation).toEqual('Hello');\n     * ```\n     *\n     * When interacting with `Scope` in tests, additional helper methods are available on the\n     * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional\n     * details.\n     *\n     *\n     * @param {Object.<string, function()>=} providers Map of service factory which need to be\n     *                                       provided for the current scope. Defaults to {@link ng}.\n     * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should\n     *                              append/override services provided by `providers`. This is handy\n     *                              when unit-testing and having the need to override a default\n     *                              service.\n     * @returns {Object} Newly created scope.\n     *\n     */\n    function Scope() {\n      this.$id = nextUid();\n      this.$$phase = this.$parent = this.$$watchers =\n                     this.$$nextSibling = this.$$prevSibling =\n                     this.$$childHead = this.$$childTail = null;\n      this.$root = this;\n      this.$$destroyed = false;\n      this.$$listeners = {};\n      this.$$listenerCount = {};\n      this.$$isolateBindings = null;\n    }\n\n    /**\n     * @ngdoc property\n     * @name $rootScope.Scope#$id\n     *\n     * @description\n     * Unique scope ID (monotonically increasing) useful for debugging.\n     */\n\n     /**\n      * @ngdoc property\n      * @name $rootScope.Scope#$parent\n      *\n      * @description\n      * Reference to the parent scope.\n      */\n\n      /**\n       * @ngdoc property\n       * @name $rootScope.Scope#$root\n       *\n       * @description\n       * Reference to the root scope.\n       */\n\n    Scope.prototype = {\n      constructor: Scope,\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$new\n       * @kind function\n       *\n       * @description\n       * Creates a new child {@link ng.$rootScope.Scope scope}.\n       *\n       * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.\n       * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.\n       *\n       * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is\n       * desired for the scope and its child scopes to be permanently detached from the parent and\n       * thus stop participating in model change detection and listener notification by invoking.\n       *\n       * @param {boolean} isolate If true, then the scope does not prototypically inherit from the\n       *         parent scope. The scope is isolated, as it can not see parent scope properties.\n       *         When creating widgets, it is useful for the widget to not accidentally read parent\n       *         state.\n       *\n       * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`\n       *                              of the newly created scope. Defaults to `this` scope if not provided.\n       *                              This is used when creating a transclude scope to correctly place it\n       *                              in the scope hierarchy while maintaining the correct prototypical\n       *                              inheritance.\n       *\n       * @returns {Object} The newly created child scope.\n       *\n       */\n      $new: function(isolate, parent) {\n        var child;\n\n        parent = parent || this;\n\n        if (isolate) {\n          child = new Scope();\n          child.$root = this.$root;\n        } else {\n          // Only create a child scope class if somebody asks for one,\n          // but cache it to allow the VM to optimize lookups.\n          if (!this.$$ChildScope) {\n            this.$$ChildScope = function ChildScope() {\n              this.$$watchers = this.$$nextSibling =\n                  this.$$childHead = this.$$childTail = null;\n              this.$$listeners = {};\n              this.$$listenerCount = {};\n              this.$id = nextUid();\n              this.$$ChildScope = null;\n            };\n            this.$$ChildScope.prototype = this;\n          }\n          child = new this.$$ChildScope();\n        }\n        child.$parent = parent;\n        child.$$prevSibling = parent.$$childTail;\n        if (parent.$$childHead) {\n          parent.$$childTail.$$nextSibling = child;\n          parent.$$childTail = child;\n        } else {\n          parent.$$childHead = parent.$$childTail = child;\n        }\n\n        // When the new scope is not isolated or we inherit from `this`, and\n        // the parent scope is destroyed, the property `$$destroyed` is inherited\n        // prototypically. In all other cases, this property needs to be set\n        // when the parent scope is destroyed.\n        // The listener needs to be added after the parent is set\n        if (isolate || parent != this) child.$on('$destroy', destroyChild);\n\n        return child;\n\n        function destroyChild() {\n          child.$$destroyed = true;\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watch\n       * @kind function\n       *\n       * @description\n       * Registers a `listener` callback to be executed whenever the `watchExpression` changes.\n       *\n       * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest\n       *   $digest()} and should return the value that will be watched. (Since\n       *   {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the\n       *   `watchExpression` can execute multiple times per\n       *   {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)\n       * - The `listener` is called only when the value from the current `watchExpression` and the\n       *   previous call to `watchExpression` are not equal (with the exception of the initial run,\n       *   see below). Inequality is determined according to reference inequality,\n       *   [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)\n       *    via the `!==` Javascript operator, unless `objectEquality == true`\n       *   (see next point)\n       * - When `objectEquality == true`, inequality of the `watchExpression` is determined\n       *   according to the {@link angular.equals} function. To save the value of the object for\n       *   later comparison, the {@link angular.copy} function is used. This therefore means that\n       *   watching complex objects will have adverse memory and performance implications.\n       * - The watch `listener` may change the model, which may trigger other `listener`s to fire.\n       *   This is achieved by rerunning the watchers until no changes are detected. The rerun\n       *   iteration limit is 10 to prevent an infinite loop deadlock.\n       *\n       *\n       * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,\n       * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`\n       * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a\n       * change is detected, be prepared for multiple calls to your listener.)\n       *\n       * After a watcher is registered with the scope, the `listener` fn is called asynchronously\n       * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the\n       * watcher. In rare cases, this is undesirable because the listener is called when the result\n       * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you\n       * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the\n       * listener was called due to initialization.\n       *\n       *\n       *\n       * # Example\n       * ```js\n           // let's assume that scope was dependency injected as the $rootScope\n           var scope = $rootScope;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n\n\n\n           // Using a function as a watchExpression\n           var food;\n           scope.foodCounter = 0;\n           expect(scope.foodCounter).toEqual(0);\n           scope.$watch(\n             // This function returns the value being watched. It is called for each turn of the $digest loop\n             function() { return food; },\n             // This is the change listener, called when the value returned from the above function changes\n             function(newValue, oldValue) {\n               if ( newValue !== oldValue ) {\n                 // Only increment the counter if the value changed\n                 scope.foodCounter = scope.foodCounter + 1;\n               }\n             }\n           );\n           // No digest has been run so the counter will be zero\n           expect(scope.foodCounter).toEqual(0);\n\n           // Run the digest but since food has not changed count will still be zero\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(0);\n\n           // Update food and run digest.  Now the counter will increment\n           food = 'cheeseburger';\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(1);\n\n       * ```\n       *\n       *\n       *\n       * @param {(function()|string)} watchExpression Expression that is evaluated on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers\n       *    a call to the `listener`.\n       *\n       *    - `string`: Evaluated as {@link guide/expression expression}\n       *    - `function(scope)`: called with current `scope` as a parameter.\n       * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value\n       *    of `watchExpression` changes.\n       *\n       *    - `newVal` contains the current value of the `watchExpression`\n       *    - `oldVal` contains the previous value of the `watchExpression`\n       *    - `scope` refers to the current scope\n       * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of\n       *     comparing for reference equality.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $watch: function(watchExp, listener, objectEquality) {\n        var get = $parse(watchExp);\n\n        if (get.$$watchDelegate) {\n          return get.$$watchDelegate(this, listener, objectEquality, get);\n        }\n        var scope = this,\n            array = scope.$$watchers,\n            watcher = {\n              fn: listener,\n              last: initWatchVal,\n              get: get,\n              exp: watchExp,\n              eq: !!objectEquality\n            };\n\n        lastDirtyWatch = null;\n\n        if (!isFunction(listener)) {\n          watcher.fn = noop;\n        }\n\n        if (!array) {\n          array = scope.$$watchers = [];\n        }\n        // we use unshift since we use a while loop in $digest for speed.\n        // the while loop reads in reverse order.\n        array.unshift(watcher);\n\n        return function deregisterWatch() {\n          arrayRemove(array, watcher);\n          lastDirtyWatch = null;\n        };\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchGroup\n       * @kind function\n       *\n       * @description\n       * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.\n       * If any one expression in the collection changes the `listener` is executed.\n       *\n       * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every\n       *   call to $digest() to see if any items changes.\n       * - The `listener` is called whenever any expression in the `watchExpressions` array changes.\n       *\n       * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually\n       * watched using {@link ng.$rootScope.Scope#$watch $watch()}\n       *\n       * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any\n       *    expression in `watchExpressions` changes\n       *    The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    The `scope` refers to the current scope.\n       * @returns {function()} Returns a de-registration function for all listeners.\n       */\n      $watchGroup: function(watchExpressions, listener) {\n        var oldValues = new Array(watchExpressions.length);\n        var newValues = new Array(watchExpressions.length);\n        var deregisterFns = [];\n        var self = this;\n        var changeReactionScheduled = false;\n        var firstRun = true;\n\n        if (!watchExpressions.length) {\n          // No expressions means we call the listener ASAP\n          var shouldCall = true;\n          self.$evalAsync(function() {\n            if (shouldCall) listener(newValues, newValues, self);\n          });\n          return function deregisterWatchGroup() {\n            shouldCall = false;\n          };\n        }\n\n        if (watchExpressions.length === 1) {\n          // Special case size of one\n          return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {\n            newValues[0] = value;\n            oldValues[0] = oldValue;\n            listener(newValues, (value === oldValue) ? newValues : oldValues, scope);\n          });\n        }\n\n        forEach(watchExpressions, function(expr, i) {\n          var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {\n            newValues[i] = value;\n            oldValues[i] = oldValue;\n            if (!changeReactionScheduled) {\n              changeReactionScheduled = true;\n              self.$evalAsync(watchGroupAction);\n            }\n          });\n          deregisterFns.push(unwatchFn);\n        });\n\n        function watchGroupAction() {\n          changeReactionScheduled = false;\n\n          if (firstRun) {\n            firstRun = false;\n            listener(newValues, newValues, self);\n          } else {\n            listener(newValues, oldValues, self);\n          }\n        }\n\n        return function deregisterWatchGroup() {\n          while (deregisterFns.length) {\n            deregisterFns.shift()();\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchCollection\n       * @kind function\n       *\n       * @description\n       * Shallow watches the properties of an object and fires whenever any of the properties change\n       * (for arrays, this implies watching the array items; for object maps, this implies watching\n       * the properties). If a change is detected, the `listener` callback is fired.\n       *\n       * - The `obj` collection is observed via standard $watch operation and is examined on every\n       *   call to $digest() to see if any items have been added, removed, or moved.\n       * - The `listener` is called whenever anything within the `obj` has changed. Examples include\n       *   adding, removing, and moving items belonging to an object or array.\n       *\n       *\n       * # Example\n       * ```js\n          $scope.names = ['igor', 'matias', 'misko', 'james'];\n          $scope.dataCount = 4;\n\n          $scope.$watchCollection('names', function(newNames, oldNames) {\n            $scope.dataCount = newNames.length;\n          });\n\n          expect($scope.dataCount).toEqual(4);\n          $scope.$digest();\n\n          //still at 4 ... no changes\n          expect($scope.dataCount).toEqual(4);\n\n          $scope.names.pop();\n          $scope.$digest();\n\n          //now there's been a change\n          expect($scope.dataCount).toEqual(3);\n       * ```\n       *\n       *\n       * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The\n       *    expression value should evaluate to an object or an array which is observed on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the\n       *    collection will trigger a call to the `listener`.\n       *\n       * @param {function(newCollection, oldCollection, scope)} listener a callback function called\n       *    when a change is detected.\n       *    - The `newCollection` object is the newly modified data obtained from the `obj` expression\n       *    - The `oldCollection` object is a copy of the former collection data.\n       *      Due to performance considerations, the`oldCollection` value is computed only if the\n       *      `listener` function declares two or more arguments.\n       *    - The `scope` argument refers to the current scope.\n       *\n       * @returns {function()} Returns a de-registration function for this listener. When the\n       *    de-registration function is executed, the internal watch operation is terminated.\n       */\n      $watchCollection: function(obj, listener) {\n        $watchCollectionInterceptor.$stateful = true;\n\n        var self = this;\n        // the current value, updated on each dirty-check run\n        var newValue;\n        // a shallow copy of the newValue from the last dirty-check run,\n        // updated to match newValue during dirty-check run\n        var oldValue;\n        // a shallow copy of the newValue from when the last change happened\n        var veryOldValue;\n        // only track veryOldValue if the listener is asking for it\n        var trackVeryOldValue = (listener.length > 1);\n        var changeDetected = 0;\n        var changeDetector = $parse(obj, $watchCollectionInterceptor);\n        var internalArray = [];\n        var internalObject = {};\n        var initRun = true;\n        var oldLength = 0;\n\n        function $watchCollectionInterceptor(_value) {\n          newValue = _value;\n          var newLength, key, bothNaN, newItem, oldItem;\n\n          // If the new value is undefined, then return undefined as the watch may be a one-time watch\n          if (isUndefined(newValue)) return;\n\n          if (!isObject(newValue)) { // if primitive\n            if (oldValue !== newValue) {\n              oldValue = newValue;\n              changeDetected++;\n            }\n          } else if (isArrayLike(newValue)) {\n            if (oldValue !== internalArray) {\n              // we are transitioning from something which was not an array into array.\n              oldValue = internalArray;\n              oldLength = oldValue.length = 0;\n              changeDetected++;\n            }\n\n            newLength = newValue.length;\n\n            if (oldLength !== newLength) {\n              // if lengths do not match we need to trigger change notification\n              changeDetected++;\n              oldValue.length = oldLength = newLength;\n            }\n            // copy the items to oldValue and look for changes.\n            for (var i = 0; i < newLength; i++) {\n              oldItem = oldValue[i];\n              newItem = newValue[i];\n\n              bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n              if (!bothNaN && (oldItem !== newItem)) {\n                changeDetected++;\n                oldValue[i] = newItem;\n              }\n            }\n          } else {\n            if (oldValue !== internalObject) {\n              // we are transitioning from something which was not an object into object.\n              oldValue = internalObject = {};\n              oldLength = 0;\n              changeDetected++;\n            }\n            // copy the items to oldValue and look for changes.\n            newLength = 0;\n            for (key in newValue) {\n              if (newValue.hasOwnProperty(key)) {\n                newLength++;\n                newItem = newValue[key];\n                oldItem = oldValue[key];\n\n                if (key in oldValue) {\n                  bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n                  if (!bothNaN && (oldItem !== newItem)) {\n                    changeDetected++;\n                    oldValue[key] = newItem;\n                  }\n                } else {\n                  oldLength++;\n                  oldValue[key] = newItem;\n                  changeDetected++;\n                }\n              }\n            }\n            if (oldLength > newLength) {\n              // we used to have more keys, need to find them and destroy them.\n              changeDetected++;\n              for (key in oldValue) {\n                if (!newValue.hasOwnProperty(key)) {\n                  oldLength--;\n                  delete oldValue[key];\n                }\n              }\n            }\n          }\n          return changeDetected;\n        }\n\n        function $watchCollectionAction() {\n          if (initRun) {\n            initRun = false;\n            listener(newValue, newValue, self);\n          } else {\n            listener(newValue, veryOldValue, self);\n          }\n\n          // make a copy for the next time a collection is changed\n          if (trackVeryOldValue) {\n            if (!isObject(newValue)) {\n              //primitive\n              veryOldValue = newValue;\n            } else if (isArrayLike(newValue)) {\n              veryOldValue = new Array(newValue.length);\n              for (var i = 0; i < newValue.length; i++) {\n                veryOldValue[i] = newValue[i];\n              }\n            } else { // if object\n              veryOldValue = {};\n              for (var key in newValue) {\n                if (hasOwnProperty.call(newValue, key)) {\n                  veryOldValue[key] = newValue[key];\n                }\n              }\n            }\n          }\n        }\n\n        return this.$watch(changeDetector, $watchCollectionAction);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$digest\n       * @kind function\n       *\n       * @description\n       * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and\n       * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change\n       * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}\n       * until no more listeners are firing. This means that it is possible to get into an infinite\n       * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of\n       * iterations exceeds 10.\n       *\n       * Usually, you don't call `$digest()` directly in\n       * {@link ng.directive:ngController controllers} or in\n       * {@link ng.$compileProvider#directive directives}.\n       * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within\n       * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.\n       *\n       * If you want to be notified whenever `$digest()` is called,\n       * you can register a `watchExpression` function with\n       * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.\n       *\n       * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.\n       *\n       * # Example\n       * ```js\n           var scope = ...;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n       * ```\n       *\n       */\n      $digest: function() {\n        var watch, value, last,\n            watchers,\n            length,\n            dirty, ttl = TTL,\n            next, current, target = this,\n            watchLog = [],\n            logIdx, logMsg, asyncTask;\n\n        beginPhase('$digest');\n        // Check for changes to browser url that happened in sync before the call to $digest\n        $browser.$$checkUrlChange();\n\n        if (this === $rootScope && applyAsyncId !== null) {\n          // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then\n          // cancel the scheduled $apply and flush the queue of expressions to be evaluated.\n          $browser.defer.cancel(applyAsyncId);\n          flushApplyAsync();\n        }\n\n        lastDirtyWatch = null;\n\n        do { // \"while dirty\" loop\n          dirty = false;\n          current = target;\n\n          while (asyncQueue.length) {\n            try {\n              asyncTask = asyncQueue.shift();\n              asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n            lastDirtyWatch = null;\n          }\n\n          traverseScopesLoop:\n          do { // \"traverse the scopes\" loop\n            if ((watchers = current.$$watchers)) {\n              // process our watches\n              length = watchers.length;\n              while (length--) {\n                try {\n                  watch = watchers[length];\n                  // Most common watches are on primitives, in which case we can short\n                  // circuit it with === operator, only when === fails do we use .equals\n                  if (watch) {\n                    if ((value = watch.get(current)) !== (last = watch.last) &&\n                        !(watch.eq\n                            ? equals(value, last)\n                            : (typeof value === 'number' && typeof last === 'number'\n                               && isNaN(value) && isNaN(last)))) {\n                      dirty = true;\n                      lastDirtyWatch = watch;\n                      watch.last = watch.eq ? copy(value, null) : value;\n                      watch.fn(value, ((last === initWatchVal) ? value : last), current);\n                      if (ttl < 5) {\n                        logIdx = 4 - ttl;\n                        if (!watchLog[logIdx]) watchLog[logIdx] = [];\n                        watchLog[logIdx].push({\n                          msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,\n                          newVal: value,\n                          oldVal: last\n                        });\n                      }\n                    } else if (watch === lastDirtyWatch) {\n                      // If the most recently dirty watcher is now clean, short circuit since the remaining watchers\n                      // have already been tested.\n                      dirty = false;\n                      break traverseScopesLoop;\n                    }\n                  }\n                } catch (e) {\n                  $exceptionHandler(e);\n                }\n              }\n            }\n\n            // Insanity Warning: scope depth-first traversal\n            // yes, this code is a bit crazy, but it works and we have tests to prove it!\n            // this piece should be kept in sync with the traversal in $broadcast\n            if (!(next = (current.$$childHead ||\n                (current !== target && current.$$nextSibling)))) {\n              while (current !== target && !(next = current.$$nextSibling)) {\n                current = current.$parent;\n              }\n            }\n          } while ((current = next));\n\n          // `break traverseScopesLoop;` takes us to here\n\n          if ((dirty || asyncQueue.length) && !(ttl--)) {\n            clearPhase();\n            throw $rootScopeMinErr('infdig',\n                '{0} $digest() iterations reached. Aborting!\\n' +\n                'Watchers fired in the last 5 iterations: {1}',\n                TTL, watchLog);\n          }\n\n        } while (dirty || asyncQueue.length);\n\n        clearPhase();\n\n        while (postDigestQueue.length) {\n          try {\n            postDigestQueue.shift()();\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        }\n      },\n\n\n      /**\n       * @ngdoc event\n       * @name $rootScope.Scope#$destroy\n       * @eventType broadcast on scope being destroyed\n       *\n       * @description\n       * Broadcasted when a scope and its children are being destroyed.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$destroy\n       * @kind function\n       *\n       * @description\n       * Removes the current scope (and all of its children) from the parent scope. Removal implies\n       * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer\n       * propagate to the current scope and its children. Removal also implies that the current\n       * scope is eligible for garbage collection.\n       *\n       * The `$destroy()` is usually used by directives such as\n       * {@link ng.directive:ngRepeat ngRepeat} for managing the\n       * unrolling of the loop.\n       *\n       * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.\n       * Application code can register a `$destroy` event handler that will give it a chance to\n       * perform any necessary cleanup.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n      $destroy: function() {\n        // we can't destroy the root scope or a scope that has been already destroyed\n        if (this.$$destroyed) return;\n        var parent = this.$parent;\n\n        this.$broadcast('$destroy');\n        this.$$destroyed = true;\n        if (this === $rootScope) return;\n\n        for (var eventName in this.$$listenerCount) {\n          decrementListenerCount(this, this.$$listenerCount[eventName], eventName);\n        }\n\n        // sever all the references to parent scopes (after this cleanup, the current scope should\n        // not be retained by any of our references and should be eligible for garbage collection)\n        if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;\n        if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;\n        if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;\n        if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;\n\n        // Disable listeners, watchers and apply/digest methods\n        this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;\n        this.$on = this.$watch = this.$watchGroup = function() { return noop; };\n        this.$$listeners = {};\n\n        // All of the code below is bogus code that works around V8's memory leak via optimized code\n        // and inline caches.\n        //\n        // see:\n        // - https://code.google.com/p/v8/issues/detail?id=2073#c26\n        // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909\n        // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451\n\n        this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =\n            this.$$childTail = this.$root = this.$$watchers = null;\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$eval\n       * @kind function\n       *\n       * @description\n       * Executes the `expression` on the current scope and returns the result. Any exceptions in\n       * the expression are propagated (uncaught). This is useful when evaluating Angular\n       * expressions.\n       *\n       * # Example\n       * ```js\n           var scope = ng.$rootScope.Scope();\n           scope.a = 1;\n           scope.b = 2;\n\n           expect(scope.$eval('a+b')).toEqual(3);\n           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);\n       * ```\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       * @returns {*} The result of evaluating the expression.\n       */\n      $eval: function(expr, locals) {\n        return $parse(expr)(this, locals);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$evalAsync\n       * @kind function\n       *\n       * @description\n       * Executes the expression on the current scope at a later point in time.\n       *\n       * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only\n       * that:\n       *\n       *   - it will execute after the function that scheduled the evaluation (preferably before DOM\n       *     rendering).\n       *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after\n       *     `expression` execution.\n       *\n       * Any exceptions from the execution of the expression are forwarded to the\n       * {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle\n       * will be scheduled. However, it is encouraged to always call code that changes the model\n       * from within an `$apply` call. That includes code evaluated via `$evalAsync`.\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       */\n      $evalAsync: function(expr, locals) {\n        // if we are outside of an $digest loop and this is the first time we are scheduling async\n        // task also schedule async auto-flush\n        if (!$rootScope.$$phase && !asyncQueue.length) {\n          $browser.defer(function() {\n            if (asyncQueue.length) {\n              $rootScope.$digest();\n            }\n          });\n        }\n\n        asyncQueue.push({scope: this, expression: expr, locals: locals});\n      },\n\n      $$postDigest: function(fn) {\n        postDigestQueue.push(fn);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$apply\n       * @kind function\n       *\n       * @description\n       * `$apply()` is used to execute an expression in angular from outside of the angular\n       * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).\n       * Because we are calling into the angular framework we need to perform proper scope life\n       * cycle of {@link ng.$exceptionHandler exception handling},\n       * {@link ng.$rootScope.Scope#$digest executing watches}.\n       *\n       * ## Life cycle\n       *\n       * # Pseudo-Code of `$apply()`\n       * ```js\n           function $apply(expr) {\n             try {\n               return $eval(expr);\n             } catch (e) {\n               $exceptionHandler(e);\n             } finally {\n               $root.$digest();\n             }\n           }\n       * ```\n       *\n       *\n       * Scope's `$apply()` method transitions through the following stages:\n       *\n       * 1. The {@link guide/expression expression} is executed using the\n       *    {@link ng.$rootScope.Scope#$eval $eval()} method.\n       * 2. Any exceptions from the execution of the expression are forwarded to the\n       *    {@link ng.$exceptionHandler $exceptionHandler} service.\n       * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the\n       *    expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.\n       *\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       *\n       * @returns {*} The result of evaluating the expression.\n       */\n      $apply: function(expr) {\n        try {\n          beginPhase('$apply');\n          return this.$eval(expr);\n        } catch (e) {\n          $exceptionHandler(e);\n        } finally {\n          clearPhase();\n          try {\n            $rootScope.$digest();\n          } catch (e) {\n            $exceptionHandler(e);\n            throw e;\n          }\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$applyAsync\n       * @kind function\n       *\n       * @description\n       * Schedule the invocation of $apply to occur at a later time. The actual time difference\n       * varies across browsers, but is typically around ~10 milliseconds.\n       *\n       * This can be used to queue up multiple expressions which need to be evaluated in the same\n       * digest.\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       */\n      $applyAsync: function(expr) {\n        var scope = this;\n        expr && applyAsyncQueue.push($applyAsyncExpression);\n        scheduleApplyAsync();\n\n        function $applyAsyncExpression() {\n          scope.$eval(expr);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$on\n       * @kind function\n       *\n       * @description\n       * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for\n       * discussion of event life cycle.\n       *\n       * The event listener function format is: `function(event, args...)`. The `event` object\n       * passed into the listener has the following attributes:\n       *\n       *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or\n       *     `$broadcast`-ed.\n       *   - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the\n       *     event propagates through the scope hierarchy, this property is set to null.\n       *   - `name` - `{string}`: name of the event.\n       *   - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel\n       *     further event propagation (available only for events that were `$emit`-ed).\n       *   - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag\n       *     to true.\n       *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.\n       *\n       * @param {string} name Event name to listen on.\n       * @param {function(event, ...args)} listener Function to call when the event is emitted.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $on: function(name, listener) {\n        var namedListeners = this.$$listeners[name];\n        if (!namedListeners) {\n          this.$$listeners[name] = namedListeners = [];\n        }\n        namedListeners.push(listener);\n\n        var current = this;\n        do {\n          if (!current.$$listenerCount[name]) {\n            current.$$listenerCount[name] = 0;\n          }\n          current.$$listenerCount[name]++;\n        } while ((current = current.$parent));\n\n        var self = this;\n        return function() {\n          var indexOfListener = namedListeners.indexOf(listener);\n          if (indexOfListener !== -1) {\n            namedListeners[indexOfListener] = null;\n            decrementListenerCount(self, 1, name);\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$emit\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` upwards through the scope hierarchy notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$emit` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event traverses upwards toward the root scope and calls all\n       * registered listeners along the way. The event will stop propagating if one of the listeners\n       * cancels it.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to emit.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).\n       */\n      $emit: function(name, args) {\n        var empty = [],\n            namedListeners,\n            scope = this,\n            stopPropagation = false,\n            event = {\n              name: name,\n              targetScope: scope,\n              stopPropagation: function() {stopPropagation = true;},\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            },\n            listenerArgs = concat([event], arguments, 1),\n            i, length;\n\n        do {\n          namedListeners = scope.$$listeners[name] || empty;\n          event.currentScope = scope;\n          for (i = 0, length = namedListeners.length; i < length; i++) {\n\n            // if listeners were deregistered, defragment the array\n            if (!namedListeners[i]) {\n              namedListeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n            try {\n              //allow all listeners attached to the current scope to run\n              namedListeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n          //if any listener on the current scope stops propagation, prevent bubbling\n          if (stopPropagation) {\n            event.currentScope = null;\n            return event;\n          }\n          //traverse upwards\n          scope = scope.$parent;\n        } while (scope);\n\n        event.currentScope = null;\n\n        return event;\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$broadcast\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` downwards to all child scopes (and their children) notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$broadcast` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event propagates to all direct and indirect scopes of the current\n       * scope and calls all registered listeners along the way. The event cannot be canceled.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to broadcast.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}\n       */\n      $broadcast: function(name, args) {\n        var target = this,\n            current = target,\n            next = target,\n            event = {\n              name: name,\n              targetScope: target,\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            };\n\n        if (!target.$$listenerCount[name]) return event;\n\n        var listenerArgs = concat([event], arguments, 1),\n            listeners, i, length;\n\n        //down while you can, then up and next sibling or up and next sibling until back at root\n        while ((current = next)) {\n          event.currentScope = current;\n          listeners = current.$$listeners[name] || [];\n          for (i = 0, length = listeners.length; i < length; i++) {\n            // if listeners were deregistered, defragment the array\n            if (!listeners[i]) {\n              listeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n\n            try {\n              listeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n\n          // Insanity Warning: scope depth-first traversal\n          // yes, this code is a bit crazy, but it works and we have tests to prove it!\n          // this piece should be kept in sync with the traversal in $digest\n          // (though it differs due to having the extra check for $$listenerCount)\n          if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||\n              (current !== target && current.$$nextSibling)))) {\n            while (current !== target && !(next = current.$$nextSibling)) {\n              current = current.$parent;\n            }\n          }\n        }\n\n        event.currentScope = null;\n        return event;\n      }\n    };\n\n    var $rootScope = new Scope();\n\n    //The internal queues. Expose them on the $rootScope for debugging/testing purposes.\n    var asyncQueue = $rootScope.$$asyncQueue = [];\n    var postDigestQueue = $rootScope.$$postDigestQueue = [];\n    var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];\n\n    return $rootScope;\n\n\n    function beginPhase(phase) {\n      if ($rootScope.$$phase) {\n        throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);\n      }\n\n      $rootScope.$$phase = phase;\n    }\n\n    function clearPhase() {\n      $rootScope.$$phase = null;\n    }\n\n\n    function decrementListenerCount(current, count, name) {\n      do {\n        current.$$listenerCount[name] -= count;\n\n        if (current.$$listenerCount[name] === 0) {\n          delete current.$$listenerCount[name];\n        }\n      } while ((current = current.$parent));\n    }\n\n    /**\n     * function used as an initial value for watchers.\n     * because it's unique we can easily tell it apart from other values\n     */\n    function initWatchVal() {}\n\n    function flushApplyAsync() {\n      while (applyAsyncQueue.length) {\n        try {\n          applyAsyncQueue.shift()();\n        } catch (e) {\n          $exceptionHandler(e);\n        }\n      }\n      applyAsyncId = null;\n    }\n\n    function scheduleApplyAsync() {\n      if (applyAsyncId === null) {\n        applyAsyncId = $browser.defer(function() {\n          $rootScope.$apply(flushApplyAsync);\n        });\n      }\n    }\n  }];\n}\n\n/**\n * @description\n * Private service to sanitize uris for links and images. Used by $compile and $sanitize.\n */\nfunction $$SanitizeUriProvider() {\n  var aHrefSanitizationWhitelist = /^\\s*(https?|ftp|mailto|tel|file):/,\n    imgSrcSanitizationWhitelist = /^\\s*((https?|ftp|file|blob):|data:image\\/)/;\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      aHrefSanitizationWhitelist = regexp;\n      return this;\n    }\n    return aHrefSanitizationWhitelist;\n  };\n\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      imgSrcSanitizationWhitelist = regexp;\n      return this;\n    }\n    return imgSrcSanitizationWhitelist;\n  };\n\n  this.$get = function() {\n    return function sanitizeUri(uri, isImage) {\n      var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;\n      var normalizedVal;\n      normalizedVal = urlResolve(uri).href;\n      if (normalizedVal !== '' && !normalizedVal.match(regex)) {\n        return 'unsafe:' + normalizedVal;\n      }\n      return uri;\n    };\n  };\n}\n\nvar $sceMinErr = minErr('$sce');\n\nvar SCE_CONTEXTS = {\n  HTML: 'html',\n  CSS: 'css',\n  URL: 'url',\n  // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a\n  // url.  (e.g. ng-include, script src, templateUrl)\n  RESOURCE_URL: 'resourceUrl',\n  JS: 'js'\n};\n\n// Helper functions follow.\n\nfunction adjustMatcher(matcher) {\n  if (matcher === 'self') {\n    return matcher;\n  } else if (isString(matcher)) {\n    // Strings match exactly except for 2 wildcards - '*' and '**'.\n    // '*' matches any character except those from the set ':/.?&'.\n    // '**' matches any character (like .* in a RegExp).\n    // More than 2 *'s raises an error as it's ill defined.\n    if (matcher.indexOf('***') > -1) {\n      throw $sceMinErr('iwcard',\n          'Illegal sequence *** in string matcher.  String: {0}', matcher);\n    }\n    matcher = escapeForRegexp(matcher).\n                  replace('\\\\*\\\\*', '.*').\n                  replace('\\\\*', '[^:/.?&;]*');\n    return new RegExp('^' + matcher + '$');\n  } else if (isRegExp(matcher)) {\n    // The only other type of matcher allowed is a Regexp.\n    // Match entire URL / disallow partial matches.\n    // Flags are reset (i.e. no global, ignoreCase or multiline)\n    return new RegExp('^' + matcher.source + '$');\n  } else {\n    throw $sceMinErr('imatcher',\n        'Matchers may only be \"self\", string patterns or RegExp objects');\n  }\n}\n\n\nfunction adjustMatchers(matchers) {\n  var adjustedMatchers = [];\n  if (isDefined(matchers)) {\n    forEach(matchers, function(matcher) {\n      adjustedMatchers.push(adjustMatcher(matcher));\n    });\n  }\n  return adjustedMatchers;\n}\n\n\n/**\n * @ngdoc service\n * @name $sceDelegate\n * @kind function\n *\n * @description\n *\n * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict\n * Contextual Escaping (SCE)} services to AngularJS.\n *\n * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of\n * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS.  This is\n * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to\n * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things\n * work because `$sce` delegates to `$sceDelegate` for these operations.\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.\n *\n * The default instance of `$sceDelegate` should work out of the box with little pain.  While you\n * can override it completely to change the behavior of `$sce`, the common case would\n * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting\n * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as\n * templates.  Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist\n * $sceDelegateProvider.resourceUrlWhitelist} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n */\n\n/**\n * @ngdoc provider\n * @name $sceDelegateProvider\n * @description\n *\n * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate\n * $sceDelegate} service.  This allows one to get/set the whitelists and blacklists used to ensure\n * that the URLs used for sourcing Angular templates are safe.  Refer {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and\n * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n *\n * For the general details about this service in Angular, read the main page for {@link ng.$sce\n * Strict Contextual Escaping (SCE)}.\n *\n * **Example**:  Consider the following case. <a name=\"example\"></a>\n *\n * - your app is hosted at url `http://myapp.example.com/`\n * - but some of your templates are hosted on other domains you control such as\n *   `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.\n * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.\n *\n * Here is what a secure configuration for this scenario might look like:\n *\n * ```\n *  angular.module('myApp', []).config(function($sceDelegateProvider) {\n *    $sceDelegateProvider.resourceUrlWhitelist([\n *      // Allow same origin resource loads.\n *      'self',\n *      // Allow loading from our assets domain.  Notice the difference between * and **.\n *      'http://srv*.assets.example.com/**'\n *    ]);\n *\n *    // The blacklist overrides the whitelist so the open redirect here is blocked.\n *    $sceDelegateProvider.resourceUrlBlacklist([\n *      'http://myapp.example.com/clickThru**'\n *    ]);\n *  });\n * ```\n */\n\nfunction $SceDelegateProvider() {\n  this.SCE_CONTEXTS = SCE_CONTEXTS;\n\n  // Resource URLs can also be trusted by policy.\n  var resourceUrlWhitelist = ['self'],\n      resourceUrlBlacklist = [];\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlWhitelist\n   * @kind function\n   *\n   * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     Note: **an empty whitelist array will block all URLs**!\n   *\n   * @return {Array} the currently set whitelist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is `['self']` allowing only\n   * same origin resource requests.\n   *\n   * @description\n   * Sets/Gets the whitelist of trusted resource URLs.\n   */\n  this.resourceUrlWhitelist = function(value) {\n    if (arguments.length) {\n      resourceUrlWhitelist = adjustMatchers(value);\n    }\n    return resourceUrlWhitelist;\n  };\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlBlacklist\n   * @kind function\n   *\n   * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     The typical usage for the blacklist is to **block\n   *     [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as\n   *     these would otherwise be trusted but actually return content from the redirected domain.\n   *\n   *     Finally, **the blacklist overrides the whitelist** and has the final say.\n   *\n   * @return {Array} the currently set blacklist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there\n   * is no blacklist.)\n   *\n   * @description\n   * Sets/Gets the blacklist of trusted resource URLs.\n   */\n\n  this.resourceUrlBlacklist = function(value) {\n    if (arguments.length) {\n      resourceUrlBlacklist = adjustMatchers(value);\n    }\n    return resourceUrlBlacklist;\n  };\n\n  this.$get = ['$injector', function($injector) {\n\n    var htmlSanitizer = function htmlSanitizer(html) {\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    };\n\n    if ($injector.has('$sanitize')) {\n      htmlSanitizer = $injector.get('$sanitize');\n    }\n\n\n    function matchUrl(matcher, parsedUrl) {\n      if (matcher === 'self') {\n        return urlIsSameOrigin(parsedUrl);\n      } else {\n        // definitely a regex.  See adjustMatchers()\n        return !!matcher.exec(parsedUrl.href);\n      }\n    }\n\n    function isResourceUrlAllowedByPolicy(url) {\n      var parsedUrl = urlResolve(url.toString());\n      var i, n, allowed = false;\n      // Ensure that at least one item from the whitelist allows this url.\n      for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {\n        if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {\n          allowed = true;\n          break;\n        }\n      }\n      if (allowed) {\n        // Ensure that no item from the blacklist blocked this url.\n        for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {\n          if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {\n            allowed = false;\n            break;\n          }\n        }\n      }\n      return allowed;\n    }\n\n    function generateHolderType(Base) {\n      var holderType = function TrustedValueHolderType(trustedValue) {\n        this.$$unwrapTrustedValue = function() {\n          return trustedValue;\n        };\n      };\n      if (Base) {\n        holderType.prototype = new Base();\n      }\n      holderType.prototype.valueOf = function sceValueOf() {\n        return this.$$unwrapTrustedValue();\n      };\n      holderType.prototype.toString = function sceToString() {\n        return this.$$unwrapTrustedValue().toString();\n      };\n      return holderType;\n    }\n\n    var trustedValueHolderBase = generateHolderType(),\n        byType = {};\n\n    byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#trustAs\n     *\n     * @description\n     * Returns an object that is trusted by angular for use in specified strict\n     * contextual escaping contexts (such as ng-bind-html, ng-include, any src\n     * attribute interpolation, any dom event binding attribute interpolation\n     * such as for onclick,  etc.) that uses the provided value.\n     * See {@link ng.$sce $sce} for enabling strict contextual escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resourceUrl, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n    function trustAs(type, trustedValue) {\n      var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (!Constructor) {\n        throw $sceMinErr('icontext',\n            'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',\n            type, trustedValue);\n      }\n      if (trustedValue === null || trustedValue === undefined || trustedValue === '') {\n        return trustedValue;\n      }\n      // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting\n      // mutable objects, we ensure here that the value passed in is actually a string.\n      if (typeof trustedValue !== 'string') {\n        throw $sceMinErr('itype',\n            'Attempted to trust a non-string value in a content requiring a string: Context: {0}',\n            type);\n      }\n      return new Constructor(trustedValue);\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#valueOf\n     *\n     * @description\n     * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs\n     * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.\n     *\n     * If the passed parameter is not a value that had been returned by {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.\n     *\n     * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}\n     *      call or anything else.\n     * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if `value` is the result of such a call.  Otherwise, returns\n     *     `value` unchanged.\n     */\n    function valueOf(maybeTrusted) {\n      if (maybeTrusted instanceof trustedValueHolderBase) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      } else {\n        return maybeTrusted;\n      }\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#getTrusted\n     *\n     * @description\n     * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and\n     * returns the originally supplied value if the queried context type is a supertype of the\n     * created type.  If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} call.\n     * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if valid in this context.  Otherwise, throws an exception.\n     */\n    function getTrusted(type, maybeTrusted) {\n      if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {\n        return maybeTrusted;\n      }\n      var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (constructor && maybeTrusted instanceof constructor) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      }\n      // If we get here, then we may only take one of two actions.\n      // 1. sanitize the value for the requested type, or\n      // 2. throw an exception.\n      if (type === SCE_CONTEXTS.RESOURCE_URL) {\n        if (isResourceUrlAllowedByPolicy(maybeTrusted)) {\n          return maybeTrusted;\n        } else {\n          throw $sceMinErr('insecurl',\n              'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',\n              maybeTrusted.toString());\n        }\n      } else if (type === SCE_CONTEXTS.HTML) {\n        return htmlSanitizer(maybeTrusted);\n      }\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    }\n\n    return { trustAs: trustAs,\n             getTrusted: getTrusted,\n             valueOf: valueOf };\n  }];\n}\n\n\n/**\n * @ngdoc provider\n * @name $sceProvider\n * @description\n *\n * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.\n * -   enable/disable Strict Contextual Escaping (SCE) in a module\n * -   override the default implementation with a custom delegate\n *\n * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.\n */\n\n/* jshint maxlen: false*/\n\n/**\n * @ngdoc service\n * @name $sce\n * @kind function\n *\n * @description\n *\n * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.\n *\n * # Strict Contextual Escaping\n *\n * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain\n * contexts to result in a value that is marked as safe to use for that context.  One example of\n * such a context is binding arbitrary html controlled by the user via `ng-bind-html`.  We refer\n * to these contexts as privileged or SCE contexts.\n *\n * As of version 1.2, Angular ships with SCE enabled by default.\n *\n * Note:  When enabled (the default), IE<11 in quirks mode is not supported.  In this mode, IE<11 allow\n * one to execute arbitrary javascript by the use of the expression() syntax.  Refer\n * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.\n * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`\n * to the top of your HTML document.\n *\n * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for\n * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.\n *\n * Here's an example of a binding in a privileged context:\n *\n * ```\n * <input ng-model=\"userHtml\">\n * <div ng-bind-html=\"userHtml\"></div>\n * ```\n *\n * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user.  With SCE\n * disabled, this application allows the user to render arbitrary HTML into the DIV.\n * In a more realistic example, one may be rendering user comments, blog articles, etc. via\n * bindings.  (HTML is just one example of a context where rendering user controlled input creates\n * security vulnerabilities.)\n *\n * For the case of HTML, you might use a library, either on the client side, or on the server side,\n * to sanitize unsafe HTML before binding to the value and rendering it in the document.\n *\n * How would you ensure that every place that used these types of bindings was bound to a value that\n * was sanitized by your library (or returned as safe for rendering by your server?)  How can you\n * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some\n * properties/fields and forgot to update the binding to the sanitized value?\n *\n * To be secure by default, you want to ensure that any such bindings are disallowed unless you can\n * determine that something explicitly says it's safe to use a value for binding in that\n * context.  You can then audit your code (a simple grep would do) to ensure that this is only done\n * for those values that you can easily tell are safe - because they were received from your server,\n * sanitized by your library, etc.  You can organize your codebase to help with this - perhaps\n * allowing only the files in a specific directory to do this.  Ensuring that the internal API\n * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.\n *\n * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}\n * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to\n * obtain values that will be accepted by SCE / privileged contexts.\n *\n *\n * ## How does it work?\n *\n * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted\n * $sce.getTrusted(context, value)} rather than to the value directly.  Directives use {@link\n * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the\n * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.\n *\n * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link\n * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}.  Here's the actual code (slightly\n * simplified):\n *\n * ```\n * var ngBindHtmlDirective = ['$sce', function($sce) {\n *   return function(scope, element, attr) {\n *     scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {\n *       element.html(value || '');\n *     });\n *   };\n * }];\n * ```\n *\n * ## Impact on loading templates\n *\n * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as\n * `templateUrl`'s specified by {@link guide/directive directives}.\n *\n * By default, Angular only loads templates from the same domain and protocol as the application\n * document.  This is done by calling {@link ng.$sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on the template URL.  To load templates from other domains and/or\n * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist\n * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.\n *\n * *Please note*:\n * The browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy apply in addition to this and may further restrict whether the template is successfully\n * loaded.  This means that without the right CORS policy, loading templates from a different domain\n * won't work on all browsers.  Also, loading templates from `file://` URL does not work on some\n * browsers.\n *\n * ## This feels like too much overhead\n *\n * It's important to remember that SCE only applies to interpolation expressions.\n *\n * If your expressions are constant literals, they're automatically trusted and you don't need to\n * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.\n * `<div ng-bind-html=\"'<b>implicitly trusted</b>'\"></div>`) just works.\n *\n * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them\n * through {@link ng.$sce#getTrusted $sce.getTrusted}.  SCE doesn't play a role here.\n *\n * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load\n * templates in `ng-include` from your application's domain without having to even know about SCE.\n * It blocks loading templates from other domains or loading templates over http from an https\n * served document.  You can change these by setting your own custom {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.\n *\n * This significantly reduces the overhead.  It is far easier to pay the small overhead and have an\n * application that's secure and can be audited to verify that with much more ease than bolting\n * security onto an application later.\n *\n * <a name=\"contexts\"></a>\n * ## What trusted context types are supported?\n *\n * | Context             | Notes          |\n * |---------------------|----------------|\n * | `$sce.HTML`         | For HTML that's safe to source into the application.  The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |\n * | `$sce.CSS`          | For CSS that's safe to source into the application.  Currently unused.  Feel free to use it in your own directives. |\n * | `$sce.URL`          | For URLs that are safe to follow as links.  Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |\n * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application.  Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.)  <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |\n * | `$sce.JS`           | For JavaScript that is safe to execute in your application's context.  Currently unused.  Feel free to use it in your own directives. |\n *\n * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name=\"resourceUrlPatternItem\"></a>\n *\n *  Each element in these arrays must be one of the following:\n *\n *  - **'self'**\n *    - The special **string**, `'self'`, can be used to match against all URLs of the **same\n *      domain** as the application document using the **same protocol**.\n *  - **String** (except the special value `'self'`)\n *    - The string is matched against the full *normalized / absolute URL* of the resource\n *      being tested (substring matches are not good enough.)\n *    - There are exactly **two wildcard sequences** - `*` and `**`.  All other characters\n *      match themselves.\n *    - `*`: matches zero or more occurrences of any character other than one of the following 6\n *      characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'.  It's a useful wildcard for use\n *      in a whitelist.\n *    - `**`: matches zero or more occurrences of *any* character.  As such, it's not\n *      not appropriate to use in for a scheme, domain, etc. as it would match too much.  (e.g.\n *      http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might\n *      not have been the intention.)  Its usage at the very end of the path is ok.  (e.g.\n *      http://foo.example.com/templates/**).\n *  - **RegExp** (*see caveat below*)\n *    - *Caveat*:  While regular expressions are powerful and offer great flexibility,  their syntax\n *      (and all the inevitable escaping) makes them *harder to maintain*.  It's easy to\n *      accidentally introduce a bug when one updates a complex expression (imho, all regexes should\n *      have good test coverage.).  For instance, the use of `.` in the regex is correct only in a\n *      small number of cases.  A `.` character in the regex used when matching the scheme or a\n *      subdomain could be matched against a `:` or literal `.` that was likely not intended.   It\n *      is highly recommended to use the string patterns and only fall back to regular expressions\n *      if they as a last resort.\n *    - The regular expression must be an instance of RegExp (i.e. not a string.)  It is\n *      matched against the **entire** *normalized / absolute URL* of the resource being tested\n *      (even when the RegExp did not have the `^` and `$` codes.)  In addition, any flags\n *      present on the RegExp (such as multiline, global, ignoreCase) are ignored.\n *    - If you are generating your JavaScript from some other templating engine (not\n *      recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),\n *      remember to escape your regular expression (and be aware that you might need more than\n *      one level of escaping depending on your templating engine and the way you interpolated\n *      the value.)  Do make use of your platform's escaping mechanism as it might be good\n *      enough before coding your own.  e.g. Ruby has\n *      [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)\n *      and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).\n *      Javascript lacks a similar built in function for escaping.  Take a look at Google\n *      Closure library's [goog.string.regExpEscape(s)](\n *      http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.\n *\n * ## Show me an example using SCE.\n *\n * <example module=\"mySceApp\" deps=\"angular-sanitize.js\">\n * <file name=\"index.html\">\n *   <div ng-controller=\"AppController as myCtrl\">\n *     <i ng-bind-html=\"myCtrl.explicitlyTrustedHtml\" id=\"explicitlyTrustedHtml\"></i><br><br>\n *     <b>User comments</b><br>\n *     By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when\n *     $sanitize is available.  If $sanitize isn't available, this results in an error instead of an\n *     exploit.\n *     <div class=\"well\">\n *       <div ng-repeat=\"userComment in myCtrl.userComments\">\n *         <b>{{userComment.name}}</b>:\n *         <span ng-bind-html=\"userComment.htmlComment\" class=\"htmlComment\"></span>\n *         <br>\n *       </div>\n *     </div>\n *   </div>\n * </file>\n *\n * <file name=\"script.js\">\n *   angular.module('mySceApp', ['ngSanitize'])\n *     .controller('AppController', ['$http', '$templateCache', '$sce',\n *       function($http, $templateCache, $sce) {\n *         var self = this;\n *         $http.get(\"test_data.json\", {cache: $templateCache}).success(function(userComments) {\n *           self.userComments = userComments;\n *         });\n *         self.explicitlyTrustedHtml = $sce.trustAsHtml(\n *             '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *             'sanitization.&quot;\">Hover over this text.</span>');\n *       }]);\n * </file>\n *\n * <file name=\"test_data.json\">\n * [\n *   { \"name\": \"Alice\",\n *     \"htmlComment\":\n *         \"<span onmouseover='this.textContent=\\\"PWN3D!\\\"'>Is <i>anyone</i> reading this?</span>\"\n *   },\n *   { \"name\": \"Bob\",\n *     \"htmlComment\": \"<i>Yes!</i>  Am I the only other one?\"\n *   }\n * ]\n * </file>\n *\n * <file name=\"protractor.js\" type=\"protractor\">\n *   describe('SCE doc demo', function() {\n *     it('should sanitize untrusted values', function() {\n *       expect(element.all(by.css('.htmlComment')).first().getInnerHtml())\n *           .toBe('<span>Is <i>anyone</i> reading this?</span>');\n *     });\n *\n *     it('should NOT sanitize explicitly trusted values', function() {\n *       expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(\n *           '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *           'sanitization.&quot;\">Hover over this text.</span>');\n *     });\n *   });\n * </file>\n * </example>\n *\n *\n *\n * ## Can I disable SCE completely?\n *\n * Yes, you can.  However, this is strongly discouraged.  SCE gives you a lot of security benefits\n * for little coding overhead.  It will be much harder to take an SCE disabled application and\n * either secure it on your own or enable SCE at a later stage.  It might make sense to disable SCE\n * for cases where you have a lot of existing code that was written before SCE was introduced and\n * you're migrating them a module at a time.\n *\n * That said, here's how you can completely disable SCE:\n *\n * ```\n * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {\n *   // Completely disable SCE.  For demonstration purposes only!\n *   // Do not use in new projects.\n *   $sceProvider.enabled(false);\n * });\n * ```\n *\n */\n/* jshint maxlen: 100 */\n\nfunction $SceProvider() {\n  var enabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $sceProvider#enabled\n   * @kind function\n   *\n   * @param {boolean=} value If provided, then enables/disables SCE.\n   * @return {boolean} true if SCE is enabled, false otherwise.\n   *\n   * @description\n   * Enables/disables SCE and returns the current value.\n   */\n  this.enabled = function(value) {\n    if (arguments.length) {\n      enabled = !!value;\n    }\n    return enabled;\n  };\n\n\n  /* Design notes on the default implementation for SCE.\n   *\n   * The API contract for the SCE delegate\n   * -------------------------------------\n   * The SCE delegate object must provide the following 3 methods:\n   *\n   * - trustAs(contextEnum, value)\n   *     This method is used to tell the SCE service that the provided value is OK to use in the\n   *     contexts specified by contextEnum.  It must return an object that will be accepted by\n   *     getTrusted() for a compatible contextEnum and return this value.\n   *\n   * - valueOf(value)\n   *     For values that were not produced by trustAs(), return them as is.  For values that were\n   *     produced by trustAs(), return the corresponding input value to trustAs.  Basically, if\n   *     trustAs is wrapping the given values into some type, this operation unwraps it when given\n   *     such a value.\n   *\n   * - getTrusted(contextEnum, value)\n   *     This function should return the a value that is safe to use in the context specified by\n   *     contextEnum or throw and exception otherwise.\n   *\n   * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be\n   * opaque or wrapped in some holder object.  That happens to be an implementation detail.  For\n   * instance, an implementation could maintain a registry of all trusted objects by context.  In\n   * such a case, trustAs() would return the same object that was passed in.  getTrusted() would\n   * return the same object passed in if it was found in the registry under a compatible context or\n   * throw an exception otherwise.  An implementation might only wrap values some of the time based\n   * on some criteria.  getTrusted() might return a value and not throw an exception for special\n   * constants or objects even if not wrapped.  All such implementations fulfill this contract.\n   *\n   *\n   * A note on the inheritance model for SCE contexts\n   * ------------------------------------------------\n   * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types.  This\n   * is purely an implementation details.\n   *\n   * The contract is simply this:\n   *\n   *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)\n   *     will also succeed.\n   *\n   * Inheritance happens to capture this in a natural way.  In some future, we\n   * may not use inheritance anymore.  That is OK because no code outside of\n   * sce.js and sceSpecs.js would need to be aware of this detail.\n   */\n\n  this.$get = ['$parse', '$sceDelegate', function(\n                $parse,   $sceDelegate) {\n    // Prereq: Ensure that we're not running in IE<11 quirks mode.  In that mode, IE < 11 allow\n    // the \"expression(javascript expression)\" syntax which is insecure.\n    if (enabled && msie < 8) {\n      throw $sceMinErr('iequirks',\n        'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +\n        'mode.  You can fix this by adding the text <!doctype html> to the top of your HTML ' +\n        'document.  See http://docs.angularjs.org/api/ng.$sce for more information.');\n    }\n\n    var sce = shallowCopy(SCE_CONTEXTS);\n\n    /**\n     * @ngdoc method\n     * @name $sce#isEnabled\n     * @kind function\n     *\n     * @return {Boolean} true if SCE is enabled, false otherwise.  If you want to set the value, you\n     * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.\n     *\n     * @description\n     * Returns a boolean indicating if SCE is enabled.\n     */\n    sce.isEnabled = function() {\n      return enabled;\n    };\n    sce.trustAs = $sceDelegate.trustAs;\n    sce.getTrusted = $sceDelegate.getTrusted;\n    sce.valueOf = $sceDelegate.valueOf;\n\n    if (!enabled) {\n      sce.trustAs = sce.getTrusted = function(type, value) { return value; };\n      sce.valueOf = identity;\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAs\n     *\n     * @description\n     * Converts Angular {@link guide/expression expression} into a function.  This is like {@link\n     * ng.$parse $parse} and is identical when the expression is a literal constant.  Otherwise, it\n     * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,\n     * *result*)}\n     *\n     * @param {string} type The kind of SCE context in which this result will be used.\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n    sce.parseAs = function sceParseAs(type, expr) {\n      var parsed = $parse(expr);\n      if (parsed.literal && parsed.constant) {\n        return parsed;\n      } else {\n        return $parse(expr, function(value) {\n          return sce.getTrusted(type, value);\n        });\n      }\n    };\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAs\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.  As such,\n     * returns an object that is trusted by angular for use in specified strict contextual\n     * escaping contexts (such as ng-bind-html, ng-include, any src attribute\n     * interpolation, any dom event binding attribute interpolation such as for onclick,  etc.)\n     * that uses the provided value.  See * {@link ng.$sce $sce} for enabling strict contextual\n     * escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resource_url, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsHtml(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml\n     *     $sce.getTrustedHtml(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl\n     *     $sce.getTrustedUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl\n     *     $sce.getTrustedResourceUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the return\n     *     value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsJs(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs\n     *     $sce.getTrustedJs(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrusted\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}.  As such,\n     * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the\n     * originally supplied value if the queried context type is a supertype of the created type.\n     * If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}\n     *                         call.\n     * @returns {*} The value the was originally provided to\n     *              {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.\n     *              Otherwise, throws an exception.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedHtml(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedCss\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedCss(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sceDelegate.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedJs\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedJs(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsHtml(expression string)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsCss\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsCss(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsResourceUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsJs(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    // Shorthand delegations.\n    var parse = sce.parseAs,\n        getTrusted = sce.getTrusted,\n        trustAs = sce.trustAs;\n\n    forEach(SCE_CONTEXTS, function(enumValue, name) {\n      var lName = lowercase(name);\n      sce[camelCase(\"parse_as_\" + lName)] = function(expr) {\n        return parse(enumValue, expr);\n      };\n      sce[camelCase(\"get_trusted_\" + lName)] = function(value) {\n        return getTrusted(enumValue, value);\n      };\n      sce[camelCase(\"trust_as_\" + lName)] = function(value) {\n        return trustAs(enumValue, value);\n      };\n    });\n\n    return sce;\n  }];\n}\n\n/**\n * !!! This is an undocumented \"private\" service !!!\n *\n * @name $sniffer\n * @requires $window\n * @requires $document\n *\n * @property {boolean} history Does the browser support html5 history api ?\n * @property {boolean} transitions Does the browser support CSS transition events ?\n * @property {boolean} animations Does the browser support CSS animation events ?\n *\n * @description\n * This is very simple implementation of testing browser's features.\n */\nfunction $SnifferProvider() {\n  this.$get = ['$window', '$document', function($window, $document) {\n    var eventSupport = {},\n        android =\n          int((/android (\\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),\n        boxee = /Boxee/i.test(($window.navigator || {}).userAgent),\n        document = $document[0] || {},\n        vendorPrefix,\n        vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,\n        bodyStyle = document.body && document.body.style,\n        transitions = false,\n        animations = false,\n        match;\n\n    if (bodyStyle) {\n      for (var prop in bodyStyle) {\n        if (match = vendorRegex.exec(prop)) {\n          vendorPrefix = match[0];\n          vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);\n          break;\n        }\n      }\n\n      if (!vendorPrefix) {\n        vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';\n      }\n\n      transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));\n      animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));\n\n      if (android && (!transitions ||  !animations)) {\n        transitions = isString(document.body.style.webkitTransition);\n        animations = isString(document.body.style.webkitAnimation);\n      }\n    }\n\n\n    return {\n      // Android has history.pushState, but it does not update location correctly\n      // so let's not use the history API at all.\n      // http://code.google.com/p/android/issues/detail?id=17471\n      // https://github.com/angular/angular.js/issues/904\n\n      // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has\n      // so let's not use the history API also\n      // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined\n      // jshint -W018\n      history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),\n      // jshint +W018\n      hasEvent: function(event) {\n        // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have\n        // it. In particular the event is not fired when backspace or delete key are pressed or\n        // when cut operation is performed.\n        // IE10+ implements 'input' event but it erroneously fires under various situations,\n        // e.g. when placeholder changes, or a form is focused.\n        if (event === 'input' && msie <= 11) return false;\n\n        if (isUndefined(eventSupport[event])) {\n          var divElm = document.createElement('div');\n          eventSupport[event] = 'on' + event in divElm;\n        }\n\n        return eventSupport[event];\n      },\n      csp: csp(),\n      vendorPrefix: vendorPrefix,\n      transitions: transitions,\n      animations: animations,\n      android: android\n    };\n  }];\n}\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc service\n * @name $templateRequest\n *\n * @description\n * The `$templateRequest` service downloads the provided template using `$http` and, upon success,\n * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data\n * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted\n * by setting the 2nd parameter of the function to true).\n *\n * @param {string} tpl The HTTP request template URL\n * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty\n *\n * @return {Promise} the HTTP Promise for the given.\n *\n * @property {number} totalPendingRequests total amount of pending template requests being downloaded.\n */\nfunction $TemplateRequestProvider() {\n  this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {\n    function handleRequestFn(tpl, ignoreRequestError) {\n      handleRequestFn.totalPendingRequests++;\n\n      var transformResponse = $http.defaults && $http.defaults.transformResponse;\n\n      if (isArray(transformResponse)) {\n        transformResponse = transformResponse.filter(function(transformer) {\n          return transformer !== defaultHttpResponseTransform;\n        });\n      } else if (transformResponse === defaultHttpResponseTransform) {\n        transformResponse = null;\n      }\n\n      var httpOptions = {\n        cache: $templateCache,\n        transformResponse: transformResponse\n      };\n\n      return $http.get(tpl, httpOptions)\n        ['finally'](function() {\n          handleRequestFn.totalPendingRequests--;\n        })\n        .then(function(response) {\n          return response.data;\n        }, handleError);\n\n      function handleError(resp) {\n        if (!ignoreRequestError) {\n          throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);\n        }\n        return $q.reject(resp);\n      }\n    }\n\n    handleRequestFn.totalPendingRequests = 0;\n\n    return handleRequestFn;\n  }];\n}\n\nfunction $$TestabilityProvider() {\n  this.$get = ['$rootScope', '$browser', '$location',\n       function($rootScope,   $browser,   $location) {\n\n    /**\n     * @name $testability\n     *\n     * @description\n     * The private $$testability service provides a collection of methods for use when debugging\n     * or by automated test and debugging tools.\n     */\n    var testability = {};\n\n    /**\n     * @name $$testability#findBindings\n     *\n     * @description\n     * Returns an array of elements that are bound (via ng-bind or {{}})\n     * to expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The binding expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression. Filters and whitespace are ignored.\n     */\n    testability.findBindings = function(element, expression, opt_exactMatch) {\n      var bindings = element.getElementsByClassName('ng-binding');\n      var matches = [];\n      forEach(bindings, function(binding) {\n        var dataBinding = angular.element(binding).data('$binding');\n        if (dataBinding) {\n          forEach(dataBinding, function(bindingName) {\n            if (opt_exactMatch) {\n              var matcher = new RegExp('(^|\\\\s)' + escapeForRegexp(expression) + '(\\\\s|\\\\||$)');\n              if (matcher.test(bindingName)) {\n                matches.push(binding);\n              }\n            } else {\n              if (bindingName.indexOf(expression) != -1) {\n                matches.push(binding);\n              }\n            }\n          });\n        }\n      });\n      return matches;\n    };\n\n    /**\n     * @name $$testability#findModels\n     *\n     * @description\n     * Returns an array of elements that are two-way found via ng-model to\n     * expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The model expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression.\n     */\n    testability.findModels = function(element, expression, opt_exactMatch) {\n      var prefixes = ['ng-', 'data-ng-', 'ng\\\\:'];\n      for (var p = 0; p < prefixes.length; ++p) {\n        var attributeEquals = opt_exactMatch ? '=' : '*=';\n        var selector = '[' + prefixes[p] + 'model' + attributeEquals + '\"' + expression + '\"]';\n        var elements = element.querySelectorAll(selector);\n        if (elements.length) {\n          return elements;\n        }\n      }\n    };\n\n    /**\n     * @name $$testability#getLocation\n     *\n     * @description\n     * Shortcut for getting the location in a browser agnostic way. Returns\n     *     the path, search, and hash. (e.g. /path?a=b#hash)\n     */\n    testability.getLocation = function() {\n      return $location.url();\n    };\n\n    /**\n     * @name $$testability#setLocation\n     *\n     * @description\n     * Shortcut for navigating to a location without doing a full page reload.\n     *\n     * @param {string} url The location url (path, search and hash,\n     *     e.g. /path?a=b#hash) to go to.\n     */\n    testability.setLocation = function(url) {\n      if (url !== $location.url()) {\n        $location.url(url);\n        $rootScope.$digest();\n      }\n    };\n\n    /**\n     * @name $$testability#whenStable\n     *\n     * @description\n     * Calls the callback when $timeout and $http requests are completed.\n     *\n     * @param {function} callback\n     */\n    testability.whenStable = function(callback) {\n      $browser.notifyWhenNoOutstandingRequests(callback);\n    };\n\n    return testability;\n  }];\n}\n\nfunction $TimeoutProvider() {\n  this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',\n       function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {\n    var deferreds = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $timeout\n      *\n      * @description\n      * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch\n      * block and delegates any exceptions to\n      * {@link ng.$exceptionHandler $exceptionHandler} service.\n      *\n      * The return value of registering a timeout function is a promise, which will be resolved when\n      * the timeout is reached and the timeout function is executed.\n      *\n      * To cancel a timeout request, call `$timeout.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to\n      * synchronously flush the queue of deferred functions.\n      *\n      * @param {function()} fn A function, whose execution should be delayed.\n      * @param {number=} [delay=0] Delay in milliseconds.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this\n      *   promise will be resolved with is the return value of the `fn` function.\n      *\n      */\n    function timeout(fn, delay, invokeApply) {\n      var skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise,\n          timeoutId;\n\n      timeoutId = $browser.defer(function() {\n        try {\n          deferred.resolve(fn());\n        } catch (e) {\n          deferred.reject(e);\n          $exceptionHandler(e);\n        }\n        finally {\n          delete deferreds[promise.$$timeoutId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n      }, delay);\n\n      promise.$$timeoutId = timeoutId;\n      deferreds[timeoutId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $timeout#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`. As a result of this, the promise will be\n      * resolved with a rejection.\n      *\n      * @param {Promise=} promise Promise returned by the `$timeout` function.\n      * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n      *   canceled.\n      */\n    timeout.cancel = function(promise) {\n      if (promise && promise.$$timeoutId in deferreds) {\n        deferreds[promise.$$timeoutId].reject('canceled');\n        delete deferreds[promise.$$timeoutId];\n        return $browser.defer.cancel(promise.$$timeoutId);\n      }\n      return false;\n    };\n\n    return timeout;\n  }];\n}\n\n// NOTE:  The usage of window and document instead of $window and $document here is\n// deliberate.  This service depends on the specific behavior of anchor nodes created by the\n// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and\n// cause us to break tests.  In addition, when the browser resolves a URL for XHR, it\n// doesn't know about mocked locations and resolves URLs to the real document - which is\n// exactly the behavior needed here.  There is little value is mocking these out for this\n// service.\nvar urlParsingNode = document.createElement(\"a\");\nvar originUrl = urlResolve(window.location.href);\n\n\n/**\n *\n * Implementation Notes for non-IE browsers\n * ----------------------------------------\n * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,\n * results both in the normalizing and parsing of the URL.  Normalizing means that a relative\n * URL will be resolved into an absolute URL in the context of the application document.\n * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related\n * properties are all populated to reflect the normalized URL.  This approach has wide\n * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc.  See\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *\n * Implementation Notes for IE\n * ---------------------------\n * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other\n * browsers.  However, the parsed components will not be set if the URL assigned did not specify\n * them.  (e.g. if you assign a.href = \"foo\", then a.protocol, a.host, etc. will be empty.)  We\n * work around that by performing the parsing in a 2nd step by taking a previously normalized\n * URL (e.g. by assigning to a.href) and assigning it a.href again.  This correctly populates the\n * properties such as protocol, hostname, port, etc.\n *\n * IE7 does not normalize the URL when assigned to an anchor node.  (Apparently, it does, if one\n * uses the inner HTML approach to assign the URL as part of an HTML snippet -\n * http://stackoverflow.com/a/472729)  However, setting img[src] does normalize the URL.\n * Unfortunately, setting img[src] to something like \"javascript:foo\" on IE throws an exception.\n * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that\n * method and IE < 8 is unsupported.\n *\n * References:\n *   http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement\n *   http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *   http://url.spec.whatwg.org/#urlutils\n *   https://github.com/angular/angular.js/pull/2902\n *   http://james.padolsey.com/javascript/parsing-urls-with-the-dom/\n *\n * @kind function\n * @param {string} url The URL to be parsed.\n * @description Normalizes and parses a URL.\n * @returns {object} Returns the normalized URL as a dictionary.\n *\n *   | member name   | Description    |\n *   |---------------|----------------|\n *   | href          | A normalized version of the provided URL if it was not an absolute URL |\n *   | protocol      | The protocol including the trailing colon                              |\n *   | host          | The host and port (if the port is non-default) of the normalizedUrl    |\n *   | search        | The search params, minus the question mark                             |\n *   | hash          | The hash string, minus the hash symbol\n *   | hostname      | The hostname\n *   | port          | The port, without \":\"\n *   | pathname      | The pathname, beginning with \"/\"\n *\n */\nfunction urlResolve(url) {\n  var href = url;\n\n  if (msie) {\n    // Normalize before parse.  Refer Implementation Notes on why this is\n    // done in two steps on IE.\n    urlParsingNode.setAttribute(\"href\", href);\n    href = urlParsingNode.href;\n  }\n\n  urlParsingNode.setAttribute('href', href);\n\n  // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n  return {\n    href: urlParsingNode.href,\n    protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n    host: urlParsingNode.host,\n    search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n    hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n    hostname: urlParsingNode.hostname,\n    port: urlParsingNode.port,\n    pathname: (urlParsingNode.pathname.charAt(0) === '/')\n      ? urlParsingNode.pathname\n      : '/' + urlParsingNode.pathname\n  };\n}\n\n/**\n * Parse a request URL and determine whether this is a same-origin request as the application document.\n *\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\n * or a parsed URL object.\n * @returns {boolean} Whether the request is for the same origin as the application document.\n */\nfunction urlIsSameOrigin(requestUrl) {\n  var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;\n  return (parsed.protocol === originUrl.protocol &&\n          parsed.host === originUrl.host);\n}\n\n/**\n * @ngdoc service\n * @name $window\n *\n * @description\n * A reference to the browser's `window` object. While `window`\n * is globally available in JavaScript, it causes testability problems, because\n * it is a global variable. In angular we always refer to it through the\n * `$window` service, so it may be overridden, removed or mocked for testing.\n *\n * Expressions, like the one defined for the `ngClick` directive in the example\n * below, are evaluated with respect to the current scope.  Therefore, there is\n * no risk of inadvertently coding in a dependency on a global value in such an\n * expression.\n *\n * @example\n   <example module=\"windowExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('windowExample', [])\n           .controller('ExampleController', ['$scope', '$window', function($scope, $window) {\n             $scope.greeting = 'Hello, World!';\n             $scope.doGreeting = function(greeting) {\n               $window.alert(greeting);\n             };\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"text\" ng-model=\"greeting\" />\n         <button ng-click=\"doGreeting(greeting)\">ALERT</button>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n      it('should display the greeting in the input box', function() {\n       element(by.model('greeting')).sendKeys('Hello, E2E Tests');\n       // If we click the button it will block the test runner\n       // element(':button').click();\n      });\n     </file>\n   </example>\n */\nfunction $WindowProvider() {\n  this.$get = valueFn(window);\n}\n\n/* global currencyFilter: true,\n dateFilter: true,\n filterFilter: true,\n jsonFilter: true,\n limitToFilter: true,\n lowercaseFilter: true,\n numberFilter: true,\n orderByFilter: true,\n uppercaseFilter: true,\n */\n\n/**\n * @ngdoc provider\n * @name $filterProvider\n * @description\n *\n * Filters are just functions which transform input to an output. However filters need to be\n * Dependency Injected. To achieve this a filter definition consists of a factory function which is\n * annotated with dependencies and is responsible for creating a filter function.\n *\n * ```js\n *   // Filter registration\n *   function MyModule($provide, $filterProvider) {\n *     // create a service to demonstrate injection (not always needed)\n *     $provide.value('greet', function(name){\n *       return 'Hello ' + name + '!';\n *     });\n *\n *     // register a filter factory which uses the\n *     // greet service to demonstrate DI.\n *     $filterProvider.register('greet', function(greet){\n *       // return the filter function which uses the greet service\n *       // to generate salutation\n *       return function(text) {\n *         // filters need to be forgiving so check input validity\n *         return text && greet(text) || text;\n *       };\n *     });\n *   }\n * ```\n *\n * The filter function is registered with the `$injector` under the filter name suffix with\n * `Filter`.\n *\n * ```js\n *   it('should be the same instance', inject(\n *     function($filterProvider) {\n *       $filterProvider.register('reverse', function(){\n *         return ...;\n *       });\n *     },\n *     function($filter, reverseFilter) {\n *       expect($filter('reverse')).toBe(reverseFilter);\n *     });\n * ```\n *\n *\n * For more information about how angular filters work, and how to create your own filters, see\n * {@link guide/filter Filters} in the Angular Developer Guide.\n */\n\n/**\n * @ngdoc service\n * @name $filter\n * @kind function\n * @description\n * Filters are used for formatting data displayed to the user.\n *\n * The general syntax in templates is as follows:\n *\n *         {{ expression [| filter_name[:parameter_value] ... ] }}\n *\n * @param {String} name Name of the filter function to retrieve\n * @return {Function} the filter function\n * @example\n   <example name=\"$filter\" module=\"filterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"MainCtrl\">\n        <h3>{{ originalText }}</h3>\n        <h3>{{ filteredText }}</h3>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n      angular.module('filterExample', [])\n      .controller('MainCtrl', function($scope, $filter) {\n        $scope.originalText = 'hello';\n        $scope.filteredText = $filter('uppercase')($scope.originalText);\n      });\n     </file>\n   </example>\n  */\n$FilterProvider.$inject = ['$provide'];\nfunction $FilterProvider($provide) {\n  var suffix = 'Filter';\n\n  /**\n   * @ngdoc method\n   * @name $filterProvider#register\n   * @param {string|Object} name Name of the filter function, or an object map of filters where\n   *    the keys are the filter names and the values are the filter factories.\n   * @returns {Object} Registered filter instance, or if a map of filters was provided then a map\n   *    of the registered filter instances.\n   */\n  function register(name, factory) {\n    if (isObject(name)) {\n      var filters = {};\n      forEach(name, function(filter, key) {\n        filters[key] = register(key, filter);\n      });\n      return filters;\n    } else {\n      return $provide.factory(name + suffix, factory);\n    }\n  }\n  this.register = register;\n\n  this.$get = ['$injector', function($injector) {\n    return function(name) {\n      return $injector.get(name + suffix);\n    };\n  }];\n\n  ////////////////////////////////////////\n\n  /* global\n    currencyFilter: false,\n    dateFilter: false,\n    filterFilter: false,\n    jsonFilter: false,\n    limitToFilter: false,\n    lowercaseFilter: false,\n    numberFilter: false,\n    orderByFilter: false,\n    uppercaseFilter: false,\n  */\n\n  register('currency', currencyFilter);\n  register('date', dateFilter);\n  register('filter', filterFilter);\n  register('json', jsonFilter);\n  register('limitTo', limitToFilter);\n  register('lowercase', lowercaseFilter);\n  register('number', numberFilter);\n  register('orderBy', orderByFilter);\n  register('uppercase', uppercaseFilter);\n}\n\n/**\n * @ngdoc filter\n * @name filter\n * @kind function\n *\n * @description\n * Selects a subset of items from `array` and returns it as a new array.\n *\n * @param {Array} array The source array.\n * @param {string|Object|function()} expression The predicate to be used for selecting items from\n *   `array`.\n *\n *   Can be one of:\n *\n *   - `string`: The string is used for matching against the contents of the `array`. All strings or\n *     objects with string properties in `array` that match this string will be returned. This also\n *     applies to nested object properties.\n *     The predicate can be negated by prefixing the string with `!`.\n *\n *   - `Object`: A pattern object can be used to filter specific properties on objects contained\n *     by `array`. For example `{name:\"M\", phone:\"1\"}` predicate will return an array of items\n *     which have property `name` containing \"M\" and property `phone` containing \"1\". A special\n *     property name `$` can be used (as in `{$:\"text\"}`) to accept a match against any\n *     property of the object or its nested object properties. That's equivalent to the simple\n *     substring match with a `string` as described above. The predicate can be negated by prefixing\n *     the string with `!`.\n *     For example `{name: \"!M\"}` predicate will return an array of items which have property `name`\n *     not containing \"M\".\n *\n *     Note that a named property will match properties on the same level only, while the special\n *     `$` property will match properties on the same level or deeper. E.g. an array item like\n *     `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but\n *     **will** be matched by `{$: 'John'}`.\n *\n *   - `function(value, index)`: A predicate function can be used to write arbitrary filters. The\n *     function is called for each element of `array`. The final result is an array of those\n *     elements that the predicate returned true for.\n *\n * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in\n *     determining if the expected value (from the filter expression) and actual value (from\n *     the object in the array) should be considered a match.\n *\n *   Can be one of:\n *\n *   - `function(actual, expected)`:\n *     The function will be given the object value and the predicate value to compare and\n *     should return true if both values should be considered equal.\n *\n *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.\n *     This is essentially strict comparison of expected and actual.\n *\n *   - `false|undefined`: A short hand for a function which will look for a substring match in case\n *     insensitive way.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <div ng-init=\"friends = [{name:'John', phone:'555-1276'},\n                                {name:'Mary', phone:'800-BIG-MARY'},\n                                {name:'Mike', phone:'555-4321'},\n                                {name:'Adam', phone:'555-5678'},\n                                {name:'Julie', phone:'555-8765'},\n                                {name:'Juliette', phone:'555-5678'}]\"></div>\n\n       Search: <input ng-model=\"searchText\">\n       <table id=\"searchTextResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friend in friends | filter:searchText\">\n           <td>{{friend.name}}</td>\n           <td>{{friend.phone}}</td>\n         </tr>\n       </table>\n       <hr>\n       Any: <input ng-model=\"search.$\"> <br>\n       Name only <input ng-model=\"search.name\"><br>\n       Phone only <input ng-model=\"search.phone\"><br>\n       Equality <input type=\"checkbox\" ng-model=\"strict\"><br>\n       <table id=\"searchObjResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friendObj in friends | filter:search:strict\">\n           <td>{{friendObj.name}}</td>\n           <td>{{friendObj.phone}}</td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var expectFriendNames = function(expectedNames, key) {\n         element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {\n           arr.forEach(function(wd, i) {\n             expect(wd.getText()).toMatch(expectedNames[i]);\n           });\n         });\n       };\n\n       it('should search across all fields when filtering with a string', function() {\n         var searchText = element(by.model('searchText'));\n         searchText.clear();\n         searchText.sendKeys('m');\n         expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');\n\n         searchText.clear();\n         searchText.sendKeys('76');\n         expectFriendNames(['John', 'Julie'], 'friend');\n       });\n\n       it('should search in specific fields when filtering with a predicate object', function() {\n         var searchAny = element(by.model('search.$'));\n         searchAny.clear();\n         searchAny.sendKeys('i');\n         expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');\n       });\n       it('should use a equal comparison when comparator is true', function() {\n         var searchName = element(by.model('search.name'));\n         var strict = element(by.model('strict'));\n         searchName.clear();\n         searchName.sendKeys('Julie');\n         strict.click();\n         expectFriendNames(['Julie'], 'friendObj');\n       });\n     </file>\n   </example>\n */\nfunction filterFilter() {\n  return function(array, expression, comparator) {\n    if (!isArray(array)) return array;\n\n    var predicateFn;\n    var matchAgainstAnyProp;\n\n    switch (typeof expression) {\n      case 'function':\n        predicateFn = expression;\n        break;\n      case 'boolean':\n      case 'number':\n      case 'string':\n        matchAgainstAnyProp = true;\n        //jshint -W086\n      case 'object':\n        //jshint +W086\n        predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);\n        break;\n      default:\n        return array;\n    }\n\n    return array.filter(predicateFn);\n  };\n}\n\n// Helper functions for `filterFilter`\nfunction createPredicateFn(expression, comparator, matchAgainstAnyProp) {\n  var shouldMatchPrimitives = isObject(expression) && ('$' in expression);\n  var predicateFn;\n\n  if (comparator === true) {\n    comparator = equals;\n  } else if (!isFunction(comparator)) {\n    comparator = function(actual, expected) {\n      if (isObject(actual) || isObject(expected)) {\n        // Prevent an object to be considered equal to a string like `'[object'`\n        return false;\n      }\n\n      actual = lowercase('' + actual);\n      expected = lowercase('' + expected);\n      return actual.indexOf(expected) !== -1;\n    };\n  }\n\n  predicateFn = function(item) {\n    if (shouldMatchPrimitives && !isObject(item)) {\n      return deepCompare(item, expression.$, comparator, false);\n    }\n    return deepCompare(item, expression, comparator, matchAgainstAnyProp);\n  };\n\n  return predicateFn;\n}\n\nfunction deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {\n  var actualType = typeof actual;\n  var expectedType = typeof expected;\n\n  if ((expectedType === 'string') && (expected.charAt(0) === '!')) {\n    return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);\n  } else if (isArray(actual)) {\n    // In case `actual` is an array, consider it a match\n    // if ANY of it's items matches `expected`\n    return actual.some(function(item) {\n      return deepCompare(item, expected, comparator, matchAgainstAnyProp);\n    });\n  }\n\n  switch (actualType) {\n    case 'object':\n      var key;\n      if (matchAgainstAnyProp) {\n        for (key in actual) {\n          if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {\n            return true;\n          }\n        }\n        return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);\n      } else if (expectedType === 'object') {\n        for (key in expected) {\n          var expectedVal = expected[key];\n          if (isFunction(expectedVal)) {\n            continue;\n          }\n\n          var matchAnyProperty = key === '$';\n          var actualVal = matchAnyProperty ? actual : actual[key];\n          if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {\n            return false;\n          }\n        }\n        return true;\n      } else {\n        return comparator(actual, expected);\n      }\n      break;\n    case 'function':\n      return false;\n    default:\n      return comparator(actual, expected);\n  }\n}\n\n/**\n * @ngdoc filter\n * @name currency\n * @kind function\n *\n * @description\n * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default\n * symbol for current locale is used.\n *\n * @param {number} amount Input to filter.\n * @param {string=} symbol Currency symbol or identifier to be displayed.\n * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\n * @returns {string} Formatted number.\n *\n *\n * @example\n   <example module=\"currencyExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('currencyExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.amount = 1234.56;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"number\" ng-model=\"amount\"> <br>\n         default currency symbol ($): <span id=\"currency-default\">{{amount | currency}}</span><br>\n         custom currency identifier (USD$): <span id=\"currency-custom\">{{amount | currency:\"USD$\"}}</span>\n         no fractions (0): <span id=\"currency-no-fractions\">{{amount | currency:\"USD$\":0}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should init with 1234.56', function() {\n         expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');\n         expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');\n       });\n       it('should update', function() {\n         if (browser.params.browser == 'safari') {\n           // Safari does not understand the minus key. See\n           // https://github.com/angular/protractor/issues/481\n           return;\n         }\n         element(by.model('amount')).clear();\n         element(by.model('amount')).sendKeys('-1234');\n         expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');\n         expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');\n       });\n     </file>\n   </example>\n */\ncurrencyFilter.$inject = ['$locale'];\nfunction currencyFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(amount, currencySymbol, fractionSize) {\n    if (isUndefined(currencySymbol)) {\n      currencySymbol = formats.CURRENCY_SYM;\n    }\n\n    if (isUndefined(fractionSize)) {\n      fractionSize = formats.PATTERNS[1].maxFrac;\n    }\n\n    // if null or undefined pass it through\n    return (amount == null)\n        ? amount\n        : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).\n            replace(/\\u00A4/g, currencySymbol);\n  };\n}\n\n/**\n * @ngdoc filter\n * @name number\n * @kind function\n *\n * @description\n * Formats a number as text.\n *\n * If the input is not a number an empty string is returned.\n *\n * @param {number|string} number Number to format.\n * @param {(number|string)=} fractionSize Number of decimal places to round the number to.\n * If this is not provided then the fraction size is computed from the current locale's number\n * formatting pattern. In the case of the default locale, it will be 3.\n * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.\n *\n * @example\n   <example module=\"numberFilterExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('numberFilterExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.val = 1234.56789;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         Enter number: <input ng-model='val'><br>\n         Default formatting: <span id='number-default'>{{val | number}}</span><br>\n         No fractions: <span>{{val | number:0}}</span><br>\n         Negative number: <span>{{-val | number:4}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format numbers', function() {\n         expect(element(by.id('number-default')).getText()).toBe('1,234.568');\n         expect(element(by.binding('val | number:0')).getText()).toBe('1,235');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');\n       });\n\n       it('should update', function() {\n         element(by.model('val')).clear();\n         element(by.model('val')).sendKeys('3374.333');\n         expect(element(by.id('number-default')).getText()).toBe('3,374.333');\n         expect(element(by.binding('val | number:0')).getText()).toBe('3,374');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');\n      });\n     </file>\n   </example>\n */\n\n\nnumberFilter.$inject = ['$locale'];\nfunction numberFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(number, fractionSize) {\n\n    // if null or undefined pass it through\n    return (number == null)\n        ? number\n        : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,\n                       fractionSize);\n  };\n}\n\nvar DECIMAL_SEP = '.';\nfunction formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {\n  if (!isFinite(number) || isObject(number)) return '';\n\n  var isNegative = number < 0;\n  number = Math.abs(number);\n  var numStr = number + '',\n      formatedText = '',\n      parts = [];\n\n  var hasExponent = false;\n  if (numStr.indexOf('e') !== -1) {\n    var match = numStr.match(/([\\d\\.]+)e(-?)(\\d+)/);\n    if (match && match[2] == '-' && match[3] > fractionSize + 1) {\n      number = 0;\n    } else {\n      formatedText = numStr;\n      hasExponent = true;\n    }\n  }\n\n  if (!hasExponent) {\n    var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;\n\n    // determine fractionSize if it is not specified\n    if (isUndefined(fractionSize)) {\n      fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);\n    }\n\n    // safely round numbers in JS without hitting imprecisions of floating-point arithmetics\n    // inspired by:\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\n    number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);\n\n    var fraction = ('' + number).split(DECIMAL_SEP);\n    var whole = fraction[0];\n    fraction = fraction[1] || '';\n\n    var i, pos = 0,\n        lgroup = pattern.lgSize,\n        group = pattern.gSize;\n\n    if (whole.length >= (lgroup + group)) {\n      pos = whole.length - lgroup;\n      for (i = 0; i < pos; i++) {\n        if ((pos - i) % group === 0 && i !== 0) {\n          formatedText += groupSep;\n        }\n        formatedText += whole.charAt(i);\n      }\n    }\n\n    for (i = pos; i < whole.length; i++) {\n      if ((whole.length - i) % lgroup === 0 && i !== 0) {\n        formatedText += groupSep;\n      }\n      formatedText += whole.charAt(i);\n    }\n\n    // format fraction part.\n    while (fraction.length < fractionSize) {\n      fraction += '0';\n    }\n\n    if (fractionSize && fractionSize !== \"0\") formatedText += decimalSep + fraction.substr(0, fractionSize);\n  } else {\n    if (fractionSize > 0 && number < 1) {\n      formatedText = number.toFixed(fractionSize);\n      number = parseFloat(formatedText);\n    }\n  }\n\n  if (number === 0) {\n    isNegative = false;\n  }\n\n  parts.push(isNegative ? pattern.negPre : pattern.posPre,\n             formatedText,\n             isNegative ? pattern.negSuf : pattern.posSuf);\n  return parts.join('');\n}\n\nfunction padNumber(num, digits, trim) {\n  var neg = '';\n  if (num < 0) {\n    neg =  '-';\n    num = -num;\n  }\n  num = '' + num;\n  while (num.length < digits) num = '0' + num;\n  if (trim)\n    num = num.substr(num.length - digits);\n  return neg + num;\n}\n\n\nfunction dateGetter(name, size, offset, trim) {\n  offset = offset || 0;\n  return function(date) {\n    var value = date['get' + name]();\n    if (offset > 0 || value > -offset)\n      value += offset;\n    if (value === 0 && offset == -12) value = 12;\n    return padNumber(value, size, trim);\n  };\n}\n\nfunction dateStrGetter(name, shortForm) {\n  return function(date, formats) {\n    var value = date['get' + name]();\n    var get = uppercase(shortForm ? ('SHORT' + name) : name);\n\n    return formats[get][value];\n  };\n}\n\nfunction timeZoneGetter(date) {\n  var zone = -1 * date.getTimezoneOffset();\n  var paddedZone = (zone >= 0) ? \"+\" : \"\";\n\n  paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +\n                padNumber(Math.abs(zone % 60), 2);\n\n  return paddedZone;\n}\n\nfunction getFirstThursdayOfYear(year) {\n    // 0 = index of January\n    var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();\n    // 4 = index of Thursday (+1 to account for 1st = 5)\n    // 11 = index of *next* Thursday (+1 account for 1st = 12)\n    return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);\n}\n\nfunction getThursdayThisWeek(datetime) {\n    return new Date(datetime.getFullYear(), datetime.getMonth(),\n      // 4 = index of Thursday\n      datetime.getDate() + (4 - datetime.getDay()));\n}\n\nfunction weekGetter(size) {\n   return function(date) {\n      var firstThurs = getFirstThursdayOfYear(date.getFullYear()),\n         thisThurs = getThursdayThisWeek(date);\n\n      var diff = +thisThurs - +firstThurs,\n         result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week\n\n      return padNumber(result, size);\n   };\n}\n\nfunction ampmGetter(date, formats) {\n  return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];\n}\n\nvar DATE_FORMATS = {\n  yyyy: dateGetter('FullYear', 4),\n    yy: dateGetter('FullYear', 2, 0, true),\n     y: dateGetter('FullYear', 1),\n  MMMM: dateStrGetter('Month'),\n   MMM: dateStrGetter('Month', true),\n    MM: dateGetter('Month', 2, 1),\n     M: dateGetter('Month', 1, 1),\n    dd: dateGetter('Date', 2),\n     d: dateGetter('Date', 1),\n    HH: dateGetter('Hours', 2),\n     H: dateGetter('Hours', 1),\n    hh: dateGetter('Hours', 2, -12),\n     h: dateGetter('Hours', 1, -12),\n    mm: dateGetter('Minutes', 2),\n     m: dateGetter('Minutes', 1),\n    ss: dateGetter('Seconds', 2),\n     s: dateGetter('Seconds', 1),\n     // while ISO 8601 requires fractions to be prefixed with `.` or `,`\n     // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions\n   sss: dateGetter('Milliseconds', 3),\n  EEEE: dateStrGetter('Day'),\n   EEE: dateStrGetter('Day', true),\n     a: ampmGetter,\n     Z: timeZoneGetter,\n    ww: weekGetter(2),\n     w: weekGetter(1)\n};\n\nvar DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,\n    NUMBER_STRING = /^\\-?\\d+$/;\n\n/**\n * @ngdoc filter\n * @name date\n * @kind function\n *\n * @description\n *   Formats `date` to a string based on the requested `format`.\n *\n *   `format` string can be composed of the following elements:\n *\n *   * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)\n *   * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)\n *   * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)\n *   * `'MMMM'`: Month in year (January-December)\n *   * `'MMM'`: Month in year (Jan-Dec)\n *   * `'MM'`: Month in year, padded (01-12)\n *   * `'M'`: Month in year (1-12)\n *   * `'dd'`: Day in month, padded (01-31)\n *   * `'d'`: Day in month (1-31)\n *   * `'EEEE'`: Day in Week,(Sunday-Saturday)\n *   * `'EEE'`: Day in Week, (Sun-Sat)\n *   * `'HH'`: Hour in day, padded (00-23)\n *   * `'H'`: Hour in day (0-23)\n *   * `'hh'`: Hour in AM/PM, padded (01-12)\n *   * `'h'`: Hour in AM/PM, (1-12)\n *   * `'mm'`: Minute in hour, padded (00-59)\n *   * `'m'`: Minute in hour (0-59)\n *   * `'ss'`: Second in minute, padded (00-59)\n *   * `'s'`: Second in minute (0-59)\n *   * `'sss'`: Millisecond in second, padded (000-999)\n *   * `'a'`: AM/PM marker\n *   * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)\n *   * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year\n *   * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year\n *\n *   `format` string can also be one of the following predefined\n *   {@link guide/i18n localizable formats}:\n *\n *   * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale\n *     (e.g. Sep 3, 2010 12:05:08 PM)\n *   * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US  locale (e.g. 9/3/10 12:05 PM)\n *   * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US  locale\n *     (e.g. Friday, September 3, 2010)\n *   * `'longDate'`: equivalent to `'MMMM d, y'` for en_US  locale (e.g. September 3, 2010)\n *   * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US  locale (e.g. Sep 3, 2010)\n *   * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)\n *   * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)\n *   * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)\n *\n *   `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.\n *   `\"h 'in the morning'\"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence\n *   (e.g. `\"h 'o''clock'\"`).\n *\n * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or\n *    number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its\n *    shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is\n *    specified in the string input, the time is considered to be in the local timezone.\n * @param {string=} format Formatting rules (see Description). If not specified,\n *    `mediumDate` is used.\n * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.\n *    If not specified, the timezone of the browser will be used.\n * @returns {string} Formatted string or the input if input is not recognized as date/millis.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:\n           <span>{{1288323623006 | date:'medium'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:\n          <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:\n          <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:\"MM/dd/yyyy 'at' h:mma\"}}</span>:\n          <span>{{'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"}}</span><br>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format date', function() {\n         expect(element(by.binding(\"1288323623006 | date:'medium'\")).getText()).\n            toMatch(/Oct 2\\d, 2010 \\d{1,2}:\\d{2}:\\d{2} (AM|PM)/);\n         expect(element(by.binding(\"1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'\")).getText()).\n            toMatch(/2010\\-10\\-2\\d \\d{2}:\\d{2}:\\d{2} (\\-|\\+)?\\d{4}/);\n         expect(element(by.binding(\"'1288323623006' | date:'MM/dd/yyyy @ h:mma'\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 @ \\d{1,2}:\\d{2}(AM|PM)/);\n         expect(element(by.binding(\"'1288323623006' | date:\\\"MM/dd/yyyy 'at' h:mma\\\"\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 at \\d{1,2}:\\d{2}(AM|PM)/);\n       });\n     </file>\n   </example>\n */\ndateFilter.$inject = ['$locale'];\nfunction dateFilter($locale) {\n\n\n  var R_ISO8601_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:\\.(\\d+))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d))?)?$/;\n                     // 1        2       3         4          5          6          7          8  9     10      11\n  function jsonStringToDate(string) {\n    var match;\n    if (match = string.match(R_ISO8601_STR)) {\n      var date = new Date(0),\n          tzHour = 0,\n          tzMin  = 0,\n          dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,\n          timeSetter = match[8] ? date.setUTCHours : date.setHours;\n\n      if (match[9]) {\n        tzHour = int(match[9] + match[10]);\n        tzMin = int(match[9] + match[11]);\n      }\n      dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));\n      var h = int(match[4] || 0) - tzHour;\n      var m = int(match[5] || 0) - tzMin;\n      var s = int(match[6] || 0);\n      var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);\n      timeSetter.call(date, h, m, s, ms);\n      return date;\n    }\n    return string;\n  }\n\n\n  return function(date, format, timezone) {\n    var text = '',\n        parts = [],\n        fn, match;\n\n    format = format || 'mediumDate';\n    format = $locale.DATETIME_FORMATS[format] || format;\n    if (isString(date)) {\n      date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);\n    }\n\n    if (isNumber(date)) {\n      date = new Date(date);\n    }\n\n    if (!isDate(date)) {\n      return date;\n    }\n\n    while (format) {\n      match = DATE_FORMATS_SPLIT.exec(format);\n      if (match) {\n        parts = concat(parts, match, 1);\n        format = parts.pop();\n      } else {\n        parts.push(format);\n        format = null;\n      }\n    }\n\n    if (timezone && timezone === 'UTC') {\n      date = new Date(date.getTime());\n      date.setMinutes(date.getMinutes() + date.getTimezoneOffset());\n    }\n    forEach(parts, function(value) {\n      fn = DATE_FORMATS[value];\n      text += fn ? fn(date, $locale.DATETIME_FORMATS)\n                 : value.replace(/(^'|'$)/g, '').replace(/''/g, \"'\");\n    });\n\n    return text;\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name json\n * @kind function\n *\n * @description\n *   Allows you to convert a JavaScript object into JSON string.\n *\n *   This filter is mostly useful for debugging. When using the double curly {{value}} notation\n *   the binding is automatically converted to JSON.\n *\n * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.\n * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.\n * @returns {string} JSON string.\n *\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <pre id=\"default-spacing\">{{ {'name':'value'} | json }}</pre>\n       <pre id=\"custom-spacing\">{{ {'name':'value'} | json:4 }}</pre>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should jsonify filtered objects', function() {\n         expect(element(by.id('default-spacing')).getText()).toMatch(/\\{\\n  \"name\": ?\"value\"\\n}/);\n         expect(element(by.id('custom-spacing')).getText()).toMatch(/\\{\\n    \"name\": ?\"value\"\\n}/);\n       });\n     </file>\n   </example>\n *\n */\nfunction jsonFilter() {\n  return function(object, spacing) {\n    if (isUndefined(spacing)) {\n        spacing = 2;\n    }\n    return toJson(object, spacing);\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name lowercase\n * @kind function\n * @description\n * Converts string to lowercase.\n * @see angular.lowercase\n */\nvar lowercaseFilter = valueFn(lowercase);\n\n\n/**\n * @ngdoc filter\n * @name uppercase\n * @kind function\n * @description\n * Converts string to uppercase.\n * @see angular.uppercase\n */\nvar uppercaseFilter = valueFn(uppercase);\n\n/**\n * @ngdoc filter\n * @name limitTo\n * @kind function\n *\n * @description\n * Creates a new array or string containing only a specified number of elements. The elements\n * are taken from either the beginning or the end of the source array, string or number, as specified by\n * the value and sign (positive or negative) of `limit`. If a number is used as input, it is\n * converted to a string.\n *\n * @param {Array|string|number} input Source array, string or number to be limited.\n * @param {string|number} limit The length of the returned array or string. If the `limit` number\n *     is positive, `limit` number of items from the beginning of the source array/string are copied.\n *     If the number is negative, `limit` number  of items from the end of the source array/string\n *     are copied. The `limit` will be trimmed if it exceeds `array.length`\n * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array\n *     had less than `limit` elements.\n *\n * @example\n   <example module=\"limitToExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('limitToExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.numbers = [1,2,3,4,5,6,7,8,9];\n             $scope.letters = \"abcdefghi\";\n             $scope.longNumber = 2345432342;\n             $scope.numLimit = 3;\n             $scope.letterLimit = 3;\n             $scope.longNumberLimit = 3;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         Limit {{numbers}} to: <input type=\"number\" step=\"1\" ng-model=\"numLimit\">\n         <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>\n         Limit {{letters}} to: <input type=\"number\" step=\"1\" ng-model=\"letterLimit\">\n         <p>Output letters: {{ letters | limitTo:letterLimit }}</p>\n         Limit {{longNumber}} to: <input type=\"number\" step=\"1\" ng-model=\"longNumberLimit\">\n         <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var numLimitInput = element(by.model('numLimit'));\n       var letterLimitInput = element(by.model('letterLimit'));\n       var longNumberLimitInput = element(by.model('longNumberLimit'));\n       var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));\n       var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));\n       var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));\n\n       it('should limit the number array to first three items', function() {\n         expect(numLimitInput.getAttribute('value')).toBe('3');\n         expect(letterLimitInput.getAttribute('value')).toBe('3');\n         expect(longNumberLimitInput.getAttribute('value')).toBe('3');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abc');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 234');\n       });\n\n       // There is a bug in safari and protractor that doesn't like the minus key\n       // it('should update the output when -3 is entered', function() {\n       //   numLimitInput.clear();\n       //   numLimitInput.sendKeys('-3');\n       //   letterLimitInput.clear();\n       //   letterLimitInput.sendKeys('-3');\n       //   longNumberLimitInput.clear();\n       //   longNumberLimitInput.sendKeys('-3');\n       //   expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');\n       //   expect(limitedLetters.getText()).toEqual('Output letters: ghi');\n       //   expect(limitedLongNumber.getText()).toEqual('Output long number: 342');\n       // });\n\n       it('should not exceed the maximum size of input array', function() {\n         numLimitInput.clear();\n         numLimitInput.sendKeys('100');\n         letterLimitInput.clear();\n         letterLimitInput.sendKeys('100');\n         longNumberLimitInput.clear();\n         longNumberLimitInput.sendKeys('100');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');\n       });\n     </file>\n   </example>\n*/\nfunction limitToFilter() {\n  return function(input, limit) {\n    if (isNumber(input)) input = input.toString();\n    if (!isArray(input) && !isString(input)) return input;\n\n    if (Math.abs(Number(limit)) === Infinity) {\n      limit = Number(limit);\n    } else {\n      limit = int(limit);\n    }\n\n    //NaN check on limit\n    if (limit) {\n      return limit > 0 ? input.slice(0, limit) : input.slice(limit);\n    } else {\n      return isString(input) ? \"\" : [];\n    }\n  };\n}\n\n/**\n * @ngdoc filter\n * @name orderBy\n * @kind function\n *\n * @description\n * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically\n * for strings and numerically for numbers. Note: if you notice numbers are not being sorted\n * correctly, make sure they are actually being saved as numbers and not strings.\n *\n * @param {Array} array The array to sort.\n * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be\n *    used by the comparator to determine the order of elements.\n *\n *    Can be one of:\n *\n *    - `function`: Getter function. The result of this function will be sorted using the\n *      `<`, `=`, `>` operator.\n *    - `string`: An Angular expression. The result of this expression is used to compare elements\n *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by\n *      3 first characters of a property called `name`). The result of a constant expression\n *      is interpreted as a property name to be used in comparisons (for example `\"special name\"`\n *      to sort object by the value of their `special name` property). An expression can be\n *      optionally prefixed with `+` or `-` to control ascending or descending sort order\n *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array\n *      element itself is used to compare where sorting.\n *    - `Array`: An array of function or string predicates. The first predicate in the array\n *      is used for sorting, but when two items are equivalent, the next predicate is used.\n *\n *    If the predicate is missing or empty then it defaults to `'+'`.\n *\n * @param {boolean=} reverse Reverse the order of the array.\n * @returns {Array} Sorted copy of the source array.\n *\n * @example\n   <example module=\"orderByExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('orderByExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.friends =\n                 [{name:'John', phone:'555-1212', age:10},\n                  {name:'Mary', phone:'555-9876', age:19},\n                  {name:'Mike', phone:'555-4321', age:21},\n                  {name:'Adam', phone:'555-5678', age:35},\n                  {name:'Julie', phone:'555-8765', age:29}];\n             $scope.predicate = '-age';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>\n         <hr/>\n         [ <a href=\"\" ng-click=\"predicate=''\">unsorted</a> ]\n         <table class=\"friend\">\n           <tr>\n             <th><a href=\"\" ng-click=\"predicate = 'name'; reverse=false\">Name</a>\n                 (<a href=\"\" ng-click=\"predicate = '-name'; reverse=false\">^</a>)</th>\n             <th><a href=\"\" ng-click=\"predicate = 'phone'; reverse=!reverse\">Phone Number</a></th>\n             <th><a href=\"\" ng-click=\"predicate = 'age'; reverse=!reverse\">Age</a></th>\n           </tr>\n           <tr ng-repeat=\"friend in friends | orderBy:predicate:reverse\">\n             <td>{{friend.name}}</td>\n             <td>{{friend.phone}}</td>\n             <td>{{friend.age}}</td>\n           </tr>\n         </table>\n       </div>\n     </file>\n   </example>\n *\n * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the\n * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the\n * desired parameters.\n *\n * Example:\n *\n * @example\n  <example module=\"orderByExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <table class=\"friend\">\n          <tr>\n            <th><a href=\"\" ng-click=\"reverse=false;order('name', false)\">Name</a>\n              (<a href=\"\" ng-click=\"order('-name',false)\">^</a>)</th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('phone', reverse)\">Phone Number</a></th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('age',reverse)\">Age</a></th>\n          </tr>\n          <tr ng-repeat=\"friend in friends\">\n            <td>{{friend.name}}</td>\n            <td>{{friend.phone}}</td>\n            <td>{{friend.age}}</td>\n          </tr>\n        </table>\n      </div>\n    </file>\n\n    <file name=\"script.js\">\n      angular.module('orderByExample', [])\n        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {\n          var orderBy = $filter('orderBy');\n          $scope.friends = [\n            { name: 'John',    phone: '555-1212',    age: 10 },\n            { name: 'Mary',    phone: '555-9876',    age: 19 },\n            { name: 'Mike',    phone: '555-4321',    age: 21 },\n            { name: 'Adam',    phone: '555-5678',    age: 35 },\n            { name: 'Julie',   phone: '555-8765',    age: 29 }\n          ];\n          $scope.order = function(predicate, reverse) {\n            $scope.friends = orderBy($scope.friends, predicate, reverse);\n          };\n          $scope.order('-age',false);\n        }]);\n    </file>\n</example>\n */\norderByFilter.$inject = ['$parse'];\nfunction orderByFilter($parse) {\n  return function(array, sortPredicate, reverseOrder) {\n    if (!(isArrayLike(array))) return array;\n    sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];\n    if (sortPredicate.length === 0) { sortPredicate = ['+']; }\n    sortPredicate = sortPredicate.map(function(predicate) {\n      var descending = false, get = predicate || identity;\n      if (isString(predicate)) {\n        if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {\n          descending = predicate.charAt(0) == '-';\n          predicate = predicate.substring(1);\n        }\n        if (predicate === '') {\n          // Effectively no predicate was passed so we compare identity\n          return reverseComparator(compare, descending);\n        }\n        get = $parse(predicate);\n        if (get.constant) {\n          var key = get();\n          return reverseComparator(function(a, b) {\n            return compare(a[key], b[key]);\n          }, descending);\n        }\n      }\n      return reverseComparator(function(a, b) {\n        return compare(get(a),get(b));\n      }, descending);\n    });\n    return slice.call(array).sort(reverseComparator(comparator, reverseOrder));\n\n    function comparator(o1, o2) {\n      for (var i = 0; i < sortPredicate.length; i++) {\n        var comp = sortPredicate[i](o1, o2);\n        if (comp !== 0) return comp;\n      }\n      return 0;\n    }\n    function reverseComparator(comp, descending) {\n      return descending\n          ? function(a, b) {return comp(b,a);}\n          : comp;\n    }\n\n    function isPrimitive(value) {\n      switch (typeof value) {\n        case 'number': /* falls through */\n        case 'boolean': /* falls through */\n        case 'string':\n          return true;\n        default:\n          return false;\n      }\n    }\n\n    function objectToString(value) {\n      if (value === null) return 'null';\n      if (typeof value.valueOf === 'function') {\n        value = value.valueOf();\n        if (isPrimitive(value)) return value;\n      }\n      if (typeof value.toString === 'function') {\n        value = value.toString();\n        if (isPrimitive(value)) return value;\n      }\n      return '';\n    }\n\n    function compare(v1, v2) {\n      var t1 = typeof v1;\n      var t2 = typeof v2;\n      if (t1 === t2 && t1 === \"object\") {\n        v1 = objectToString(v1);\n        v2 = objectToString(v2);\n      }\n      if (t1 === t2) {\n        if (t1 === \"string\") {\n           v1 = v1.toLowerCase();\n           v2 = v2.toLowerCase();\n        }\n        if (v1 === v2) return 0;\n        return v1 < v2 ? -1 : 1;\n      } else {\n        return t1 < t2 ? -1 : 1;\n      }\n    }\n  };\n}\n\nfunction ngDirective(directive) {\n  if (isFunction(directive)) {\n    directive = {\n      link: directive\n    };\n  }\n  directive.restrict = directive.restrict || 'AC';\n  return valueFn(directive);\n}\n\n/**\n * @ngdoc directive\n * @name a\n * @restrict E\n *\n * @description\n * Modifies the default behavior of the html A tag so that the default action is prevented when\n * the href attribute is empty.\n *\n * This change permits the easy creation of action links with the `ngClick` directive\n * without changing the location or causing page reloads, e.g.:\n * `<a href=\"\" ng-click=\"list.addItem()\">Add Item</a>`\n */\nvar htmlAnchorDirective = valueFn({\n  restrict: 'E',\n  compile: function(element, attr) {\n    if (!attr.href && !attr.xlinkHref && !attr.name) {\n      return function(scope, element) {\n        // If the linked element is not an anchor tag anymore, do nothing\n        if (element[0].nodeName.toLowerCase() !== 'a') return;\n\n        // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n        var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n                   'xlink:href' : 'href';\n        element.on('click', function(event) {\n          // if we have no href url, then don't navigate anywhere.\n          if (!element.attr(href)) {\n            event.preventDefault();\n          }\n        });\n      };\n    }\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngHref\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in an href attribute will\n * make the link go to the wrong URL if the user clicks it before\n * Angular has a chance to replace the `{{hash}}` markup with its\n * value. Until Angular replaces the markup the link will be broken\n * and will most likely return a 404 error. The `ngHref` directive\n * solves this problem.\n *\n * The wrong way to write it:\n * ```html\n * <a href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <a ng-href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * @element A\n * @param {template} ngHref any string which can contain `{{}}` markup.\n *\n * @example\n * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes\n * in links and their different behaviors:\n    <example>\n      <file name=\"index.html\">\n        <input ng-model=\"value\" /><br />\n        <a id=\"link-1\" href ng-click=\"value = 1\">link 1</a> (link, don't reload)<br />\n        <a id=\"link-2\" href=\"\" ng-click=\"value = 2\">link 2</a> (link, don't reload)<br />\n        <a id=\"link-3\" ng-href=\"/{{'123'}}\">link 3</a> (link, reload!)<br />\n        <a id=\"link-4\" href=\"\" name=\"xx\" ng-click=\"value = 4\">anchor</a> (link, don't reload)<br />\n        <a id=\"link-5\" name=\"xxx\" ng-click=\"value = 5\">anchor</a> (no link)<br />\n        <a id=\"link-6\" ng-href=\"{{value}}\">link</a> (link, change location)\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should execute ng-click but not reload when href without value', function() {\n          element(by.id('link-1')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('1');\n          expect(element(by.id('link-1')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when href empty string', function() {\n          element(by.id('link-2')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('2');\n          expect(element(by.id('link-2')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click and change url when ng-href specified', function() {\n          expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\\/123$/);\n\n          element(by.id('link-3')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/123$/);\n            });\n          }, 5000, 'page should navigate to /123');\n        });\n\n        xit('should execute ng-click but not reload when href empty string and name specified', function() {\n          element(by.id('link-4')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('4');\n          expect(element(by.id('link-4')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when no href but name specified', function() {\n          element(by.id('link-5')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('5');\n          expect(element(by.id('link-5')).getAttribute('href')).toBe(null);\n        });\n\n        it('should only change url when only ng-href', function() {\n          element(by.model('value')).clear();\n          element(by.model('value')).sendKeys('6');\n          expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\\/6$/);\n\n          element(by.id('link-6')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/6$/);\n            });\n          }, 5000, 'page should navigate to /6');\n        });\n      </file>\n    </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngSrc\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `src` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrc` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img src=\"http://www.gravatar.com/avatar/{{hash}}\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-src=\"http://www.gravatar.com/avatar/{{hash}}\"/>\n * ```\n *\n * @element IMG\n * @param {template} ngSrc any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngSrcset\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrcset` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\"/>\n * ```\n *\n * @element IMG\n * @param {template} ngSrcset any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngDisabled\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:\n * ```html\n * <div ng-init=\"scope = { isDisabled: false }\">\n *  <button disabled=\"{{scope.isDisabled}}\">Disabled</button>\n * </div>\n * ```\n *\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as disabled. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngDisabled` directive solves this problem for the `disabled` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        Click me to toggle: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n        <button ng-model=\"button\" ng-disabled=\"checked\">Button</button>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle button', function() {\n          expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,\n *     then special attribute \"disabled\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngChecked\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as checked. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngChecked` directive solves this problem for the `checked` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        Check me to check both: <input type=\"checkbox\" ng-model=\"master\"><br/>\n        <input id=\"checkSlave\" type=\"checkbox\" ng-checked=\"master\">\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should check both checkBoxes', function() {\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();\n          element(by.model('master')).click();\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,\n *     then special attribute \"checked\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngReadonly\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as readonly. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngReadonly` directive solves this problem for the `readonly` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        Check me to make text readonly: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n        <input type=\"text\" ng-readonly=\"checked\" value=\"I'm Angular\"/>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle readonly attr', function() {\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,\n *     then special attribute \"readonly\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSelected\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as selected. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngSelected` directive solves this problem for the `selected` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        Check me to select: <input type=\"checkbox\" ng-model=\"selected\"><br/>\n        <select>\n          <option>Hello!</option>\n          <option id=\"greet\" ng-selected=\"selected\">Greetings!</option>\n        </select>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should select Greetings!', function() {\n          expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();\n          element(by.model('selected')).click();\n          expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element OPTION\n * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,\n *     then special attribute \"selected\" will be set on the element\n */\n\n/**\n * @ngdoc directive\n * @name ngOpen\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as open. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngOpen` directive solves this problem for the `open` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n     <example>\n       <file name=\"index.html\">\n         Check me check multiple: <input type=\"checkbox\" ng-model=\"open\"><br/>\n         <details id=\"details\" ng-open=\"open\">\n            <summary>Show/Hide me</summary>\n         </details>\n       </file>\n       <file name=\"protractor.js\" type=\"protractor\">\n         it('should toggle open', function() {\n           expect(element(by.id('details')).getAttribute('open')).toBeFalsy();\n           element(by.model('open')).click();\n           expect(element(by.id('details')).getAttribute('open')).toBeTruthy();\n         });\n       </file>\n     </example>\n *\n * @element DETAILS\n * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,\n *     then special attribute \"open\" will be set on the element\n */\n\nvar ngAttributeAliasDirectives = {};\n\n\n// boolean attrs are evaluated\nforEach(BOOLEAN_ATTR, function(propName, attrName) {\n  // binding to multiple is not supported\n  if (propName == \"multiple\") return;\n\n  var normalized = directiveNormalize('ng-' + attrName);\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      restrict: 'A',\n      priority: 100,\n      link: function(scope, element, attr) {\n        scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {\n          attr.$set(attrName, !!value);\n        });\n      }\n    };\n  };\n});\n\n// aliased input attrs are evaluated\nforEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {\n  ngAttributeAliasDirectives[ngAttr] = function() {\n    return {\n      priority: 100,\n      link: function(scope, element, attr) {\n        //special case ngPattern when a literal regular expression value\n        //is used as the expression (this way we don't have to watch anything).\n        if (ngAttr === \"ngPattern\" && attr.ngPattern.charAt(0) == \"/\") {\n          var match = attr.ngPattern.match(REGEX_STRING_REGEXP);\n          if (match) {\n            attr.$set(\"ngPattern\", new RegExp(match[1], match[2]));\n            return;\n          }\n        }\n\n        scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {\n          attr.$set(ngAttr, value);\n        });\n      }\n    };\n  };\n});\n\n// ng-src, ng-srcset, ng-href are interpolated\nforEach(['src', 'srcset', 'href'], function(attrName) {\n  var normalized = directiveNormalize('ng-' + attrName);\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      priority: 99, // it needs to run after the attributes are interpolated\n      link: function(scope, element, attr) {\n        var propName = attrName,\n            name = attrName;\n\n        if (attrName === 'href' &&\n            toString.call(element.prop('href')) === '[object SVGAnimatedString]') {\n          name = 'xlinkHref';\n          attr.$attr[name] = 'xlink:href';\n          propName = null;\n        }\n\n        attr.$observe(normalized, function(value) {\n          if (!value) {\n            if (attrName === 'href') {\n              attr.$set(name, null);\n            }\n            return;\n          }\n\n          attr.$set(name, value);\n\n          // on IE, if \"ng:src\" directive declaration is used and \"src\" attribute doesn't exist\n          // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need\n          // to set the property as well to achieve the desired effect.\n          // we use attr[attrName] value since $set can sanitize the url.\n          if (msie && propName) element.prop(propName, attr[name]);\n        });\n      }\n    };\n  };\n});\n\n/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true\n */\nvar nullFormCtrl = {\n  $addControl: noop,\n  $$renameControl: nullFormRenameControl,\n  $removeControl: noop,\n  $setValidity: noop,\n  $setDirty: noop,\n  $setPristine: noop,\n  $setSubmitted: noop\n},\nSUBMITTED_CLASS = 'ng-submitted';\n\nfunction nullFormRenameControl(control, name) {\n  control.$name = name;\n}\n\n/**\n * @ngdoc type\n * @name form.FormController\n *\n * @property {boolean} $pristine True if user has not interacted with the form yet.\n * @property {boolean} $dirty True if user has already interacted with the form.\n * @property {boolean} $valid True if all of the containing forms and controls are valid.\n * @property {boolean} $invalid True if at least one containing control or form is invalid.\n * @property {boolean} $submitted True if user has submitted the form even if its invalid.\n *\n * @property {Object} $error Is an object hash, containing references to controls or\n *  forms with failing validators, where:\n *\n *  - keys are validation tokens (error names),\n *  - values are arrays of controls or forms that have a failing validator for given error name.\n *\n *  Built-in validation tokens:\n *\n *  - `email`\n *  - `max`\n *  - `maxlength`\n *  - `min`\n *  - `minlength`\n *  - `number`\n *  - `pattern`\n *  - `required`\n *  - `url`\n *  - `date`\n *  - `datetimelocal`\n *  - `time`\n *  - `week`\n *  - `month`\n *\n * @description\n * `FormController` keeps track of all its controls and nested forms as well as the state of them,\n * such as being valid/invalid or dirty/pristine.\n *\n * Each {@link ng.directive:form form} directive creates an instance\n * of `FormController`.\n *\n */\n//asks for $scope to fool the BC controller module\nFormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];\nfunction FormController(element, attrs, $scope, $animate, $interpolate) {\n  var form = this,\n      controls = [];\n\n  var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;\n\n  // init state\n  form.$error = {};\n  form.$$success = {};\n  form.$pending = undefined;\n  form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);\n  form.$dirty = false;\n  form.$pristine = true;\n  form.$valid = true;\n  form.$invalid = false;\n  form.$submitted = false;\n\n  parentForm.$addControl(form);\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$rollbackViewValue\n   *\n   * @description\n   * Rollback all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is typically needed by the reset button of\n   * a form that uses `ng-model-options` to pend updates.\n   */\n  form.$rollbackViewValue = function() {\n    forEach(controls, function(control) {\n      control.$rollbackViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$commitViewValue\n   *\n   * @description\n   * Commit all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  form.$commitViewValue = function() {\n    forEach(controls, function(control) {\n      control.$commitViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$addControl\n   *\n   * @description\n   * Register a control with the form.\n   *\n   * Input elements using ngModelController do this automatically when they are linked.\n   */\n  form.$addControl = function(control) {\n    // Breaking change - before, inputs whose name was \"hasOwnProperty\" were quietly ignored\n    // and not added to the scope.  Now we throw an error.\n    assertNotHasOwnProperty(control.$name, 'input');\n    controls.push(control);\n\n    if (control.$name) {\n      form[control.$name] = control;\n    }\n  };\n\n  // Private API: rename a form control\n  form.$$renameControl = function(control, newName) {\n    var oldName = control.$name;\n\n    if (form[oldName] === control) {\n      delete form[oldName];\n    }\n    form[newName] = control;\n    control.$name = newName;\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$removeControl\n   *\n   * @description\n   * Deregister a control from the form.\n   *\n   * Input elements using ngModelController do this automatically when they are destroyed.\n   */\n  form.$removeControl = function(control) {\n    if (control.$name && form[control.$name] === control) {\n      delete form[control.$name];\n    }\n    forEach(form.$pending, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$error, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$$success, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n\n    arrayRemove(controls, control);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setValidity\n   *\n   * @description\n   * Sets the validity of a form control.\n   *\n   * This method will also propagate to parent forms.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: element,\n    set: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        object[property] = [controller];\n      } else {\n        var index = list.indexOf(controller);\n        if (index === -1) {\n          list.push(controller);\n        }\n      }\n    },\n    unset: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        return;\n      }\n      arrayRemove(list, controller);\n      if (list.length === 0) {\n        delete object[property];\n      }\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setDirty\n   *\n   * @description\n   * Sets the form to a dirty state.\n   *\n   * This method can be called to add the 'ng-dirty' class and set the form to a dirty\n   * state (ng-dirty class). This method will also propagate to parent forms.\n   */\n  form.$setDirty = function() {\n    $animate.removeClass(element, PRISTINE_CLASS);\n    $animate.addClass(element, DIRTY_CLASS);\n    form.$dirty = true;\n    form.$pristine = false;\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setPristine\n   *\n   * @description\n   * Sets the form to its pristine state.\n   *\n   * This method can be called to remove the 'ng-dirty' class and set the form to its pristine\n   * state (ng-pristine class). This method will also propagate to all the controls contained\n   * in this form.\n   *\n   * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after\n   * saving or resetting it.\n   */\n  form.$setPristine = function() {\n    $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);\n    form.$dirty = false;\n    form.$pristine = true;\n    form.$submitted = false;\n    forEach(controls, function(control) {\n      control.$setPristine();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setUntouched\n   *\n   * @description\n   * Sets the form to its untouched state.\n   *\n   * This method can be called to remove the 'ng-touched' class and set the form controls to their\n   * untouched state (ng-untouched class).\n   *\n   * Setting a form controls back to their untouched state is often useful when setting the form\n   * back to its pristine state.\n   */\n  form.$setUntouched = function() {\n    forEach(controls, function(control) {\n      control.$setUntouched();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setSubmitted\n   *\n   * @description\n   * Sets the form to its submitted state.\n   */\n  form.$setSubmitted = function() {\n    $animate.addClass(element, SUBMITTED_CLASS);\n    form.$submitted = true;\n    parentForm.$setSubmitted();\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ngForm\n * @restrict EAC\n *\n * @description\n * Nestable alias of {@link ng.directive:form `form`} directive. HTML\n * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a\n * sub-group of controls needs to be determined.\n *\n * Note: the purpose of `ngForm` is to group controls,\n * but not to be a replacement for the `<form>` tag with all of its capabilities\n * (e.g. posting to the server, ...).\n *\n * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n *\n */\n\n /**\n * @ngdoc directive\n * @name form\n * @restrict E\n *\n * @description\n * Directive that instantiates\n * {@link form.FormController FormController}.\n *\n * If the `name` attribute is specified, the form controller is published onto the current scope under\n * this name.\n *\n * # Alias: {@link ng.directive:ngForm `ngForm`}\n *\n * In Angular forms can be nested. This means that the outer form is valid when all of the child\n * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so\n * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to\n * `<form>` but can be nested.  This allows you to have nested forms, which is very useful when\n * using Angular validation directives in forms that are dynamically generated using the\n * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`\n * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an\n * `ngForm` directive and nest these in an outer `form` element.\n *\n *\n * # CSS classes\n *  - `ng-valid` is set if the form is valid.\n *  - `ng-invalid` is set if the form is invalid.\n *  - `ng-pristine` is set if the form is pristine.\n *  - `ng-dirty` is set if the form is dirty.\n *  - `ng-submitted` is set if the form was submitted.\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n *\n * # Submitting a form and preventing the default action\n *\n * Since the role of forms in client-side Angular applications is different than in classical\n * roundtrip apps, it is desirable for the browser not to translate the form submission into a full\n * page reload that sends the data to the server. Instead some javascript logic should be triggered\n * to handle the form submission in an application-specific way.\n *\n * For this reason, Angular prevents the default action (form submission to the server) unless the\n * `<form>` element has an `action` attribute specified.\n *\n * You can use one of the following two ways to specify what javascript method should be called when\n * a form is submitted:\n *\n * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element\n * - {@link ng.directive:ngClick ngClick} directive on the first\n  *  button or input field of type submit (input[type=submit])\n *\n * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}\n * or {@link ng.directive:ngClick ngClick} directives.\n * This is because of the following form submission rules in the HTML specification:\n *\n * - If a form has only one input field then hitting enter in this field triggers form submit\n * (`ngSubmit`)\n * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter\n * doesn't trigger submit\n * - if a form has one or more input fields and one or more buttons or input[type=submit] then\n * hitting enter in any of the input fields will trigger the click handler on the *first* button or\n * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)\n *\n * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is\n * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * ## Animation Hooks\n *\n * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.\n * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any\n * other validations that are performed within the form. Animations in ngForm are similar to how\n * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well\n * as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style a form element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-form {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-form.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n    <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"formExample\">\n      <file name=\"index.html\">\n       <script>\n         angular.module('formExample', [])\n           .controller('FormController', ['$scope', function($scope) {\n             $scope.userType = 'guest';\n           }]);\n       </script>\n       <style>\n        .my-form {\n          -webkit-transition:all linear 0.5s;\n          transition:all linear 0.5s;\n          background: transparent;\n        }\n        .my-form.ng-invalid {\n          background: red;\n        }\n       </style>\n       <form name=\"myForm\" ng-controller=\"FormController\" class=\"my-form\">\n         userType: <input name=\"input\" ng-model=\"userType\" required>\n         <span class=\"error\" ng-show=\"myForm.input.$error.required\">Required!</span><br>\n         <tt>userType = {{userType}}</tt><br>\n         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>\n         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>\n         <tt>myForm.$valid = {{myForm.$valid}}</tt><br>\n         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should initialize to model', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n\n          expect(userType.getText()).toContain('guest');\n          expect(valid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var userInput = element(by.model('userType'));\n\n          userInput.clear();\n          userInput.sendKeys('');\n\n          expect(userType.getText()).toEqual('userType =');\n          expect(valid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n *\n * @param {string=} name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n */\nvar formDirectiveFactory = function(isNgForm) {\n  return ['$timeout', function($timeout) {\n    var formDirective = {\n      name: 'form',\n      restrict: isNgForm ? 'EAC' : 'E',\n      controller: FormController,\n      compile: function ngFormCompile(formElement) {\n        // Setup initial state of the control\n        formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);\n\n        return {\n          pre: function ngFormPreLink(scope, formElement, attr, controller) {\n            // if `action` attr is not present on the form, prevent the default action (submission)\n            if (!('action' in attr)) {\n              // we can't use jq events because if a form is destroyed during submission the default\n              // action is not prevented. see #1238\n              //\n              // IE 9 is not affected because it doesn't fire a submit event and try to do a full\n              // page reload if the form was destroyed by submission of the form via a click handler\n              // on a button in the form. Looks like an IE9 specific bug.\n              var handleFormSubmission = function(event) {\n                scope.$apply(function() {\n                  controller.$commitViewValue();\n                  controller.$setSubmitted();\n                });\n\n                event.preventDefault();\n              };\n\n              addEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n\n              // unregister the preventDefault listener so that we don't not leak memory but in a\n              // way that will achieve the prevention of the default action.\n              formElement.on('$destroy', function() {\n                $timeout(function() {\n                  removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n                }, 0, false);\n              });\n            }\n\n            var parentFormCtrl = controller.$$parentForm,\n                alias = controller.$name;\n\n            if (alias) {\n              setter(scope, null, alias, controller, alias);\n              attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {\n                if (alias === newValue) return;\n                setter(scope, null, alias, undefined, alias);\n                alias = newValue;\n                setter(scope, null, alias, controller, alias);\n                parentFormCtrl.$$renameControl(controller, alias);\n              });\n            }\n            formElement.on('$destroy', function() {\n              parentFormCtrl.$removeControl(controller);\n              if (alias) {\n                setter(scope, null, alias, undefined, alias);\n              }\n              extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards\n            });\n          }\n        };\n      }\n    };\n\n    return formDirective;\n  }];\n};\n\nvar formDirective = formDirectiveFactory();\nvar ngFormDirective = formDirectiveFactory(true);\n\n/* global VALID_CLASS: false,\n  INVALID_CLASS: false,\n  PRISTINE_CLASS: false,\n  DIRTY_CLASS: false,\n  UNTOUCHED_CLASS: false,\n  TOUCHED_CLASS: false,\n  $ngModelMinErr: false,\n*/\n\n// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231\nvar ISO_DATE_REGEXP = /\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)/;\nvar URL_REGEXP = /^(ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?$/;\nvar EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;\nvar NUMBER_REGEXP = /^\\s*(\\-|\\+)?(\\d+|(\\d*(\\.\\d*)))\\s*$/;\nvar DATE_REGEXP = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nvar DATETIMELOCAL_REGEXP = /^(\\d{4})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\nvar WEEK_REGEXP = /^(\\d{4})-W(\\d\\d)$/;\nvar MONTH_REGEXP = /^(\\d{4})-(\\d\\d)$/;\nvar TIME_REGEXP = /^(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\n\nvar inputType = {\n\n  /**\n   * @ngdoc input\n   * @name input[text]\n   *\n   * @description\n   * Standard HTML text input with angular data binding, inherited by most of the `input` elements.\n   *\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Adds `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n   *    This parameter is ignored for input[type=password] controls, which will never trim the\n   *    input.\n   *\n   * @example\n      <example name=\"text-input-directive\" module=\"textInputExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('textInputExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 text: 'guest',\n                 word: /^\\s*\\w*\\s*$/\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           Single word: <input type=\"text\" name=\"input\" ng-model=\"example.text\"\n                               ng-pattern=\"example.word\" required ng-trim=\"false\">\n           <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n             Required!</span>\n           <span class=\"error\" ng-show=\"myForm.input.$error.pattern\">\n             Single word only!</span>\n\n           <tt>text = {{example.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('example.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('guest');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if multi word', function() {\n            input.clear();\n            input.sendKeys('hello world');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'text': textInputType,\n\n    /**\n     * @ngdoc input\n     * @name input[date]\n     *\n     * @description\n     * Input with date validation and transformation. In browsers that do not yet support\n     * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601\n     * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many\n     * modern browsers do not yet support this input type, it is important to provide cues to users on the\n     * expected input format via a placeholder or label.\n     *\n     * The model must always be a Date object, otherwise Angular will throw an error.\n     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n     *\n     * The timezone to be used to read/write the `Date` instance in the model can be defined using\n     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n     *\n     * @param {string} ngModel Assignable angular expression to data-bind to.\n     * @param {string=} name Property name of the form under which the control is published.\n     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n     * valid ISO date string (yyyy-MM-dd).\n     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n     * a valid ISO date string (yyyy-MM-dd).\n     * @param {string=} required Sets `required` validation error key if the value is not entered.\n     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n     *    `required` when you want to data-bind to the `required` attribute.\n     * @param {string=} ngChange Angular expression to be executed when input changes due to user\n     *    interaction with the input element.\n     *\n     * @example\n     <example name=\"date-input-directive\" module=\"dateInputExample\">\n     <file name=\"index.html\">\n       <script>\n          angular.module('dateInputExample', [])\n            .controller('DateController', ['$scope', function($scope) {\n              $scope.example = {\n                value: new Date(2013, 9, 22)\n              };\n            }]);\n       </script>\n       <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n          Pick a date in 2013:\n          <input type=\"date\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n              placeholder=\"yyyy-MM-dd\" min=\"2013-01-01\" max=\"2013-12-31\" required />\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.date\">\n              Not a valid date!</span>\n           <tt>value = {{example.value | date: \"yyyy-MM-dd\"}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n       </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        var value = element(by.binding('example.value | date: \"yyyy-MM-dd\"'));\n        var valid = element(by.binding('myForm.input.$valid'));\n        var input = element(by.model('example.value'));\n\n        // currently protractor/webdriver does not support\n        // sending keys to all known HTML5 input controls\n        // for various browsers (see https://github.com/angular/protractor/issues/562).\n        function setInput(val) {\n          // set the value of the element and force validation.\n          var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n          \"ipt.value = '\" + val + \"';\" +\n          \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n          browser.executeScript(scr);\n        }\n\n        it('should initialize to model', function() {\n          expect(value.getText()).toContain('2013-10-22');\n          expect(valid.getText()).toContain('myForm.input.$valid = true');\n        });\n\n        it('should be invalid if empty', function() {\n          setInput('');\n          expect(value.getText()).toEqual('value =');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n\n        it('should be invalid if over max', function() {\n          setInput('2015-01-01');\n          expect(value.getText()).toContain('');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n     </file>\n     </example>\n     */\n  'date': createDateInputType('date', DATE_REGEXP,\n         createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),\n         'yyyy-MM-dd'),\n\n   /**\n    * @ngdoc input\n    * @name input[datetime-local]\n    *\n    * @description\n    * Input with datetime validation and transformation. In browsers that do not yet support\n    * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"datetimelocal-input-directive\" module=\"dateExample\">\n    <file name=\"index.html\">\n      <script>\n        angular.module('dateExample', [])\n          .controller('DateController', ['$scope', function($scope) {\n            $scope.example = {\n              value: new Date(2010, 11, 28, 14, 57)\n            };\n          }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        Pick a date between in 2013:\n        <input type=\"datetime-local\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"yyyy-MM-ddTHH:mm:ss\" min=\"2001-01-01T00:00:00\" max=\"2013-12-31T00:00:00\" required />\n        <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n        <span class=\"error\" ng-show=\"myForm.input.$error.datetimelocal\">\n            Not a valid date!</span>\n        <tt>value = {{example.value | date: \"yyyy-MM-ddTHH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM-ddTHH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2010-12-28T14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01-01T23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,\n      createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),\n      'yyyy-MM-ddTHH:mm:ss.sss'),\n\n  /**\n   * @ngdoc input\n   * @name input[time]\n   *\n   * @description\n   * Input with time validation and transformation. In browsers that do not yet support\n   * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a\n   * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"time-input-directive\" module=\"timeExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('timeExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(1970, 0, 1, 14, 57, 0)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        Pick a between 8am and 5pm:\n        <input type=\"time\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"HH:mm:ss\" min=\"08:00:00\" max=\"17:00:00\" required />\n        <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n        <span class=\"error\" ng-show=\"myForm.input.$error.time\">\n            Not a valid date!</span>\n        <tt>value = {{example.value | date: \"HH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"HH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'time': createDateInputType('time', TIME_REGEXP,\n      createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),\n     'HH:mm:ss.sss'),\n\n   /**\n    * @ngdoc input\n    * @name input[week]\n    *\n    * @description\n    * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support\n    * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * week format (yyyy-W##), for example: `2013-W02`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO week format (yyyy-W##).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO week format (yyyy-W##).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"week-input-directive\" module=\"weekExample\">\n    <file name=\"index.html\">\n      <script>\n      angular.module('weekExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 0, 3)\n          };\n        }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        Pick a date between in 2013:\n        <input id=\"exampleInput\" type=\"week\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"YYYY-W##\" min=\"2012-W32\" max=\"2013-W52\" required />\n        <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n        <span class=\"error\" ng-show=\"myForm.input.$error.week\">\n            Not a valid date!</span>\n        <tt>value = {{example.value | date: \"yyyy-Www\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-Www\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-W01');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-W01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),\n\n  /**\n   * @ngdoc input\n   * @name input[month]\n   *\n   * @description\n   * Input with month validation and transformation. In browsers that do not yet support\n   * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * month format (yyyy-MM), for example: `2009-01`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   * If the model is not set to the first of the month, the next view to model update will set it\n   * to the first of the month.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be\n   * a valid ISO month format (yyyy-MM).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must\n   * be a valid ISO month format (yyyy-MM).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"month-input-directive\" module=\"monthExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('monthExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 9, 1)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n       Pick a month in 2013:\n       <input id=\"exampleInput\" type=\"month\" name=\"input\" ng-model=\"example.value\"\n          placeholder=\"yyyy-MM\" min=\"2013-01\" max=\"2013-12\" required />\n       <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n          Required!</span>\n       <span class=\"error\" ng-show=\"myForm.input.$error.month\">\n          Not a valid month!</span>\n       <tt>value = {{example.value | date: \"yyyy-MM\"}}</tt><br/>\n       <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n       <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n       <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n       <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-10');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'month': createDateInputType('month', MONTH_REGEXP,\n     createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),\n     'yyyy-MM'),\n\n  /**\n   * @ngdoc input\n   * @name input[number]\n   *\n   * @description\n   * Text input with number validation and transformation. Sets the `number` validation\n   * error if not a valid number.\n   *\n   * The model must always be a number, otherwise Angular will throw an error.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"number-input-directive\" module=\"numberExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('numberExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 value: 12\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           Number: <input type=\"number\" name=\"input\" ng-model=\"example.value\"\n                          min=\"0\" max=\"99\" required>\n           <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n             Required!</span>\n           <span class=\"error\" ng-show=\"myForm.input.$error.number\">\n             Not valid number!</span>\n           <tt>value = {{example.value}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var value = element(by.binding('example.value'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.value'));\n\n          it('should initialize to model', function() {\n            expect(value.getText()).toContain('12');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if over max', function() {\n            input.clear();\n            input.sendKeys('123');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'number': numberInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[url]\n   *\n   * @description\n   * Text input with URL validation. Sets the `url` validation error key if the content is not a\n   * valid URL.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex\n   * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify\n   * the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"url-input-directive\" module=\"urlExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('urlExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.url = {\n                 text: 'http://google.com'\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           URL: <input type=\"url\" name=\"input\" ng-model=\"url.text\" required>\n           <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n             Required!</span>\n           <span class=\"error\" ng-show=\"myForm.input.$error.url\">\n             Not valid url!</span>\n           <tt>text = {{url.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n           <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('url.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('url.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('http://google.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not url', function() {\n            input.clear();\n            input.sendKeys('box');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'url': urlInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[email]\n   *\n   * @description\n   * Text input with email validation. Sets the `email` validation error key if not a valid email\n   * address.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex\n   * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can\n   * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"email-input-directive\" module=\"emailExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('emailExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.email = {\n                 text: 'me@example.com'\n               };\n             }]);\n         </script>\n           <form name=\"myForm\" ng-controller=\"ExampleController\">\n             Email: <input type=\"email\" name=\"input\" ng-model=\"email.text\" required>\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.email\">\n               Not valid email!</span>\n             <tt>text = {{email.text}}</tt><br/>\n             <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n             <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n             <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n             <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n             <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>\n           </form>\n         </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('email.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('email.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('me@example.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not email', function() {\n            input.clear();\n            input.sendKeys('xxx');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'email': emailInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[radio]\n   *\n   * @description\n   * HTML radio button.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string} value The value to which the expression should be set when selected.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {string} ngValue Angular expression which sets the value to which the expression should\n   *    be set when selected.\n   *\n   * @example\n      <example name=\"radio-input-directive\" module=\"radioExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('radioExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.color = {\n                 name: 'blue'\n               };\n               $scope.specialValue = {\n                 \"id\": \"12345\",\n                 \"value\": \"green\"\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <input type=\"radio\" ng-model=\"color.name\" value=\"red\">  Red <br/>\n           <input type=\"radio\" ng-model=\"color.name\" ng-value=\"specialValue\"> Green <br/>\n           <input type=\"radio\" ng-model=\"color.name\" value=\"blue\"> Blue <br/>\n           <tt>color = {{color.name | json}}</tt><br/>\n          </form>\n          Note that `ng-value=\"specialValue\"` sets radio item's value to be the value of `$scope.specialValue`.\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var color = element(by.binding('color.name'));\n\n            expect(color.getText()).toContain('blue');\n\n            element.all(by.model('color.name')).get(0).click();\n\n            expect(color.getText()).toContain('red');\n          });\n        </file>\n      </example>\n   */\n  'radio': radioInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[checkbox]\n   *\n   * @description\n   * HTML checkbox.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {expression=} ngTrueValue The value to which the expression should be set when selected.\n   * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"checkbox-input-directive\" module=\"checkboxExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('checkboxExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.checkboxModel = {\n                value1 : true,\n                value2 : 'YES'\n              };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           Value1: <input type=\"checkbox\" ng-model=\"checkboxModel.value1\"> <br/>\n           Value2: <input type=\"checkbox\" ng-model=\"checkboxModel.value2\"\n                          ng-true-value=\"'YES'\" ng-false-value=\"'NO'\"> <br/>\n           <tt>value1 = {{checkboxModel.value1}}</tt><br/>\n           <tt>value2 = {{checkboxModel.value2}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var value1 = element(by.binding('checkboxModel.value1'));\n            var value2 = element(by.binding('checkboxModel.value2'));\n\n            expect(value1.getText()).toContain('true');\n            expect(value2.getText()).toContain('YES');\n\n            element(by.model('checkboxModel.value1')).click();\n            element(by.model('checkboxModel.value2')).click();\n\n            expect(value1.getText()).toContain('false');\n            expect(value2.getText()).toContain('NO');\n          });\n        </file>\n      </example>\n   */\n  'checkbox': checkboxInputType,\n\n  'hidden': noop,\n  'button': noop,\n  'submit': noop,\n  'reset': noop,\n  'file': noop\n};\n\nfunction stringBasedInputType(ctrl) {\n  ctrl.$formatters.push(function(value) {\n    return ctrl.$isEmpty(value) ? value : value.toString();\n  });\n}\n\nfunction textInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n}\n\nfunction baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  var type = lowercase(element[0].type);\n\n  // In composition mode, users are still inputing intermediate text buffer,\n  // hold the listener until composition is done.\n  // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent\n  if (!$sniffer.android) {\n    var composing = false;\n\n    element.on('compositionstart', function(data) {\n      composing = true;\n    });\n\n    element.on('compositionend', function() {\n      composing = false;\n      listener();\n    });\n  }\n\n  var listener = function(ev) {\n    if (timeout) {\n      $browser.defer.cancel(timeout);\n      timeout = null;\n    }\n    if (composing) return;\n    var value = element.val(),\n        event = ev && ev.type;\n\n    // By default we will trim the value\n    // If the attribute ng-trim exists we will avoid trimming\n    // If input type is 'password', the value is never trimmed\n    if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {\n      value = trim(value);\n    }\n\n    // If a control is suffering from bad input (due to native validators), browsers discard its\n    // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the\n    // control's value is the same empty value twice in a row.\n    if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {\n      ctrl.$setViewValue(value, event);\n    }\n  };\n\n  // if the browser does support \"input\" event, we are fine - except on IE9 which doesn't fire the\n  // input event on backspace, delete or cut\n  if ($sniffer.hasEvent('input')) {\n    element.on('input', listener);\n  } else {\n    var timeout;\n\n    var deferListener = function(ev, input, origValue) {\n      if (!timeout) {\n        timeout = $browser.defer(function() {\n          timeout = null;\n          if (!input || input.value !== origValue) {\n            listener(ev);\n          }\n        });\n      }\n    };\n\n    element.on('keydown', function(event) {\n      var key = event.keyCode;\n\n      // ignore\n      //    command            modifiers                   arrows\n      if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;\n\n      deferListener(event, this, this.value);\n    });\n\n    // if user modifies input value using context menu in IE, we need \"paste\" and \"cut\" events to catch it\n    if ($sniffer.hasEvent('paste')) {\n      element.on('paste cut', deferListener);\n    }\n  }\n\n  // if user paste into input using mouse on older browser\n  // or form autocomplete on newer browser, we need \"change\" event to catch it\n  element.on('change', listener);\n\n  ctrl.$render = function() {\n    element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);\n  };\n}\n\nfunction weekParser(isoWeek, existingDate) {\n  if (isDate(isoWeek)) {\n    return isoWeek;\n  }\n\n  if (isString(isoWeek)) {\n    WEEK_REGEXP.lastIndex = 0;\n    var parts = WEEK_REGEXP.exec(isoWeek);\n    if (parts) {\n      var year = +parts[1],\n          week = +parts[2],\n          hours = 0,\n          minutes = 0,\n          seconds = 0,\n          milliseconds = 0,\n          firstThurs = getFirstThursdayOfYear(year),\n          addDays = (week - 1) * 7;\n\n      if (existingDate) {\n        hours = existingDate.getHours();\n        minutes = existingDate.getMinutes();\n        seconds = existingDate.getSeconds();\n        milliseconds = existingDate.getMilliseconds();\n      }\n\n      return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);\n    }\n  }\n\n  return NaN;\n}\n\nfunction createDateParser(regexp, mapping) {\n  return function(iso, date) {\n    var parts, map;\n\n    if (isDate(iso)) {\n      return iso;\n    }\n\n    if (isString(iso)) {\n      // When a date is JSON'ified to wraps itself inside of an extra\n      // set of double quotes. This makes the date parsing code unable\n      // to match the date string and parse it as a date.\n      if (iso.charAt(0) == '\"' && iso.charAt(iso.length - 1) == '\"') {\n        iso = iso.substring(1, iso.length - 1);\n      }\n      if (ISO_DATE_REGEXP.test(iso)) {\n        return new Date(iso);\n      }\n      regexp.lastIndex = 0;\n      parts = regexp.exec(iso);\n\n      if (parts) {\n        parts.shift();\n        if (date) {\n          map = {\n            yyyy: date.getFullYear(),\n            MM: date.getMonth() + 1,\n            dd: date.getDate(),\n            HH: date.getHours(),\n            mm: date.getMinutes(),\n            ss: date.getSeconds(),\n            sss: date.getMilliseconds() / 1000\n          };\n        } else {\n          map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };\n        }\n\n        forEach(parts, function(part, index) {\n          if (index < mapping.length) {\n            map[mapping[index]] = +part;\n          }\n        });\n        return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);\n      }\n    }\n\n    return NaN;\n  };\n}\n\nfunction createDateInputType(type, regexp, parseDate, format) {\n  return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {\n    badInputChecker(scope, element, attr, ctrl);\n    baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n    var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;\n    var previousDate;\n\n    ctrl.$$parserName = type;\n    ctrl.$parsers.push(function(value) {\n      if (ctrl.$isEmpty(value)) return null;\n      if (regexp.test(value)) {\n        // Note: We cannot read ctrl.$modelValue, as there might be a different\n        // parser/formatter in the processing chain so that the model\n        // contains some different data format!\n        var parsedDate = parseDate(value, previousDate);\n        if (timezone === 'UTC') {\n          parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());\n        }\n        return parsedDate;\n      }\n      return undefined;\n    });\n\n    ctrl.$formatters.push(function(value) {\n      if (value && !isDate(value)) {\n        throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);\n      }\n      if (isValidDate(value)) {\n        previousDate = value;\n        if (previousDate && timezone === 'UTC') {\n          var timezoneOffset = 60000 * previousDate.getTimezoneOffset();\n          previousDate = new Date(previousDate.getTime() + timezoneOffset);\n        }\n        return $filter('date')(value, format, timezone);\n      } else {\n        previousDate = null;\n        return '';\n      }\n    });\n\n    if (isDefined(attr.min) || attr.ngMin) {\n      var minVal;\n      ctrl.$validators.min = function(value) {\n        return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;\n      };\n      attr.$observe('min', function(val) {\n        minVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    if (isDefined(attr.max) || attr.ngMax) {\n      var maxVal;\n      ctrl.$validators.max = function(value) {\n        return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;\n      };\n      attr.$observe('max', function(val) {\n        maxVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    function isValidDate(value) {\n      // Invalid Date: getTime() returns NaN\n      return value && !(value.getTime && value.getTime() !== value.getTime());\n    }\n\n    function parseObservedDateValue(val) {\n      return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;\n    }\n  };\n}\n\nfunction badInputChecker(scope, element, attr, ctrl) {\n  var node = element[0];\n  var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);\n  if (nativeValidation) {\n    ctrl.$parsers.push(function(value) {\n      var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};\n      // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):\n      // - also sets validity.badInput (should only be validity.typeMismatch).\n      // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)\n      // - can ignore this case as we can still read out the erroneous email...\n      return validity.badInput && !validity.typeMismatch ? undefined : value;\n    });\n  }\n}\n\nfunction numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  badInputChecker(scope, element, attr, ctrl);\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n  ctrl.$$parserName = 'number';\n  ctrl.$parsers.push(function(value) {\n    if (ctrl.$isEmpty(value))      return null;\n    if (NUMBER_REGEXP.test(value)) return parseFloat(value);\n    return undefined;\n  });\n\n  ctrl.$formatters.push(function(value) {\n    if (!ctrl.$isEmpty(value)) {\n      if (!isNumber(value)) {\n        throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);\n      }\n      value = value.toString();\n    }\n    return value;\n  });\n\n  if (attr.min || attr.ngMin) {\n    var minVal;\n    ctrl.$validators.min = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;\n    };\n\n    attr.$observe('min', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      minVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n\n  if (attr.max || attr.ngMax) {\n    var maxVal;\n    ctrl.$validators.max = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;\n    };\n\n    attr.$observe('max', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      maxVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n}\n\nfunction urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'url';\n  ctrl.$validators.url = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || URL_REGEXP.test(value);\n  };\n}\n\nfunction emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'email';\n  ctrl.$validators.email = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);\n  };\n}\n\nfunction radioInputType(scope, element, attr, ctrl) {\n  // make the name unique, if not defined\n  if (isUndefined(attr.name)) {\n    element.attr('name', nextUid());\n  }\n\n  var listener = function(ev) {\n    if (element[0].checked) {\n      ctrl.$setViewValue(attr.value, ev && ev.type);\n    }\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    var value = attr.value;\n    element[0].checked = (value == ctrl.$viewValue);\n  };\n\n  attr.$observe('value', ctrl.$render);\n}\n\nfunction parseConstantExpr($parse, context, name, expression, fallback) {\n  var parseFn;\n  if (isDefined(expression)) {\n    parseFn = $parse(expression);\n    if (!parseFn.constant) {\n      throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +\n                                   '`{1}`.', name, expression);\n    }\n    return parseFn(context);\n  }\n  return fallback;\n}\n\nfunction checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n  var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);\n  var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);\n\n  var listener = function(ev) {\n    ctrl.$setViewValue(element[0].checked, ev && ev.type);\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    element[0].checked = ctrl.$viewValue;\n  };\n\n  // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`\n  // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert\n  // it to a boolean.\n  ctrl.$isEmpty = function(value) {\n    return value === false;\n  };\n\n  ctrl.$formatters.push(function(value) {\n    return equals(value, trueValue);\n  });\n\n  ctrl.$parsers.push(function(value) {\n    return value ? trueValue : falseValue;\n  });\n}\n\n\n/**\n * @ngdoc directive\n * @name textarea\n * @restrict E\n *\n * @description\n * HTML textarea element control with angular data-binding. The data-binding and validation\n * properties of this element are exactly the same as those of the\n * {@link ng.directive:input input element}.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the\n *    RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for\n *    patterns defined as scope expressions.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n */\n\n\n/**\n * @ngdoc directive\n * @name input\n * @restrict E\n *\n * @description\n * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,\n * input state control, and validation.\n * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Not every feature offered is available for all input types.\n * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.\n * </div>\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {boolean=} ngRequired Sets `required` attribute if set to true\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the\n *    RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for\n *    patterns defined as scope expressions.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n *    This parameter is ignored for input[type=password] controls, which will never trim the\n *    input.\n *\n * @example\n    <example name=\"input-directive\" module=\"inputExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('inputExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.user = {name: 'guest', last: 'visitor'};\n            }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <form name=\"myForm\">\n           User name: <input type=\"text\" name=\"userName\" ng-model=\"user.name\" required>\n           <span class=\"error\" ng-show=\"myForm.userName.$error.required\">\n             Required!</span><br>\n           Last name: <input type=\"text\" name=\"lastName\" ng-model=\"user.last\"\n             ng-minlength=\"3\" ng-maxlength=\"10\">\n           <span class=\"error\" ng-show=\"myForm.lastName.$error.minlength\">\n             Too short!</span>\n           <span class=\"error\" ng-show=\"myForm.lastName.$error.maxlength\">\n             Too long!</span><br>\n         </form>\n         <hr>\n         <tt>user = {{user}}</tt><br/>\n         <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>\n         <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>\n         <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>\n         <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>\n         <tt>myForm.$valid = {{myForm.$valid}}</tt><br>\n         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>\n         <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>\n         <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>\n       </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var user = element(by.exactBinding('user'));\n        var userNameValid = element(by.binding('myForm.userName.$valid'));\n        var lastNameValid = element(by.binding('myForm.lastName.$valid'));\n        var lastNameError = element(by.binding('myForm.lastName.$error'));\n        var formValid = element(by.binding('myForm.$valid'));\n        var userNameInput = element(by.model('user.name'));\n        var userLastInput = element(by.model('user.last'));\n\n        it('should initialize to model', function() {\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty when required', function() {\n          userNameInput.clear();\n          userNameInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('false');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be valid if empty when min length is set', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"\"}');\n          expect(lastNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if less than required min length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('xx');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('minlength');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be invalid if longer than max length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('some ridiculously long name');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('maxlength');\n          expect(formValid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n */\nvar inputDirective = ['$browser', '$sniffer', '$filter', '$parse',\n    function($browser, $sniffer, $filter, $parse) {\n  return {\n    restrict: 'E',\n    require: ['?ngModel'],\n    link: {\n      pre: function(scope, element, attr, ctrls) {\n        if (ctrls[0]) {\n          (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,\n                                                              $browser, $filter, $parse);\n        }\n      }\n    }\n  };\n}];\n\n\n\nvar CONSTANT_VALUE_REGEXP = /^(true|false|\\d+)$/;\n/**\n * @ngdoc directive\n * @name ngValue\n *\n * @description\n * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},\n * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to\n * the bound value.\n *\n * `ngValue` is useful when dynamically generating lists of radio buttons using\n * {@link ngRepeat `ngRepeat`}, as shown below.\n *\n * Likewise, `ngValue` can be used to generate `<option>` elements for\n * the {@link select `select`} element. In that case however, only strings are supported\n * for the `value `attribute, so the resulting `ngModel` will always be a string.\n * Support for `select` models with non-string values is available via `ngOptions`.\n *\n * @element input\n * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute\n *   of the `input` element\n *\n * @example\n    <example name=\"ngValue-directive\" module=\"valueExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('valueExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.names = ['pizza', 'unicorns', 'robots'];\n              $scope.my = { favorite: 'unicorns' };\n            }]);\n       </script>\n        <form ng-controller=\"ExampleController\">\n          <h2>Which is your favorite?</h2>\n            <label ng-repeat=\"name in names\" for=\"{{name}}\">\n              {{name}}\n              <input type=\"radio\"\n                     ng-model=\"my.favorite\"\n                     ng-value=\"name\"\n                     id=\"{{name}}\"\n                     name=\"favorite\">\n            </label>\n          <div>You chose {{my.favorite}}</div>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var favorite = element(by.binding('my.favorite'));\n\n        it('should initialize to model', function() {\n          expect(favorite.getText()).toContain('unicorns');\n        });\n        it('should bind the values to the inputs', function() {\n          element.all(by.model('my.favorite')).get(0).click();\n          expect(favorite.getText()).toContain('pizza');\n        });\n      </file>\n    </example>\n */\nvar ngValueDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    compile: function(tpl, tplAttr) {\n      if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {\n        return function ngValueConstantLink(scope, elm, attr) {\n          attr.$set('value', scope.$eval(attr.ngValue));\n        };\n      } else {\n        return function ngValueLink(scope, elm, attr) {\n          scope.$watch(attr.ngValue, function valueWatchAction(value) {\n            attr.$set('value', value);\n          });\n        };\n      }\n    }\n  };\n};\n\n/**\n * @ngdoc directive\n * @name ngBind\n * @restrict AC\n *\n * @description\n * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element\n * with the value of a given expression, and to update the text content when the value of that\n * expression changes.\n *\n * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like\n * `{{ expression }}` which is similar but less verbose.\n *\n * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily\n * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an\n * element attribute, it makes the bindings invisible to the user while the page is loading.\n *\n * An alternative solution to this problem would be using the\n * {@link ng.directive:ngCloak ngCloak} directive.\n *\n *\n * @element ANY\n * @param {expression} ngBind {@link guide/expression Expression} to evaluate.\n *\n * @example\n * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.name = 'Whirled';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         Enter name: <input type=\"text\" ng-model=\"name\"><br>\n         Hello <span ng-bind=\"name\"></span>!\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var nameInput = element(by.model('name'));\n\n         expect(element(by.binding('name')).getText()).toBe('Whirled');\n         nameInput.clear();\n         nameInput.sendKeys('world');\n         expect(element(by.binding('name')).getText()).toBe('world');\n       });\n     </file>\n   </example>\n */\nvar ngBindDirective = ['$compile', function($compile) {\n  return {\n    restrict: 'AC',\n    compile: function ngBindCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBind);\n        element = element[0];\n        scope.$watch(attr.ngBind, function ngBindWatchAction(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindTemplate\n *\n * @description\n * The `ngBindTemplate` directive specifies that the element\n * text content should be replaced with the interpolation of the template\n * in the `ngBindTemplate` attribute.\n * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`\n * expressions. This directive is needed since some HTML elements\n * (such as TITLE and OPTION) cannot contain SPAN elements.\n *\n * @element ANY\n * @param {string} ngBindTemplate template of form\n *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.\n *\n * @example\n * Try it here: enter text in text box and watch the greeting change.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.salutation = 'Hello';\n             $scope.name = 'World';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n        Salutation: <input type=\"text\" ng-model=\"salutation\"><br>\n        Name: <input type=\"text\" ng-model=\"name\"><br>\n        <pre ng-bind-template=\"{{salutation}} {{name}}!\"></pre>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var salutationElem = element(by.binding('salutation'));\n         var salutationInput = element(by.model('salutation'));\n         var nameInput = element(by.model('name'));\n\n         expect(salutationElem.getText()).toBe('Hello World!');\n\n         salutationInput.clear();\n         salutationInput.sendKeys('Greetings');\n         nameInput.clear();\n         nameInput.sendKeys('user');\n\n         expect(salutationElem.getText()).toBe('Greetings user!');\n       });\n     </file>\n   </example>\n */\nvar ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {\n  return {\n    compile: function ngBindTemplateCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindTemplateLink(scope, element, attr) {\n        var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));\n        $compile.$$addBindingInfo(element, interpolateFn.expressions);\n        element = element[0];\n        attr.$observe('ngBindTemplate', function(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindHtml\n *\n * @description\n * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,\n * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.\n * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link\n * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}\n * in your module's dependencies, you need to include \"angular-sanitize.js\" in your application.\n *\n * You may also bypass sanitization for values you know are safe. To do so, bind to\n * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}.  See the example\n * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.\n *\n * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you\n * will have an exception (instead of an exploit.)\n *\n * @element ANY\n * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.\n *\n * @example\n\n   <example module=\"bindHtmlExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n        <p ng-bind-html=\"myHTML\"></p>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n       angular.module('bindHtmlExample', ['ngSanitize'])\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.myHTML =\n              'I am an <code>HTML</code>string with ' +\n              '<a href=\"#\">links!</a> and other <em>stuff</em>';\n         }]);\n     </file>\n\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind-html', function() {\n         expect(element(by.binding('myHTML')).getText()).toBe(\n             'I am an HTMLstring with links! and other stuff');\n       });\n     </file>\n   </example>\n */\nvar ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {\n  return {\n    restrict: 'A',\n    compile: function ngBindHtmlCompile(tElement, tAttrs) {\n      var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);\n      var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {\n        return (value || '').toString();\n      });\n      $compile.$$addBindingClass(tElement);\n\n      return function ngBindHtmlLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBindHtml);\n\n        scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {\n          // we re-evaluate the expr because we want a TrustedValueHolderType\n          // for $sce, not a string\n          element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');\n        });\n      };\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngChange\n *\n * @description\n * Evaluate the given expression when the user changes the input.\n * The expression is evaluated immediately, unlike the JavaScript onchange event\n * which only triggers at the end of a change (usually, when the user leaves the\n * form element or presses the return key).\n *\n * The `ngChange` expression is only evaluated when a change in the input value causes\n * a new value to be committed to the model.\n *\n * It will not be evaluated:\n * * if the value returned from the `$parsers` transformation pipeline has not changed\n * * if the input has continued to be invalid since the model will stay `null`\n * * if the model is changed programmatically and not by a change to the input value\n *\n *\n * Note, this directive requires `ngModel` to be present.\n *\n * @element input\n * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change\n * in input value.\n *\n * @example\n * <example name=\"ngChange-directive\" module=\"changeExample\">\n *   <file name=\"index.html\">\n *     <script>\n *       angular.module('changeExample', [])\n *         .controller('ExampleController', ['$scope', function($scope) {\n *           $scope.counter = 0;\n *           $scope.change = function() {\n *             $scope.counter++;\n *           };\n *         }]);\n *     </script>\n *     <div ng-controller=\"ExampleController\">\n *       <input type=\"checkbox\" ng-model=\"confirmed\" ng-change=\"change()\" id=\"ng-change-example1\" />\n *       <input type=\"checkbox\" ng-model=\"confirmed\" id=\"ng-change-example2\" />\n *       <label for=\"ng-change-example2\">Confirmed</label><br />\n *       <tt>debug = {{confirmed}}</tt><br/>\n *       <tt>counter = {{counter}}</tt><br/>\n *     </div>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var counter = element(by.binding('counter'));\n *     var debug = element(by.binding('confirmed'));\n *\n *     it('should evaluate the expression if changing from view', function() {\n *       expect(counter.getText()).toContain('0');\n *\n *       element(by.id('ng-change-example1')).click();\n *\n *       expect(counter.getText()).toContain('1');\n *       expect(debug.getText()).toContain('true');\n *     });\n *\n *     it('should not evaluate the expression if changing from model', function() {\n *       element(by.id('ng-change-example2')).click();\n\n *       expect(counter.getText()).toContain('0');\n *       expect(debug.getText()).toContain('true');\n *     });\n *   </file>\n * </example>\n */\nvar ngChangeDirective = valueFn({\n  restrict: 'A',\n  require: 'ngModel',\n  link: function(scope, element, attr, ctrl) {\n    ctrl.$viewChangeListeners.push(function() {\n      scope.$eval(attr.ngChange);\n    });\n  }\n});\n\nfunction classDirective(name, selector) {\n  name = 'ngClass' + name;\n  return ['$animate', function($animate) {\n    return {\n      restrict: 'AC',\n      link: function(scope, element, attr) {\n        var oldVal;\n\n        scope.$watch(attr[name], ngClassWatchAction, true);\n\n        attr.$observe('class', function(value) {\n          ngClassWatchAction(scope.$eval(attr[name]));\n        });\n\n\n        if (name !== 'ngClass') {\n          scope.$watch('$index', function($index, old$index) {\n            // jshint bitwise: false\n            var mod = $index & 1;\n            if (mod !== (old$index & 1)) {\n              var classes = arrayClasses(scope.$eval(attr[name]));\n              mod === selector ?\n                addClasses(classes) :\n                removeClasses(classes);\n            }\n          });\n        }\n\n        function addClasses(classes) {\n          var newClasses = digestClassCounts(classes, 1);\n          attr.$addClass(newClasses);\n        }\n\n        function removeClasses(classes) {\n          var newClasses = digestClassCounts(classes, -1);\n          attr.$removeClass(newClasses);\n        }\n\n        function digestClassCounts(classes, count) {\n          var classCounts = element.data('$classCounts') || {};\n          var classesToUpdate = [];\n          forEach(classes, function(className) {\n            if (count > 0 || classCounts[className]) {\n              classCounts[className] = (classCounts[className] || 0) + count;\n              if (classCounts[className] === +(count > 0)) {\n                classesToUpdate.push(className);\n              }\n            }\n          });\n          element.data('$classCounts', classCounts);\n          return classesToUpdate.join(' ');\n        }\n\n        function updateClasses(oldClasses, newClasses) {\n          var toAdd = arrayDifference(newClasses, oldClasses);\n          var toRemove = arrayDifference(oldClasses, newClasses);\n          toAdd = digestClassCounts(toAdd, 1);\n          toRemove = digestClassCounts(toRemove, -1);\n          if (toAdd && toAdd.length) {\n            $animate.addClass(element, toAdd);\n          }\n          if (toRemove && toRemove.length) {\n            $animate.removeClass(element, toRemove);\n          }\n        }\n\n        function ngClassWatchAction(newVal) {\n          if (selector === true || scope.$index % 2 === selector) {\n            var newClasses = arrayClasses(newVal || []);\n            if (!oldVal) {\n              addClasses(newClasses);\n            } else if (!equals(newVal,oldVal)) {\n              var oldClasses = arrayClasses(oldVal);\n              updateClasses(oldClasses, newClasses);\n            }\n          }\n          oldVal = shallowCopy(newVal);\n        }\n      }\n    };\n\n    function arrayDifference(tokens1, tokens2) {\n      var values = [];\n\n      outer:\n      for (var i = 0; i < tokens1.length; i++) {\n        var token = tokens1[i];\n        for (var j = 0; j < tokens2.length; j++) {\n          if (token == tokens2[j]) continue outer;\n        }\n        values.push(token);\n      }\n      return values;\n    }\n\n    function arrayClasses(classVal) {\n      if (isArray(classVal)) {\n        return classVal;\n      } else if (isString(classVal)) {\n        return classVal.split(' ');\n      } else if (isObject(classVal)) {\n        var classes = [];\n        forEach(classVal, function(v, k) {\n          if (v) {\n            classes = classes.concat(k.split(' '));\n          }\n        });\n        return classes;\n      }\n      return classVal;\n    }\n  }];\n}\n\n/**\n * @ngdoc directive\n * @name ngClass\n * @restrict AC\n *\n * @description\n * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding\n * an expression that represents all classes to be added.\n *\n * The directive operates in three different ways, depending on which of three types the expression\n * evaluates to:\n *\n * 1. If the expression evaluates to a string, the string should be one or more space-delimited class\n * names.\n *\n * 2. If the expression evaluates to an array, each element of the array should be a string that is\n * one or more space-delimited class names.\n *\n * 3. If the expression evaluates to an object, then for each key-value pair of the\n * object with a truthy value the corresponding key is used as a class name.\n *\n * The directive won't add duplicate classes if a particular class was already set.\n *\n * When the expression changes, the previously added classes are removed and only then the\n * new classes are added.\n *\n * @animations\n * **add** - happens just before the class is applied to the elements\n *\n * **remove** - happens just before the class is removed from the element\n *\n * @element ANY\n * @param {expression} ngClass {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class\n *   names, an array, or a map of class names to boolean values. In the case of a map, the\n *   names of the properties whose values are truthy will be added as css classes to the\n *   element.\n *\n * @example Example that demonstrates basic bindings via ngClass directive.\n   <example>\n     <file name=\"index.html\">\n       <p ng-class=\"{strike: deleted, bold: important, red: error}\">Map Syntax Example</p>\n       <input type=\"checkbox\" ng-model=\"deleted\"> deleted (apply \"strike\" class)<br>\n       <input type=\"checkbox\" ng-model=\"important\"> important (apply \"bold\" class)<br>\n       <input type=\"checkbox\" ng-model=\"error\"> error (apply \"red\" class)\n       <hr>\n       <p ng-class=\"style\">Using String Syntax</p>\n       <input type=\"text\" ng-model=\"style\" placeholder=\"Type: bold strike red\">\n       <hr>\n       <p ng-class=\"[style1, style2, style3]\">Using Array Syntax</p>\n       <input ng-model=\"style1\" placeholder=\"Type: bold, strike or red\"><br>\n       <input ng-model=\"style2\" placeholder=\"Type: bold, strike or red\"><br>\n       <input ng-model=\"style3\" placeholder=\"Type: bold, strike or red\"><br>\n     </file>\n     <file name=\"style.css\">\n       .strike {\n         text-decoration: line-through;\n       }\n       .bold {\n           font-weight: bold;\n       }\n       .red {\n           color: red;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var ps = element.all(by.css('p'));\n\n       it('should let you toggle the class', function() {\n\n         expect(ps.first().getAttribute('class')).not.toMatch(/bold/);\n         expect(ps.first().getAttribute('class')).not.toMatch(/red/);\n\n         element(by.model('important')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/bold/);\n\n         element(by.model('error')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/red/);\n       });\n\n       it('should let you toggle string example', function() {\n         expect(ps.get(1).getAttribute('class')).toBe('');\n         element(by.model('style')).clear();\n         element(by.model('style')).sendKeys('red');\n         expect(ps.get(1).getAttribute('class')).toBe('red');\n       });\n\n       it('array example should have 3 classes', function() {\n         expect(ps.last().getAttribute('class')).toBe('');\n         element(by.model('style1')).sendKeys('bold');\n         element(by.model('style2')).sendKeys('strike');\n         element(by.model('style3')).sendKeys('red');\n         expect(ps.last().getAttribute('class')).toBe('bold strike red');\n       });\n     </file>\n   </example>\n\n   ## Animations\n\n   The example below demonstrates how to perform animations using ngClass.\n\n   <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n     <file name=\"index.html\">\n      <input id=\"setbtn\" type=\"button\" value=\"set\" ng-click=\"myVar='my-class'\">\n      <input id=\"clearbtn\" type=\"button\" value=\"clear\" ng-click=\"myVar=''\">\n      <br>\n      <span class=\"base-class\" ng-class=\"myVar\">Sample Text</span>\n     </file>\n     <file name=\"style.css\">\n       .base-class {\n         -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n       }\n\n       .base-class.my-class {\n         color: red;\n         font-size:3em;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class', function() {\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n\n         element(by.id('setbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).\n           toMatch(/my-class/);\n\n         element(by.id('clearbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n       });\n     </file>\n   </example>\n\n\n   ## ngClass and pre-existing CSS3 Transitions/Animations\n   The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.\n   Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder\n   any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure\n   to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and\n   {@link ng.$animate#removeClass $animate.removeClass}.\n */\nvar ngClassDirective = classDirective('', true);\n\n/**\n * @ngdoc directive\n * @name ngClassOdd\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}}\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassOddDirective = classDirective('Odd', 0);\n\n/**\n * @ngdoc directive\n * @name ngClassEven\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The\n *   result of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}} &nbsp; &nbsp; &nbsp;\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassEvenDirective = classDirective('Even', 1);\n\n/**\n * @ngdoc directive\n * @name ngCloak\n * @restrict AC\n *\n * @description\n * The `ngCloak` directive is used to prevent the Angular html template from being briefly\n * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this\n * directive to avoid the undesirable flicker effect caused by the html template display.\n *\n * The directive can be applied to the `<body>` element, but the preferred usage is to apply\n * multiple `ngCloak` directives to small portions of the page to permit progressive rendering\n * of the browser view.\n *\n * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and\n * `angular.min.js`.\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```css\n * [ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {\n *   display: none !important;\n * }\n * ```\n *\n * When this css rule is loaded by the browser, all html elements (including their children) that\n * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive\n * during the compilation of the template it deletes the `ngCloak` element attribute, making\n * the compiled element visible.\n *\n * For the best result, the `angular.js` script must be loaded in the head section of the html\n * document; alternatively, the css rule above must be included in the external stylesheet of the\n * application.\n *\n * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they\n * cannot match the `[ng\\:cloak]` selector. To work around this limitation, you must add the css\n * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.\n *\n * @element ANY\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <div id=\"template1\" ng-cloak>{{ 'hello' }}</div>\n        <div id=\"template2\" ng-cloak class=\"ng-cloak\">{{ 'hello IE7' }}</div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should remove the template directive and css class', function() {\n         expect($('#template1').getAttribute('ng-cloak')).\n           toBeNull();\n         expect($('#template2').getAttribute('ng-cloak')).\n           toBeNull();\n       });\n     </file>\n   </example>\n *\n */\nvar ngCloakDirective = ngDirective({\n  compile: function(element, attr) {\n    attr.$set('ngCloak', undefined);\n    element.removeClass('ng-cloak');\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngController\n *\n * @description\n * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular\n * supports the principles behind the Model-View-Controller design pattern.\n *\n * MVC components in angular:\n *\n * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties\n *   are accessed through bindings.\n * * View — The template (HTML with data bindings) that is rendered into the View.\n * * Controller — The `ngController` directive specifies a Controller class; the class contains business\n *   logic behind the application to decorate the scope with functions and values\n *\n * Note that you can also attach controllers to the DOM by declaring it in a route definition\n * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller\n * again using `ng-controller` in the template itself.  This will cause the controller to be attached\n * and executed twice.\n *\n * @element ANY\n * @scope\n * @priority 500\n * @param {expression} ngController Name of a constructor function registered with the current\n * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}\n * that on the current scope evaluates to a constructor function.\n *\n * The controller instance can be published into a scope property by specifying\n * `ng-controller=\"as propertyName\"`.\n *\n * If the current `$controllerProvider` is configured to use globals (via\n * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may\n * also be the name of a globally accessible constructor function (not recommended).\n *\n * @example\n * Here is a simple form for editing user contact information. Adding, removing, clearing, and\n * greeting are methods declared on the controller (see source tab). These methods can\n * easily be called from the angular markup. Any changes to the data are automatically reflected\n * in the View without the need for a manual update.\n *\n * Two different declaration styles are included below:\n *\n * * one binds methods and properties directly onto the controller using `this`:\n * `ng-controller=\"SettingsController1 as settings\"`\n * * one injects `$scope` into the controller:\n * `ng-controller=\"SettingsController2\"`\n *\n * The second option is more common in the Angular community, and is generally used in boilerplates\n * and in this guide. However, there are advantages to binding properties directly to the controller\n * and avoiding scope.\n *\n * * Using `controller as` makes it obvious which controller you are accessing in the template when\n * multiple controllers apply to an element.\n * * If you are writing your controllers as classes you have easier access to the properties and\n * methods, which will appear on the scope, from inside the controller code.\n * * Since there is always a `.` in the bindings, you don't have to worry about prototypal\n * inheritance masking primitives.\n *\n * This example demonstrates the `controller as` syntax.\n *\n * <example name=\"ngControllerAs\" module=\"controllerAsExample\">\n *   <file name=\"index.html\">\n *    <div id=\"ctrl-as-exmpl\" ng-controller=\"SettingsController1 as settings\">\n *      Name: <input type=\"text\" ng-model=\"settings.name\"/>\n *      [ <a href=\"\" ng-click=\"settings.greet()\">greet</a> ]<br/>\n *      Contact:\n *      <ul>\n *        <li ng-repeat=\"contact in settings.contacts\">\n *          <select ng-model=\"contact.type\">\n *             <option>phone</option>\n *             <option>email</option>\n *          </select>\n *          <input type=\"text\" ng-model=\"contact.value\"/>\n *          [ <a href=\"\" ng-click=\"settings.clearContact(contact)\">clear</a>\n *          | <a href=\"\" ng-click=\"settings.removeContact(contact)\">X</a> ]\n *        </li>\n *        <li>[ <a href=\"\" ng-click=\"settings.addContact()\">add</a> ]</li>\n *     </ul>\n *    </div>\n *   </file>\n *   <file name=\"app.js\">\n *    angular.module('controllerAsExample', [])\n *      .controller('SettingsController1', SettingsController1);\n *\n *    function SettingsController1() {\n *      this.name = \"John Smith\";\n *      this.contacts = [\n *        {type: 'phone', value: '408 555 1212'},\n *        {type: 'email', value: 'john.smith@example.org'} ];\n *    }\n *\n *    SettingsController1.prototype.greet = function() {\n *      alert(this.name);\n *    };\n *\n *    SettingsController1.prototype.addContact = function() {\n *      this.contacts.push({type: 'email', value: 'yourname@example.org'});\n *    };\n *\n *    SettingsController1.prototype.removeContact = function(contactToRemove) {\n *     var index = this.contacts.indexOf(contactToRemove);\n *      this.contacts.splice(index, 1);\n *    };\n *\n *    SettingsController1.prototype.clearContact = function(contact) {\n *      contact.type = 'phone';\n *      contact.value = '';\n *    };\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it('should check controller as', function() {\n *       var container = element(by.id('ctrl-as-exmpl'));\n *         expect(container.element(by.model('settings.name'))\n *           .getAttribute('value')).toBe('John Smith');\n *\n *       var firstRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(0));\n *       var secondRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(1));\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('408 555 1212');\n *\n *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('john.smith@example.org');\n *\n *       firstRepeat.element(by.linkText('clear')).click();\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('');\n *\n *       container.element(by.linkText('add')).click();\n *\n *       expect(container.element(by.repeater('contact in settings.contacts').row(2))\n *           .element(by.model('contact.value'))\n *           .getAttribute('value'))\n *           .toBe('yourname@example.org');\n *     });\n *   </file>\n * </example>\n *\n * This example demonstrates the \"attach to `$scope`\" style of controller.\n *\n * <example name=\"ngController\" module=\"controllerExample\">\n *  <file name=\"index.html\">\n *   <div id=\"ctrl-exmpl\" ng-controller=\"SettingsController2\">\n *     Name: <input type=\"text\" ng-model=\"name\"/>\n *     [ <a href=\"\" ng-click=\"greet()\">greet</a> ]<br/>\n *     Contact:\n *     <ul>\n *       <li ng-repeat=\"contact in contacts\">\n *         <select ng-model=\"contact.type\">\n *            <option>phone</option>\n *            <option>email</option>\n *         </select>\n *         <input type=\"text\" ng-model=\"contact.value\"/>\n *         [ <a href=\"\" ng-click=\"clearContact(contact)\">clear</a>\n *         | <a href=\"\" ng-click=\"removeContact(contact)\">X</a> ]\n *       </li>\n *       <li>[ <a href=\"\" ng-click=\"addContact()\">add</a> ]</li>\n *    </ul>\n *   </div>\n *  </file>\n *  <file name=\"app.js\">\n *   angular.module('controllerExample', [])\n *     .controller('SettingsController2', ['$scope', SettingsController2]);\n *\n *   function SettingsController2($scope) {\n *     $scope.name = \"John Smith\";\n *     $scope.contacts = [\n *       {type:'phone', value:'408 555 1212'},\n *       {type:'email', value:'john.smith@example.org'} ];\n *\n *     $scope.greet = function() {\n *       alert($scope.name);\n *     };\n *\n *     $scope.addContact = function() {\n *       $scope.contacts.push({type:'email', value:'yourname@example.org'});\n *     };\n *\n *     $scope.removeContact = function(contactToRemove) {\n *       var index = $scope.contacts.indexOf(contactToRemove);\n *       $scope.contacts.splice(index, 1);\n *     };\n *\n *     $scope.clearContact = function(contact) {\n *       contact.type = 'phone';\n *       contact.value = '';\n *     };\n *   }\n *  </file>\n *  <file name=\"protractor.js\" type=\"protractor\">\n *    it('should check controller', function() {\n *      var container = element(by.id('ctrl-exmpl'));\n *\n *      expect(container.element(by.model('name'))\n *          .getAttribute('value')).toBe('John Smith');\n *\n *      var firstRepeat =\n *          container.element(by.repeater('contact in contacts').row(0));\n *      var secondRepeat =\n *          container.element(by.repeater('contact in contacts').row(1));\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('408 555 1212');\n *      expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('john.smith@example.org');\n *\n *      firstRepeat.element(by.linkText('clear')).click();\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('');\n *\n *      container.element(by.linkText('add')).click();\n *\n *      expect(container.element(by.repeater('contact in contacts').row(2))\n *          .element(by.model('contact.value'))\n *          .getAttribute('value'))\n *          .toBe('yourname@example.org');\n *    });\n *  </file>\n *</example>\n\n */\nvar ngControllerDirective = [function() {\n  return {\n    restrict: 'A',\n    scope: true,\n    controller: '@',\n    priority: 500\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngCsp\n *\n * @element html\n * @description\n * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.\n *\n * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.\n *\n * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).\n * For Angular to be CSP compatible there are only two things that we need to do differently:\n *\n * - don't use `Function` constructor to generate optimized value getters\n * - don't inject custom stylesheet into the document\n *\n * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`\n * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will\n * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will\n * be raised.\n *\n * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically\n * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).\n * To make those directives work in CSP mode, include the `angular-csp.css` manually.\n *\n * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This\n * autodetection however triggers a CSP error to be logged in the console:\n *\n * ```\n * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of\n * script in the following Content Security Policy directive: \"default-src 'self'\". Note that\n * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.\n * ```\n *\n * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`\n * directive on the root element of the application or on the `angular.js` script tag, whichever\n * appears first in the html document.\n *\n * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*\n *\n * @example\n * This example shows how to apply the `ngCsp` directive to the `html` tag.\n   ```html\n     <!doctype html>\n     <html ng-app ng-csp>\n     ...\n     ...\n     </html>\n   ```\n  * @example\n      // Note: the suffix `.csp` in the example name triggers\n      // csp mode in our http server!\n      <example name=\"example.csp\" module=\"cspExample\" ng-csp=\"true\">\n        <file name=\"index.html\">\n          <div ng-controller=\"MainController as ctrl\">\n            <div>\n              <button ng-click=\"ctrl.inc()\" id=\"inc\">Increment</button>\n              <span id=\"counter\">\n                {{ctrl.counter}}\n              </span>\n            </div>\n\n            <div>\n              <button ng-click=\"ctrl.evil()\" id=\"evil\">Evil</button>\n              <span id=\"evilError\">\n                {{ctrl.evilError}}\n              </span>\n            </div>\n          </div>\n        </file>\n        <file name=\"script.js\">\n           angular.module('cspExample', [])\n             .controller('MainController', function() {\n                this.counter = 0;\n                this.inc = function() {\n                  this.counter++;\n                };\n                this.evil = function() {\n                  // jshint evil:true\n                  try {\n                    eval('1+2');\n                  } catch (e) {\n                    this.evilError = e.message;\n                  }\n                };\n              });\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var util, webdriver;\n\n          var incBtn = element(by.id('inc'));\n          var counter = element(by.id('counter'));\n          var evilBtn = element(by.id('evil'));\n          var evilError = element(by.id('evilError'));\n\n          function getAndClearSevereErrors() {\n            return browser.manage().logs().get('browser').then(function(browserLog) {\n              return browserLog.filter(function(logEntry) {\n                return logEntry.level.value > webdriver.logging.Level.WARNING.value;\n              });\n            });\n          }\n\n          function clearErrors() {\n            getAndClearSevereErrors();\n          }\n\n          function expectNoErrors() {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              expect(filteredLog.length).toEqual(0);\n              if (filteredLog.length) {\n                console.log('browser console errors: ' + util.inspect(filteredLog));\n              }\n            });\n          }\n\n          function expectError(regex) {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              var found = false;\n              filteredLog.forEach(function(log) {\n                if (log.message.match(regex)) {\n                  found = true;\n                }\n              });\n              if (!found) {\n                throw new Error('expected an error that matches ' + regex);\n              }\n            });\n          }\n\n          beforeEach(function() {\n            util = require('util');\n            webdriver = require('protractor/node_modules/selenium-webdriver');\n          });\n\n          // For now, we only test on Chrome,\n          // as Safari does not load the page with Protractor's injected scripts,\n          // and Firefox webdriver always disables content security policy (#6358)\n          if (browser.params.browser !== 'chrome') {\n            return;\n          }\n\n          it('should not report errors when the page is loaded', function() {\n            // clear errors so we are not dependent on previous tests\n            clearErrors();\n            // Need to reload the page as the page is already loaded when\n            // we come here\n            browser.driver.getCurrentUrl().then(function(url) {\n              browser.get(url);\n            });\n            expectNoErrors();\n          });\n\n          it('should evaluate expressions', function() {\n            expect(counter.getText()).toEqual('0');\n            incBtn.click();\n            expect(counter.getText()).toEqual('1');\n            expectNoErrors();\n          });\n\n          it('should throw and report an error when using \"eval\"', function() {\n            evilBtn.click();\n            expect(evilError.getText()).toMatch(/Content Security Policy/);\n            expectError(/Content Security Policy/);\n          });\n        </file>\n      </example>\n  */\n\n// ngCsp is not implemented as a proper directive any more, because we need it be processed while we\n// bootstrap the system (before $parse is instantiated), for this reason we just have\n// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc\n\n/**\n * @ngdoc directive\n * @name ngClick\n *\n * @description\n * The ngClick directive allows you to specify custom behavior when\n * an element is clicked.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon\n * click. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-click=\"count = count + 1\" ng-init=\"count=0\">\n        Increment\n      </button>\n      <span>\n        count: {{count}}\n      </span>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-click', function() {\n         expect(element(by.binding('count')).getText()).toMatch('0');\n         element(by.css('button')).click();\n         expect(element(by.binding('count')).getText()).toMatch('1');\n       });\n     </file>\n   </example>\n */\n/*\n * A collection of directives that allows creation of custom event handlers that are defined as\n * angular expressions and are compiled and executed within the current scope.\n */\nvar ngEventDirectives = {};\n\n// For events that might fire synchronously during DOM manipulation\n// we need to execute their event handlers asynchronously using $evalAsync,\n// so that they are not executed in an inconsistent state.\nvar forceAsyncEvents = {\n  'blur': true,\n  'focus': true\n};\nforEach(\n  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),\n  function(eventName) {\n    var directiveName = directiveNormalize('ng-' + eventName);\n    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {\n      return {\n        restrict: 'A',\n        compile: function($element, attr) {\n          // We expose the powerful $event object on the scope that provides access to the Window,\n          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better\n          // checks at the cost of speed since event handler expressions are not executed as\n          // frequently as regular change detection.\n          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);\n          return function ngEventHandler(scope, element) {\n            element.on(eventName, function(event) {\n              var callback = function() {\n                fn(scope, {$event:event});\n              };\n              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {\n                scope.$evalAsync(callback);\n              } else {\n                scope.$apply(callback);\n              }\n            });\n          };\n        }\n      };\n    }];\n  }\n);\n\n/**\n * @ngdoc directive\n * @name ngDblclick\n *\n * @description\n * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon\n * a dblclick. (The Event object is available as `$event`)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-dblclick=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on double click)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousedown\n *\n * @description\n * The ngMousedown directive allows you to specify custom behavior on mousedown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon\n * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousedown=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse down)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseup\n *\n * @description\n * Specify custom behavior on mouseup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon\n * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseup=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse up)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngMouseover\n *\n * @description\n * Specify custom behavior on mouseover event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon\n * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseover=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse is over)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseenter\n *\n * @description\n * Specify custom behavior on mouseenter event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon\n * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseenter=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse enters)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseleave\n *\n * @description\n * Specify custom behavior on mouseleave event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon\n * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseleave=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse leaves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousemove\n *\n * @description\n * Specify custom behavior on mousemove event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon\n * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousemove=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse moves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeydown\n *\n * @description\n * Specify custom behavior on keydown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon\n * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keydown=\"count = count + 1\" ng-init=\"count=0\">\n      key down count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeyup\n *\n * @description\n * Specify custom behavior on keyup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon\n * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <p>Typing in the input box below updates the key count</p>\n       <input ng-keyup=\"count = count + 1\" ng-init=\"count=0\"> key up count: {{count}}\n\n       <p>Typing in the input box below updates the keycode</p>\n       <input ng-keyup=\"event=$event\">\n       <p>event keyCode: {{ event.keyCode }}</p>\n       <p>event altKey: {{ event.altKey }}</p>\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeypress\n *\n * @description\n * Specify custom behavior on keypress event.\n *\n * @element ANY\n * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon\n * keypress. ({@link guide/expression#-event- Event object is available as `$event`}\n * and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keypress=\"count = count + 1\" ng-init=\"count=0\">\n      key press count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSubmit\n *\n * @description\n * Enables binding angular expressions to onsubmit events.\n *\n * Additionally it prevents the default action (which for form means sending the request to the\n * server and reloading the current page), but only if the form does not contain `action`,\n * `data-action`, or `x-action` attributes.\n *\n * <div class=\"alert alert-warning\">\n * **Warning:** Be careful not to cause \"double-submission\" by using both the `ngClick` and\n * `ngSubmit` handlers together. See the\n * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}\n * for a detailed discussion of when `ngSubmit` may be triggered.\n * </div>\n *\n * @element form\n * @priority 0\n * @param {expression} ngSubmit {@link guide/expression Expression} to eval.\n * ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example module=\"submitExample\">\n     <file name=\"index.html\">\n      <script>\n        angular.module('submitExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.list = [];\n            $scope.text = 'hello';\n            $scope.submit = function() {\n              if ($scope.text) {\n                $scope.list.push(this.text);\n                $scope.text = '';\n              }\n            };\n          }]);\n      </script>\n      <form ng-submit=\"submit()\" ng-controller=\"ExampleController\">\n        Enter text and hit enter:\n        <input type=\"text\" ng-model=\"text\" name=\"text\" />\n        <input type=\"submit\" id=\"submit\" value=\"Submit\" />\n        <pre>list={{list}}</pre>\n      </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-submit', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n         expect(element(by.model('text')).getAttribute('value')).toBe('');\n       });\n       it('should ignore empty strings', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n        });\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngFocus\n *\n * @description\n * Specify custom behavior on focus event.\n *\n * Note: As the `focus` event is executed synchronously when calling `input.focus()`\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon\n * focus. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngBlur\n *\n * @description\n * Specify custom behavior on blur event.\n *\n * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when\n * an element has lost focus.\n *\n * Note: As the `blur` event is executed synchronously also during DOM manipulations\n * (e.g. removing a focussed input),\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon\n * blur. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngCopy\n *\n * @description\n * Specify custom behavior on copy event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon\n * copy. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-copy=\"copied=true\" ng-init=\"copied=false; value='copy me'\" ng-model=\"value\">\n      copied: {{copied}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngCut\n *\n * @description\n * Specify custom behavior on cut event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon\n * cut. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-cut=\"cut=true\" ng-init=\"cut=false; value='cut me'\" ng-model=\"value\">\n      cut: {{cut}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngPaste\n *\n * @description\n * Specify custom behavior on paste event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon\n * paste. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-paste=\"paste=true\" ng-init=\"paste=false\" placeholder='paste here'>\n      pasted: {{paste}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngIf\n * @restrict A\n *\n * @description\n * The `ngIf` directive removes or recreates a portion of the DOM tree based on an\n * {expression}. If the expression assigned to `ngIf` evaluates to a false\n * value then the element is removed from the DOM, otherwise a clone of the\n * element is reinserted into the DOM.\n *\n * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the\n * element in the DOM rather than changing its visibility via the `display` css property.  A common\n * case when this difference is significant is when using css selectors that rely on an element's\n * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.\n *\n * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope\n * is created when the element is restored.  The scope created within `ngIf` inherits from\n * its parent scope using\n * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).\n * An important implication of this is if `ngModel` is used within `ngIf` to bind to\n * a javascript primitive defined in the parent scope. In this case any modifications made to the\n * variable within the child scope will override (hide) the value in the parent scope.\n *\n * Also, `ngIf` recreates elements using their compiled state. An example of this behavior\n * is if an element's class attribute is directly modified after it's compiled, using something like\n * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element\n * the added class will be lost because the original compiled state is used to regenerate the element.\n *\n * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`\n * and `leave` effects.\n *\n * @animations\n * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container\n * leave - happens just before the `ngIf` contents are removed from the DOM\n *\n * @element ANY\n * @scope\n * @priority 600\n * @param {expression} ngIf If the {@link guide/expression expression} is falsy then\n *     the element is removed from the DOM tree. If it is truthy a copy of the compiled\n *     element is added to the DOM tree.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\" ng-init=\"checked=true\" /><br/>\n      Show when checked:\n      <span ng-if=\"checked\" class=\"animate-if\">\n        This is removed when the checkbox is unchecked.\n      </span>\n    </file>\n    <file name=\"animations.css\">\n      .animate-if {\n        background:white;\n        border:1px solid black;\n        padding:10px;\n      }\n\n      .animate-if.ng-enter, .animate-if.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n      }\n\n      .animate-if.ng-enter,\n      .animate-if.ng-leave.ng-leave-active {\n        opacity:0;\n      }\n\n      .animate-if.ng-leave,\n      .animate-if.ng-enter.ng-enter-active {\n        opacity:1;\n      }\n    </file>\n  </example>\n */\nvar ngIfDirective = ['$animate', function($animate) {\n  return {\n    multiElement: true,\n    transclude: 'element',\n    priority: 600,\n    terminal: true,\n    restrict: 'A',\n    $$tlb: true,\n    link: function($scope, $element, $attr, ctrl, $transclude) {\n        var block, childScope, previousElements;\n        $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {\n\n          if (value) {\n            if (!childScope) {\n              $transclude(function(clone, newScope) {\n                childScope = newScope;\n                clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block = {\n                  clone: clone\n                };\n                $animate.enter(clone, $element.parent(), $element);\n              });\n            }\n          } else {\n            if (previousElements) {\n              previousElements.remove();\n              previousElements = null;\n            }\n            if (childScope) {\n              childScope.$destroy();\n              childScope = null;\n            }\n            if (block) {\n              previousElements = getBlockNodes(block.clone);\n              $animate.leave(previousElements).then(function() {\n                previousElements = null;\n              });\n              block = null;\n            }\n          }\n        });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngInclude\n * @restrict ECA\n *\n * @description\n * Fetches, compiles and includes an external HTML fragment.\n *\n * By default, the template URL is restricted to the same domain and protocol as the\n * application document. This is done by calling {@link $sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols\n * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or\n * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link\n * ng.$sce Strict Contextual Escaping}.\n *\n * In addition, the browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy may further restrict whether the template is successfully loaded.\n * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`\n * access on some browsers.\n *\n * @animations\n * enter - animation is used to bring new content into the browser.\n * leave - animation is used to animate existing content away.\n *\n * The enter and leave animation occur concurrently.\n *\n * @scope\n * @priority 400\n *\n * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,\n *                 make sure you wrap it in **single** quotes, e.g. `src=\"'myPartialTemplate.html'\"`.\n * @param {string=} onload Expression to evaluate when a new partial is loaded.\n *\n * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll\n *                  $anchorScroll} to scroll the viewport after the content is loaded.\n *\n *                  - If the attribute is not set, disable scrolling.\n *                  - If the attribute is set without value, enable scrolling.\n *                  - Otherwise enable scrolling only if the expression evaluates to truthy value.\n *\n * @example\n  <example module=\"includeExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n     <div ng-controller=\"ExampleController\">\n       <select ng-model=\"template\" ng-options=\"t.name for t in templates\">\n        <option value=\"\">(blank)</option>\n       </select>\n       url of the template: <code>{{template.url}}</code>\n       <hr/>\n       <div class=\"slide-animate-container\">\n         <div class=\"slide-animate\" ng-include=\"template.url\"></div>\n       </div>\n     </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('includeExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.templates =\n            [ { name: 'template1.html', url: 'template1.html'},\n              { name: 'template2.html', url: 'template2.html'} ];\n          $scope.template = $scope.templates[0];\n        }]);\n     </file>\n    <file name=\"template1.html\">\n      Content of template1.html\n    </file>\n    <file name=\"template2.html\">\n      Content of template2.html\n    </file>\n    <file name=\"animations.css\">\n      .slide-animate-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .slide-animate {\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter, .slide-animate.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n        display:block;\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter {\n        top:-50px;\n      }\n      .slide-animate.ng-enter.ng-enter-active {\n        top:0;\n      }\n\n      .slide-animate.ng-leave {\n        top:0;\n      }\n      .slide-animate.ng-leave.ng-leave-active {\n        top:50px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var templateSelect = element(by.model('template'));\n      var includeElem = element(by.css('[ng-include]'));\n\n      it('should load template1.html', function() {\n        expect(includeElem.getText()).toMatch(/Content of template1.html/);\n      });\n\n      it('should load template2.html', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          // See https://github.com/angular/protractor/issues/480\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(2).click();\n        expect(includeElem.getText()).toMatch(/Content of template2.html/);\n      });\n\n      it('should change to blank', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(0).click();\n        expect(includeElem.isPresent()).toBe(false);\n      });\n    </file>\n  </example>\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentRequested\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted every time the ngInclude content is requested.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentLoaded\n * @eventType emit on the current ngInclude scope\n * @description\n * Emitted every time the ngInclude content is reloaded.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentError\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\nvar ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',\n                  function($templateRequest,   $anchorScroll,   $animate,   $sce) {\n  return {\n    restrict: 'ECA',\n    priority: 400,\n    terminal: true,\n    transclude: 'element',\n    controller: angular.noop,\n    compile: function(element, attr) {\n      var srcExp = attr.ngInclude || attr.src,\n          onloadExp = attr.onload || '',\n          autoScrollExp = attr.autoscroll;\n\n      return function(scope, $element, $attr, ctrl, $transclude) {\n        var changeCounter = 0,\n            currentScope,\n            previousElement,\n            currentElement;\n\n        var cleanupLastIncludeContent = function() {\n          if (previousElement) {\n            previousElement.remove();\n            previousElement = null;\n          }\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n          if (currentElement) {\n            $animate.leave(currentElement).then(function() {\n              previousElement = null;\n            });\n            previousElement = currentElement;\n            currentElement = null;\n          }\n        };\n\n        scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {\n          var afterAnimation = function() {\n            if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {\n              $anchorScroll();\n            }\n          };\n          var thisChangeId = ++changeCounter;\n\n          if (src) {\n            //set the 2nd param to true to ignore the template request error so that the inner\n            //contents and scope can be cleaned up.\n            $templateRequest(src, true).then(function(response) {\n              if (thisChangeId !== changeCounter) return;\n              var newScope = scope.$new();\n              ctrl.template = response;\n\n              // Note: This will also link all children of ng-include that were contained in the original\n              // html. If that content contains controllers, ... they could pollute/change the scope.\n              // However, using ng-include on an element with additional content does not make sense...\n              // Note: We can't remove them in the cloneAttchFn of $transclude as that\n              // function is called before linking the content, which would apply child\n              // directives to non existing elements.\n              var clone = $transclude(newScope, function(clone) {\n                cleanupLastIncludeContent();\n                $animate.enter(clone, null, $element).then(afterAnimation);\n              });\n\n              currentScope = newScope;\n              currentElement = clone;\n\n              currentScope.$emit('$includeContentLoaded', src);\n              scope.$eval(onloadExp);\n            }, function() {\n              if (thisChangeId === changeCounter) {\n                cleanupLastIncludeContent();\n                scope.$emit('$includeContentError', src);\n              }\n            });\n            scope.$emit('$includeContentRequested', src);\n          } else {\n            cleanupLastIncludeContent();\n            ctrl.template = null;\n          }\n        });\n      };\n    }\n  };\n}];\n\n// This directive is called during the $transclude call of the first `ngInclude` directive.\n// It will replace and compile the content of the element with the loaded template.\n// We need this directive so that the element content is already filled when\n// the link function of another directive on the same element as ngInclude\n// is called.\nvar ngIncludeFillContentDirective = ['$compile',\n  function($compile) {\n    return {\n      restrict: 'ECA',\n      priority: -400,\n      require: 'ngInclude',\n      link: function(scope, $element, $attr, ctrl) {\n        if (/SVG/.test($element[0].toString())) {\n          // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not\n          // support innerHTML, so detect this here and try to generate the contents\n          // specially.\n          $element.empty();\n          $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,\n              function namespaceAdaptedClone(clone) {\n            $element.append(clone);\n          }, {futureParentElement: $element});\n          return;\n        }\n\n        $element.html(ctrl.template);\n        $compile($element.contents())(scope);\n      }\n    };\n  }];\n\n/**\n * @ngdoc directive\n * @name ngInit\n * @restrict AC\n *\n * @description\n * The `ngInit` directive allows you to evaluate an expression in the\n * current scope.\n *\n * <div class=\"alert alert-error\">\n * The only appropriate use of `ngInit` is for aliasing special properties of\n * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you\n * should use {@link guide/controller controllers} rather than `ngInit`\n * to initialize values on a scope.\n * </div>\n * <div class=\"alert alert-warning\">\n * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make\n * sure you have parenthesis for correct precedence:\n * <pre class=\"prettyprint\">\n * `<div ng-init=\"test1 = (data | orderBy:'name')\"></div>`\n * </pre>\n * </div>\n *\n * @priority 450\n *\n * @element ANY\n * @param {expression} ngInit {@link guide/expression Expression} to eval.\n *\n * @example\n   <example module=\"initExample\">\n     <file name=\"index.html\">\n   <script>\n     angular.module('initExample', [])\n       .controller('ExampleController', ['$scope', function($scope) {\n         $scope.list = [['a', 'b'], ['c', 'd']];\n       }]);\n   </script>\n   <div ng-controller=\"ExampleController\">\n     <div ng-repeat=\"innerList in list\" ng-init=\"outerIndex = $index\">\n       <div ng-repeat=\"value in innerList\" ng-init=\"innerIndex = $index\">\n          <span class=\"example-init\">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>\n       </div>\n     </div>\n   </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should alias index positions', function() {\n         var elements = element.all(by.css('.example-init'));\n         expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');\n         expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');\n         expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');\n         expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');\n       });\n     </file>\n   </example>\n */\nvar ngInitDirective = ngDirective({\n  priority: 450,\n  compile: function() {\n    return {\n      pre: function(scope, element, attrs) {\n        scope.$eval(attrs.ngInit);\n      }\n    };\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngList\n *\n * @description\n * Text input that converts between a delimited string and an array of strings. The default\n * delimiter is a comma followed by a space - equivalent to `ng-list=\", \"`. You can specify a custom\n * delimiter as the value of the `ngList` attribute - for example, `ng-list=\" | \"`.\n *\n * The behaviour of the directive is affected by the use of the `ngTrim` attribute.\n * * If `ngTrim` is set to `\"false\"` then whitespace around both the separator and each\n *   list item is respected. This implies that the user of the directive is responsible for\n *   dealing with whitespace but also allows you to use whitespace as a delimiter, such as a\n *   tab or newline character.\n * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected\n *   when joining the list items back together) and whitespace around each list item is stripped\n *   before it is added to the model.\n *\n * ### Example with Validation\n *\n * <example name=\"ngList-directive\" module=\"listExample\">\n *   <file name=\"app.js\">\n *      angular.module('listExample', [])\n *        .controller('ExampleController', ['$scope', function($scope) {\n *          $scope.names = ['morpheus', 'neo', 'trinity'];\n *        }]);\n *   </file>\n *   <file name=\"index.html\">\n *    <form name=\"myForm\" ng-controller=\"ExampleController\">\n *      List: <input name=\"namesInput\" ng-model=\"names\" ng-list required>\n *      <span class=\"error\" ng-show=\"myForm.namesInput.$error.required\">\n *        Required!</span>\n *      <br>\n *      <tt>names = {{names}}</tt><br/>\n *      <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>\n *      <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>\n *      <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n *      <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n *     </form>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var listInput = element(by.model('names'));\n *     var names = element(by.exactBinding('names'));\n *     var valid = element(by.binding('myForm.namesInput.$valid'));\n *     var error = element(by.css('span.error'));\n *\n *     it('should initialize to model', function() {\n *       expect(names.getText()).toContain('[\"morpheus\",\"neo\",\"trinity\"]');\n *       expect(valid.getText()).toContain('true');\n *       expect(error.getCssValue('display')).toBe('none');\n *     });\n *\n *     it('should be invalid if empty', function() {\n *       listInput.clear();\n *       listInput.sendKeys('');\n *\n *       expect(names.getText()).toContain('');\n *       expect(valid.getText()).toContain('false');\n *       expect(error.getCssValue('display')).not.toBe('none');\n *     });\n *   </file>\n * </example>\n *\n * ### Example - splitting on whitespace\n * <example name=\"ngList-directive-newlines\">\n *   <file name=\"index.html\">\n *    <textarea ng-model=\"list\" ng-list=\"&#10;\" ng-trim=\"false\"></textarea>\n *    <pre>{{ list | json }}</pre>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it(\"should split the text by newlines\", function() {\n *       var listInput = element(by.model('list'));\n *       var output = element(by.binding('list | json'));\n *       listInput.sendKeys('abc\\ndef\\nghi');\n *       expect(output.getText()).toContain('[\\n  \"abc\",\\n  \"def\",\\n  \"ghi\"\\n]');\n *     });\n *   </file>\n * </example>\n *\n * @element input\n * @param {string=} ngList optional delimiter that should be used to split the value.\n */\nvar ngListDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    require: 'ngModel',\n    link: function(scope, element, attr, ctrl) {\n      // We want to control whitespace trimming so we use this convoluted approach\n      // to access the ngList attribute, which doesn't pre-trim the attribute\n      var ngList = element.attr(attr.$attr.ngList) || ', ';\n      var trimValues = attr.ngTrim !== 'false';\n      var separator = trimValues ? trim(ngList) : ngList;\n\n      var parse = function(viewValue) {\n        // If the viewValue is invalid (say required but empty) it will be `undefined`\n        if (isUndefined(viewValue)) return;\n\n        var list = [];\n\n        if (viewValue) {\n          forEach(viewValue.split(separator), function(value) {\n            if (value) list.push(trimValues ? trim(value) : value);\n          });\n        }\n\n        return list;\n      };\n\n      ctrl.$parsers.push(parse);\n      ctrl.$formatters.push(function(value) {\n        if (isArray(value)) {\n          return value.join(ngList);\n        }\n\n        return undefined;\n      });\n\n      // Override the standard $isEmpty because an empty array means the input is empty.\n      ctrl.$isEmpty = function(value) {\n        return !value || !value.length;\n      };\n    }\n  };\n};\n\n/* global VALID_CLASS: true,\n  INVALID_CLASS: true,\n  PRISTINE_CLASS: true,\n  DIRTY_CLASS: true,\n  UNTOUCHED_CLASS: true,\n  TOUCHED_CLASS: true,\n*/\n\nvar VALID_CLASS = 'ng-valid',\n    INVALID_CLASS = 'ng-invalid',\n    PRISTINE_CLASS = 'ng-pristine',\n    DIRTY_CLASS = 'ng-dirty',\n    UNTOUCHED_CLASS = 'ng-untouched',\n    TOUCHED_CLASS = 'ng-touched',\n    PENDING_CLASS = 'ng-pending';\n\n\nvar $ngModelMinErr = new minErr('ngModel');\n\n/**\n * @ngdoc type\n * @name ngModel.NgModelController\n *\n * @property {string} $viewValue Actual string value in the view.\n * @property {*} $modelValue The value in the model that the control is bound to.\n * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever\n       the control reads value from the DOM. The functions are called in array order, each passing\n       its return value through to the next. The last return value is forwarded to the\n       {@link ngModel.NgModelController#$validators `$validators`} collection.\n\nParsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue\n`$viewValue`}.\n\nReturning `undefined` from a parser means a parse error occurred. In that case,\nno {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`\nwill be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}\nis set to `true`. The parse error is stored in `ngModel.$error.parse`.\n\n *\n * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever\n       the model value changes. The functions are called in reverse array order, each passing the value through to the\n       next. The last return value is used as the actual DOM value.\n       Used to format / convert values for display in the control.\n * ```js\n * function formatter(value) {\n *   if (value) {\n *     return value.toUpperCase();\n *   }\n * }\n * ngModel.$formatters.push(formatter);\n * ```\n *\n * @property {Object.<string, function>} $validators A collection of validators that are applied\n *      whenever the model value changes. The key value within the object refers to the name of the\n *      validator while the function refers to the validation operation. The validation operation is\n *      provided with the model value as an argument and must return a true or false value depending\n *      on the response of that validation.\n *\n * ```js\n * ngModel.$validators.validCharacters = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *   return /[0-9]+/.test(value) &&\n *          /[a-z]+/.test(value) &&\n *          /[A-Z]+/.test(value) &&\n *          /\\W+/.test(value);\n * };\n * ```\n *\n * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to\n *      perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided\n *      is expected to return a promise when it is run during the model validation process. Once the promise\n *      is delivered then the validation status will be set to true when fulfilled and false when rejected.\n *      When the asynchronous validators are triggered, each of the validators will run in parallel and the model\n *      value will only be updated once all validators have been fulfilled. As long as an asynchronous validator\n *      is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators\n *      will only run once all synchronous validators have passed.\n *\n * Please note that if $http is used then it is important that the server returns a success HTTP response code\n * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.\n *\n * ```js\n * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *\n *   // Lookup user by username\n *   return $http.get('/api/users/' + value).\n *      then(function resolved() {\n *        //username exists, this means validation fails\n *        return $q.reject('exists');\n *      }, function rejected() {\n *        //username does not exist, therefore this validation passes\n *        return true;\n *      });\n * };\n * ```\n *\n * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the\n *     view value has changed. It is called with no arguments, and its return value is ignored.\n *     This can be used in place of additional $watches against the model value.\n *\n * @property {Object} $error An object hash with all failing validator ids as keys.\n * @property {Object} $pending An object hash with all pending validator ids as keys.\n *\n * @property {boolean} $untouched True if control has not lost focus yet.\n * @property {boolean} $touched True if control has lost focus.\n * @property {boolean} $pristine True if user has not interacted with the control yet.\n * @property {boolean} $dirty True if user has already interacted with the control.\n * @property {boolean} $valid True if there is no error.\n * @property {boolean} $invalid True if at least one error on the control.\n * @property {string} $name The name attribute of the control.\n *\n * @description\n *\n * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.\n * The controller contains services for data-binding, validation, CSS updates, and value formatting\n * and parsing. It purposefully does not contain any logic which deals with DOM rendering or\n * listening to DOM events.\n * Such DOM related logic should be provided by other directives which make use of\n * `NgModelController` for data-binding to control elements.\n * Angular provides this DOM logic for most {@link input `input`} elements.\n * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example\n * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.\n *\n * @example\n * ### Custom Control Example\n * This example shows how to use `NgModelController` with a custom control to achieve\n * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)\n * collaborate together to achieve the desired result.\n *\n * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element\n * contents be edited in place by the user.  This will not work on older browsers.\n *\n * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}\n * module to automatically remove \"bad\" content like inline event listener (e.g. `<span onclick=\"...\">`).\n * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks\n * that content using the `$sce` service.\n *\n * <example name=\"NgModelController\" module=\"customControl\" deps=\"angular-sanitize.js\">\n    <file name=\"style.css\">\n      [contenteditable] {\n        border: 1px solid black;\n        background-color: white;\n        min-height: 20px;\n      }\n\n      .ng-invalid {\n        border: 1px solid red;\n      }\n\n    </file>\n    <file name=\"script.js\">\n      angular.module('customControl', ['ngSanitize']).\n        directive('contenteditable', ['$sce', function($sce) {\n          return {\n            restrict: 'A', // only activate on element attribute\n            require: '?ngModel', // get a hold of NgModelController\n            link: function(scope, element, attrs, ngModel) {\n              if (!ngModel) return; // do nothing if no ng-model\n\n              // Specify how UI should be updated\n              ngModel.$render = function() {\n                element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));\n              };\n\n              // Listen for change events to enable binding\n              element.on('blur keyup change', function() {\n                scope.$evalAsync(read);\n              });\n              read(); // initialize\n\n              // Write data to the model\n              function read() {\n                var html = element.html();\n                // When we clear the content editable the browser leaves a <br> behind\n                // If strip-br attribute is provided then we strip this out\n                if ( attrs.stripBr && html == '<br>' ) {\n                  html = '';\n                }\n                ngModel.$setViewValue(html);\n              }\n            }\n          };\n        }]);\n    </file>\n    <file name=\"index.html\">\n      <form name=\"myForm\">\n       <div contenteditable\n            name=\"myWidget\" ng-model=\"userContent\"\n            strip-br=\"true\"\n            required>Change me!</div>\n        <span ng-show=\"myForm.myWidget.$error.required\">Required!</span>\n       <hr>\n       <textarea ng-model=\"userContent\"></textarea>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n    it('should data-bind and become invalid', function() {\n      if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {\n        // SafariDriver can't handle contenteditable\n        // and Firefox driver can't clear contenteditables very well\n        return;\n      }\n      var contentEditable = element(by.css('[contenteditable]'));\n      var content = 'Change me!';\n\n      expect(contentEditable.getText()).toEqual(content);\n\n      contentEditable.clear();\n      contentEditable.sendKeys(protractor.Key.BACK_SPACE);\n      expect(contentEditable.getText()).toEqual('');\n      expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);\n    });\n    </file>\n * </example>\n *\n *\n */\nvar NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',\n    function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {\n  this.$viewValue = Number.NaN;\n  this.$modelValue = Number.NaN;\n  this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.\n  this.$validators = {};\n  this.$asyncValidators = {};\n  this.$parsers = [];\n  this.$formatters = [];\n  this.$viewChangeListeners = [];\n  this.$untouched = true;\n  this.$touched = false;\n  this.$pristine = true;\n  this.$dirty = false;\n  this.$valid = true;\n  this.$invalid = false;\n  this.$error = {}; // keep invalid keys here\n  this.$$success = {}; // keep valid keys here\n  this.$pending = undefined; // keep pending keys here\n  this.$name = $interpolate($attr.name || '', false)($scope);\n\n\n  var parsedNgModel = $parse($attr.ngModel),\n      parsedNgModelAssign = parsedNgModel.assign,\n      ngModelGet = parsedNgModel,\n      ngModelSet = parsedNgModelAssign,\n      pendingDebounce = null,\n      ctrl = this;\n\n  this.$$setOptions = function(options) {\n    ctrl.$options = options;\n    if (options && options.getterSetter) {\n      var invokeModelGetter = $parse($attr.ngModel + '()'),\n          invokeModelSetter = $parse($attr.ngModel + '($$$p)');\n\n      ngModelGet = function($scope) {\n        var modelValue = parsedNgModel($scope);\n        if (isFunction(modelValue)) {\n          modelValue = invokeModelGetter($scope);\n        }\n        return modelValue;\n      };\n      ngModelSet = function($scope, newValue) {\n        if (isFunction(parsedNgModel($scope))) {\n          invokeModelSetter($scope, {$$$p: ctrl.$modelValue});\n        } else {\n          parsedNgModelAssign($scope, ctrl.$modelValue);\n        }\n      };\n    } else if (!parsedNgModel.assign) {\n      throw $ngModelMinErr('nonassign', \"Expression '{0}' is non-assignable. Element: {1}\",\n          $attr.ngModel, startingTag($element));\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$render\n   *\n   * @description\n   * Called when the view needs to be updated. It is expected that the user of the ng-model\n   * directive will implement this method.\n   *\n   * The `$render()` method is invoked in the following situations:\n   *\n   * * `$rollbackViewValue()` is called.  If we are rolling back the view value to the last\n   *   committed value then `$render()` is called to update the input control.\n   * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and\n   *   the `$viewValue` are different to last time.\n   *\n   * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of\n   * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`\n   * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be\n   * invoked if you only change a property on the objects.\n   */\n  this.$render = noop;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$isEmpty\n   *\n   * @description\n   * This is called when we need to determine if the value of an input is empty.\n   *\n   * For instance, the required directive does this to work out if the input has data or not.\n   *\n   * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.\n   *\n   * You can override this for input directives whose concept of being empty is different to the\n   * default. The `checkboxInputType` directive does this because in its case a value of `false`\n   * implies empty.\n   *\n   * @param {*} value The value of the input to check for emptiness.\n   * @returns {boolean} True if `value` is \"empty\".\n   */\n  this.$isEmpty = function(value) {\n    return isUndefined(value) || value === '' || value === null || value !== value;\n  };\n\n  var parentForm = $element.inheritedData('$formController') || nullFormCtrl,\n      currentValidationRunId = 0;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setValidity\n   *\n   * @description\n   * Change the validity state, and notify the form.\n   *\n   * This method can be called within $parsers/$formatters or a custom validation implementation.\n   * However, in most cases it should be sufficient to use the `ngModel.$validators` and\n   * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.\n   *\n   * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned\n   *        to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`\n   *        (for unfulfilled `$asyncValidators`), so that it is available for data-binding.\n   *        The `validationErrorKey` should be in camelCase and will get converted into dash-case\n   *        for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`\n   *        class and can be bound to as  `{{someForm.someControl.$error.myError}}` .\n   * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),\n   *                          or skipped (null). Pending is used for unfulfilled `$asyncValidators`.\n   *                          Skipped is used by Angular when validators do not run because of parse errors and\n   *                          when `$asyncValidators` do not run because any of the `$validators` failed.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: $element,\n    set: function(object, property) {\n      object[property] = true;\n    },\n    unset: function(object, property) {\n      delete object[property];\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setPristine\n   *\n   * @description\n   * Sets the control to its pristine state.\n   *\n   * This method can be called to remove the `ng-dirty` class and set the control to its pristine\n   * state (`ng-pristine` class). A model is considered to be pristine when the control\n   * has not been changed from when first compiled.\n   */\n  this.$setPristine = function() {\n    ctrl.$dirty = false;\n    ctrl.$pristine = true;\n    $animate.removeClass($element, DIRTY_CLASS);\n    $animate.addClass($element, PRISTINE_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setDirty\n   *\n   * @description\n   * Sets the control to its dirty state.\n   *\n   * This method can be called to remove the `ng-pristine` class and set the control to its dirty\n   * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed\n   * from when first compiled.\n   */\n  this.$setDirty = function() {\n    ctrl.$dirty = true;\n    ctrl.$pristine = false;\n    $animate.removeClass($element, PRISTINE_CLASS);\n    $animate.addClass($element, DIRTY_CLASS);\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setUntouched\n   *\n   * @description\n   * Sets the control to its untouched state.\n   *\n   * This method can be called to remove the `ng-touched` class and set the control to its\n   * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched\n   * by default, however this function can be used to restore that state if the model has\n   * already been touched by the user.\n   */\n  this.$setUntouched = function() {\n    ctrl.$touched = false;\n    ctrl.$untouched = true;\n    $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setTouched\n   *\n   * @description\n   * Sets the control to its touched state.\n   *\n   * This method can be called to remove the `ng-untouched` class and set the control to its\n   * touched state (`ng-touched` class). A model is considered to be touched when the user has\n   * first focused the control element and then shifted focus away from the control (blur event).\n   */\n  this.$setTouched = function() {\n    ctrl.$touched = true;\n    ctrl.$untouched = false;\n    $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$rollbackViewValue\n   *\n   * @description\n   * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,\n   * which may be caused by a pending debounced event or because the input is waiting for a some\n   * future event.\n   *\n   * If you have an input that uses `ng-model-options` to set up debounced events or events such\n   * as blur you can have a situation where there is a period when the `$viewValue`\n   * is out of synch with the ngModel's `$modelValue`.\n   *\n   * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`\n   * programmatically before these debounced/future events have resolved/occurred, because Angular's\n   * dirty checking mechanism is not able to tell whether the model has actually changed or not.\n   *\n   * The `$rollbackViewValue()` method should be called before programmatically changing the model of an\n   * input which may have such events pending. This is important in order to make sure that the\n   * input field will be updated with the new model value and any pending operations are cancelled.\n   *\n   * <example name=\"ng-model-cancel-update\" module=\"cancel-update-example\">\n   *   <file name=\"app.js\">\n   *     angular.module('cancel-update-example', [])\n   *\n   *     .controller('CancelUpdateController', ['$scope', function($scope) {\n   *       $scope.resetWithCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myForm.myInput1.$rollbackViewValue();\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *       $scope.resetWithoutCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *     }]);\n   *   </file>\n   *   <file name=\"index.html\">\n   *     <div ng-controller=\"CancelUpdateController\">\n   *       <p>Try typing something in each input.  See that the model only updates when you\n   *          blur off the input.\n   *        </p>\n   *        <p>Now see what happens if you start typing then press the Escape key</p>\n   *\n   *       <form name=\"myForm\" ng-model-options=\"{ updateOn: 'blur' }\">\n   *         <p>With $rollbackViewValue()</p>\n   *         <input name=\"myInput1\" ng-model=\"myValue\" ng-keydown=\"resetWithCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *\n   *         <p>Without $rollbackViewValue()</p>\n   *         <input name=\"myInput2\" ng-model=\"myValue\" ng-keydown=\"resetWithoutCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *       </form>\n   *     </div>\n   *   </file>\n   * </example>\n   */\n  this.$rollbackViewValue = function() {\n    $timeout.cancel(pendingDebounce);\n    ctrl.$viewValue = ctrl.$$lastCommittedViewValue;\n    ctrl.$render();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$validate\n   *\n   * @description\n   * Runs each of the registered validators (first synchronous validators and then\n   * asynchronous validators).\n   * If the validity changes to invalid, the model will be set to `undefined`,\n   * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.\n   * If the validity changes to valid, it will set the model to the last available valid\n   * modelValue, i.e. either the last parsed value or the last value set from the scope.\n   */\n  this.$validate = function() {\n    // ignore $validate before model is initialized\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      return;\n    }\n\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    // Note: we use the $$rawModelValue as $modelValue might have been\n    // set to undefined during a view -> model update that found validation\n    // errors. We can't parse the view here, since that could change\n    // the model although neither viewValue nor the model on the scope changed\n    var modelValue = ctrl.$$rawModelValue;\n\n    // Check if the there's a parse error, so we don't unset it accidentially\n    var parserName = ctrl.$$parserName || 'parse';\n    var parserValid = ctrl.$error[parserName] ? false : undefined;\n\n    var prevValid = ctrl.$valid;\n    var prevModelValue = ctrl.$modelValue;\n\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n\n    ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {\n      // If there was no change in validity, don't update the model\n      // This prevents changing an invalid modelValue to undefined\n      if (!allowInvalid && prevValid !== allValid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n\n        if (ctrl.$modelValue !== prevModelValue) {\n          ctrl.$$writeModelToScope();\n        }\n      }\n    });\n\n  };\n\n  this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {\n    currentValidationRunId++;\n    var localValidationRunId = currentValidationRunId;\n\n    // check parser error\n    if (!processParseErrors(parseValid)) {\n      validationDone(false);\n      return;\n    }\n    if (!processSyncValidators()) {\n      validationDone(false);\n      return;\n    }\n    processAsyncValidators();\n\n    function processParseErrors(parseValid) {\n      var errorKey = ctrl.$$parserName || 'parse';\n      if (parseValid === undefined) {\n        setValidity(errorKey, null);\n      } else {\n        setValidity(errorKey, parseValid);\n        if (!parseValid) {\n          forEach(ctrl.$validators, function(v, name) {\n            setValidity(name, null);\n          });\n          forEach(ctrl.$asyncValidators, function(v, name) {\n            setValidity(name, null);\n          });\n          return false;\n        }\n      }\n      return true;\n    }\n\n    function processSyncValidators() {\n      var syncValidatorsValid = true;\n      forEach(ctrl.$validators, function(validator, name) {\n        var result = validator(modelValue, viewValue);\n        syncValidatorsValid = syncValidatorsValid && result;\n        setValidity(name, result);\n      });\n      if (!syncValidatorsValid) {\n        forEach(ctrl.$asyncValidators, function(v, name) {\n          setValidity(name, null);\n        });\n        return false;\n      }\n      return true;\n    }\n\n    function processAsyncValidators() {\n      var validatorPromises = [];\n      var allValid = true;\n      forEach(ctrl.$asyncValidators, function(validator, name) {\n        var promise = validator(modelValue, viewValue);\n        if (!isPromiseLike(promise)) {\n          throw $ngModelMinErr(\"$asyncValidators\",\n            \"Expected asynchronous validator to return a promise but got '{0}' instead.\", promise);\n        }\n        setValidity(name, undefined);\n        validatorPromises.push(promise.then(function() {\n          setValidity(name, true);\n        }, function(error) {\n          allValid = false;\n          setValidity(name, false);\n        }));\n      });\n      if (!validatorPromises.length) {\n        validationDone(true);\n      } else {\n        $q.all(validatorPromises).then(function() {\n          validationDone(allValid);\n        }, noop);\n      }\n    }\n\n    function setValidity(name, isValid) {\n      if (localValidationRunId === currentValidationRunId) {\n        ctrl.$setValidity(name, isValid);\n      }\n    }\n\n    function validationDone(allValid) {\n      if (localValidationRunId === currentValidationRunId) {\n\n        doneCallback(allValid);\n      }\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$commitViewValue\n   *\n   * @description\n   * Commit a pending update to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  this.$commitViewValue = function() {\n    var viewValue = ctrl.$viewValue;\n\n    $timeout.cancel(pendingDebounce);\n\n    // If the view value has not changed then we should just exit, except in the case where there is\n    // a native validator on the element. In this case the validation state may have changed even though\n    // the viewValue has stayed empty.\n    if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {\n      return;\n    }\n    ctrl.$$lastCommittedViewValue = viewValue;\n\n    // change to dirty\n    if (ctrl.$pristine) {\n      this.$setDirty();\n    }\n    this.$$parseAndValidate();\n  };\n\n  this.$$parseAndValidate = function() {\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    var modelValue = viewValue;\n    var parserValid = isUndefined(modelValue) ? undefined : true;\n\n    if (parserValid) {\n      for (var i = 0; i < ctrl.$parsers.length; i++) {\n        modelValue = ctrl.$parsers[i](modelValue);\n        if (isUndefined(modelValue)) {\n          parserValid = false;\n          break;\n        }\n      }\n    }\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      // ctrl.$modelValue has not been touched yet...\n      ctrl.$modelValue = ngModelGet($scope);\n    }\n    var prevModelValue = ctrl.$modelValue;\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n    ctrl.$$rawModelValue = modelValue;\n\n    if (allowInvalid) {\n      ctrl.$modelValue = modelValue;\n      writeToModelIfNeeded();\n    }\n\n    // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.\n    // This can happen if e.g. $setViewValue is called from inside a parser\n    ctrl.$$runValidators(parserValid, modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {\n      if (!allowInvalid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n        writeToModelIfNeeded();\n      }\n    });\n\n    function writeToModelIfNeeded() {\n      if (ctrl.$modelValue !== prevModelValue) {\n        ctrl.$$writeModelToScope();\n      }\n    }\n  };\n\n  this.$$writeModelToScope = function() {\n    ngModelSet($scope, ctrl.$modelValue);\n    forEach(ctrl.$viewChangeListeners, function(listener) {\n      try {\n        listener();\n      } catch (e) {\n        $exceptionHandler(e);\n      }\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setViewValue\n   *\n   * @description\n   * Update the view value.\n   *\n   * This method should be called when an input directive want to change the view value; typically,\n   * this is done from within a DOM event handler.\n   *\n   * For example {@link ng.directive:input input} calls it when the value of the input changes and\n   * {@link ng.directive:select select} calls it when an option is selected.\n   *\n   * If the new `value` is an object (rather than a string or a number), we should make a copy of the\n   * object before passing it to `$setViewValue`.  This is because `ngModel` does not perform a deep\n   * watch of objects, it only looks for a change of identity. If you only change the property of\n   * the object then ngModel will not realise that the object has changed and will not invoke the\n   * `$parsers` and `$validators` pipelines.\n   *\n   * For this reason, you should not change properties of the copy once it has been passed to\n   * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.\n   *\n   * When this method is called, the new `value` will be staged for committing through the `$parsers`\n   * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged\n   * value sent directly for processing, finally to be applied to `$modelValue` and then the\n   * **expression** specified in the `ng-model` attribute.\n   *\n   * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.\n   *\n   * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`\n   * and the `default` trigger is not listed, all those actions will remain pending until one of the\n   * `updateOn` events is triggered on the DOM element.\n   * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}\n   * directive is used with a custom debounce for this particular event.\n   *\n   * Note that calling this function does not trigger a `$digest`.\n   *\n   * @param {string} value Value from the view.\n   * @param {string} trigger Event that triggered the update.\n   */\n  this.$setViewValue = function(value, trigger) {\n    ctrl.$viewValue = value;\n    if (!ctrl.$options || ctrl.$options.updateOnDefault) {\n      ctrl.$$debounceViewValueCommit(trigger);\n    }\n  };\n\n  this.$$debounceViewValueCommit = function(trigger) {\n    var debounceDelay = 0,\n        options = ctrl.$options,\n        debounce;\n\n    if (options && isDefined(options.debounce)) {\n      debounce = options.debounce;\n      if (isNumber(debounce)) {\n        debounceDelay = debounce;\n      } else if (isNumber(debounce[trigger])) {\n        debounceDelay = debounce[trigger];\n      } else if (isNumber(debounce['default'])) {\n        debounceDelay = debounce['default'];\n      }\n    }\n\n    $timeout.cancel(pendingDebounce);\n    if (debounceDelay) {\n      pendingDebounce = $timeout(function() {\n        ctrl.$commitViewValue();\n      }, debounceDelay);\n    } else if ($rootScope.$$phase) {\n      ctrl.$commitViewValue();\n    } else {\n      $scope.$apply(function() {\n        ctrl.$commitViewValue();\n      });\n    }\n  };\n\n  // model -> value\n  // Note: we cannot use a normal scope.$watch as we want to detect the following:\n  // 1. scope value is 'a'\n  // 2. user enters 'b'\n  // 3. ng-change kicks in and reverts scope value to 'a'\n  //    -> scope value did not change since the last digest as\n  //       ng-change executes in apply phase\n  // 4. view should be changed back to 'a'\n  $scope.$watch(function ngModelWatch() {\n    var modelValue = ngModelGet($scope);\n\n    // if scope model value and ngModel value are out of sync\n    // TODO(perf): why not move this to the action fn?\n    if (modelValue !== ctrl.$modelValue) {\n      ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;\n\n      var formatters = ctrl.$formatters,\n          idx = formatters.length;\n\n      var viewValue = modelValue;\n      while (idx--) {\n        viewValue = formatters[idx](viewValue);\n      }\n      if (ctrl.$viewValue !== viewValue) {\n        ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;\n        ctrl.$render();\n\n        ctrl.$$runValidators(undefined, modelValue, viewValue, noop);\n      }\n    }\n\n    return modelValue;\n  });\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngModel\n *\n * @element input\n * @priority 1\n *\n * @description\n * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a\n * property on the scope using {@link ngModel.NgModelController NgModelController},\n * which is created and exposed by this directive.\n *\n * `ngModel` is responsible for:\n *\n * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`\n *   require.\n * - Providing validation behavior (i.e. required, number, email, url).\n * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).\n * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.\n * - Registering the control with its parent {@link ng.directive:form form}.\n *\n * Note: `ngModel` will try to bind to the property given by evaluating the expression on the\n * current scope. If the property doesn't already exist on this scope, it will be created\n * implicitly and added to the scope.\n *\n * For best practices on using `ngModel`, see:\n *\n *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)\n *\n * For basic examples, how to use `ngModel`, see:\n *\n *  - {@link ng.directive:input input}\n *    - {@link input[text] text}\n *    - {@link input[checkbox] checkbox}\n *    - {@link input[radio] radio}\n *    - {@link input[number] number}\n *    - {@link input[email] email}\n *    - {@link input[url] url}\n *    - {@link input[date] date}\n *    - {@link input[datetime-local] datetime-local}\n *    - {@link input[time] time}\n *    - {@link input[month] month}\n *    - {@link input[week] week}\n *  - {@link ng.directive:select select}\n *  - {@link ng.directive:textarea textarea}\n *\n * # CSS classes\n * The following CSS classes are added and removed on the associated input/select/textarea element\n * depending on the validity of the model.\n *\n *  - `ng-valid`: the model is valid\n *  - `ng-invalid`: the model is invalid\n *  - `ng-valid-[key]`: for each valid key added by `$setValidity`\n *  - `ng-invalid-[key]`: for each invalid key added by `$setValidity`\n *  - `ng-pristine`: the control hasn't been interacted with yet\n *  - `ng-dirty`: the control has been interacted with\n *  - `ng-touched`: the control has been blurred\n *  - `ng-untouched`: the control hasn't been blurred\n *  - `ng-pending`: any `$asyncValidators` are unfulfilled\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n * ## Animation Hooks\n *\n * Animations within models are triggered when any of the associated CSS classes are added and removed\n * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,\n * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.\n * The animations that are triggered within ngModel are similar to how they work in ngClass and\n * animations can be hooked into using CSS transitions, keyframes as well as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style an input element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-input {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-input.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n * <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"inputExample\">\n     <file name=\"index.html\">\n       <script>\n        angular.module('inputExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.val = '1';\n          }]);\n       </script>\n       <style>\n         .my-input {\n           -webkit-transition:all linear 0.5s;\n           transition:all linear 0.5s;\n           background: transparent;\n         }\n         .my-input.ng-invalid {\n           color:white;\n           background: red;\n         }\n       </style>\n       Update input to see transitions when valid/invalid.\n       Integer is a valid value.\n       <form name=\"testForm\" ng-controller=\"ExampleController\">\n         <input ng-model=\"val\" ng-pattern=\"/^\\d+$/\" name=\"anim\" class=\"my-input\" />\n       </form>\n     </file>\n * </example>\n *\n * ## Binding to a getter/setter\n *\n * Sometimes it's helpful to bind `ngModel` to a getter/setter function.  A getter/setter is a\n * function that returns a representation of the model when called with zero arguments, and sets\n * the internal state of a model when called with an argument. It's sometimes useful to use this\n * for models that have an internal representation that's different than what the model exposes\n * to the view.\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more\n * frequently than other parts of your code.\n * </div>\n *\n * You use this behavior by adding `ng-model-options=\"{ getterSetter: true }\"` to an element that\n * has `ng-model` attached to it. You can also add `ng-model-options=\"{ getterSetter: true }\"` to\n * a `<form>`, which will enable this behavior for all `<input>`s within it. See\n * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.\n *\n * The following example shows how to use `ngModel` with a getter/setter:\n *\n * @example\n * <example name=\"ngModel-getter-setter\" module=\"getterSetterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <form name=\"userForm\">\n           Name:\n           <input type=\"text\" name=\"userName\"\n                  ng-model=\"user.name\"\n                  ng-model-options=\"{ getterSetter: true }\" />\n         </form>\n         <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n       </div>\n     </file>\n     <file name=\"app.js\">\n       angular.module('getterSetterExample', [])\n         .controller('ExampleController', ['$scope', function($scope) {\n           var _name = 'Brian';\n           $scope.user = {\n             name: function(newName) {\n               if (angular.isDefined(newName)) {\n                 _name = newName;\n               }\n               return _name;\n             }\n           };\n         }]);\n     </file>\n * </example>\n */\nvar ngModelDirective = ['$rootScope', function($rootScope) {\n  return {\n    restrict: 'A',\n    require: ['ngModel', '^?form', '^?ngModelOptions'],\n    controller: NgModelController,\n    // Prelink needs to run before any input directive\n    // so that we can set the NgModelOptions in NgModelController\n    // before anyone else uses it.\n    priority: 1,\n    compile: function ngModelCompile(element) {\n      // Setup initial state of the control\n      element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);\n\n      return {\n        pre: function ngModelPreLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0],\n              formCtrl = ctrls[1] || nullFormCtrl;\n\n          modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);\n\n          // notify others, especially parent forms\n          formCtrl.$addControl(modelCtrl);\n\n          attr.$observe('name', function(newValue) {\n            if (modelCtrl.$name !== newValue) {\n              formCtrl.$$renameControl(modelCtrl, newValue);\n            }\n          });\n\n          scope.$on('$destroy', function() {\n            formCtrl.$removeControl(modelCtrl);\n          });\n        },\n        post: function ngModelPostLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0];\n          if (modelCtrl.$options && modelCtrl.$options.updateOn) {\n            element.on(modelCtrl.$options.updateOn, function(ev) {\n              modelCtrl.$$debounceViewValueCommit(ev && ev.type);\n            });\n          }\n\n          element.on('blur', function(ev) {\n            if (modelCtrl.$touched) return;\n\n            if ($rootScope.$$phase) {\n              scope.$evalAsync(modelCtrl.$setTouched);\n            } else {\n              scope.$apply(modelCtrl.$setTouched);\n            }\n          });\n        }\n      };\n    }\n  };\n}];\n\nvar DEFAULT_REGEXP = /(\\s+|^)default(\\s+|$)/;\n\n/**\n * @ngdoc directive\n * @name ngModelOptions\n *\n * @description\n * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of\n * events that will trigger a model update and/or a debouncing delay so that the actual update only\n * takes place when a timer expires; this timer will be reset after another change takes place.\n *\n * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might\n * be different than the value in the actual model. This means that if you update the model you\n * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in\n * order to make sure it is synchronized with the model and that any debounced action is canceled.\n *\n * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}\n * method is by making sure the input is placed inside a form that has a `name` attribute. This is\n * important because `form` controllers are published to the related scope under the name in their\n * `name` attribute.\n *\n * Any pending changes will take place immediately when an enclosing form is submitted via the\n * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * `ngModelOptions` has an effect on the element it's declared on and its descendants.\n *\n * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:\n *   - `updateOn`: string specifying which event should the input be bound to. You can set several\n *     events using an space delimited list. There is a special event called `default` that\n *     matches the default events belonging of the control.\n *   - `debounce`: integer value which contains the debounce model update value in milliseconds. A\n *     value of 0 triggers an immediate update. If an object is supplied instead, you can specify a\n *     custom value for each event. For example:\n *     `ng-model-options=\"{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }\"`\n *   - `allowInvalid`: boolean value which indicates that the model can be set with values that did\n *     not validate correctly instead of the default behavior of setting the model to undefined.\n *   - `getterSetter`: boolean value which determines whether or not to treat functions bound to\n       `ngModel` as getters/setters.\n *   - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for\n *     `<input type=\"date\">`, `<input type=\"time\">`, ... . Right now, the only supported value is `'UTC'`,\n *     otherwise the default timezone of the browser will be used.\n *\n * @example\n\n  The following example shows how to override immediate updates. Changes on the inputs within the\n  form will update the model only when the control loses focus (blur event). If `escape` key is\n  pressed while the input field is focused, the value is reset to the value in the current model.\n\n  <example name=\"ngModelOptions-directive-blur\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          Name:\n          <input type=\"text\" name=\"userName\"\n                 ng-model=\"user.name\"\n                 ng-model-options=\"{ updateOn: 'blur' }\"\n                 ng-keyup=\"cancel($event)\" /><br />\n\n          Other data:\n          <input type=\"text\" ng-model=\"user.data\" /><br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say', data: '' };\n\n          $scope.cancel = function(e) {\n            if (e.keyCode == 27) {\n              $scope.userForm.userName.$rollbackViewValue();\n            }\n          };\n        }]);\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var model = element(by.binding('user.name'));\n      var input = element(by.model('user.name'));\n      var other = element(by.model('user.data'));\n\n      it('should allow custom events', function() {\n        input.sendKeys(' hello');\n        input.click();\n        expect(model.getText()).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say hello');\n      });\n\n      it('should $rollbackViewValue when model changes', function() {\n        input.sendKeys(' hello');\n        expect(input.getAttribute('value')).toEqual('say hello');\n        input.sendKeys(protractor.Key.ESCAPE);\n        expect(input.getAttribute('value')).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say');\n      });\n    </file>\n  </example>\n\n  This one shows how to debounce model changes. Model will be updated only 1 sec after last change.\n  If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.\n\n  <example name=\"ngModelOptions-directive-debounce\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          Name:\n          <input type=\"text\" name=\"userName\"\n                 ng-model=\"user.name\"\n                 ng-model-options=\"{ debounce: 1000 }\" />\n          <button ng-click=\"userForm.userName.$rollbackViewValue(); user.name=''\">Clear</button><br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say' };\n        }]);\n    </file>\n  </example>\n\n  This one shows how to bind to getter/setters:\n\n  <example name=\"ngModelOptions-directive-getter-setter\" module=\"getterSetterExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          Name:\n          <input type=\"text\" name=\"userName\"\n                 ng-model=\"user.name\"\n                 ng-model-options=\"{ getterSetter: true }\" />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('getterSetterExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          var _name = 'Brian';\n          $scope.user = {\n            name: function(newName) {\n              return angular.isDefined(newName) ? (_name = newName) : _name;\n            }\n          };\n        }]);\n    </file>\n  </example>\n */\nvar ngModelOptionsDirective = function() {\n  return {\n    restrict: 'A',\n    controller: ['$scope', '$attrs', function($scope, $attrs) {\n      var that = this;\n      this.$options = $scope.$eval($attrs.ngModelOptions);\n      // Allow adding/overriding bound events\n      if (this.$options.updateOn !== undefined) {\n        this.$options.updateOnDefault = false;\n        // extract \"default\" pseudo-event from list of events that can trigger a model update\n        this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {\n          that.$options.updateOnDefault = true;\n          return ' ';\n        }));\n      } else {\n        this.$options.updateOnDefault = true;\n      }\n    }]\n  };\n};\n\n\n\n// helper methods\nfunction addSetValidityMethod(context) {\n  var ctrl = context.ctrl,\n      $element = context.$element,\n      classCache = {},\n      set = context.set,\n      unset = context.unset,\n      parentForm = context.parentForm,\n      $animate = context.$animate;\n\n  classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));\n\n  ctrl.$setValidity = setValidity;\n\n  function setValidity(validationErrorKey, state, controller) {\n    if (state === undefined) {\n      createAndSet('$pending', validationErrorKey, controller);\n    } else {\n      unsetAndCleanup('$pending', validationErrorKey, controller);\n    }\n    if (!isBoolean(state)) {\n      unset(ctrl.$error, validationErrorKey, controller);\n      unset(ctrl.$$success, validationErrorKey, controller);\n    } else {\n      if (state) {\n        unset(ctrl.$error, validationErrorKey, controller);\n        set(ctrl.$$success, validationErrorKey, controller);\n      } else {\n        set(ctrl.$error, validationErrorKey, controller);\n        unset(ctrl.$$success, validationErrorKey, controller);\n      }\n    }\n    if (ctrl.$pending) {\n      cachedToggleClass(PENDING_CLASS, true);\n      ctrl.$valid = ctrl.$invalid = undefined;\n      toggleValidationCss('', null);\n    } else {\n      cachedToggleClass(PENDING_CLASS, false);\n      ctrl.$valid = isObjectEmpty(ctrl.$error);\n      ctrl.$invalid = !ctrl.$valid;\n      toggleValidationCss('', ctrl.$valid);\n    }\n\n    // re-read the state as the set/unset methods could have\n    // combined state in ctrl.$error[validationError] (used for forms),\n    // where setting/unsetting only increments/decrements the value,\n    // and does not replace it.\n    var combinedState;\n    if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {\n      combinedState = undefined;\n    } else if (ctrl.$error[validationErrorKey]) {\n      combinedState = false;\n    } else if (ctrl.$$success[validationErrorKey]) {\n      combinedState = true;\n    } else {\n      combinedState = null;\n    }\n\n    toggleValidationCss(validationErrorKey, combinedState);\n    parentForm.$setValidity(validationErrorKey, combinedState, ctrl);\n  }\n\n  function createAndSet(name, value, controller) {\n    if (!ctrl[name]) {\n      ctrl[name] = {};\n    }\n    set(ctrl[name], value, controller);\n  }\n\n  function unsetAndCleanup(name, value, controller) {\n    if (ctrl[name]) {\n      unset(ctrl[name], value, controller);\n    }\n    if (isObjectEmpty(ctrl[name])) {\n      ctrl[name] = undefined;\n    }\n  }\n\n  function cachedToggleClass(className, switchValue) {\n    if (switchValue && !classCache[className]) {\n      $animate.addClass($element, className);\n      classCache[className] = true;\n    } else if (!switchValue && classCache[className]) {\n      $animate.removeClass($element, className);\n      classCache[className] = false;\n    }\n  }\n\n  function toggleValidationCss(validationErrorKey, isValid) {\n    validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';\n\n    cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);\n    cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);\n  }\n}\n\nfunction isObjectEmpty(obj) {\n  if (obj) {\n    for (var prop in obj) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * @ngdoc directive\n * @name ngNonBindable\n * @restrict AC\n * @priority 1000\n *\n * @description\n * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current\n * DOM element. This is useful if the element contains what appears to be Angular directives and\n * bindings but which should be ignored by Angular. This could be the case if you have a site that\n * displays snippets of code, for instance.\n *\n * @element ANY\n *\n * @example\n * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,\n * but the one wrapped in `ngNonBindable` is left alone.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <div>Normal: {{1 + 2}}</div>\n        <div ng-non-bindable>Ignored: {{1 + 2}}</div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-non-bindable', function() {\n         expect(element(by.binding('1 + 2')).getText()).toContain('3');\n         expect(element.all(by.css('div')).last().getText()).toMatch(/1 \\+ 2/);\n       });\n      </file>\n    </example>\n */\nvar ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });\n\n/**\n * @ngdoc directive\n * @name ngPluralize\n * @restrict EA\n *\n * @description\n * `ngPluralize` is a directive that displays messages according to en-US localization rules.\n * These rules are bundled with angular.js, but can be overridden\n * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive\n * by specifying the mappings between\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * and the strings to be displayed.\n *\n * # Plural categories and explicit number rules\n * There are two\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * in Angular's default en-US locale: \"one\" and \"other\".\n *\n * While a plural category may match many numbers (for example, in en-US locale, \"other\" can match\n * any number that is not 1), an explicit number rule can only match one number. For example, the\n * explicit number rule for \"3\" matches the number 3. There are examples of plural categories\n * and explicit number rules throughout the rest of this documentation.\n *\n * # Configuring ngPluralize\n * You configure ngPluralize by providing 2 attributes: `count` and `when`.\n * You can also provide an optional attribute, `offset`.\n *\n * The value of the `count` attribute can be either a string or an {@link guide/expression\n * Angular expression}; these are evaluated on the current scope for its bound value.\n *\n * The `when` attribute specifies the mappings between plural categories and the actual\n * string to be displayed. The value of the attribute should be a JSON object.\n *\n * The following example shows how to configure ngPluralize:\n *\n * ```html\n * <ng-pluralize count=\"personCount\"\n                 when=\"{'0': 'Nobody is viewing.',\n *                      'one': '1 person is viewing.',\n *                      'other': '{} people are viewing.'}\">\n * </ng-pluralize>\n *```\n *\n * In the example, `\"0: Nobody is viewing.\"` is an explicit number rule. If you did not\n * specify this rule, 0 would be matched to the \"other\" category and \"0 people are viewing\"\n * would be shown instead of \"Nobody is viewing\". You can specify an explicit number rule for\n * other numbers, for example 12, so that instead of showing \"12 people are viewing\", you can\n * show \"a dozen people are viewing\".\n *\n * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted\n * into pluralized strings. In the previous example, Angular will replace `{}` with\n * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder\n * for <span ng-non-bindable>{{numberExpression}}</span>.\n *\n * # Configuring ngPluralize with offset\n * The `offset` attribute allows further customization of pluralized text, which can result in\n * a better user experience. For example, instead of the message \"4 people are viewing this document\",\n * you might display \"John, Kate and 2 others are viewing this document\".\n * The offset attribute allows you to offset a number by any desired value.\n * Let's take a look at an example:\n *\n * ```html\n * <ng-pluralize count=\"personCount\" offset=2\n *               when=\"{'0': 'Nobody is viewing.',\n *                      '1': '{{person1}} is viewing.',\n *                      '2': '{{person1}} and {{person2}} are viewing.',\n *                      'one': '{{person1}}, {{person2}} and one other person are viewing.',\n *                      'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n * </ng-pluralize>\n * ```\n *\n * Notice that we are still using two plural categories(one, other), but we added\n * three explicit number rules 0, 1 and 2.\n * When one person, perhaps John, views the document, \"John is viewing\" will be shown.\n * When three people view the document, no explicit number rule is found, so\n * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.\n * In this case, plural category 'one' is matched and \"John, Mary and one other person are viewing\"\n * is shown.\n *\n * Note that when you specify offsets, you must provide explicit number rules for\n * numbers from 0 up to and including the offset. If you use an offset of 3, for example,\n * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for\n * plural categories \"one\" and \"other\".\n *\n * @param {string|expression} count The variable to be bound to.\n * @param {string} when The mapping between plural category to its corresponding strings.\n * @param {number=} offset Offset to deduct from the total number.\n *\n * @example\n    <example module=\"pluralizeExample\">\n      <file name=\"index.html\">\n        <script>\n          angular.module('pluralizeExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.person1 = 'Igor';\n              $scope.person2 = 'Misko';\n              $scope.personCount = 1;\n            }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          Person 1:<input type=\"text\" ng-model=\"person1\" value=\"Igor\" /><br/>\n          Person 2:<input type=\"text\" ng-model=\"person2\" value=\"Misko\" /><br/>\n          Number of People:<input type=\"text\" ng-model=\"personCount\" value=\"1\" /><br/>\n\n          <!--- Example with simple pluralization rules for en locale --->\n          Without Offset:\n          <ng-pluralize count=\"personCount\"\n                        when=\"{'0': 'Nobody is viewing.',\n                               'one': '1 person is viewing.',\n                               'other': '{} people are viewing.'}\">\n          </ng-pluralize><br>\n\n          <!--- Example with offset --->\n          With Offset(2):\n          <ng-pluralize count=\"personCount\" offset=2\n                        when=\"{'0': 'Nobody is viewing.',\n                               '1': '{{person1}} is viewing.',\n                               '2': '{{person1}} and {{person2}} are viewing.',\n                               'one': '{{person1}}, {{person2}} and one other person are viewing.',\n                               'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n          </ng-pluralize>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should show correct pluralized string', function() {\n          var withoutOffset = element.all(by.css('ng-pluralize')).get(0);\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var countInput = element(by.model('personCount'));\n\n          expect(withoutOffset.getText()).toEqual('1 person is viewing.');\n          expect(withOffset.getText()).toEqual('Igor is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('0');\n\n          expect(withoutOffset.getText()).toEqual('Nobody is viewing.');\n          expect(withOffset.getText()).toEqual('Nobody is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('2');\n\n          expect(withoutOffset.getText()).toEqual('2 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('3');\n\n          expect(withoutOffset.getText()).toEqual('3 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('4');\n\n          expect(withoutOffset.getText()).toEqual('4 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');\n        });\n        it('should show data-bound names', function() {\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var personCount = element(by.model('personCount'));\n          var person1 = element(by.model('person1'));\n          var person2 = element(by.model('person2'));\n          personCount.clear();\n          personCount.sendKeys('4');\n          person1.clear();\n          person1.sendKeys('Di');\n          person2.clear();\n          person2.sendKeys('Vojta');\n          expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');\n        });\n      </file>\n    </example>\n */\nvar ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {\n  var BRACE = /{}/g,\n      IS_WHEN = /^when(Minus)?(.+)$/;\n\n  return {\n    restrict: 'EA',\n    link: function(scope, element, attr) {\n      var numberExp = attr.count,\n          whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs\n          offset = attr.offset || 0,\n          whens = scope.$eval(whenExp) || {},\n          whensExpFns = {},\n          startSymbol = $interpolate.startSymbol(),\n          endSymbol = $interpolate.endSymbol(),\n          braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,\n          watchRemover = angular.noop,\n          lastCount;\n\n      forEach(attr, function(expression, attributeName) {\n        var tmpMatch = IS_WHEN.exec(attributeName);\n        if (tmpMatch) {\n          var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);\n          whens[whenKey] = element.attr(attr.$attr[attributeName]);\n        }\n      });\n      forEach(whens, function(expression, key) {\n        whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));\n\n      });\n\n      scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {\n        var count = parseFloat(newVal);\n        var countIsNaN = isNaN(count);\n\n        if (!countIsNaN && !(count in whens)) {\n          // If an explicit number rule such as 1, 2, 3... is defined, just use it.\n          // Otherwise, check it against pluralization rules in $locale service.\n          count = $locale.pluralCat(count - offset);\n        }\n\n        // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.\n        // In JS `NaN !== NaN`, so we have to exlicitly check.\n        if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {\n          watchRemover();\n          watchRemover = scope.$watch(whensExpFns[count], updateElementText);\n          lastCount = count;\n        }\n      });\n\n      function updateElementText(newText) {\n        element.text(newText || '');\n      }\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngRepeat\n *\n * @description\n * The `ngRepeat` directive instantiates a template once per item from a collection. Each template\n * instance gets its own scope, where the given loop variable is set to the current collection item,\n * and `$index` is set to the item index or key.\n *\n * Special properties are exposed on the local scope of each template instance, including:\n *\n * | Variable  | Type            | Details                                                                     |\n * |-----------|-----------------|-----------------------------------------------------------------------------|\n * | `$index`  | {@type number}  | iterator offset of the repeated element (0..length-1)                       |\n * | `$first`  | {@type boolean} | true if the repeated element is first in the iterator.                      |\n * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |\n * | `$last`   | {@type boolean} | true if the repeated element is last in the iterator.                       |\n * | `$even`   | {@type boolean} | true if the iterator position `$index` is even (otherwise false).           |\n * | `$odd`    | {@type boolean} | true if the iterator position `$index` is odd (otherwise false).            |\n *\n * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.\n * This may be useful when, for instance, nesting ngRepeats.\n *\n * # Iterating over object properties\n *\n * It is possible to get `ngRepeat` to iterate over the properties of an object using the following\n * syntax:\n *\n * ```js\n * <div ng-repeat=\"(key, value) in myObj\"> ... </div>\n * ```\n *\n * You need to be aware that the JavaScript specification does not define what order\n * it will return the keys for an object. In order to have a guaranteed deterministic order\n * for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**.\n *\n * If this is not desired, the recommended workaround is to convert your object into an array\n * that is sorted into the order that you prefer before providing it to `ngRepeat`.  You could\n * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)\n * or implement a `$watch` on the object yourself.\n *\n * In version 1.4 we will remove the sorting, since it seems that browsers generally follow the\n * strategy of providing keys in the order in which they were defined, although there are exceptions\n * when keys are deleted and reinstated.\n *\n *\n * # Special repeat start and end points\n * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending\n * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.\n * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)\n * up to and including the ending HTML tag where **ng-repeat-end** is placed.\n *\n * The example below makes use of this feature:\n * ```html\n *   <header ng-repeat-start=\"item in items\">\n *     Header {{ item }}\n *   </header>\n *   <div class=\"body\">\n *     Body {{ item }}\n *   </div>\n *   <footer ng-repeat-end>\n *     Footer {{ item }}\n *   </footer>\n * ```\n *\n * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:\n * ```html\n *   <header>\n *     Header A\n *   </header>\n *   <div class=\"body\">\n *     Body A\n *   </div>\n *   <footer>\n *     Footer A\n *   </footer>\n *   <header>\n *     Header B\n *   </header>\n *   <div class=\"body\">\n *     Body B\n *   </div>\n *   <footer>\n *     Footer B\n *   </footer>\n * ```\n *\n * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such\n * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).\n *\n * @animations\n * **.enter** - when a new item is added to the list or when an item is revealed after a filter\n *\n * **.leave** - when an item is removed from the list or when an item is filtered out\n *\n * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered\n *\n * @element ANY\n * @scope\n * @priority 1000\n * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These\n *   formats are currently supported:\n *\n *   * `variable in expression` – where variable is the user defined loop variable and `expression`\n *     is a scope expression giving the collection to enumerate.\n *\n *     For example: `album in artist.albums`.\n *\n *   * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,\n *     and `expression` is the scope expression giving the collection to enumerate.\n *\n *     For example: `(name, age) in {'adam':10, 'amalie':12}`.\n *\n *   * `variable in expression track by tracking_expression` – You can also provide an optional tracking function\n *     which can be used to associate the objects in the collection with the DOM elements. If no tracking function\n *     is specified the ng-repeat associates elements by identity in the collection. It is an error to have\n *     more than one tracking function to resolve to the same key. (This would mean that two distinct objects are\n *     mapped to the same DOM element, which is not possible.)  Filters should be applied to the expression,\n *     before specifying a tracking expression.\n *\n *     For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements\n *     will be associated by item identity in the array.\n *\n *     For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique\n *     `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements\n *     with the corresponding item in the array by identity. Moving the same object in array would move the DOM\n *     element in the same way in the DOM.\n *\n *     For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this\n *     case the object identity does not matter. Two objects are considered equivalent as long as their `id`\n *     property is same.\n *\n *     For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter\n *     to items in conjunction with a tracking expression.\n *\n *   * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the\n *     intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message\n *     when a filter is active on the repeater, but the filtered result set is empty.\n *\n *     For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after\n *     the items have been processed through the filter.\n *\n * @example\n * This example initializes the scope to a list of names and\n * then uses `ngRepeat` to display every person:\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-init=\"friends = [\n        {name:'John', age:25, gender:'boy'},\n        {name:'Jessie', age:30, gender:'girl'},\n        {name:'Johanna', age:28, gender:'girl'},\n        {name:'Joy', age:15, gender:'girl'},\n        {name:'Mary', age:28, gender:'girl'},\n        {name:'Peter', age:95, gender:'boy'},\n        {name:'Sebastian', age:50, gender:'boy'},\n        {name:'Erika', age:27, gender:'girl'},\n        {name:'Patrick', age:40, gender:'boy'},\n        {name:'Samantha', age:60, gender:'girl'}\n      ]\">\n        I have {{friends.length}} friends. They are:\n        <input type=\"search\" ng-model=\"q\" placeholder=\"filter friends...\" />\n        <ul class=\"example-animate-container\">\n          <li class=\"animate-repeat\" ng-repeat=\"friend in friends | filter:q as results\">\n            [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.\n          </li>\n          <li class=\"animate-repeat\" ng-if=\"results.length == 0\">\n            <strong>No results found...</strong>\n          </li>\n        </ul>\n      </div>\n    </file>\n    <file name=\"animations.css\">\n      .example-animate-container {\n        background:white;\n        border:1px solid black;\n        list-style:none;\n        margin:0;\n        padding:0 10px;\n      }\n\n      .animate-repeat {\n        line-height:40px;\n        list-style:none;\n        box-sizing:border-box;\n      }\n\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter,\n      .animate-repeat.ng-leave {\n        -webkit-transition:all linear 0.5s;\n        transition:all linear 0.5s;\n      }\n\n      .animate-repeat.ng-leave.ng-leave-active,\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter {\n        opacity:0;\n        max-height:0;\n      }\n\n      .animate-repeat.ng-leave,\n      .animate-repeat.ng-move.ng-move-active,\n      .animate-repeat.ng-enter.ng-enter-active {\n        opacity:1;\n        max-height:40px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var friends = element.all(by.repeater('friend in friends'));\n\n      it('should render initial data set', function() {\n        expect(friends.count()).toBe(10);\n        expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');\n        expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');\n        expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');\n        expect(element(by.binding('friends.length')).getText())\n            .toMatch(\"I have 10 friends. They are:\");\n      });\n\n       it('should update repeater when filter predicate changes', function() {\n         expect(friends.count()).toBe(10);\n\n         element(by.model('q')).sendKeys('ma');\n\n         expect(friends.count()).toBe(2);\n         expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');\n         expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');\n       });\n      </file>\n    </example>\n */\nvar ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {\n  var NG_REMOVED = '$$NG_REMOVED';\n  var ngRepeatMinErr = minErr('ngRepeat');\n\n  var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {\n    // TODO(perf): generate setters to shave off ~40ms or 1-1.5%\n    scope[valueIdentifier] = value;\n    if (keyIdentifier) scope[keyIdentifier] = key;\n    scope.$index = index;\n    scope.$first = (index === 0);\n    scope.$last = (index === (arrayLength - 1));\n    scope.$middle = !(scope.$first || scope.$last);\n    // jshint bitwise: false\n    scope.$odd = !(scope.$even = (index&1) === 0);\n    // jshint bitwise: true\n  };\n\n  var getBlockStart = function(block) {\n    return block.clone[0];\n  };\n\n  var getBlockEnd = function(block) {\n    return block.clone[block.clone.length - 1];\n  };\n\n\n  return {\n    restrict: 'A',\n    multiElement: true,\n    transclude: 'element',\n    priority: 1000,\n    terminal: true,\n    $$tlb: true,\n    compile: function ngRepeatCompile($element, $attr) {\n      var expression = $attr.ngRepeat;\n      var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');\n\n      var match = expression.match(/^\\s*([\\s\\S]+?)\\s+in\\s+([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+track\\s+by\\s+([\\s\\S]+?))?\\s*$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iexp', \"Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.\",\n            expression);\n      }\n\n      var lhs = match[1];\n      var rhs = match[2];\n      var aliasAs = match[3];\n      var trackByExp = match[4];\n\n      match = lhs.match(/^(?:(\\s*[\\$\\w]+)|\\(\\s*([\\$\\w]+)\\s*,\\s*([\\$\\w]+)\\s*\\))$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iidexp', \"'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.\",\n            lhs);\n      }\n      var valueIdentifier = match[3] || match[1];\n      var keyIdentifier = match[2];\n\n      if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||\n          /^(null|undefined|this|\\$index|\\$first|\\$middle|\\$last|\\$even|\\$odd|\\$parent|\\$root|\\$id)$/.test(aliasAs))) {\n        throw ngRepeatMinErr('badident', \"alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.\",\n          aliasAs);\n      }\n\n      var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;\n      var hashFnLocals = {$id: hashKey};\n\n      if (trackByExp) {\n        trackByExpGetter = $parse(trackByExp);\n      } else {\n        trackByIdArrayFn = function(key, value) {\n          return hashKey(value);\n        };\n        trackByIdObjFn = function(key) {\n          return key;\n        };\n      }\n\n      return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {\n\n        if (trackByExpGetter) {\n          trackByIdExpFn = function(key, value, index) {\n            // assign key, value, and $index to the locals so that they can be used in hash functions\n            if (keyIdentifier) hashFnLocals[keyIdentifier] = key;\n            hashFnLocals[valueIdentifier] = value;\n            hashFnLocals.$index = index;\n            return trackByExpGetter($scope, hashFnLocals);\n          };\n        }\n\n        // Store a list of elements from previous run. This is a hash where key is the item from the\n        // iterator, and the value is objects with following properties.\n        //   - scope: bound scope\n        //   - element: previous element.\n        //   - index: position\n        //\n        // We are using no-proto object so that we don't need to guard against inherited props via\n        // hasOwnProperty.\n        var lastBlockMap = createMap();\n\n        //watch props\n        $scope.$watchCollection(rhs, function ngRepeatAction(collection) {\n          var index, length,\n              previousNode = $element[0],     // node that cloned nodes should be inserted after\n                                              // initialized to the comment node anchor\n              nextNode,\n              // Same as lastBlockMap but it has the current state. It will become the\n              // lastBlockMap on the next iteration.\n              nextBlockMap = createMap(),\n              collectionLength,\n              key, value, // key/value of iteration\n              trackById,\n              trackByIdFn,\n              collectionKeys,\n              block,       // last object information {scope, element, id}\n              nextBlockOrder,\n              elementsToRemove;\n\n          if (aliasAs) {\n            $scope[aliasAs] = collection;\n          }\n\n          if (isArrayLike(collection)) {\n            collectionKeys = collection;\n            trackByIdFn = trackByIdExpFn || trackByIdArrayFn;\n          } else {\n            trackByIdFn = trackByIdExpFn || trackByIdObjFn;\n            // if object, extract keys, sort them and use to determine order of iteration over obj props\n            collectionKeys = [];\n            for (var itemKey in collection) {\n              if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {\n                collectionKeys.push(itemKey);\n              }\n            }\n            collectionKeys.sort();\n          }\n\n          collectionLength = collectionKeys.length;\n          nextBlockOrder = new Array(collectionLength);\n\n          // locate existing items\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            trackById = trackByIdFn(key, value, index);\n            if (lastBlockMap[trackById]) {\n              // found previously seen block\n              block = lastBlockMap[trackById];\n              delete lastBlockMap[trackById];\n              nextBlockMap[trackById] = block;\n              nextBlockOrder[index] = block;\n            } else if (nextBlockMap[trackById]) {\n              // if collision detected. restore lastBlockMap and throw an error\n              forEach(nextBlockOrder, function(block) {\n                if (block && block.scope) lastBlockMap[block.id] = block;\n              });\n              throw ngRepeatMinErr('dupes',\n                  \"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}\",\n                  expression, trackById, value);\n            } else {\n              // new never before seen block\n              nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};\n              nextBlockMap[trackById] = true;\n            }\n          }\n\n          // remove leftover items\n          for (var blockKey in lastBlockMap) {\n            block = lastBlockMap[blockKey];\n            elementsToRemove = getBlockNodes(block.clone);\n            $animate.leave(elementsToRemove);\n            if (elementsToRemove[0].parentNode) {\n              // if the element was not removed yet because of pending animation, mark it as deleted\n              // so that we can ignore it later\n              for (index = 0, length = elementsToRemove.length; index < length; index++) {\n                elementsToRemove[index][NG_REMOVED] = true;\n              }\n            }\n            block.scope.$destroy();\n          }\n\n          // we are not using forEach for perf reasons (trying to avoid #call)\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            block = nextBlockOrder[index];\n\n            if (block.scope) {\n              // if we have already seen this object, then we need to reuse the\n              // associated scope/element\n\n              nextNode = previousNode;\n\n              // skip nodes that are already pending removal via leave animation\n              do {\n                nextNode = nextNode.nextSibling;\n              } while (nextNode && nextNode[NG_REMOVED]);\n\n              if (getBlockStart(block) != nextNode) {\n                // existing item which got moved\n                $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));\n              }\n              previousNode = getBlockEnd(block);\n              updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n            } else {\n              // new item which we don't know about\n              $transclude(function ngRepeatTransclude(clone, scope) {\n                block.scope = scope;\n                // http://jsperf.com/clone-vs-createcomment\n                var endNode = ngRepeatEndComment.cloneNode(false);\n                clone[clone.length++] = endNode;\n\n                // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?\n                $animate.enter(clone, null, jqLite(previousNode));\n                previousNode = endNode;\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block.clone = clone;\n                nextBlockMap[block.id] = block;\n                updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n              });\n            }\n          }\n          lastBlockMap = nextBlockMap;\n        });\n      };\n    }\n  };\n}];\n\nvar NG_HIDE_CLASS = 'ng-hide';\nvar NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';\n/**\n * @ngdoc directive\n * @name ngShow\n *\n * @description\n * The `ngShow` directive shows or hides the given HTML element based on the expression\n * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding\n * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is visible) -->\n * <div ng-show=\"myValue\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is hidden) -->\n * <div ng-show=\"myValue\" class=\"ng-hide\"></div>\n * ```\n *\n * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope\n * with extra animation classes that can be added.\n *\n * ```css\n * .ng-hide:not(.ng-hide-animate) {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngShow`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass except that\n * you must also include the !important flag to override the display property\n * so that you can perform an animation when the element is hidden during the time of the animation.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   /&#42; this is required as of 1.3x to properly\n *      apply all styling in a show/hide animation &#42;/\n *   transition: 0s linear all;\n * }\n *\n * .my-element.ng-hide-add-active,\n * .my-element.ng-hide-remove-active {\n *   /&#42; the transition is defined in the active class &#42;/\n *   transition: 1s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible\n * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden\n *\n * @element ANY\n * @param {expression} ngShow If the {@link guide/expression expression} is truthy\n *     then the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-show\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-show\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-show {\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-show.ng-hide-add.ng-hide-add-active,\n      .animate-show.ng-hide-remove.ng-hide-remove-active {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n      }\n\n      .animate-show.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngShowDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngShow, function ngShowWatchAction(value) {\n        // we're adding a temporary, animation-specific class for ng-hide since this way\n        // we can control when the element is actually displayed on screen without having\n        // to have a global/greedy CSS selector that breaks when other animations are run.\n        // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845\n        $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngHide\n *\n * @description\n * The `ngHide` directive shows or hides the given HTML element based on the expression\n * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding\n * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is hidden) -->\n * <div ng-hide=\"myValue\" class=\"ng-hide\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is visible) -->\n * <div ng-hide=\"myValue\"></div>\n * ```\n *\n * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class in CSS:\n *\n * ```css\n * .ng-hide {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngHide`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`\n * CSS class is added and removed for you instead of your own CSS class.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   transition: 0.5s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden\n * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible\n *\n * @element ANY\n * @param {expression} ngHide If the {@link guide/expression expression} is truthy then\n *     the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-hide\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-hide\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-hide {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-hide.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngHideDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngHide, function ngHideWatchAction(value) {\n        // The comment inside of the ngShowDirective explains why we add and\n        // remove a temporary class for the show/hide animation\n        $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngStyle\n * @restrict AC\n *\n * @description\n * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.\n *\n * @element ANY\n * @param {expression} ngStyle\n *\n * {@link guide/expression Expression} which evals to an\n * object whose keys are CSS style names and values are corresponding values for those CSS\n * keys.\n *\n * Since some CSS style names are not valid keys for an object, they must be quoted.\n * See the 'background-color' style in the example below.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <input type=\"button\" value=\"set color\" ng-click=\"myStyle={color:'red'}\">\n        <input type=\"button\" value=\"set background\" ng-click=\"myStyle={'background-color':'blue'}\">\n        <input type=\"button\" value=\"clear\" ng-click=\"myStyle={}\">\n        <br/>\n        <span ng-style=\"myStyle\">Sample Text</span>\n        <pre>myStyle={{myStyle}}</pre>\n     </file>\n     <file name=\"style.css\">\n       span {\n         color: black;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var colorSpan = element(by.css('span'));\n\n       it('should check ng-style', function() {\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n         element(by.css('input[value=\\'set color\\']')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');\n         element(by.css('input[value=clear]')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n       });\n     </file>\n   </example>\n */\nvar ngStyleDirective = ngDirective(function(scope, element, attr) {\n  scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {\n    if (oldStyles && (newStyles !== oldStyles)) {\n      forEach(oldStyles, function(val, style) { element.css(style, '');});\n    }\n    if (newStyles) element.css(newStyles);\n  });\n});\n\n/**\n * @ngdoc directive\n * @name ngSwitch\n * @restrict EA\n *\n * @description\n * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.\n * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location\n * as specified in the template.\n *\n * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it\n * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element\n * matches the value obtained from the evaluated expression. In other words, you define a container element\n * (where you place the directive), place an expression on the **`on=\"...\"` attribute**\n * (or the **`ng-switch=\"...\"` attribute**), define any inner elements inside of the directive and place\n * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on\n * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default\n * attribute is displayed.\n *\n * <div class=\"alert alert-info\">\n * Be aware that the attribute values to match against cannot be expressions. They are interpreted\n * as literal string values to match against.\n * For example, **`ng-switch-when=\"someVal\"`** will match against the string `\"someVal\"` not against the\n * value of the expression `$scope.someVal`.\n * </div>\n\n * @animations\n * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container\n * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM\n *\n * @usage\n *\n * ```\n * <ANY ng-switch=\"expression\">\n *   <ANY ng-switch-when=\"matchValue1\">...</ANY>\n *   <ANY ng-switch-when=\"matchValue2\">...</ANY>\n *   <ANY ng-switch-default>...</ANY>\n * </ANY>\n * ```\n *\n *\n * @scope\n * @priority 1200\n * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.\n * On child elements add:\n *\n * * `ngSwitchWhen`: the case statement to match against. If match then this\n *   case will be displayed. If the same match appears multiple times, all the\n *   elements will be displayed.\n * * `ngSwitchDefault`: the default case when no other case match. If there\n *   are multiple default cases, all of them will be displayed when no other\n *   case match.\n *\n *\n * @example\n  <example module=\"switchExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <select ng-model=\"selection\" ng-options=\"item for item in items\">\n        </select>\n        <tt>selection={{selection}}</tt>\n        <hr/>\n        <div class=\"animate-switch-container\"\n          ng-switch on=\"selection\">\n            <div class=\"animate-switch\" ng-switch-when=\"settings\">Settings Div</div>\n            <div class=\"animate-switch\" ng-switch-when=\"home\">Home Span</div>\n            <div class=\"animate-switch\" ng-switch-default>default</div>\n        </div>\n      </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('switchExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.items = ['settings', 'home', 'other'];\n          $scope.selection = $scope.items[0];\n        }]);\n    </file>\n    <file name=\"animations.css\">\n      .animate-switch-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .animate-switch {\n        padding:10px;\n      }\n\n      .animate-switch.ng-animate {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n      }\n\n      .animate-switch.ng-leave.ng-leave-active,\n      .animate-switch.ng-enter {\n        top:-50px;\n      }\n      .animate-switch.ng-leave,\n      .animate-switch.ng-enter.ng-enter-active {\n        top:0;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var switchElem = element(by.css('[ng-switch]'));\n      var select = element(by.model('selection'));\n\n      it('should start in settings', function() {\n        expect(switchElem.getText()).toMatch(/Settings Div/);\n      });\n      it('should change to home', function() {\n        select.all(by.css('option')).get(1).click();\n        expect(switchElem.getText()).toMatch(/Home Span/);\n      });\n      it('should select default', function() {\n        select.all(by.css('option')).get(2).click();\n        expect(switchElem.getText()).toMatch(/default/);\n      });\n    </file>\n  </example>\n */\nvar ngSwitchDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'EA',\n    require: 'ngSwitch',\n\n    // asks for $scope to fool the BC controller module\n    controller: ['$scope', function ngSwitchController() {\n     this.cases = {};\n    }],\n    link: function(scope, element, attr, ngSwitchController) {\n      var watchExpr = attr.ngSwitch || attr.on,\n          selectedTranscludes = [],\n          selectedElements = [],\n          previousLeaveAnimations = [],\n          selectedScopes = [];\n\n      var spliceFactory = function(array, index) {\n          return function() { array.splice(index, 1); };\n      };\n\n      scope.$watch(watchExpr, function ngSwitchWatchAction(value) {\n        var i, ii;\n        for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {\n          $animate.cancel(previousLeaveAnimations[i]);\n        }\n        previousLeaveAnimations.length = 0;\n\n        for (i = 0, ii = selectedScopes.length; i < ii; ++i) {\n          var selected = getBlockNodes(selectedElements[i].clone);\n          selectedScopes[i].$destroy();\n          var promise = previousLeaveAnimations[i] = $animate.leave(selected);\n          promise.then(spliceFactory(previousLeaveAnimations, i));\n        }\n\n        selectedElements.length = 0;\n        selectedScopes.length = 0;\n\n        if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {\n          forEach(selectedTranscludes, function(selectedTransclude) {\n            selectedTransclude.transclude(function(caseElement, selectedScope) {\n              selectedScopes.push(selectedScope);\n              var anchor = selectedTransclude.element;\n              caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');\n              var block = { clone: caseElement };\n\n              selectedElements.push(block);\n              $animate.enter(caseElement, anchor.parent(), anchor);\n            });\n          });\n        }\n      });\n    }\n  };\n}];\n\nvar ngSwitchWhenDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attrs, ctrl, $transclude) {\n    ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);\n    ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });\n  }\n});\n\nvar ngSwitchDefaultDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attr, ctrl, $transclude) {\n    ctrl.cases['?'] = (ctrl.cases['?'] || []);\n    ctrl.cases['?'].push({ transclude: $transclude, element: element });\n   }\n});\n\n/**\n * @ngdoc directive\n * @name ngTransclude\n * @restrict EAC\n *\n * @description\n * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.\n *\n * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.\n *\n * @element ANY\n *\n * @example\n   <example module=\"transcludeExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('transcludeExample', [])\n          .directive('pane', function(){\n             return {\n               restrict: 'E',\n               transclude: true,\n               scope: { title:'@' },\n               template: '<div style=\"border: 1px solid black;\">' +\n                           '<div style=\"background-color: gray\">{{title}}</div>' +\n                           '<ng-transclude></ng-transclude>' +\n                         '</div>'\n             };\n         })\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.title = 'Lorem Ipsum';\n           $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';\n         }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input ng-model=\"title\"> <br/>\n         <textarea ng-model=\"text\"></textarea> <br/>\n         <pane title=\"{{title}}\">{{text}}</pane>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        it('should have transcluded', function() {\n          var titleElement = element(by.model('title'));\n          titleElement.clear();\n          titleElement.sendKeys('TITLE');\n          var textElement = element(by.model('text'));\n          textElement.clear();\n          textElement.sendKeys('TEXT');\n          expect(element(by.binding('title')).getText()).toEqual('TITLE');\n          expect(element(by.binding('text')).getText()).toEqual('TEXT');\n        });\n     </file>\n   </example>\n *\n */\nvar ngTranscludeDirective = ngDirective({\n  restrict: 'EAC',\n  link: function($scope, $element, $attrs, controller, $transclude) {\n    if (!$transclude) {\n      throw minErr('ngTransclude')('orphan',\n       'Illegal use of ngTransclude directive in the template! ' +\n       'No parent directive that requires a transclusion found. ' +\n       'Element: {0}',\n       startingTag($element));\n    }\n\n    $transclude(function(clone) {\n      $element.empty();\n      $element.append(clone);\n    });\n  }\n});\n\n/**\n * @ngdoc directive\n * @name script\n * @restrict E\n *\n * @description\n * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the\n * template can be used by {@link ng.directive:ngInclude `ngInclude`},\n * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the\n * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be\n * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.\n *\n * @param {string} type Must be set to `'text/ng-template'`.\n * @param {string} id Cache name of the template.\n *\n * @example\n  <example>\n    <file name=\"index.html\">\n      <script type=\"text/ng-template\" id=\"/tpl.html\">\n        Content of the template.\n      </script>\n\n      <a ng-click=\"currentTpl='/tpl.html'\" id=\"tpl-link\">Load inlined template</a>\n      <div id=\"tpl-content\" ng-include src=\"currentTpl\"></div>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      it('should load template defined inside script tag', function() {\n        element(by.css('#tpl-link')).click();\n        expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);\n      });\n    </file>\n  </example>\n */\nvar scriptDirective = ['$templateCache', function($templateCache) {\n  return {\n    restrict: 'E',\n    terminal: true,\n    compile: function(element, attr) {\n      if (attr.type == 'text/ng-template') {\n        var templateUrl = attr.id,\n            text = element[0].text;\n\n        $templateCache.put(templateUrl, text);\n      }\n    }\n  };\n}];\n\nvar ngOptionsMinErr = minErr('ngOptions');\n/**\n * @ngdoc directive\n * @name select\n * @restrict E\n *\n * @description\n * HTML `SELECT` element with angular data-binding.\n *\n * # `ngOptions`\n *\n * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`\n * elements for the `<select>` element using the array or object obtained by evaluating the\n * `ngOptions` comprehension expression.\n *\n * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a\n * similar result. However, `ngOptions` provides some benefits such as reducing memory and\n * increasing speed by not creating a new scope for each repeated instance, as well as providing\n * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the\n * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound\n *  to a non-string value. This is because an option element can only be bound to string values at\n * present.\n *\n * When an item in the `<select>` menu is selected, the array element or object property\n * represented by the selected option will be bound to the model identified by the `ngModel`\n * directive.\n *\n * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can\n * be nested into the `<select>` element. This element will then represent the `null` or \"not selected\"\n * option. See example below for demonstration.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** `ngModel` compares by reference, not value. This is important when binding to an\n * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).\n * </div>\n *\n * ## `select` **`as`**\n *\n * Using `select` **`as`** will bind the result of the `select` expression to the model, but\n * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)\n * or property name (for object data sources) of the value within the collection. If a **`track by`** expression\n * is used, the result of that expression will be set as the value of the `option` and `select` elements.\n *\n *\n * ### `select` **`as`** and **`track by`**\n *\n * <div class=\"alert alert-warning\">\n * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.\n * </div>\n *\n * Consider the following example:\n *\n * ```html\n * <select ng-options=\"item.subItem as item.label for item in values track by item.id\" ng-model=\"selected\">\n * ```\n *\n * ```js\n * $scope.values = [{\n *   id: 1,\n *   label: 'aLabel',\n *   subItem: { name: 'aSubItem' }\n * }, {\n *   id: 2,\n *   label: 'bLabel',\n *   subItem: { name: 'bSubItem' }\n * }];\n *\n * $scope.selected = { name: 'aSubItem' };\n * ```\n *\n * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element\n * of the data source (to `item` in this example). To calculate whether an element is selected, we do the\n * following:\n *\n * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`\n * 2. Apply **`track by`** to the already selected value in `ngModel`.\n *    In the example: this is not possible as **`track by`** refers to `item.id`, but the selected\n *    value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to\n *    a wrong object, the selected element can't be found, `<select>` is always reset to the \"not\n *    selected\" option.\n *\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required The control is considered valid only if value is entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {comprehension_expression=} ngOptions in one of the following forms:\n *\n *   * for array data sources:\n *     * `label` **`for`** `value` **`in`** `array`\n *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`\n *     * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`\n *        (for including a filter with `track by`)\n *   * for object data sources:\n *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`group by`** `group`\n *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`\n *\n * Where:\n *\n *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.\n *   * `value`: local variable which will refer to each item in the `array` or each property value\n *      of `object` during iteration.\n *   * `key`: local variable which will refer to a property name in `object` during iteration.\n *   * `label`: The result of this expression will be the label for `<option>` element. The\n *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).\n *   * `select`: The result of this expression will be bound to the model of the parent `<select>`\n *      element. If not specified, `select` expression will default to `value`.\n *   * `group`: The result of this expression will be used to group options using the `<optgroup>`\n *      DOM element.\n *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be\n *      used to identify the objects in the array. The `trackexpr` will most likely refer to the\n *     `value` variable (e.g. `value.propertyName`). With this the selection is preserved\n *      even when the options are recreated (e.g. reloaded from the server).\n *\n * @example\n    <example module=\"selectExample\">\n      <file name=\"index.html\">\n        <script>\n        angular.module('selectExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.colors = [\n              {name:'black', shade:'dark'},\n              {name:'white', shade:'light'},\n              {name:'red', shade:'dark'},\n              {name:'blue', shade:'dark'},\n              {name:'yellow', shade:'light'}\n            ];\n            $scope.myColor = $scope.colors[2]; // red\n          }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          <ul>\n            <li ng-repeat=\"color in colors\">\n              Name: <input ng-model=\"color.name\">\n              [<a href ng-click=\"colors.splice($index, 1)\">X</a>]\n            </li>\n            <li>\n              [<a href ng-click=\"colors.push({})\">add</a>]\n            </li>\n          </ul>\n          <hr/>\n          Color (null not allowed):\n          <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\"></select><br>\n\n          Color (null allowed):\n          <span  class=\"nullable\">\n            <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\">\n              <option value=\"\">-- choose color --</option>\n            </select>\n          </span><br/>\n\n          Color grouped by shade:\n          <select ng-model=\"myColor\" ng-options=\"color.name group by color.shade for color in colors\">\n          </select><br/>\n\n\n          Select <a href ng-click=\"myColor = { name:'not in list', shade: 'other' }\">bogus</a>.<br>\n          <hr/>\n          Currently selected: {{ {selected_color:myColor} }}\n          <div style=\"border:solid 1px black; height:20px\"\n               ng-style=\"{'background-color':myColor.name}\">\n          </div>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n         it('should check ng-options', function() {\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');\n           element.all(by.model('myColor')).first().click();\n           element.all(by.css('select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');\n           element(by.css('.nullable select[ng-model=\"myColor\"]')).click();\n           element.all(by.css('.nullable select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');\n         });\n      </file>\n    </example>\n */\n\nvar ngOptionsDirective = valueFn({\n  restrict: 'A',\n  terminal: true\n});\n\n// jshint maxlen: false\nvar selectDirective = ['$compile', '$parse', function($compile,   $parse) {\n                         //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888\n  var NG_OPTIONS_REGEXP = /^\\s*([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+group\\s+by\\s+([\\s\\S]+?))?\\s+for\\s+(?:([\\$\\w][\\$\\w]*)|(?:\\(\\s*([\\$\\w][\\$\\w]*)\\s*,\\s*([\\$\\w][\\$\\w]*)\\s*\\)))\\s+in\\s+([\\s\\S]+?)(?:\\s+track\\s+by\\s+([\\s\\S]+?))?$/,\n      nullModelCtrl = {$setViewValue: noop};\n// jshint maxlen: 100\n\n  return {\n    restrict: 'E',\n    require: ['select', '?ngModel'],\n    controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {\n      var self = this,\n          optionsMap = {},\n          ngModelCtrl = nullModelCtrl,\n          nullOption,\n          unknownOption;\n\n\n      self.databound = $attrs.ngModel;\n\n\n      self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {\n        ngModelCtrl = ngModelCtrl_;\n        nullOption = nullOption_;\n        unknownOption = unknownOption_;\n      };\n\n\n      self.addOption = function(value, element) {\n        assertNotHasOwnProperty(value, '\"option value\"');\n        optionsMap[value] = true;\n\n        if (ngModelCtrl.$viewValue == value) {\n          $element.val(value);\n          if (unknownOption.parent()) unknownOption.remove();\n        }\n        // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459\n        // Adding an <option selected=\"selected\"> element to a <select required=\"required\"> should\n        // automatically select the new element\n        if (element && element[0].hasAttribute('selected')) {\n          element[0].selected = true;\n        }\n      };\n\n\n      self.removeOption = function(value) {\n        if (this.hasOption(value)) {\n          delete optionsMap[value];\n          if (ngModelCtrl.$viewValue === value) {\n            this.renderUnknownOption(value);\n          }\n        }\n      };\n\n\n      self.renderUnknownOption = function(val) {\n        var unknownVal = '? ' + hashKey(val) + ' ?';\n        unknownOption.val(unknownVal);\n        $element.prepend(unknownOption);\n        $element.val(unknownVal);\n        unknownOption.prop('selected', true); // needed for IE\n      };\n\n\n      self.hasOption = function(value) {\n        return optionsMap.hasOwnProperty(value);\n      };\n\n      $scope.$on('$destroy', function() {\n        // disable unknown option so that we don't do work when the whole select is being destroyed\n        self.renderUnknownOption = noop;\n      });\n    }],\n\n    link: function(scope, element, attr, ctrls) {\n      // if ngModel is not defined, we don't need to do anything\n      if (!ctrls[1]) return;\n\n      var selectCtrl = ctrls[0],\n          ngModelCtrl = ctrls[1],\n          multiple = attr.multiple,\n          optionsExp = attr.ngOptions,\n          nullOption = false, // if false, user will not be able to select it (used by ngOptions)\n          emptyOption,\n          renderScheduled = false,\n          // we can't just jqLite('<option>') since jqLite is not smart enough\n          // to create it in <select> and IE barfs otherwise.\n          optionTemplate = jqLite(document.createElement('option')),\n          optGroupTemplate =jqLite(document.createElement('optgroup')),\n          unknownOption = optionTemplate.clone();\n\n      // find \"null\" option\n      for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {\n        if (children[i].value === '') {\n          emptyOption = nullOption = children.eq(i);\n          break;\n        }\n      }\n\n      selectCtrl.init(ngModelCtrl, nullOption, unknownOption);\n\n      // required validator\n      if (multiple) {\n        ngModelCtrl.$isEmpty = function(value) {\n          return !value || value.length === 0;\n        };\n      }\n\n      if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);\n      else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);\n      else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);\n\n\n      ////////////////////////////\n\n\n\n      function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {\n        ngModelCtrl.$render = function() {\n          var viewValue = ngModelCtrl.$viewValue;\n\n          if (selectCtrl.hasOption(viewValue)) {\n            if (unknownOption.parent()) unknownOption.remove();\n            selectElement.val(viewValue);\n            if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy\n          } else {\n            if (isUndefined(viewValue) && emptyOption) {\n              selectElement.val('');\n            } else {\n              selectCtrl.renderUnknownOption(viewValue);\n            }\n          }\n        };\n\n        selectElement.on('change', function() {\n          scope.$apply(function() {\n            if (unknownOption.parent()) unknownOption.remove();\n            ngModelCtrl.$setViewValue(selectElement.val());\n          });\n        });\n      }\n\n      function setupAsMultiple(scope, selectElement, ctrl) {\n        var lastView;\n        ctrl.$render = function() {\n          var items = new HashMap(ctrl.$viewValue);\n          forEach(selectElement.find('option'), function(option) {\n            option.selected = isDefined(items.get(option.value));\n          });\n        };\n\n        // we have to do it on each watch since ngModel watches reference, but\n        // we need to work of an array, so we need to see if anything was inserted/removed\n        scope.$watch(function selectMultipleWatch() {\n          if (!equals(lastView, ctrl.$viewValue)) {\n            lastView = shallowCopy(ctrl.$viewValue);\n            ctrl.$render();\n          }\n        });\n\n        selectElement.on('change', function() {\n          scope.$apply(function() {\n            var array = [];\n            forEach(selectElement.find('option'), function(option) {\n              if (option.selected) {\n                array.push(option.value);\n              }\n            });\n            ctrl.$setViewValue(array);\n          });\n        });\n      }\n\n      function setupAsOptions(scope, selectElement, ctrl) {\n        var match;\n\n        if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {\n          throw ngOptionsMinErr('iexp',\n            \"Expected expression in form of \" +\n            \"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'\" +\n            \" but got '{0}'. Element: {1}\",\n            optionsExp, startingTag(selectElement));\n        }\n\n        var displayFn = $parse(match[2] || match[1]),\n            valueName = match[4] || match[6],\n            selectAs = / as /.test(match[0]) && match[1],\n            selectAsFn = selectAs ? $parse(selectAs) : null,\n            keyName = match[5],\n            groupByFn = $parse(match[3] || ''),\n            valueFn = $parse(match[2] ? match[1] : valueName),\n            valuesFn = $parse(match[7]),\n            track = match[8],\n            trackFn = track ? $parse(match[8]) : null,\n            trackKeysCache = {},\n            // This is an array of array of existing option groups in DOM.\n            // We try to reuse these if possible\n            // - optionGroupsCache[0] is the options with no option group\n            // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element\n            optionGroupsCache = [[{element: selectElement, label:''}]],\n            //re-usable object to represent option's locals\n            locals = {};\n\n        if (nullOption) {\n          // compile the element since there might be bindings in it\n          $compile(nullOption)(scope);\n\n          // remove the class, which is added automatically because we recompile the element and it\n          // becomes the compilation root\n          nullOption.removeClass('ng-scope');\n\n          // we need to remove it before calling selectElement.empty() because otherwise IE will\n          // remove the label from the element. wtf?\n          nullOption.remove();\n        }\n\n        // clear contents, we'll add what's needed based on the model\n        selectElement.empty();\n\n        selectElement.on('change', selectionChanged);\n\n        ctrl.$render = render;\n\n        scope.$watchCollection(valuesFn, scheduleRendering);\n        scope.$watchCollection(getLabels, scheduleRendering);\n\n        if (multiple) {\n          scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);\n        }\n\n        // ------------------------------------------------------------------ //\n\n        function callExpression(exprFn, key, value) {\n          locals[valueName] = value;\n          if (keyName) locals[keyName] = key;\n          return exprFn(scope, locals);\n        }\n\n        function selectionChanged() {\n          scope.$apply(function() {\n            var collection = valuesFn(scope) || [];\n            var viewValue;\n            if (multiple) {\n              viewValue = [];\n              forEach(selectElement.val(), function(selectedKey) {\n                  selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;\n                viewValue.push(getViewValue(selectedKey, collection[selectedKey]));\n              });\n            } else {\n              var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();\n              viewValue = getViewValue(selectedKey, collection[selectedKey]);\n            }\n            ctrl.$setViewValue(viewValue);\n            render();\n          });\n        }\n\n        function getViewValue(key, value) {\n          if (key === '?') {\n            return undefined;\n          } else if (key === '') {\n            return null;\n          } else {\n            var viewValueFn = selectAsFn ? selectAsFn : valueFn;\n            return callExpression(viewValueFn, key, value);\n          }\n        }\n\n        function getLabels() {\n          var values = valuesFn(scope);\n          var toDisplay;\n          if (values && isArray(values)) {\n            toDisplay = new Array(values.length);\n            for (var i = 0, ii = values.length; i < ii; i++) {\n              toDisplay[i] = callExpression(displayFn, i, values[i]);\n            }\n            return toDisplay;\n          } else if (values) {\n            // TODO: Add a test for this case\n            toDisplay = {};\n            for (var prop in values) {\n              if (values.hasOwnProperty(prop)) {\n                toDisplay[prop] = callExpression(displayFn, prop, values[prop]);\n              }\n            }\n          }\n          return toDisplay;\n        }\n\n        function createIsSelectedFn(viewValue) {\n          var selectedSet;\n          if (multiple) {\n            if (trackFn && isArray(viewValue)) {\n\n              selectedSet = new HashMap([]);\n              for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {\n                // tracking by key\n                selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);\n              }\n            } else {\n              selectedSet = new HashMap(viewValue);\n            }\n          } else if (trackFn) {\n            viewValue = callExpression(trackFn, null, viewValue);\n          }\n\n          return function isSelected(key, value) {\n            var compareValueFn;\n            if (trackFn) {\n              compareValueFn = trackFn;\n            } else if (selectAsFn) {\n              compareValueFn = selectAsFn;\n            } else {\n              compareValueFn = valueFn;\n            }\n\n            if (multiple) {\n              return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));\n            } else {\n              return viewValue === callExpression(compareValueFn, key, value);\n            }\n          };\n        }\n\n        function scheduleRendering() {\n          if (!renderScheduled) {\n            scope.$$postDigest(render);\n            renderScheduled = true;\n          }\n        }\n\n        /**\n         * A new labelMap is created with each render.\n         * This function is called for each existing option with added=false,\n         * and each new option with added=true.\n         * - Labels that are passed to this method twice,\n         * (once with added=true and once with added=false) will end up with a value of 0, and\n         * will cause no change to happen to the corresponding option.\n         * - Labels that are passed to this method only once with added=false will end up with a\n         * value of -1 and will eventually be passed to selectCtrl.removeOption()\n         * - Labels that are passed to this method only once with added=true will end up with a\n         * value of 1 and will eventually be passed to selectCtrl.addOption()\n        */\n        function updateLabelMap(labelMap, label, added) {\n          labelMap[label] = labelMap[label] || 0;\n          labelMap[label] += (added ? 1 : -1);\n        }\n\n        function render() {\n          renderScheduled = false;\n\n          // Temporary location for the option groups before we render them\n          var optionGroups = {'':[]},\n              optionGroupNames = [''],\n              optionGroupName,\n              optionGroup,\n              option,\n              existingParent, existingOptions, existingOption,\n              viewValue = ctrl.$viewValue,\n              values = valuesFn(scope) || [],\n              keys = keyName ? sortedKeys(values) : values,\n              key,\n              value,\n              groupLength, length,\n              groupIndex, index,\n              labelMap = {},\n              selected,\n              isSelected = createIsSelectedFn(viewValue),\n              anySelected = false,\n              lastElement,\n              element,\n              label,\n              optionId;\n\n          trackKeysCache = {};\n\n          // We now build up the list of options we need (we merge later)\n          for (index = 0; length = keys.length, index < length; index++) {\n            key = index;\n            if (keyName) {\n              key = keys[index];\n              if (key.charAt(0) === '$') continue;\n            }\n            value = values[key];\n\n            optionGroupName = callExpression(groupByFn, key, value) || '';\n            if (!(optionGroup = optionGroups[optionGroupName])) {\n              optionGroup = optionGroups[optionGroupName] = [];\n              optionGroupNames.push(optionGroupName);\n            }\n\n            selected = isSelected(key, value);\n            anySelected = anySelected || selected;\n\n            label = callExpression(displayFn, key, value); // what will be seen by the user\n\n            // doing displayFn(scope, locals) || '' overwrites zero values\n            label = isDefined(label) ? label : '';\n            optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);\n            if (trackFn) {\n              trackKeysCache[optionId] = key;\n            }\n\n            optionGroup.push({\n              // either the index into array or key from object\n              id: optionId,\n              label: label,\n              selected: selected                   // determine if we should be selected\n            });\n          }\n          if (!multiple) {\n            if (nullOption || viewValue === null) {\n              // insert null option if we have a placeholder, or the model is null\n              optionGroups[''].unshift({id:'', label:'', selected:!anySelected});\n            } else if (!anySelected) {\n              // option could not be found, we have to insert the undefined item\n              optionGroups[''].unshift({id:'?', label:'', selected:true});\n            }\n          }\n\n          // Now we need to update the list of DOM nodes to match the optionGroups we computed above\n          for (groupIndex = 0, groupLength = optionGroupNames.length;\n               groupIndex < groupLength;\n               groupIndex++) {\n            // current option group name or '' if no group\n            optionGroupName = optionGroupNames[groupIndex];\n\n            // list of options for that group. (first item has the parent)\n            optionGroup = optionGroups[optionGroupName];\n\n            if (optionGroupsCache.length <= groupIndex) {\n              // we need to grow the optionGroups\n              existingParent = {\n                element: optGroupTemplate.clone().attr('label', optionGroupName),\n                label: optionGroup.label\n              };\n              existingOptions = [existingParent];\n              optionGroupsCache.push(existingOptions);\n              selectElement.append(existingParent.element);\n            } else {\n              existingOptions = optionGroupsCache[groupIndex];\n              existingParent = existingOptions[0];  // either SELECT (no group) or OPTGROUP element\n\n              // update the OPTGROUP label if not the same.\n              if (existingParent.label != optionGroupName) {\n                existingParent.element.attr('label', existingParent.label = optionGroupName);\n              }\n            }\n\n            lastElement = null;  // start at the beginning\n            for (index = 0, length = optionGroup.length; index < length; index++) {\n              option = optionGroup[index];\n              if ((existingOption = existingOptions[index + 1])) {\n                // reuse elements\n                lastElement = existingOption.element;\n                if (existingOption.label !== option.label) {\n                  updateLabelMap(labelMap, existingOption.label, false);\n                  updateLabelMap(labelMap, option.label, true);\n                  lastElement.text(existingOption.label = option.label);\n                  lastElement.prop('label', existingOption.label);\n                }\n                if (existingOption.id !== option.id) {\n                  lastElement.val(existingOption.id = option.id);\n                }\n                // lastElement.prop('selected') provided by jQuery has side-effects\n                if (lastElement[0].selected !== option.selected) {\n                  lastElement.prop('selected', (existingOption.selected = option.selected));\n                  if (msie) {\n                    // See #7692\n                    // The selected item wouldn't visually update on IE without this.\n                    // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well\n                    lastElement.prop('selected', existingOption.selected);\n                  }\n                }\n              } else {\n                // grow elements\n\n                // if it's a null option\n                if (option.id === '' && nullOption) {\n                  // put back the pre-compiled element\n                  element = nullOption;\n                } else {\n                  // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but\n                  // in this version of jQuery on some browser the .text() returns a string\n                  // rather then the element.\n                  (element = optionTemplate.clone())\n                      .val(option.id)\n                      .prop('selected', option.selected)\n                      .attr('selected', option.selected)\n                      .prop('label', option.label)\n                      .text(option.label);\n                }\n\n                existingOptions.push(existingOption = {\n                    element: element,\n                    label: option.label,\n                    id: option.id,\n                    selected: option.selected\n                });\n                updateLabelMap(labelMap, option.label, true);\n                if (lastElement) {\n                  lastElement.after(element);\n                } else {\n                  existingParent.element.append(element);\n                }\n                lastElement = element;\n              }\n            }\n            // remove any excessive OPTIONs in a group\n            index++; // increment since the existingOptions[0] is parent element not OPTION\n            while (existingOptions.length > index) {\n              option = existingOptions.pop();\n              updateLabelMap(labelMap, option.label, false);\n              option.element.remove();\n            }\n          }\n          // remove any excessive OPTGROUPs from select\n          while (optionGroupsCache.length > groupIndex) {\n            // remove all the labels in the option group\n            optionGroup = optionGroupsCache.pop();\n            for (index = 1; index < optionGroup.length; ++index) {\n              updateLabelMap(labelMap, optionGroup[index].label, false);\n            }\n            optionGroup[0].element.remove();\n          }\n          forEach(labelMap, function(count, label) {\n            if (count > 0) {\n              selectCtrl.addOption(label);\n            } else if (count < 0) {\n              selectCtrl.removeOption(label);\n            }\n          });\n        }\n      }\n    }\n  };\n}];\n\nvar optionDirective = ['$interpolate', function($interpolate) {\n  var nullSelectCtrl = {\n    addOption: noop,\n    removeOption: noop\n  };\n\n  return {\n    restrict: 'E',\n    priority: 100,\n    compile: function(element, attr) {\n      if (isUndefined(attr.value)) {\n        var interpolateFn = $interpolate(element.text(), true);\n        if (!interpolateFn) {\n          attr.$set('value', element.text());\n        }\n      }\n\n      return function(scope, element, attr) {\n        var selectCtrlName = '$selectController',\n            parent = element.parent(),\n            selectCtrl = parent.data(selectCtrlName) ||\n              parent.parent().data(selectCtrlName); // in case we are in optgroup\n\n        if (!selectCtrl || !selectCtrl.databound) {\n          selectCtrl = nullSelectCtrl;\n        }\n\n        if (interpolateFn) {\n          scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {\n            attr.$set('value', newVal);\n            if (oldVal !== newVal) {\n              selectCtrl.removeOption(oldVal);\n            }\n            selectCtrl.addOption(newVal, element);\n          });\n        } else {\n          selectCtrl.addOption(attr.value, element);\n        }\n\n        element.on('$destroy', function() {\n          selectCtrl.removeOption(attr.value);\n        });\n      };\n    }\n  };\n}];\n\nvar styleDirective = valueFn({\n  restrict: 'E',\n  terminal: false\n});\n\nvar requiredDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n      attr.required = true; // force truthy in case we are on non input element\n\n      ctrl.$validators.required = function(modelValue, viewValue) {\n        return !attr.required || !ctrl.$isEmpty(viewValue);\n      };\n\n      attr.$observe('required', function() {\n        ctrl.$validate();\n      });\n    }\n  };\n};\n\n\nvar patternDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var regexp, patternExp = attr.ngPattern || attr.pattern;\n      attr.$observe('pattern', function(regex) {\n        if (isString(regex) && regex.length > 0) {\n          regex = new RegExp('^' + regex + '$');\n        }\n\n        if (regex && !regex.test) {\n          throw minErr('ngPattern')('noregexp',\n            'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,\n            regex, startingTag(elm));\n        }\n\n        regexp = regex || undefined;\n        ctrl.$validate();\n      });\n\n      ctrl.$validators.pattern = function(value) {\n        return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);\n      };\n    }\n  };\n};\n\n\nvar maxlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var maxlength = -1;\n      attr.$observe('maxlength', function(value) {\n        var intVal = int(value);\n        maxlength = isNaN(intVal) ? -1 : intVal;\n        ctrl.$validate();\n      });\n      ctrl.$validators.maxlength = function(modelValue, viewValue) {\n        return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);\n      };\n    }\n  };\n};\n\nvar minlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var minlength = 0;\n      attr.$observe('minlength', function(value) {\n        minlength = int(value) || 0;\n        ctrl.$validate();\n      });\n      ctrl.$validators.minlength = function(modelValue, viewValue) {\n        return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;\n      };\n    }\n  };\n};\n\n  if (window.angular.bootstrap) {\n    //AngularJS is already loaded, so we can return here...\n    console.log('WARNING: Tried to load angular more than once.');\n    return;\n  }\n\n  //try to bind to jquery now so that one can write jqLite(document).ready()\n  //but we will rebind on bootstrap again.\n  bindJQuery();\n\n  publishExternalAPI(angular);\n\n  jqLite(document).ready(function() {\n    angularInit(document, bootstrap);\n  });\n\n})(window, document);\n\n!window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type=\"text/css\">@charset \"UTF-8\";[ng\\\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\\\:form{display:block;}</style>');\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/angular-ui/angular-ui-router.js",
    "content": "/**\n * State-based routing for AngularJS\n * @version v0.2.13\n * @link http://angular-ui.github.com/\n * @license MIT License, http://www.opensource.org/licenses/MIT\n */\n\n/* commonjs package manager support (eg componentjs) */\nif (typeof module !== \"undefined\" && typeof exports !== \"undefined\" && module.exports === exports){\n  module.exports = 'ui.router';\n}\n\n(function (window, angular, undefined) {\n/*jshint globalstrict:true*/\n/*global angular:false*/\n'use strict';\n\nvar isDefined = angular.isDefined,\n    isFunction = angular.isFunction,\n    isString = angular.isString,\n    isObject = angular.isObject,\n    isArray = angular.isArray,\n    forEach = angular.forEach,\n    extend = angular.extend,\n    copy = angular.copy;\n\nfunction inherit(parent, extra) {\n  return extend(new (extend(function() {}, { prototype: parent }))(), extra);\n}\n\nfunction merge(dst) {\n  forEach(arguments, function(obj) {\n    if (obj !== dst) {\n      forEach(obj, function(value, key) {\n        if (!dst.hasOwnProperty(key)) dst[key] = value;\n      });\n    }\n  });\n  return dst;\n}\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nfunction ancestors(first, second) {\n  var path = [];\n\n  for (var n in first.path) {\n    if (first.path[n] !== second.path[n]) break;\n    path.push(first.path[n]);\n  }\n  return path;\n}\n\n/**\n * IE8-safe wrapper for `Object.keys()`.\n *\n * @param {Object} object A JavaScript object.\n * @return {Array} Returns the keys of the object as an array.\n */\nfunction objectKeys(object) {\n  if (Object.keys) {\n    return Object.keys(object);\n  }\n  var result = [];\n\n  angular.forEach(object, function(val, key) {\n    result.push(key);\n  });\n  return result;\n}\n\n/**\n * IE8-safe wrapper for `Array.prototype.indexOf()`.\n *\n * @param {Array} array A JavaScript array.\n * @param {*} value A value to search the array for.\n * @return {Number} Returns the array index value of `value`, or `-1` if not present.\n */\nfunction indexOf(array, value) {\n  if (Array.prototype.indexOf) {\n    return array.indexOf(value, Number(arguments[2]) || 0);\n  }\n  var len = array.length >>> 0, from = Number(arguments[2]) || 0;\n  from = (from < 0) ? Math.ceil(from) : Math.floor(from);\n\n  if (from < 0) from += len;\n\n  for (; from < len; from++) {\n    if (from in array && array[from] === value) return from;\n  }\n  return -1;\n}\n\n/**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} currentParams The value of the current state parameters ($stateParams).\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\nfunction inheritParams(currentParams, newParams, $current, $to) {\n  var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];\n\n  for (var i in parents) {\n    if (!parents[i].params) continue;\n    parentParams = objectKeys(parents[i].params);\n    if (!parentParams.length) continue;\n\n    for (var j in parentParams) {\n      if (indexOf(inheritList, parentParams[j]) >= 0) continue;\n      inheritList.push(parentParams[j]);\n      inherited[parentParams[j]] = currentParams[parentParams[j]];\n    }\n  }\n  return extend({}, inherited, newParams);\n}\n\n/**\n * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.\n *\n * @param {Object} a The first object.\n * @param {Object} b The second object.\n * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,\n *                     it defaults to the list of keys in `a`.\n * @return {Boolean} Returns `true` if the keys match, otherwise `false`.\n */\nfunction equalForKeys(a, b, keys) {\n  if (!keys) {\n    keys = [];\n    for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility\n  }\n\n  for (var i=0; i<keys.length; i++) {\n    var k = keys[i];\n    if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized\n  }\n  return true;\n}\n\n/**\n * Returns the subset of an object, based on a list of keys.\n *\n * @param {Array} keys\n * @param {Object} values\n * @return {Boolean} Returns a subset of `values`.\n */\nfunction filterByKeys(keys, values) {\n  var filtered = {};\n\n  forEach(keys, function (name) {\n    filtered[name] = values[name];\n  });\n  return filtered;\n}\n\n// like _.indexBy\n// when you know that your index values will be unique, or you want last-one-in to win\nfunction indexBy(array, propName) {\n  var result = {};\n  forEach(array, function(item) {\n    result[item[propName]] = item;\n  });\n  return result;\n}\n\n// extracted from underscore.js\n// Return a copy of the object only containing the whitelisted properties.\nfunction pick(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  forEach(keys, function(key) {\n    if (key in obj) copy[key] = obj[key];\n  });\n  return copy;\n}\n\n// extracted from underscore.js\n// Return a copy of the object omitting the blacklisted properties.\nfunction omit(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  for (var key in obj) {\n    if (indexOf(keys, key) == -1) copy[key] = obj[key];\n  }\n  return copy;\n}\n\nfunction pluck(collection, key) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = isFunction(key) ? key(val) : val[key];\n  });\n  return result;\n}\n\nfunction filter(collection, callback) {\n  var array = isArray(collection);\n  var result = array ? [] : {};\n  forEach(collection, function(val, i) {\n    if (callback(val, i)) {\n      result[array ? result.length : i] = val;\n    }\n  });\n  return result;\n}\n\nfunction map(collection, callback) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = callback(val, i);\n  });\n  return result;\n}\n\n/**\n * @ngdoc overview\n * @name ui.router.util\n *\n * @description\n * # ui.router.util sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n *\n */\nangular.module('ui.router.util', ['ng']);\n\n/**\n * @ngdoc overview\n * @name ui.router.router\n * \n * @requires ui.router.util\n *\n * @description\n * # ui.router.router sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n */\nangular.module('ui.router.router', ['ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router.state\n * \n * @requires ui.router.router\n * @requires ui.router.util\n *\n * @description\n * # ui.router.state sub-module\n *\n * This module is a dependency of the main ui.router module. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n * \n */\nangular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router\n *\n * @requires ui.router.state\n *\n * @description\n * # ui.router\n * \n * ## The main module for ui.router \n * There are several sub-modules included with the ui.router module, however only this module is needed\n * as a dependency within your angular app. The other modules are for organization purposes. \n *\n * The modules are:\n * * ui.router - the main \"umbrella\" module\n * * ui.router.router - \n * \n * *You'll need to include **only** this module as the dependency within your angular app.*\n * \n * <pre>\n * <!doctype html>\n * <html ng-app=\"myApp\">\n * <head>\n *   <script src=\"js/angular.js\"></script>\n *   <!-- Include the ui-router script -->\n *   <script src=\"js/angular-ui-router.min.js\"></script>\n *   <script>\n *     // ...and add 'ui.router' as a dependency\n *     var myApp = angular.module('myApp', ['ui.router']);\n *   </script>\n * </head>\n * <body>\n * </body>\n * </html>\n * </pre>\n */\nangular.module('ui.router', ['ui.router.state']);\n\nangular.module('ui.router.compat', ['ui.router']);\n\n/**\n * @ngdoc object\n * @name ui.router.util.$resolve\n *\n * @requires $q\n * @requires $injector\n *\n * @description\n * Manages resolution of (acyclic) graphs of promises.\n */\n$Resolve.$inject = ['$q', '$injector'];\nfunction $Resolve(  $q,    $injector) {\n  \n  var VISIT_IN_PROGRESS = 1,\n      VISIT_DONE = 2,\n      NOTHING = {},\n      NO_DEPENDENCIES = [],\n      NO_LOCALS = NOTHING,\n      NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });\n  \n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#study\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Studies a set of invocables that are likely to be used multiple times.\n   * <pre>\n   * $resolve.study(invocables)(locals, parent, self)\n   * </pre>\n   * is equivalent to\n   * <pre>\n   * $resolve.resolve(invocables, locals, parent, self)\n   * </pre>\n   * but the former is more efficient (in fact `resolve` just calls `study` \n   * internally).\n   *\n   * @param {object} invocables Invocable objects\n   * @return {function} a function to pass in locals, parent and self\n   */\n  this.study = function (invocables) {\n    if (!isObject(invocables)) throw new Error(\"'invocables' must be an object\");\n    var invocableKeys = objectKeys(invocables || {});\n    \n    // Perform a topological sort of invocables to build an ordered plan\n    var plan = [], cycle = [], visited = {};\n    function visit(value, key) {\n      if (visited[key] === VISIT_DONE) return;\n      \n      cycle.push(key);\n      if (visited[key] === VISIT_IN_PROGRESS) {\n        cycle.splice(0, indexOf(cycle, key));\n        throw new Error(\"Cyclic dependency: \" + cycle.join(\" -> \"));\n      }\n      visited[key] = VISIT_IN_PROGRESS;\n      \n      if (isString(value)) {\n        plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);\n      } else {\n        var params = $injector.annotate(value);\n        forEach(params, function (param) {\n          if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);\n        });\n        plan.push(key, value, params);\n      }\n      \n      cycle.pop();\n      visited[key] = VISIT_DONE;\n    }\n    forEach(invocables, visit);\n    invocables = cycle = visited = null; // plan is all that's required\n    \n    function isResolve(value) {\n      return isObject(value) && value.then && value.$$promises;\n    }\n    \n    return function (locals, parent, self) {\n      if (isResolve(locals) && self === undefined) {\n        self = parent; parent = locals; locals = null;\n      }\n      if (!locals) locals = NO_LOCALS;\n      else if (!isObject(locals)) {\n        throw new Error(\"'locals' must be an object\");\n      }       \n      if (!parent) parent = NO_PARENT;\n      else if (!isResolve(parent)) {\n        throw new Error(\"'parent' must be a promise returned by $resolve.resolve()\");\n      }\n      \n      // To complete the overall resolution, we have to wait for the parent\n      // promise and for the promise for each invokable in our plan.\n      var resolution = $q.defer(),\n          result = resolution.promise,\n          promises = result.$$promises = {},\n          values = extend({}, locals),\n          wait = 1 + plan.length/3,\n          merged = false;\n          \n      function done() {\n        // Merge parent values we haven't got yet and publish our own $$values\n        if (!--wait) {\n          if (!merged) merge(values, parent.$$values); \n          result.$$values = values;\n          result.$$promises = result.$$promises || true; // keep for isResolve()\n          delete result.$$inheritedValues;\n          resolution.resolve(values);\n        }\n      }\n      \n      function fail(reason) {\n        result.$$failure = reason;\n        resolution.reject(reason);\n      }\n\n      // Short-circuit if parent has already failed\n      if (isDefined(parent.$$failure)) {\n        fail(parent.$$failure);\n        return result;\n      }\n      \n      if (parent.$$inheritedValues) {\n        merge(values, omit(parent.$$inheritedValues, invocableKeys));\n      }\n\n      // Merge parent values if the parent has already resolved, or merge\n      // parent promises and wait if the parent resolve is still in progress.\n      extend(promises, parent.$$promises);\n      if (parent.$$values) {\n        merged = merge(values, omit(parent.$$values, invocableKeys));\n        result.$$inheritedValues = omit(parent.$$values, invocableKeys);\n        done();\n      } else {\n        if (parent.$$inheritedValues) {\n          result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);\n        }        \n        parent.then(done, fail);\n      }\n      \n      // Process each invocable in the plan, but ignore any where a local of the same name exists.\n      for (var i=0, ii=plan.length; i<ii; i+=3) {\n        if (locals.hasOwnProperty(plan[i])) done();\n        else invoke(plan[i], plan[i+1], plan[i+2]);\n      }\n      \n      function invoke(key, invocable, params) {\n        // Create a deferred for this invocation. Failures will propagate to the resolution as well.\n        var invocation = $q.defer(), waitParams = 0;\n        function onfailure(reason) {\n          invocation.reject(reason);\n          fail(reason);\n        }\n        // Wait for any parameter that we have a promise for (either from parent or from this\n        // resolve; in that case study() will have made sure it's ordered before us in the plan).\n        forEach(params, function (dep) {\n          if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {\n            waitParams++;\n            promises[dep].then(function (result) {\n              values[dep] = result;\n              if (!(--waitParams)) proceed();\n            }, onfailure);\n          }\n        });\n        if (!waitParams) proceed();\n        function proceed() {\n          if (isDefined(result.$$failure)) return;\n          try {\n            invocation.resolve($injector.invoke(invocable, self, values));\n            invocation.promise.then(function (result) {\n              values[key] = result;\n              done();\n            }, onfailure);\n          } catch (e) {\n            onfailure(e);\n          }\n        }\n        // Publish promise synchronously; invocations further down in the plan may depend on it.\n        promises[key] = invocation.promise;\n      }\n      \n      return result;\n    };\n  };\n  \n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#resolve\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Resolves a set of invocables. An invocable is a function to be invoked via \n   * `$injector.invoke()`, and can have an arbitrary number of dependencies. \n   * An invocable can either return a value directly,\n   * or a `$q` promise. If a promise is returned it will be resolved and the \n   * resulting value will be used instead. Dependencies of invocables are resolved \n   * (in this order of precedence)\n   *\n   * - from the specified `locals`\n   * - from another invocable that is part of this `$resolve` call\n   * - from an invocable that is inherited from a `parent` call to `$resolve` \n   *   (or recursively\n   * - from any ancestor `$resolve` of that parent).\n   *\n   * The return value of `$resolve` is a promise for an object that contains \n   * (in this order of precedence)\n   *\n   * - any `locals` (if specified)\n   * - the resolved return values of all injectables\n   * - any values inherited from a `parent` call to `$resolve` (if specified)\n   *\n   * The promise will resolve after the `parent` promise (if any) and all promises \n   * returned by injectables have been resolved. If any invocable \n   * (or `$injector.invoke`) throws an exception, or if a promise returned by an \n   * invocable is rejected, the `$resolve` promise is immediately rejected with the \n   * same error. A rejection of a `parent` promise (if specified) will likewise be \n   * propagated immediately. Once the `$resolve` promise has been rejected, no \n   * further invocables will be called.\n   * \n   * Cyclic dependencies between invocables are not permitted and will caues `$resolve`\n   * to throw an error. As a special case, an injectable can depend on a parameter \n   * with the same name as the injectable, which will be fulfilled from the `parent` \n   * injectable of the same name. This allows inherited values to be decorated. \n   * Note that in this case any other injectable in the same `$resolve` with the same\n   * dependency would see the decorated value, not the inherited value.\n   *\n   * Note that missing dependencies -- unlike cyclic dependencies -- will cause an \n   * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous) \n   * exception.\n   *\n   * Invocables are invoked eagerly as soon as all dependencies are available. \n   * This is true even for dependencies inherited from a `parent` call to `$resolve`.\n   *\n   * As a special case, an invocable can be a string, in which case it is taken to \n   * be a service name to be passed to `$injector.get()`. This is supported primarily \n   * for backwards-compatibility with the `resolve` property of `$routeProvider` \n   * routes.\n   *\n   * @param {object} invocables functions to invoke or \n   * `$injector` services to fetch.\n   * @param {object} locals  values to make available to the injectables\n   * @param {object} parent  a promise returned by another call to `$resolve`.\n   * @param {object} self  the `this` for the invoked methods\n   * @return {object} Promise for an object that contains the resolved return value\n   * of all invocables, as well as any inherited and local values.\n   */\n  this.resolve = function (invocables, locals, parent, self) {\n    return this.study(invocables)(locals, parent, self);\n  };\n}\n\nangular.module('ui.router.util').service('$resolve', $Resolve);\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$templateFactory\n *\n * @requires $http\n * @requires $templateCache\n * @requires $injector\n *\n * @description\n * Service. Manages loading of templates.\n */\n$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];\nfunction $TemplateFactory(  $http,   $templateCache,   $injector) {\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromConfig\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a configuration object. \n   *\n   * @param {object} config Configuration object for which to load a template. \n   * The following properties are search in the specified order, and the first one \n   * that is defined is used to create the template:\n   *\n   * @param {string|object} config.template html string template or function to \n   * load via {@link ui.router.util.$templateFactory#fromString fromString}.\n   * @param {string|object} config.templateUrl url to load or a function returning \n   * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.\n   * @param {Function} config.templateProvider function to invoke via \n   * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.\n   * @param {object} params  Parameters to pass to the template function.\n   * @param {object} locals Locals to pass to `invoke` if the template is loaded \n   * via a `templateProvider`. Defaults to `{ params: params }`.\n   *\n   * @return {string|object}  The template html as a string, or a promise for \n   * that string,or `null` if no template is configured.\n   */\n  this.fromConfig = function (config, params, locals) {\n    return (\n      isDefined(config.template) ? this.fromString(config.template, params) :\n      isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :\n      isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :\n      null\n    );\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromString\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a string or a function returning a string.\n   *\n   * @param {string|object} template html template as a string or function that \n   * returns an html template as a string.\n   * @param {object} params Parameters to pass to the template function.\n   *\n   * @return {string|object} The template html as a string, or a promise for that \n   * string.\n   */\n  this.fromString = function (template, params) {\n    return isFunction(template) ? template(params) : template;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromUrl\n   * @methodOf ui.router.util.$templateFactory\n   * \n   * @description\n   * Loads a template from the a URL via `$http` and `$templateCache`.\n   *\n   * @param {string|Function} url url of the template to load, or a function \n   * that returns a url.\n   * @param {Object} params Parameters to pass to the url function.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromUrl = function (url, params) {\n    if (isFunction(url)) url = url(params);\n    if (url == null) return null;\n    else return $http\n        .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})\n        .then(function(response) { return response.data; });\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromProvider\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template by invoking an injectable provider function.\n   *\n   * @param {Function} provider Function to invoke via `$injector.invoke`\n   * @param {Object} params Parameters for the template.\n   * @param {Object} locals Locals to pass to `invoke`. Defaults to \n   * `{ params: params }`.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromProvider = function (provider, params, locals) {\n    return $injector.invoke(provider, null, locals || { params: params });\n  };\n}\n\nangular.module('ui.router.util').service('$templateFactory', $TemplateFactory);\n\nvar $$UMFP; // reference to $UrlMatcherFactoryProvider\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:UrlMatcher\n *\n * @description\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list\n * of search parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.\n * \n * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace\n * syntax, which optionally allows a regular expression for the parameter to be specified:\n *\n * * `':'` name - colon placeholder\n * * `'*'` name - catch-all placeholder\n * * `'{' name '}'` - curly placeholder\n * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the\n *   regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters). For colon \n * placeholders or curly placeholders without an explicit regexp, a path parameter matches any\n * number of characters other than '/'. For catch-all placeholders the path parameter matches\n * any number of characters.\n * \n * Examples:\n * \n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n *   trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n *   '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n *   parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n *   path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n *   in the built-in  `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n * @param {string} pattern  The pattern to compile into a matcher.\n * @param {Object} config  A configuration object hash:\n * @param {Object=} parentMatcher Used to concatenate the pattern/config onto\n *   an existing UrlMatcher\n *\n * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n *\n * @property {string} prefix  A static prefix of this pattern. The matcher guarantees that any\n *   URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns\n *   non-null) will start with this prefix.\n *\n * @property {string} source  The pattern that was passed into the constructor\n *\n * @property {string} sourcePath  The path portion of the source property\n *\n * @property {string} sourceSearch  The search portion of the source property\n *\n * @property {string} regex  The constructed regex that will be used to match against the url when \n *   it is time to determine which url will match.\n *\n * @returns {Object}  New `UrlMatcher` object\n */\nfunction UrlMatcher(pattern, config, parentMatcher) {\n  config = extend({ params: {} }, isObject(config) ? config : {});\n\n  // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n  //   '*' name\n  //   ':' name\n  //   '{' name '}'\n  //   '{' name ':' regexp '}'\n  // The regular expression is somewhat complicated due to the need to allow curly braces\n  // inside the regular expression. The placeholder regexp breaks down as follows:\n  //    ([:*])([\\w\\[\\]]+)              - classic placeholder ($1 / $2) (search version has - for snake-case)\n  //    \\{([\\w\\[\\]]+)(?:\\:( ... ))?\\}  - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n  //    (?: ... | ... | ... )+         - the regexp consists of any number of atoms, an atom being either\n  //    [^{}\\\\]+                       - anything other than curly braces or backslash\n  //    \\\\.                            - a backslash escape\n  //    \\{(?:[^{}\\\\]+|\\\\.)*\\}          - a matched set of curly braces containing other atoms\n  var placeholder       = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      searchPlaceholder = /([:]?)([\\w\\[\\]-]+)|\\{([\\w\\[\\]-]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      compiled = '^', last = 0, m,\n      segments = this.segments = [],\n      parentParams = parentMatcher ? parentMatcher.params : {},\n      params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),\n      paramNames = [];\n\n  function addParameter(id, type, config, location) {\n    paramNames.push(id);\n    if (parentParams[id]) return parentParams[id];\n    if (!/^\\w+(-+\\w+)*(?:\\[\\])?$/.test(id)) throw new Error(\"Invalid parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    if (params[id]) throw new Error(\"Duplicate parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    params[id] = new $$UMFP.Param(id, type, config, location);\n    return params[id];\n  }\n\n  function quoteRegExp(string, pattern, squash) {\n    var surroundPattern = ['',''], result = string.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, \"\\\\$&\");\n    if (!pattern) return result;\n    switch(squash) {\n      case false: surroundPattern = ['(', ')'];   break;\n      case true:  surroundPattern = ['?(', ')?']; break;\n      default:    surroundPattern = ['(' + squash + \"|\", ')?'];  break;\n    }\n    return result + surroundPattern[0] + pattern + surroundPattern[1];\n  }\n\n  this.source = pattern;\n\n  // Split into static segments separated by path parameter placeholders.\n  // The number of segments is always 1 more than the number of parameters.\n  function matchDetails(m, isSearch) {\n    var id, regexp, segment, type, cfg, arrayMode;\n    id          = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null\n    cfg         = config.params[id];\n    segment     = pattern.substring(last, m.index);\n    regexp      = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);\n    type        = $$UMFP.type(regexp || \"string\") || inherit($$UMFP.type(\"string\"), { pattern: new RegExp(regexp) });\n    return {\n      id: id, regexp: regexp, segment: segment, type: type, cfg: cfg\n    };\n  }\n\n  var p, param, segment;\n  while ((m = placeholder.exec(pattern))) {\n    p = matchDetails(m, false);\n    if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n    param = addParameter(p.id, p.type, p.cfg, \"path\");\n    compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash);\n    segments.push(p.segment);\n    last = placeholder.lastIndex;\n  }\n  segment = pattern.substring(last);\n\n  // Find any search parameter names and remove them from the last segment\n  var i = segment.indexOf('?');\n\n  if (i >= 0) {\n    var search = this.sourceSearch = segment.substring(i);\n    segment = segment.substring(0, i);\n    this.sourcePath = pattern.substring(0, last + i);\n\n    if (search.length > 0) {\n      last = 0;\n      while ((m = searchPlaceholder.exec(search))) {\n        p = matchDetails(m, true);\n        param = addParameter(p.id, p.type, p.cfg, \"search\");\n        last = placeholder.lastIndex;\n        // check if ?&\n      }\n    }\n  } else {\n    this.sourcePath = pattern;\n    this.sourceSearch = '';\n  }\n\n  compiled += quoteRegExp(segment) + (config.strict === false ? '\\/?' : '') + '$';\n  segments.push(segment);\n\n  this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);\n  this.prefix = segments[0];\n  this.$$paramNames = paramNames;\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#concat\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns a new matcher for a pattern constructed by appending the path part and adding the\n * search parameters of the specified pattern to this pattern. The current pattern is not\n * modified. This can be understood as creating a pattern for URLs that are relative to (or\n * suffixes of) the current pattern.\n *\n * @example\n * The following two matchers are equivalent:\n * <pre>\n * new UrlMatcher('/user/{id}?q').concat('/details?date');\n * new UrlMatcher('/user/{id}/details?q&date');\n * </pre>\n *\n * @param {string} pattern  The pattern to append.\n * @param {Object} config  An object hash of the configuration for the matcher.\n * @returns {UrlMatcher}  A matcher for the concatenated pattern.\n */\nUrlMatcher.prototype.concat = function (pattern, config) {\n  // Because order of search parameters is irrelevant, we can add our own search\n  // parameters to the end of the new pattern. Parse the new pattern by itself\n  // and then join the bits together, but it's much easier to do this on a string level.\n  var defaultConfig = {\n    caseInsensitive: $$UMFP.caseInsensitive(),\n    strict: $$UMFP.strictMode(),\n    squash: $$UMFP.defaultSquashPolicy()\n  };\n  return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);\n};\n\nUrlMatcher.prototype.toString = function () {\n  return this.source;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#exec\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Tests the specified path against this matcher, and returns an object containing the captured\n * parameter values, or null if the path does not match. The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `searchParams`. This means that search parameters are always treated\n * as optional.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n *   x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * </pre>\n *\n * @param {string} path  The URL path to match, e.g. `$location.path()`.\n * @param {Object} searchParams  URL search parameters, e.g. `$location.search()`.\n * @returns {Object}  The captured parameter values.\n */\nUrlMatcher.prototype.exec = function (path, searchParams) {\n  var m = this.regexp.exec(path);\n  if (!m) return null;\n  searchParams = searchParams || {};\n\n  var paramNames = this.parameters(), nTotal = paramNames.length,\n    nPath = this.segments.length - 1,\n    values = {}, i, j, cfg, paramName;\n\n  if (nPath !== m.length - 1) throw new Error(\"Unbalanced capture group in route '\" + this.source + \"'\");\n\n  function decodePathArray(string) {\n    function reverseString(str) { return str.split(\"\").reverse().join(\"\"); }\n    function unquoteDashes(str) { return str.replace(/\\\\-/, \"-\"); }\n\n    var split = reverseString(string).split(/-(?!\\\\)/);\n    var allReversed = map(split, reverseString);\n    return map(allReversed, unquoteDashes).reverse();\n  }\n\n  for (i = 0; i < nPath; i++) {\n    paramName = paramNames[i];\n    var param = this.params[paramName];\n    var paramVal = m[i+1];\n    // if the param value matches a pre-replace pair, replace the value before decoding.\n    for (j = 0; j < param.replace; j++) {\n      if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;\n    }\n    if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);\n    values[paramName] = param.value(paramVal);\n  }\n  for (/**/; i < nTotal; i++) {\n    paramName = paramNames[i];\n    values[paramName] = this.params[paramName].value(searchParams[paramName]);\n  }\n\n  return values;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#parameters\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns the names of all path and search parameters of this pattern in an unspecified order.\n * \n * @returns {Array.<string>}  An array of parameter names. Must be treated as read-only. If the\n *    pattern has no parameters, an empty array is returned.\n */\nUrlMatcher.prototype.parameters = function (param) {\n  if (!isDefined(param)) return this.$$paramNames;\n  return this.params[param] || null;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#validate\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param {Object} params The object hash of parameters to validate.\n * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.\n */\nUrlMatcher.prototype.validates = function (params) {\n  return this.params.$$validates(params);\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#format\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters. Null values for path parameters are\n * treated as empty strings.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * </pre>\n *\n * @param {Object} values  the values to substitute for the parameters in this pattern.\n * @returns {string}  the formatted URL (path and optionally search part).\n */\nUrlMatcher.prototype.format = function (values) {\n  values = values || {};\n  var segments = this.segments, params = this.parameters(), paramset = this.params;\n  if (!this.validates(values)) return null;\n\n  var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];\n\n  function encodeDashes(str) { // Replace dashes with encoded \"\\-\"\n    return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });\n  }\n\n  for (i = 0; i < nTotal; i++) {\n    var isPathParam = i < nPath;\n    var name = params[i], param = paramset[name], value = param.value(values[name]);\n    var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);\n    var squash = isDefaultValue ? param.squash : false;\n    var encoded = param.type.encode(value);\n\n    if (isPathParam) {\n      var nextSegment = segments[i + 1];\n      if (squash === false) {\n        if (encoded != null) {\n          if (isArray(encoded)) {\n            result += map(encoded, encodeDashes).join(\"-\");\n          } else {\n            result += encodeURIComponent(encoded);\n          }\n        }\n        result += nextSegment;\n      } else if (squash === true) {\n        var capture = result.match(/\\/$/) ? /\\/?(.*)/ : /(.*)/;\n        result += nextSegment.match(capture)[1];\n      } else if (isString(squash)) {\n        result += squash + nextSegment;\n      }\n    } else {\n      if (encoded == null || (isDefaultValue && squash !== false)) continue;\n      if (!isArray(encoded)) encoded = [ encoded ];\n      encoded = map(encoded, encodeURIComponent).join('&' + name + '=');\n      result += (search ? '&' : '?') + (name + '=' + encoded);\n      search = true;\n    }\n  }\n\n  return result;\n};\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:Type\n *\n * @description\n * Implements an interface to define custom parameter types that can be decoded from and encoded to\n * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}\n * objects when matching or formatting URLs, or comparing or validating parameter values.\n *\n * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more\n * information on registering custom types.\n *\n * @param {Object} config  A configuration object which contains the custom type definition.  The object's\n *        properties will override the default methods and/or pattern in `Type`'s public interface.\n * @example\n * <pre>\n * {\n *   decode: function(val) { return parseInt(val, 10); },\n *   encode: function(val) { return val && val.toString(); },\n *   equals: function(a, b) { return this.is(a) && a === b; },\n *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },\n *   pattern: /\\d+/\n * }\n * </pre>\n *\n * @property {RegExp} pattern The regular expression pattern used to match values of this type when\n *           coming from a substring of a URL.\n *\n * @returns {Object}  Returns a new `Type` object.\n */\nfunction Type(config) {\n  extend(this, config);\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#is\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Detects whether a value is of a particular type. Accepts a native (decoded) value\n * and determines whether it matches the current `Type` object.\n *\n * @param {*} val  The value to check.\n * @param {string} key  Optional. If the type check is happening in the context of a specific\n *        {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the\n *        parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.\n * @returns {Boolean}  Returns `true` if the value matches the type, otherwise `false`.\n */\nType.prototype.is = function(val, key) {\n  return true;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#encode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the\n * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it\n * only needs to be a representation of `val` that has been coerced to a string.\n *\n * @param {*} val  The value to encode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {string}  Returns a string representation of `val` that can be encoded in a URL.\n */\nType.prototype.encode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#decode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Converts a parameter value (from URL string or transition param) to a custom/native value.\n *\n * @param {string} val  The URL parameter value to decode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {*}  Returns a custom representation of the URL parameter value.\n */\nType.prototype.decode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#equals\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Determines whether two decoded values are equivalent.\n *\n * @param {*} a  A value to compare against.\n * @param {*} b  A value to compare against.\n * @returns {Boolean}  Returns `true` if the values are equivalent/equal, otherwise `false`.\n */\nType.prototype.equals = function(a, b) {\n  return a == b;\n};\n\nType.prototype.$subPattern = function() {\n  var sub = this.pattern.toString();\n  return sub.substr(1, sub.length - 2);\n};\n\nType.prototype.pattern = /.*/;\n\nType.prototype.toString = function() { return \"{Type:\" + this.name + \"}\"; };\n\n/*\n * Wraps an existing custom Type as an array of Type, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\nType.prototype.$asArray = function(mode, isSearch) {\n  if (!mode) return this;\n  if (mode === \"auto\" && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n  return new ArrayType(this, mode);\n\n  function ArrayType(type, mode) {\n    function bindTo(type, callbackName) {\n      return function() {\n        return type[callbackName].apply(type, arguments);\n      };\n    }\n\n    // Wrap non-array value as array\n    function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }\n    // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n    function arrayUnwrap(val) {\n      switch(val.length) {\n        case 0: return undefined;\n        case 1: return mode === \"auto\" ? val[0] : val;\n        default: return val;\n      }\n    }\n    function falsey(val) { return !val; }\n\n    // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n    function arrayHandler(callback, allTruthyMode) {\n      return function handleArray(val) {\n        val = arrayWrap(val);\n        var result = map(val, callback);\n        if (allTruthyMode === true)\n          return filter(result, falsey).length === 0;\n        return arrayUnwrap(result);\n      };\n    }\n\n    // Wraps type (.equals) functions to operate on each value of an array\n    function arrayEqualsHandler(callback) {\n      return function handleArray(val1, val2) {\n        var left = arrayWrap(val1), right = arrayWrap(val2);\n        if (left.length !== right.length) return false;\n        for (var i = 0; i < left.length; i++) {\n          if (!callback(left[i], right[i])) return false;\n        }\n        return true;\n      };\n    }\n\n    this.encode = arrayHandler(bindTo(type, 'encode'));\n    this.decode = arrayHandler(bindTo(type, 'decode'));\n    this.is     = arrayHandler(bindTo(type, 'is'), true);\n    this.equals = arrayEqualsHandler(bindTo(type, 'equals'));\n    this.pattern = type.pattern;\n    this.$arrayMode = mode;\n  }\n};\n\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$urlMatcherFactory\n *\n * @description\n * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory\n * is also available to providers under the name `$urlMatcherFactoryProvider`.\n */\nfunction $UrlMatcherFactory() {\n  $$UMFP = this;\n\n  var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;\n\n  function valToString(val) { return val != null ? val.toString().replace(/\\//g, \"%2F\") : val; }\n  function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, \"/\") : val; }\n//  TODO: in 1.0, make string .is() return false if value is undefined by default.\n//  function regexpMatches(val) { /*jshint validthis:true */ return isDefined(val) && this.pattern.test(val); }\n  function regexpMatches(val) { /*jshint validthis:true */ return this.pattern.test(val); }\n\n  var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {\n    string: {\n      encode: valToString,\n      decode: valFromString,\n      is: regexpMatches,\n      pattern: /[^/]*/\n    },\n    int: {\n      encode: valToString,\n      decode: function(val) { return parseInt(val, 10); },\n      is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },\n      pattern: /\\d+/\n    },\n    bool: {\n      encode: function(val) { return val ? 1 : 0; },\n      decode: function(val) { return parseInt(val, 10) !== 0; },\n      is: function(val) { return val === true || val === false; },\n      pattern: /0|1/\n    },\n    date: {\n      encode: function (val) {\n        if (!this.is(val))\n          return undefined;\n        return [ val.getFullYear(),\n          ('0' + (val.getMonth() + 1)).slice(-2),\n          ('0' + val.getDate()).slice(-2)\n        ].join(\"-\");\n      },\n      decode: function (val) {\n        if (this.is(val)) return val;\n        var match = this.capture.exec(val);\n        return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n      },\n      is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },\n      equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },\n      pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n      capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/\n    },\n    json: {\n      encode: angular.toJson,\n      decode: angular.fromJson,\n      is: angular.isObject,\n      equals: angular.equals,\n      pattern: /[^/]*/\n    },\n    any: { // does not encode/decode\n      encode: angular.identity,\n      decode: angular.identity,\n      is: angular.identity,\n      equals: angular.equals,\n      pattern: /.*/\n    }\n  };\n\n  function getDefaultConfig() {\n    return {\n      strict: isStrictMode,\n      caseInsensitive: isCaseInsensitive\n    };\n  }\n\n  function isInjectable(value) {\n    return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));\n  }\n\n  /**\n   * [Internal] Get the default value of a parameter, which may be an injectable function.\n   */\n  $UrlMatcherFactory.$$getDefaultValue = function(config) {\n    if (!isInjectable(config.value)) return config.value;\n    if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n    return injector.invoke(config.value);\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#caseInsensitive\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URL matching should be case sensitive (the default behavior), or not.\n   *\n   * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;\n   * @returns {boolean} the current value of caseInsensitive\n   */\n  this.caseInsensitive = function(value) {\n    if (isDefined(value))\n      isCaseInsensitive = value;\n    return isCaseInsensitive;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#strictMode\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URLs should match trailing slashes, or not (the default behavior).\n   *\n   * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.\n   * @returns {boolean} the current value of strictMode\n   */\n  this.strictMode = function(value) {\n    if (isDefined(value))\n      isStrictMode = value;\n    return isStrictMode;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Sets the default behavior when generating or matching URLs with default parameter values.\n   *\n   * @param {string} value A string that defines the default parameter URL squashing behavior.\n   *    `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL\n   *    `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the\n   *             parameter is surrounded by slashes, squash (remove) one slash from the URL\n   *    any other string, e.g. \"~\": When generating an href with a default parameter value, squash (remove)\n   *             the parameter value from the URL and replace it with this string.\n   */\n  this.defaultSquashPolicy = function(value) {\n    if (!isDefined(value)) return defaultSquashPolicy;\n    if (value !== true && value !== false && !isString(value))\n      throw new Error(\"Invalid squash policy: \" + value + \". Valid policies: false, true, arbitrary-string\");\n    defaultSquashPolicy = value;\n    return value;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#compile\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.\n   *\n   * @param {string} pattern  The URL pattern.\n   * @param {Object} config  The config object hash.\n   * @returns {UrlMatcher}  The UrlMatcher.\n   */\n  this.compile = function (pattern, config) {\n    return new UrlMatcher(pattern, extend(getDefaultConfig(), config));\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#isMatcher\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Returns true if the specified object is a `UrlMatcher`, or false otherwise.\n   *\n   * @param {Object} object  The object to perform the type check against.\n   * @returns {Boolean}  Returns `true` if the object matches the `UrlMatcher` interface, by\n   *          implementing all the same methods.\n   */\n  this.isMatcher = function (o) {\n    if (!isObject(o)) return false;\n    var result = true;\n\n    forEach(UrlMatcher.prototype, function(val, name) {\n      if (isFunction(val)) {\n        result = result && (isDefined(o[name]) && isFunction(o[name]));\n      }\n    });\n    return result;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#type\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to\n   * generate URLs with typed parameters.\n   *\n   * @param {string} name  The type name.\n   * @param {Object|Function} definition   The type definition. See\n   *        {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   * @param {Object|Function} definitionFn (optional) A function that is injected before the app\n   *        runtime starts.  The result of this function is merged into the existing `definition`.\n   *        See {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   *\n   * @returns {Object}  Returns `$urlMatcherFactoryProvider`.\n   *\n   * @example\n   * This is a simple example of a custom type that encodes and decodes items from an\n   * array, using the array index as the URL-encoded value:\n   *\n   * <pre>\n   * var list = ['John', 'Paul', 'George', 'Ringo'];\n   *\n   * $urlMatcherFactoryProvider.type('listItem', {\n   *   encode: function(item) {\n   *     // Represent the list item in the URL using its corresponding index\n   *     return list.indexOf(item);\n   *   },\n   *   decode: function(item) {\n   *     // Look up the list item by index\n   *     return list[parseInt(item, 10)];\n   *   },\n   *   is: function(item) {\n   *     // Ensure the item is valid by checking to see that it appears\n   *     // in the list\n   *     return list.indexOf(item) > -1;\n   *   }\n   * });\n   *\n   * $stateProvider.state('list', {\n   *   url: \"/list/{item:listItem}\",\n   *   controller: function($scope, $stateParams) {\n   *     console.log($stateParams.item);\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * // Changes URL to '/list/3', logs \"Ringo\" to the console\n   * $state.go('list', { item: \"Ringo\" });\n   * </pre>\n   *\n   * This is a more complex example of a type that relies on dependency injection to\n   * interact with services, and uses the parameter name from the URL to infer how to\n   * handle encoding and decoding parameter values:\n   *\n   * <pre>\n   * // Defines a custom type that gets a value from a service,\n   * // where each service gets different types of values from\n   * // a backend API:\n   * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {\n   *\n   *   // Matches up services to URL parameter names\n   *   var services = {\n   *     user: Users,\n   *     post: Posts\n   *   };\n   *\n   *   return {\n   *     encode: function(object) {\n   *       // Represent the object in the URL using its unique ID\n   *       return object.id;\n   *     },\n   *     decode: function(value, key) {\n   *       // Look up the object by ID, using the parameter\n   *       // name (key) to call the correct service\n   *       return services[key].findById(value);\n   *     },\n   *     is: function(object, key) {\n   *       // Check that object is a valid dbObject\n   *       return angular.isObject(object) && object.id && services[key];\n   *     }\n   *     equals: function(a, b) {\n   *       // Check the equality of decoded objects by comparing\n   *       // their unique IDs\n   *       return a.id === b.id;\n   *     }\n   *   };\n   * });\n   *\n   * // In a config() block, you can then attach URLs with\n   * // type-annotated parameters:\n   * $stateProvider.state('users', {\n   *   url: \"/users\",\n   *   // ...\n   * }).state('users.item', {\n   *   url: \"/{user:dbObject}\",\n   *   controller: function($scope, $stateParams) {\n   *     // $stateParams.user will now be an object returned from\n   *     // the Users service\n   *   },\n   *   // ...\n   * });\n   * </pre>\n   */\n  this.type = function (name, definition, definitionFn) {\n    if (!isDefined(definition)) return $types[name];\n    if ($types.hasOwnProperty(name)) throw new Error(\"A type named '\" + name + \"' has already been defined.\");\n\n    $types[name] = new Type(extend({ name: name }, definition));\n    if (definitionFn) {\n      typeQueue.push({ name: name, def: definitionFn });\n      if (!enqueue) flushTypeQueue();\n    }\n    return this;\n  };\n\n  // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s\n  function flushTypeQueue() {\n    while(typeQueue.length) {\n      var type = typeQueue.shift();\n      if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n      angular.extend($types[type.name], injector.invoke(type.def));\n    }\n  }\n\n  // Register default types. Store them in the prototype of $types.\n  forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });\n  $types = inherit($types, {});\n\n  /* No need to document $get, since it returns this */\n  this.$get = ['$injector', function ($injector) {\n    injector = $injector;\n    enqueue = false;\n    flushTypeQueue();\n\n    forEach(defaultTypes, function(type, name) {\n      if (!$types[name]) $types[name] = new Type(type);\n    });\n    return this;\n  }];\n\n  this.Param = function Param(id, type, config, location) {\n    var self = this;\n    config = unwrapShorthand(config);\n    type = getType(config, type, location);\n    var arrayMode = getArrayMode();\n    type = arrayMode ? type.$asArray(arrayMode, location === \"search\") : type;\n    if (type.name === \"string\" && !arrayMode && location === \"path\" && config.value === undefined)\n      config.value = \"\"; // for 0.2.x; in 0.3.0+ do not automatically default to \"\"\n    var isOptional = config.value !== undefined;\n    var squash = getSquashPolicy(config, isOptional);\n    var replace = getReplace(config, arrayMode, isOptional, squash);\n\n    function unwrapShorthand(config) {\n      var keys = isObject(config) ? objectKeys(config) : [];\n      var isShorthand = indexOf(keys, \"value\") === -1 && indexOf(keys, \"type\") === -1 &&\n                        indexOf(keys, \"squash\") === -1 && indexOf(keys, \"array\") === -1;\n      if (isShorthand) config = { value: config };\n      config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };\n      return config;\n    }\n\n    function getType(config, urlType, location) {\n      if (config.type && urlType) throw new Error(\"Param '\"+id+\"' has two type configurations.\");\n      if (urlType) return urlType;\n      if (!config.type) return (location === \"config\" ? $types.any : $types.string);\n      return config.type instanceof Type ? config.type : new Type(config.type);\n    }\n\n    // array config: param name (param[]) overrides default settings.  explicit config overrides param name.\n    function getArrayMode() {\n      var arrayDefaults = { array: (location === \"search\" ? \"auto\" : false) };\n      var arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n      return extend(arrayDefaults, arrayParamNomenclature, config).array;\n    }\n\n    /**\n     * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n     */\n    function getSquashPolicy(config, isOptional) {\n      var squash = config.squash;\n      if (!isOptional || squash === false) return false;\n      if (!isDefined(squash) || squash == null) return defaultSquashPolicy;\n      if (squash === true || isString(squash)) return squash;\n      throw new Error(\"Invalid squash policy: '\" + squash + \"'. Valid policies: false, true, or arbitrary string\");\n    }\n\n    function getReplace(config, arrayMode, isOptional, squash) {\n      var replace, configuredKeys, defaultPolicy = [\n        { from: \"\",   to: (isOptional || arrayMode ? undefined : \"\") },\n        { from: null, to: (isOptional || arrayMode ? undefined : \"\") }\n      ];\n      replace = isArray(config.replace) ? config.replace : [];\n      if (isString(squash))\n        replace.push({ from: squash, to: undefined });\n      configuredKeys = map(replace, function(item) { return item.from; } );\n      return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);\n    }\n\n    /**\n     * [Internal] Get the default value of a parameter, which may be an injectable function.\n     */\n    function $$getDefaultValue() {\n      if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n      return injector.invoke(config.$$fn);\n    }\n\n    /**\n     * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n     * default value, which may be the result of an injectable function.\n     */\n    function $value(value) {\n      function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }\n      function $replace(value) {\n        var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });\n        return replacement.length ? replacement[0] : value;\n      }\n      value = $replace(value);\n      return isDefined(value) ? self.type.decode(value) : $$getDefaultValue();\n    }\n\n    function toString() { return \"{Param:\" + id + \" \" + type + \" squash: '\" + squash + \"' optional: \" + isOptional + \"}\"; }\n\n    extend(this, {\n      id: id,\n      type: type,\n      location: location,\n      array: arrayMode,\n      squash: squash,\n      replace: replace,\n      isOptional: isOptional,\n      value: $value,\n      dynamic: undefined,\n      config: config,\n      toString: toString\n    });\n  };\n\n  function ParamSet(params) {\n    extend(this, params || {});\n  }\n\n  ParamSet.prototype = {\n    $$new: function() {\n      return inherit(this, extend(new ParamSet(), { $$parent: this}));\n    },\n    $$keys: function () {\n      var keys = [], chain = [], parent = this,\n        ignore = objectKeys(ParamSet.prototype);\n      while (parent) { chain.push(parent); parent = parent.$$parent; }\n      chain.reverse();\n      forEach(chain, function(paramset) {\n        forEach(objectKeys(paramset), function(key) {\n            if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);\n        });\n      });\n      return keys;\n    },\n    $$values: function(paramValues) {\n      var values = {}, self = this;\n      forEach(self.$$keys(), function(key) {\n        values[key] = self[key].value(paramValues && paramValues[key]);\n      });\n      return values;\n    },\n    $$equals: function(paramValues1, paramValues2) {\n      var equal = true, self = this;\n      forEach(self.$$keys(), function(key) {\n        var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];\n        if (!self[key].type.equals(left, right)) equal = false;\n      });\n      return equal;\n    },\n    $$validates: function $$validate(paramValues) {\n      var result = true, isOptional, val, param, self = this;\n\n      forEach(this.$$keys(), function(key) {\n        param = self[key];\n        val = paramValues[key];\n        isOptional = !val && param.isOptional;\n        result = result && (isOptional || !!param.type.is(val));\n      });\n      return result;\n    },\n    $$parent: undefined\n  };\n\n  this.ParamSet = ParamSet;\n}\n\n// Register as a provider so it's available to other providers\nangular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);\nangular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);\n\n/**\n * @ngdoc object\n * @name ui.router.router.$urlRouterProvider\n *\n * @requires ui.router.util.$urlMatcherFactoryProvider\n * @requires $locationProvider\n *\n * @description\n * `$urlRouterProvider` has the responsibility of watching `$location`. \n * When `$location` changes it runs through a list of rules one by one until a \n * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify \n * a url in a state configuration. All urls are compiled into a UrlMatcher object.\n *\n * There are several methods on `$urlRouterProvider` that make it useful to use directly\n * in your module config.\n */\n$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];\nfunction $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {\n  var rules = [], otherwise = null, interceptDeferred = false, listener;\n\n  // Returns a string that is a prefix of all strings matching the RegExp\n  function regExpPrefix(re) {\n    var prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\n    return (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\n  }\n\n  // Interpolates matched values into a String.replace()-style pattern\n  function interpolate(pattern, match) {\n    return pattern.replace(/\\$(\\$|\\d{1,2})/, function (m, what) {\n      return match[what === '$' ? 0 : Number(what)];\n    });\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#rule\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines rules that are used by `$urlRouterProvider` to find matches for\n   * specific URLs.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // Here's an example of how you might allow case insensitive urls\n   *   $urlRouterProvider.rule(function ($injector, $location) {\n   *     var path = $location.path(),\n   *         normalized = path.toLowerCase();\n   *\n   *     if (path !== normalized) {\n   *       return normalized;\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {object} rule Handler function that takes `$injector` and `$location`\n   * services as arguments. You can use them to return a valid path as a string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.rule = function (rule) {\n    if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    rules.push(rule);\n    return this;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouterProvider#otherwise\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines a path that is used when an invalid route is requested.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // if the path doesn't match any of the urls you configured\n   *   // otherwise will take care of routing the user to the\n   *   // specified url\n   *   $urlRouterProvider.otherwise('/index');\n   *\n   *   // Example of using function rule as param\n   *   $urlRouterProvider.otherwise(function ($injector, $location) {\n   *     return '/a/valid/url';\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} rule The url path you want to redirect to or a function \n   * rule that returns the url path. The function version is passed two params: \n   * `$injector` and `$location` services, and must return a url string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.otherwise = function (rule) {\n    if (isString(rule)) {\n      var redirect = rule;\n      rule = function () { return redirect; };\n    }\n    else if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    otherwise = rule;\n    return this;\n  };\n\n\n  function handleIfMatch($injector, handler, match) {\n    if (!match) return false;\n    var result = $injector.invoke(handler, handler, { $match: match });\n    return isDefined(result) ? result : true;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#when\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Registers a handler for a given url matching. if handle is a string, it is\n   * treated as a redirect, and is interpolated according to the syntax of match\n   * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n   *\n   * If the handler is a function, it is injectable. It gets invoked if `$location`\n   * matches. You have the option of inject the match object as `$match`.\n   *\n   * The handler can return\n   *\n   * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n   *   will continue trying to find another one that matches.\n   * - **string** which is treated as a redirect and passed to `$location.url()`\n   * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n   *     if ($state.$current.navigable !== state ||\n   *         !equalForKeys($match, $stateParams) {\n   *      $state.transitionTo(state, $match, false);\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} what The incoming path that you want to redirect.\n   * @param {string|object} handler The path you want to redirect your user to.\n   */\n  this.when = function (what, handler) {\n    var redirect, handlerIsString = isString(handler);\n    if (isString(what)) what = $urlMatcherFactory.compile(what);\n\n    if (!handlerIsString && !isFunction(handler) && !isArray(handler))\n      throw new Error(\"invalid 'handler' in when()\");\n\n    var strategies = {\n      matcher: function (what, handler) {\n        if (handlerIsString) {\n          redirect = $urlMatcherFactory.compile(handler);\n          handler = ['$match', function ($match) { return redirect.format($match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));\n        }, {\n          prefix: isString(what.prefix) ? what.prefix : ''\n        });\n      },\n      regex: function (what, handler) {\n        if (what.global || what.sticky) throw new Error(\"when() RegExp must not be global or sticky\");\n\n        if (handlerIsString) {\n          redirect = handler;\n          handler = ['$match', function ($match) { return interpolate(redirect, $match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path()));\n        }, {\n          prefix: regExpPrefix(what)\n        });\n      }\n    };\n\n    var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };\n\n    for (var n in check) {\n      if (check[n]) return this.rule(strategies[n](what, handler));\n    }\n\n    throw new Error(\"invalid 'what' in when()\");\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#deferIntercept\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Disables (or enables) deferring location change interception.\n   *\n   * If you wish to customize the behavior of syncing the URL (for example, if you wish to\n   * defer a transition but maintain the current URL), call this method at configuration time.\n   * Then, at run time, call `$urlRouter.listen()` after you have configured your own\n   * `$locationChangeSuccess` event handler.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *\n   *   // Prevent $urlRouter from automatically intercepting URL changes;\n   *   // this allows you to configure custom behavior in between\n   *   // location changes and route synchronization:\n   *   $urlRouterProvider.deferIntercept();\n   *\n   * }).run(function ($rootScope, $urlRouter, UserService) {\n   *\n   *   $rootScope.$on('$locationChangeSuccess', function(e) {\n   *     // UserService is an example service for managing user state\n   *     if (UserService.isLoggedIn()) return;\n   *\n   *     // Prevent $urlRouter's default handler from firing\n   *     e.preventDefault();\n   *\n   *     UserService.handleLogin().then(function() {\n   *       // Once the user has logged in, sync the current URL\n   *       // to the router:\n   *       $urlRouter.sync();\n   *     });\n   *   });\n   *\n   *   // Configures $urlRouter's listener *after* your custom listener\n   *   $urlRouter.listen();\n   * });\n   * </pre>\n   *\n   * @param {boolean} defer Indicates whether to defer location change interception. Passing\n            no parameter is equivalent to `true`.\n   */\n  this.deferIntercept = function (defer) {\n    if (defer === undefined) defer = true;\n    interceptDeferred = defer;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouter\n   *\n   * @requires $location\n   * @requires $rootScope\n   * @requires $injector\n   * @requires $browser\n   *\n   * @description\n   *\n   */\n  this.$get = $get;\n  $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];\n  function $get(   $location,   $rootScope,   $injector,   $browser) {\n\n    var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;\n\n    function appendBasePath(url, isHtml5, absolute) {\n      if (baseHref === '/') return url;\n      if (isHtml5) return baseHref.slice(0, -1) + url;\n      if (absolute) return baseHref.slice(1) + url;\n      return url;\n    }\n\n    // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree\n    function update(evt) {\n      if (evt && evt.defaultPrevented) return;\n      var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;\n      lastPushedUrl = undefined;\n      if (ignoreUpdate) return true;\n\n      function check(rule) {\n        var handled = rule($injector, $location);\n\n        if (!handled) return false;\n        if (isString(handled)) $location.replace().url(handled);\n        return true;\n      }\n      var n = rules.length, i;\n\n      for (i = 0; i < n; i++) {\n        if (check(rules[i])) return;\n      }\n      // always check otherwise last to allow dynamic updates to the set of rules\n      if (otherwise) check(otherwise);\n    }\n\n    function listen() {\n      listener = listener || $rootScope.$on('$locationChangeSuccess', update);\n      return listener;\n    }\n\n    if (!interceptDeferred) listen();\n\n    return {\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#sync\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.\n       * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,\n       * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed\n       * with the transition by calling `$urlRouter.sync()`.\n       *\n       * @example\n       * <pre>\n       * angular.module('app', ['ui.router'])\n       *   .run(function($rootScope, $urlRouter) {\n       *     $rootScope.$on('$locationChangeSuccess', function(evt) {\n       *       // Halt state change from even starting\n       *       evt.preventDefault();\n       *       // Perform custom logic\n       *       var meetsRequirement = ...\n       *       // Continue with the update and state transition if logic allows\n       *       if (meetsRequirement) $urlRouter.sync();\n       *     });\n       * });\n       * </pre>\n       */\n      sync: function() {\n        update();\n      },\n\n      listen: function() {\n        return listen();\n      },\n\n      update: function(read) {\n        if (read) {\n          location = $location.url();\n          return;\n        }\n        if ($location.url() === location) return;\n\n        $location.url(location);\n        $location.replace();\n      },\n\n      push: function(urlMatcher, params, options) {\n        $location.url(urlMatcher.format(params || {}));\n        lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;\n        if (options && options.replace) $location.replace();\n      },\n\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#href\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * A URL generation method that returns the compiled URL for a given\n       * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.\n       *\n       * @example\n       * <pre>\n       * $bob = $urlRouter.href(new UrlMatcher(\"/about/:person\"), {\n       *   person: \"bob\"\n       * });\n       * // $bob == \"/about/bob\";\n       * </pre>\n       *\n       * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.\n       * @param {object=} params An object of parameter values to fill the matcher's required parameters.\n       * @param {object=} options Options object. The options are:\n       *\n       * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n       *\n       * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n       */\n      href: function(urlMatcher, params, options) {\n        if (!urlMatcher.validates(params)) return null;\n\n        var isHtml5 = $locationProvider.html5Mode();\n        if (angular.isObject(isHtml5)) {\n          isHtml5 = isHtml5.enabled;\n        }\n        \n        var url = urlMatcher.format(params);\n        options = options || {};\n\n        if (!isHtml5 && url !== null) {\n          url = \"#\" + $locationProvider.hashPrefix() + url;\n        }\n        url = appendBasePath(url, isHtml5, options.absolute);\n\n        if (!options.absolute || !url) {\n          return url;\n        }\n\n        var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();\n        port = (port === 80 || port === 443 ? '' : ':' + port);\n\n        return [$location.protocol(), '://', $location.host(), port, slash, url].join('');\n      }\n    };\n  }\n}\n\nangular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$stateProvider\n *\n * @requires ui.router.router.$urlRouterProvider\n * @requires ui.router.util.$urlMatcherFactoryProvider\n *\n * @description\n * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\n$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];\nfunction $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {\n\n  var root, states = {}, $state, queue = {}, abstractKey = 'abstract';\n\n  // Builds state properties from definition passed to registerState()\n  var stateBuilder = {\n\n    // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.\n    // state.children = [];\n    // if (parent) parent.children.push(state);\n    parent: function(state) {\n      if (isDefined(state.parent) && state.parent) return findState(state.parent);\n      // regex matches any valid composite state name\n      // would match \"contact.list\" but not \"contacts\"\n      var compositeName = /^(.+)\\.[^.]+$/.exec(state.name);\n      return compositeName ? findState(compositeName[1]) : root;\n    },\n\n    // inherit 'data' from parent and override by own values (if any)\n    data: function(state) {\n      if (state.parent && state.parent.data) {\n        state.data = state.self.data = extend({}, state.parent.data, state.data);\n      }\n      return state.data;\n    },\n\n    // Build a URLMatcher if necessary, either via a relative or absolute URL\n    url: function(state) {\n      var url = state.url, config = { params: state.params || {} };\n\n      if (isString(url)) {\n        if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);\n        return (state.parent.navigable || root).url.concat(url, config);\n      }\n\n      if (!url || $urlMatcherFactory.isMatcher(url)) return url;\n      throw new Error(\"Invalid url '\" + url + \"' in state '\" + state + \"'\");\n    },\n\n    // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n    navigable: function(state) {\n      return state.url ? state : (state.parent ? state.parent.navigable : null);\n    },\n\n    // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params\n    ownParams: function(state) {\n      var params = state.url && state.url.params || new $$UMFP.ParamSet();\n      forEach(state.params || {}, function(config, id) {\n        if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, \"config\");\n      });\n      return params;\n    },\n\n    // Derive parameters for this state and ensure they're a super-set of parent's parameters\n    params: function(state) {\n      return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();\n    },\n\n    // If there is no explicit multi-view configuration, make one up so we don't have\n    // to handle both cases in the view directive later. Note that having an explicit\n    // 'views' property will mean the default unnamed view properties are ignored. This\n    // is also a good time to resolve view names to absolute names, so everything is a\n    // straight lookup at link time.\n    views: function(state) {\n      var views = {};\n\n      forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {\n        if (name.indexOf('@') < 0) name += '@' + state.parent.name;\n        views[name] = view;\n      });\n      return views;\n    },\n\n    // Keep a full path from the root down to this state as this is needed for state activation.\n    path: function(state) {\n      return state.parent ? state.parent.path.concat(state) : []; // exclude root from path\n    },\n\n    // Speed up $state.contains() as it's used a lot\n    includes: function(state) {\n      var includes = state.parent ? extend({}, state.parent.includes) : {};\n      includes[state.name] = true;\n      return includes;\n    },\n\n    $delegates: {}\n  };\n\n  function isRelative(stateName) {\n    return stateName.indexOf(\".\") === 0 || stateName.indexOf(\"^\") === 0;\n  }\n\n  function findState(stateOrName, base) {\n    if (!stateOrName) return undefined;\n\n    var isStr = isString(stateOrName),\n        name  = isStr ? stateOrName : stateOrName.name,\n        path  = isRelative(name);\n\n    if (path) {\n      if (!base) throw new Error(\"No reference point given for path '\"  + name + \"'\");\n      base = findState(base);\n      \n      var rel = name.split(\".\"), i = 0, pathLength = rel.length, current = base;\n\n      for (; i < pathLength; i++) {\n        if (rel[i] === \"\" && i === 0) {\n          current = base;\n          continue;\n        }\n        if (rel[i] === \"^\") {\n          if (!current.parent) throw new Error(\"Path '\" + name + \"' not valid for state '\" + base.name + \"'\");\n          current = current.parent;\n          continue;\n        }\n        break;\n      }\n      rel = rel.slice(i).join(\".\");\n      name = current.name + (current.name && rel ? \".\" : \"\") + rel;\n    }\n    var state = states[name];\n\n    if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n      return state;\n    }\n    return undefined;\n  }\n\n  function queueState(parentName, state) {\n    if (!queue[parentName]) {\n      queue[parentName] = [];\n    }\n    queue[parentName].push(state);\n  }\n\n  function flushQueuedChildren(parentName) {\n    var queued = queue[parentName] || [];\n    while(queued.length) {\n      registerState(queued.shift());\n    }\n  }\n\n  function registerState(state) {\n    // Wrap a new object around the state so we can store our private details easily.\n    state = inherit(state, {\n      self: state,\n      resolve: state.resolve || {},\n      toString: function() { return this.name; }\n    });\n\n    var name = state.name;\n    if (!isString(name) || name.indexOf('@') >= 0) throw new Error(\"State must have a valid name\");\n    if (states.hasOwnProperty(name)) throw new Error(\"State '\" + name + \"'' is already defined\");\n\n    // Get parent name\n    var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))\n        : (isString(state.parent)) ? state.parent\n        : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name\n        : '';\n\n    // If parent is not registered yet, add state to queue and register later\n    if (parentName && !states[parentName]) {\n      return queueState(parentName, state.self);\n    }\n\n    for (var key in stateBuilder) {\n      if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);\n    }\n    states[name] = state;\n\n    // Register the state in the global state list and with $urlRouter if necessary.\n    if (!state[abstractKey] && state.url) {\n      $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {\n        if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {\n          $state.transitionTo(state, $match, { inherit: true, location: false });\n        }\n      }]);\n    }\n\n    // Register any queued children\n    flushQueuedChildren(name);\n\n    return state;\n  }\n\n  // Checks text to see if it looks like a glob.\n  function isGlob (text) {\n    return text.indexOf('*') > -1;\n  }\n\n  // Returns true if glob matches current $state name.\n  function doesStateMatchGlob (glob) {\n    var globSegments = glob.split('.'),\n        segments = $state.$current.name.split('.');\n\n    //match greedy starts\n    if (globSegments[0] === '**') {\n       segments = segments.slice(indexOf(segments, globSegments[1]));\n       segments.unshift('**');\n    }\n    //match greedy ends\n    if (globSegments[globSegments.length - 1] === '**') {\n       segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);\n       segments.push('**');\n    }\n\n    if (globSegments.length != segments.length) {\n      return false;\n    }\n\n    //match single stars\n    for (var i = 0, l = globSegments.length; i < l; i++) {\n      if (globSegments[i] === '*') {\n        segments[i] = '*';\n      }\n    }\n\n    return segments.join('') === globSegments.join('');\n  }\n\n\n  // Implicit root state that is always active\n  root = registerState({\n    name: '',\n    url: '^',\n    views: null,\n    'abstract': true\n  });\n  root.navigable = null;\n\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#decorator\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Allows you to extend (carefully) or override (at your own peril) the \n   * `stateBuilder` object used internally by `$stateProvider`. This can be used \n   * to add custom functionality to ui-router, for example inferring templateUrl \n   * based on the state name.\n   *\n   * When passing only a name, it returns the current (original or decorated) builder\n   * function that matches `name`.\n   *\n   * The builder functions that can be decorated are listed below. Though not all\n   * necessarily have a good use case for decoration, that is up to you to decide.\n   *\n   * In addition, users can attach custom decorators, which will generate new \n   * properties within the state's internal definition. There is currently no clear \n   * use-case for this beyond accessing internal states (i.e. $state.$current), \n   * however, expect this to become increasingly relevant as we introduce additional \n   * meta-programming features.\n   *\n   * **Warning**: Decorators should not be interdependent because the order of \n   * execution of the builder functions in non-deterministic. Builder functions \n   * should only be dependent on the state definition object and super function.\n   *\n   *\n   * Existing builder functions and current return values:\n   *\n   * - **parent** `{object}` - returns the parent state object.\n   * - **data** `{object}` - returns state data, including any inherited data that is not\n   *   overridden by own values (if any).\n   * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n   *   or `null`.\n   * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is \n   *   navigable).\n   * - **params** `{object}` - returns an array of state params that are ensured to \n   *   be a super-set of parent's params.\n   * - **views** `{object}` - returns a views object where each key is an absolute view \n   *   name (i.e. \"viewName@stateName\") and each value is the config object \n   *   (template, controller) for the view. Even when you don't use the views object \n   *   explicitly on a state config, one is still created for you internally.\n   *   So by decorating this builder function you have access to decorating template \n   *   and controller properties.\n   * - **ownParams** `{object}` - returns an array of params that belong to the state, \n   *   not including any params defined by ancestor states.\n   * - **path** `{string}` - returns the full path from the root down to this state. \n   *   Needed for state activation.\n   * - **includes** `{object}` - returns an object that includes every state that \n   *   would pass a `$state.includes()` test.\n   *\n   * @example\n   * <pre>\n   * // Override the internal 'views' builder with a function that takes the state\n   * // definition, and a reference to the internal function being overridden:\n   * $stateProvider.decorator('views', function (state, parent) {\n   *   var result = {},\n   *       views = parent(state);\n   *\n   *   angular.forEach(views, function (config, name) {\n   *     var autoName = (state.name + '.' + name).replace('.', '/');\n   *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n   *     result[name] = config;\n   *   });\n   *   return result;\n   * });\n   *\n   * $stateProvider.state('home', {\n   *   views: {\n   *     'contact.list': { controller: 'ListController' },\n   *     'contact.item': { controller: 'ItemController' }\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * $state.go('home');\n   * // Auto-populates list and item views with /partials/home/contact/list.html,\n   * // and /partials/home/contact/item.html, respectively.\n   * </pre>\n   *\n   * @param {string} name The name of the builder function to decorate. \n   * @param {object} func A function that is responsible for decorating the original \n   * builder function. The function receives two parameters:\n   *\n   *   - `{object}` - state - The state config object.\n   *   - `{object}` - super - The original builder function.\n   *\n   * @return {object} $stateProvider - $stateProvider instance\n   */\n  this.decorator = decorator;\n  function decorator(name, func) {\n    /*jshint validthis: true */\n    if (isString(name) && !isDefined(func)) {\n      return stateBuilder[name];\n    }\n    if (!isFunction(func) || !isString(name)) {\n      return this;\n    }\n    if (stateBuilder[name] && !stateBuilder.$delegates[name]) {\n      stateBuilder.$delegates[name] = stateBuilder[name];\n    }\n    stateBuilder[name] = func;\n    return this;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#state\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Registers a state configuration under a given state name. The stateConfig object\n   * has the following acceptable properties.\n   *\n   * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n   * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n   * @param {object} stateConfig State configuration object.\n   * @param {string|function=} stateConfig.template\n   * <a id='template'></a>\n   *   html template as a string or a function that returns\n   *   an html template as a string which should be used by the uiView directives. This property \n   *   takes precedence over templateUrl.\n   *   \n   *   If `template` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by\n   *     applying the current state\n   *\n   * <pre>template:\n   *   \"<h1>inline template definition</h1>\" +\n   *   \"<div ui-view></div>\"</pre>\n   * <pre>template: function(params) {\n   *       return \"<h1>generated template</h1>\"; }</pre>\n   * </div>\n   *\n   * @param {string|function=} stateConfig.templateUrl\n   * <a id='templateUrl'></a>\n   *\n   *   path or function that returns a path to an html\n   *   template that should be used by uiView.\n   *   \n   *   If `templateUrl` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by \n   *     applying the current state\n   *\n   * <pre>templateUrl: \"home.html\"</pre>\n   * <pre>templateUrl: function(params) {\n   *     return myTemplates[params.pageId]; }</pre>\n   *\n   * @param {function=} stateConfig.templateProvider\n   * <a id='templateProvider'></a>\n   *    Provider function that returns HTML content string.\n   * <pre> templateProvider:\n   *       function(MyTemplateService, params) {\n   *         return MyTemplateService.getTemplate(params.pageId);\n   *       }</pre>\n   *\n   * @param {string|function=} stateConfig.controller\n   * <a id='controller'></a>\n   *\n   *  Controller fn that should be associated with newly\n   *   related scope or the name of a registered controller if passed as a string.\n   *   Optionally, the ControllerAs may be declared here.\n   * <pre>controller: \"MyRegisteredController\"</pre>\n   * <pre>controller:\n   *     \"MyRegisteredController as fooCtrl\"}</pre>\n   * <pre>controller: function($scope, MyService) {\n   *     $scope.data = MyService.getData(); }</pre>\n   *\n   * @param {function=} stateConfig.controllerProvider\n   * <a id='controllerProvider'></a>\n   *\n   * Injectable provider function that returns the actual controller or string.\n   * <pre>controllerProvider:\n   *   function(MyResolveData) {\n   *     if (MyResolveData.foo)\n   *       return \"FooCtrl\"\n   *     else if (MyResolveData.bar)\n   *       return \"BarCtrl\";\n   *     else return function($scope) {\n   *       $scope.baz = \"Qux\";\n   *     }\n   *   }</pre>\n   *\n   * @param {string=} stateConfig.controllerAs\n   * <a id='controllerAs'></a>\n   * \n   * A controller alias name. If present the controller will be\n   *   published to scope under the controllerAs name.\n   * <pre>controllerAs: \"myCtrl\"</pre>\n   *\n   * @param {object=} stateConfig.resolve\n   * <a id='resolve'></a>\n   *\n   * An optional map&lt;string, function&gt; of dependencies which\n   *   should be injected into the controller. If any of these dependencies are promises, \n   *   the router will wait for them all to be resolved before the controller is instantiated.\n   *   If all the promises are resolved successfully, the $stateChangeSuccess event is fired\n   *   and the values of the resolved promises are injected into any controllers that reference them.\n   *   If any  of the promises are rejected the $stateChangeError event is fired.\n   *\n   *   The map object is:\n   *   \n   *   - key - {string}: name of dependency to be injected into controller\n   *   - factory - {string|function}: If string then it is alias for service. Otherwise if function, \n   *     it is injected and return value it treated as dependency. If result is a promise, it is \n   *     resolved before its value is injected into controller.\n   *\n   * <pre>resolve: {\n   *     myResolve1:\n   *       function($http, $stateParams) {\n   *         return $http.get(\"/api/foos/\"+stateParams.fooID);\n   *       }\n   *     }</pre>\n   *\n   * @param {string=} stateConfig.url\n   * <a id='url'></a>\n   *\n   *   A url fragment with optional parameters. When a state is navigated or\n   *   transitioned to, the `$stateParams` service will be populated with any \n   *   parameters that were passed.\n   *\n   * examples:\n   * <pre>url: \"/home\"\n   * url: \"/users/:userid\"\n   * url: \"/books/{bookid:[a-zA-Z_-]}\"\n   * url: \"/books/{categoryid:int}\"\n   * url: \"/books/{publishername:string}/{categoryid:int}\"\n   * url: \"/messages?before&after\"\n   * url: \"/messages?{before:date}&{after:date}\"</pre>\n   * url: \"/messages/:mailboxid?{before:date}&{after:date}\"\n   *\n   * @param {object=} stateConfig.views\n   * <a id='views'></a>\n   * an optional map&lt;string, object&gt; which defined multiple views, or targets views\n   * manually/explicitly.\n   *\n   * Examples:\n   *\n   * Targets three named `ui-view`s in the parent state's template\n   * <pre>views: {\n   *     header: {\n   *       controller: \"headerCtrl\",\n   *       templateUrl: \"header.html\"\n   *     }, body: {\n   *       controller: \"bodyCtrl\",\n   *       templateUrl: \"body.html\"\n   *     }, footer: {\n   *       controller: \"footCtrl\",\n   *       templateUrl: \"footer.html\"\n   *     }\n   *   }</pre>\n   *\n   * Targets named `ui-view=\"header\"` from grandparent state 'top''s template, and named `ui-view=\"body\" from parent state's template.\n   * <pre>views: {\n   *     'header@top': {\n   *       controller: \"msgHeaderCtrl\",\n   *       templateUrl: \"msgHeader.html\"\n   *     }, 'body': {\n   *       controller: \"messagesCtrl\",\n   *       templateUrl: \"messages.html\"\n   *     }\n   *   }</pre>\n   *\n   * @param {boolean=} [stateConfig.abstract=false]\n   * <a id='abstract'></a>\n   * An abstract state will never be directly activated,\n   *   but can provide inherited properties to its common children states.\n   * <pre>abstract: true</pre>\n   *\n   * @param {function=} stateConfig.onEnter\n   * <a id='onEnter'></a>\n   *\n   * Callback function for when a state is entered. Good way\n   *   to trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onEnter: function(MyService, $stateParams) {\n   *     MyService.foo($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {function=} stateConfig.onExit\n   * <a id='onExit'></a>\n   *\n   * Callback function for when a state is exited. Good way to\n   *   trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onExit: function(MyService, $stateParams) {\n   *     MyService.cleanup($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {boolean=} [stateConfig.reloadOnSearch=true]\n   * <a id='reloadOnSearch'></a>\n   *\n   * If `false`, will not retrigger the same state\n   *   just because a search/query parameter has changed (via $location.search() or $location.hash()). \n   *   Useful for when you'd like to modify $location.search() without triggering a reload.\n   * <pre>reloadOnSearch: false</pre>\n   *\n   * @param {object=} stateConfig.data\n   * <a id='data'></a>\n   *\n   * Arbitrary data object, useful for custom configuration.  The parent state's `data` is\n   *   prototypally inherited.  In other words, adding a data property to a state adds it to\n   *   the entire subtree via prototypal inheritance.\n   *\n   * <pre>data: {\n   *     requiredRole: 'foo'\n   * } </pre>\n   *\n   * @param {object=} stateConfig.params\n   * <a id='params'></a>\n   *\n   * A map which optionally configures parameters declared in the `url`, or\n   *   defines additional non-url parameters.  For each parameter being\n   *   configured, add a configuration object keyed to the name of the parameter.\n   *\n   *   Each parameter configuration object may contain the following properties:\n   *\n   *   - ** value ** - {object|function=}: specifies the default value for this\n   *     parameter.  This implicitly sets this parameter as optional.\n   *\n   *     When UI-Router routes to a state and no value is\n   *     specified for this parameter in the URL or transition, the\n   *     default value will be used instead.  If `value` is a function,\n   *     it will be injected and invoked, and the return value used.\n   *\n   *     *Note*: `undefined` is treated as \"no default value\" while `null`\n   *     is treated as \"the default value is `null`\".\n   *\n   *     *Shorthand*: If you only need to configure the default value of the\n   *     parameter, you may use a shorthand syntax.   In the **`params`**\n   *     map, instead mapping the param name to a full parameter configuration\n   *     object, simply set map it to the default parameter value, e.g.:\n   *\n   * <pre>// define a parameter's default value\n   * params: {\n   *     param1: { value: \"defaultValue\" }\n   * }\n   * // shorthand default values\n   * params: {\n   *     param1: \"defaultValue\",\n   *     param2: \"param2Default\"\n   * }</pre>\n   *\n   *   - ** array ** - {boolean=}: *(default: false)* If true, the param value will be\n   *     treated as an array of values.  If you specified a Type, the value will be\n   *     treated as an array of the specified Type.  Note: query parameter values\n   *     default to a special `\"auto\"` mode.\n   *\n   *     For query parameters in `\"auto\"` mode, if multiple  values for a single parameter\n   *     are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values\n   *     are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`).  However, if\n   *     only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single\n   *     value (e.g.: `{ foo: '1' }`).\n   *\n   * <pre>params: {\n   *     param1: { array: true }\n   * }</pre>\n   *\n   *   - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when\n   *     the current parameter value is the same as the default value. If `squash` is not set, it uses the\n   *     configured default squash policy.\n   *     (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})\n   *\n   *   There are three squash settings:\n   *\n   *     - false: The parameter's default value is not squashed.  It is encoded and included in the URL\n   *     - true: The parameter's default value is omitted from the URL.  If the parameter is preceeded and followed\n   *       by slashes in the state's `url` declaration, then one of those slashes are omitted.\n   *       This can allow for cleaner looking URLs.\n   *     - `\"<arbitrary string>\"`: The parameter's default value is replaced with an arbitrary placeholder of  your choice.\n   *\n   * <pre>params: {\n   *     param1: {\n   *       value: \"defaultId\",\n   *       squash: true\n   * } }\n   * // squash \"defaultValue\" to \"~\"\n   * params: {\n   *     param1: {\n   *       value: \"defaultValue\",\n   *       squash: \"~\"\n   * } }\n   * </pre>\n   *\n   *\n   * @example\n   * <pre>\n   * // Some state name examples\n   *\n   * // stateName can be a single top-level name (must be unique).\n   * $stateProvider.state(\"home\", {});\n   *\n   * // Or it can be a nested state name. This state is a child of the\n   * // above \"home\" state.\n   * $stateProvider.state(\"home.newest\", {});\n   *\n   * // Nest states as deeply as needed.\n   * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n   *\n   * // state() returns $stateProvider, so you can chain state declarations.\n   * $stateProvider\n   *   .state(\"home\", {})\n   *   .state(\"about\", {})\n   *   .state(\"contacts\", {});\n   * </pre>\n   *\n   */\n  this.state = state;\n  function state(name, definition) {\n    /*jshint validthis: true */\n    if (isObject(name)) definition = name;\n    else definition.name = name;\n    registerState(definition);\n    return this;\n  }\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$state\n   *\n   * @requires $rootScope\n   * @requires $q\n   * @requires ui.router.state.$view\n   * @requires $injector\n   * @requires ui.router.util.$resolve\n   * @requires ui.router.state.$stateParams\n   * @requires ui.router.router.$urlRouter\n   *\n   * @property {object} params A param object, e.g. {sectionId: section.id)}, that \n   * you'd like to test against the current active state.\n   * @property {object} current A reference to the state's config object. However \n   * you passed it in. Useful for accessing custom data.\n   * @property {object} transition Currently pending transition. A promise that'll \n   * resolve or reject.\n   *\n   * @description\n   * `$state` service is responsible for representing states as well as transitioning\n   * between them. It also provides interfaces to ask for current state or even states\n   * you're coming from.\n   */\n  this.$get = $get;\n  $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];\n  function $get(   $rootScope,   $q,   $view,   $injector,   $resolve,   $stateParams,   $urlRouter,   $location,   $urlMatcherFactory) {\n\n    var TransitionSuperseded = $q.reject(new Error('transition superseded'));\n    var TransitionPrevented = $q.reject(new Error('transition prevented'));\n    var TransitionAborted = $q.reject(new Error('transition aborted'));\n    var TransitionFailed = $q.reject(new Error('transition failed'));\n\n    // Handles the case where a state which is the target of a transition is not found, and the user\n    // can optionally retry or defer the transition\n    function handleRedirect(redirect, state, params, options) {\n      /**\n       * @ngdoc event\n       * @name ui.router.state.$state#$stateNotFound\n       * @eventOf ui.router.state.$state\n       * @eventType broadcast on root scope\n       * @description\n       * Fired when a requested state **cannot be found** using the provided state name during transition.\n       * The event is broadcast allowing any handlers a single chance to deal with the error (usually by\n       * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,\n       * you can see its three properties in the example. You can use `event.preventDefault()` to abort the\n       * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.\n       *\n       * @param {Object} event Event object.\n       * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.\n       * @param {State} fromState Current state object.\n       * @param {Object} fromParams Current state params.\n       *\n       * @example\n       *\n       * <pre>\n       * // somewhere, assume lazy.state has not been defined\n       * $state.go(\"lazy.state\", {a:1, b:2}, {inherit:false});\n       *\n       * // somewhere else\n       * $scope.$on('$stateNotFound',\n       * function(event, unfoundState, fromState, fromParams){\n       *     console.log(unfoundState.to); // \"lazy.state\"\n       *     console.log(unfoundState.toParams); // {a:1, b:2}\n       *     console.log(unfoundState.options); // {inherit:false} + default options\n       * })\n       * </pre>\n       */\n      var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);\n\n      if (evt.defaultPrevented) {\n        $urlRouter.update();\n        return TransitionAborted;\n      }\n\n      if (!evt.retry) {\n        return null;\n      }\n\n      // Allow the handler to return a promise to defer state lookup retry\n      if (options.$retry) {\n        $urlRouter.update();\n        return TransitionFailed;\n      }\n      var retryTransition = $state.transition = $q.when(evt.retry);\n\n      retryTransition.then(function() {\n        if (retryTransition !== $state.transition) return TransitionSuperseded;\n        redirect.options.$retry = true;\n        return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);\n      }, function() {\n        return TransitionAborted;\n      });\n      $urlRouter.update();\n\n      return retryTransition;\n    }\n\n    root.locals = { resolve: null, globals: { $stateParams: {} } };\n\n    $state = {\n      params: {},\n      current: root.self,\n      $current: root,\n      transition: null\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#reload\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired, \n     * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon).\n     *\n     * @example\n     * <pre>\n     * var app angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.reload = function(){\n     *     $state.reload();\n     *   }\n     * });\n     * </pre>\n     *\n     * `reload()` is just an alias for:\n     * <pre>\n     * $state.transitionTo($state.current, $stateParams, { \n     *   reload: true, inherit: false, notify: true\n     * });\n     * </pre>\n     *\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.reload = function reload() {\n      return $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#go\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Convenience method for transitioning to a new state. `$state.go` calls \n     * `$state.transitionTo` internally but automatically sets options to \n     * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. \n     * This allows you to easily use an absolute or relative to path and specify \n     * only the parameters you'd like to update (while letting unspecified parameters \n     * inherit from the currently active ancestor states).\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.go('contact.detail');\n     *   };\n     * });\n     * </pre>\n     * <img src='../ngdoc_assets/StateGoExamples.png'/>\n     *\n     * @param {string} to Absolute state name or relative state path. Some examples:\n     *\n     * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n     * - `$state.go('^')` - will go to a parent state\n     * - `$state.go('^.sibling')` - will go to a sibling state\n     * - `$state.go('.child.grandchild')` - will go to grandchild state\n     *\n     * @param {object=} params A map of the parameters that will be sent to the state, \n     * will populate $stateParams. Any parameters that are not specified will be inherited from currently \n     * defined parameters. This allows, for example, going to a sibling state that shares parameters\n     * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.\n     * transitioning to a sibling will get you the parameters for all parents, transitioning to a child\n     * will get you all current parameters, etc.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *\n     * @returns {promise} A promise representing the state of the new transition.\n     *\n     * Possible success values:\n     *\n     * - $state.current\n     *\n     * <br/>Possible rejection values:\n     *\n     * - 'transition superseded' - when a newer transition has been started after this one\n     * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener\n     * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or\n     *   when a `$stateNotFound` `event.retry` promise errors.\n     * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.\n     * - *resolve error* - when an error has occurred with a `resolve`\n     *\n     */\n    $state.go = function go(to, params, options) {\n      return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#transitionTo\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}\n     * uses `transitionTo` internally. `$state.go` is recommended in most situations.\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.transitionTo('contact.detail');\n     *   };\n     * });\n     * </pre>\n     *\n     * @param {string} to State name.\n     * @param {object=} toParams A map of the parameters that will be sent to the state,\n     * will populate $stateParams.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.transitionTo = function transitionTo(to, toParams, options) {\n      toParams = toParams || {};\n      options = extend({\n        location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false\n      }, options || {});\n\n      var from = $state.$current, fromParams = $state.params, fromPath = from.path;\n      var evt, toState = findState(to, options.relative);\n\n      if (!isDefined(toState)) {\n        var redirect = { to: to, toParams: toParams, options: options };\n        var redirectResult = handleRedirect(redirect, from.self, fromParams, options);\n\n        if (redirectResult) {\n          return redirectResult;\n        }\n\n        // Always retry once if the $stateNotFound was not prevented\n        // (handles either redirect changed or state lazy-definition)\n        to = redirect.to;\n        toParams = redirect.toParams;\n        options = redirect.options;\n        toState = findState(to, options.relative);\n\n        if (!isDefined(toState)) {\n          if (!options.relative) throw new Error(\"No such state '\" + to + \"'\");\n          throw new Error(\"Could not resolve '\" + to + \"' from state '\" + options.relative + \"'\");\n        }\n      }\n      if (toState[abstractKey]) throw new Error(\"Cannot transition to abstract state '\" + to + \"'\");\n      if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);\n      if (!toState.params.$$validates(toParams)) return TransitionFailed;\n\n      toParams = toState.params.$$values(toParams);\n      to = toState;\n\n      var toPath = to.path;\n\n      // Starting from the root of the path, keep all levels that haven't changed\n      var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];\n\n      if (!options.reload) {\n        while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {\n          locals = toLocals[keep] = state.locals;\n          keep++;\n          state = toPath[keep];\n        }\n      }\n\n      // If we're going to the same state and all locals are kept, we've got nothing to do.\n      // But clear 'transition', as we still want to cancel any other pending transitions.\n      // TODO: We may not want to bump 'transition' if we're called from a location change\n      // that we've initiated ourselves, because we might accidentally abort a legitimate\n      // transition initiated from code?\n      if (shouldTriggerReload(to, from, locals, options)) {\n        if (to.self.reloadOnSearch !== false) $urlRouter.update();\n        $state.transition = null;\n        return $q.when($state.current);\n      }\n\n      // Filter parameters before we pass them to event handlers etc.\n      toParams = filterByKeys(to.params.$$keys(), toParams || {});\n\n      // Broadcast start event and cancel the transition if requested\n      if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeStart\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when the state transition **begins**. You can use `event.preventDefault()`\n         * to prevent the transition from happening and then the transition promise will be\n         * rejected with a `'transition prevented'` value.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         *\n         * @example\n         *\n         * <pre>\n         * $rootScope.$on('$stateChangeStart',\n         * function(event, toState, toParams, fromState, fromParams){\n         *     event.preventDefault();\n         *     // transitionTo() promise will be rejected with\n         *     // a 'transition prevented' error\n         * })\n         * </pre>\n         */\n        if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {\n          $urlRouter.update();\n          return TransitionPrevented;\n        }\n      }\n\n      // Resolve locals for the remaining states, but don't update any global state just\n      // yet -- if anything fails to resolve the current state needs to remain untouched.\n      // We also set up an inheritance chain for the locals here. This allows the view directive\n      // to quickly look up the correct definition for each view in the current state. Even\n      // though we create the locals object itself outside resolveState(), it is initially\n      // empty and gets filled asynchronously. We need to keep track of the promise for the\n      // (fully resolved) current locals, and pass this down the chain.\n      var resolved = $q.when(locals);\n\n      for (var l = keep; l < toPath.length; l++, state = toPath[l]) {\n        locals = toLocals[l] = inherit(locals);\n        resolved = resolveState(state, toParams, state === to, resolved, locals, options);\n      }\n\n      // Once everything is resolved, we are ready to perform the actual transition\n      // and return a promise for the new state. We also keep track of what the\n      // current promise is, so that we can detect overlapping transitions and\n      // keep only the outcome of the last transition.\n      var transition = $state.transition = resolved.then(function () {\n        var l, entering, exiting;\n\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Exit 'from' states not kept\n        for (l = fromPath.length - 1; l >= keep; l--) {\n          exiting = fromPath[l];\n          if (exiting.self.onExit) {\n            $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);\n          }\n          exiting.locals = null;\n        }\n\n        // Enter 'to' states not kept\n        for (l = keep; l < toPath.length; l++) {\n          entering = toPath[l];\n          entering.locals = toLocals[l];\n          if (entering.self.onEnter) {\n            $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);\n          }\n        }\n\n        // Run it again, to catch any transitions in callbacks\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Update globals in $state\n        $state.$current = to;\n        $state.current = to.self;\n        $state.params = toParams;\n        copy($state.params, $stateParams);\n        $state.transition = null;\n\n        if (options.location && to.navigable) {\n          $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {\n            $$avoidResync: true, replace: options.location === 'replace'\n          });\n        }\n\n        if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeSuccess\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired once the state transition is **complete**.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         */\n          $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);\n        }\n        $urlRouter.update(true);\n\n        return $state.current;\n      }, function (error) {\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        $state.transition = null;\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeError\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when an **error occurs** during transition. It's important to note that if you\n         * have any errors in your resolve functions (javascript errors, non-existent services, etc)\n         * they will not throw traditionally. You must listen for this $stateChangeError event to\n         * catch **ALL** errors.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         * @param {Error} error The resolve error object.\n         */\n        evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);\n\n        if (!evt.defaultPrevented) {\n            $urlRouter.update();\n        }\n\n        return $q.reject(error);\n      });\n\n      return transition;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#is\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Similar to {@link ui.router.state.$state#methods_includes $state.includes},\n     * but only checks for the full state name. If params is supplied then it will be\n     * tested for strict equality against the current active params object, so all params\n     * must match with none missing and no extras.\n     *\n     * @example\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // absolute name\n     * $state.is('contact.details.item'); // returns true\n     * $state.is(contactDetailItemStateObject); // returns true\n     *\n     * // relative name (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.is('.item')}\">Item</div>\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like\n     * to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object} -  If `stateOrName` is a relative state name and `options.relative` is set, .is will\n     * test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it is the state.\n     */\n    $state.is = function is(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) { return undefined; }\n      if ($state.$current !== state) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#includes\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method to determine if the current active state is equal to or is the child of the\n     * state stateName. If any params are passed then they will be tested for a match as well.\n     * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n     *\n     * @example\n     * Partial and relative names\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // Using partial names\n     * $state.includes(\"contacts\"); // returns true\n     * $state.includes(\"contacts.details\"); // returns true\n     * $state.includes(\"contacts.details.item\"); // returns true\n     * $state.includes(\"contacts.list\"); // returns false\n     * $state.includes(\"about\"); // returns false\n     *\n     * // Using relative names (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.includes('.item')}\">Item</div>\n     * </pre>\n     *\n     * Basic globbing patterns\n     * <pre>\n     * $state.$current.name = 'contacts.details.item.url';\n     *\n     * $state.includes(\"*.details.*.*\"); // returns true\n     * $state.includes(\"*.details.**\"); // returns true\n     * $state.includes(\"**.item.**\"); // returns true\n     * $state.includes(\"*.details.item.url\"); // returns true\n     * $state.includes(\"*.details.*.url\"); // returns true\n     * $state.includes(\"*.details.*\"); // returns false\n     * $state.includes(\"item.**\"); // returns false\n     * </pre>\n     *\n     * @param {string} stateOrName A partial name, relative name, or glob pattern\n     * to be searched for within the current state name.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`,\n     * that you'd like to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object=} -  If `stateOrName` is a relative state reference and `options.relative` is set,\n     * .includes will test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it does include the state\n     */\n    $state.includes = function includes(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      if (isString(stateOrName) && isGlob(stateOrName)) {\n        if (!doesStateMatchGlob(stateOrName)) {\n          return false;\n        }\n        stateOrName = $state.$current.name;\n      }\n\n      var state = findState(stateOrName, options.relative);\n      if (!isDefined(state)) { return undefined; }\n      if (!isDefined($state.$current.includes[state.name])) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;\n    };\n\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#href\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A url generation method that returns the compiled url for the given state populated with the given params.\n     *\n     * @example\n     * <pre>\n     * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.\n     * @param {object=} params An object of parameter values to fill the state's required parameters.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`lossy`** - {boolean=true} -  If true, and if there is no url associated with the state provided in the\n     *    first parameter, then the constructed href url will be built from the first navigable ancestor (aka\n     *    ancestor with a valid url).\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n     * \n     * @returns {string} compiled state url\n     */\n    $state.href = function href(stateOrName, params, options) {\n      options = extend({\n        lossy:    true,\n        inherit:  true,\n        absolute: false,\n        relative: $state.$current\n      }, options || {});\n\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) return null;\n      if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);\n      \n      var nav = (state && options.lossy) ? state.navigable : state;\n\n      if (!nav || nav.url === undefined || nav.url === null) {\n        return null;\n      }\n      return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys(), params || {}), {\n        absolute: options.absolute\n      });\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#get\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Returns the state configuration object for any specific state or all states.\n     *\n     * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for\n     * the requested state. If not provided, returns an array of ALL state configs.\n     * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.\n     * @returns {Object|Array} State configuration object or array of all objects.\n     */\n    $state.get = function (stateOrName, context) {\n      if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });\n      var state = findState(stateOrName, context || $state.$current);\n      return (state && state.self) ? state.self : null;\n    };\n\n    function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {\n      // Make a restricted $stateParams with only the parameters that apply to this state if\n      // necessary. In addition to being available to the controller and onEnter/onExit callbacks,\n      // we also need $stateParams to be available for any $injector calls we make during the\n      // dependency resolution process.\n      var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);\n      var locals = { $stateParams: $stateParams };\n\n      // Resolve 'global' dependencies for the state, i.e. those not specific to a view.\n      // We're also including $stateParams in this; that way the parameters are restricted\n      // to the set that should be visible to the state, and are independent of when we update\n      // the global $state and $stateParams values.\n      dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);\n      var promises = [dst.resolve.then(function (globals) {\n        dst.globals = globals;\n      })];\n      if (inherited) promises.push(inherited);\n\n      // Resolve template and dependencies for all views.\n      forEach(state.views, function (view, name) {\n        var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});\n        injectables.$template = [ function () {\n          return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: options.notify }) || '';\n        }];\n\n        promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {\n          // References to the controller (only instantiated at link time)\n          if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {\n            var injectLocals = angular.extend({}, injectables, locals);\n            result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);\n          } else {\n            result.$$controller = view.controller;\n          }\n          // Provide access to the state itself for internal use\n          result.$$state = state;\n          result.$$controllerAs = view.controllerAs;\n          dst[name] = result;\n        }));\n      });\n\n      // Wait for all the promises and then return the activation object\n      return $q.all(promises).then(function (values) {\n        return dst;\n      });\n    }\n\n    return $state;\n  }\n\n  function shouldTriggerReload(to, from, locals, options) {\n    if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) {\n      return true;\n    }\n  }\n}\n\nangular.module('ui.router.state')\n  .value('$stateParams', {})\n  .provider('$state', $StateProvider);\n\n\n$ViewProvider.$inject = [];\nfunction $ViewProvider() {\n\n  this.$get = $get;\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$view\n   *\n   * @requires ui.router.util.$templateFactory\n   * @requires $rootScope\n   *\n   * @description\n   *\n   */\n  $get.$inject = ['$rootScope', '$templateFactory'];\n  function $get(   $rootScope,   $templateFactory) {\n    return {\n      // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })\n      /**\n       * @ngdoc function\n       * @name ui.router.state.$view#load\n       * @methodOf ui.router.state.$view\n       *\n       * @description\n       *\n       * @param {string} name name\n       * @param {object} options option object.\n       */\n      load: function load(name, options) {\n        var result, defaults = {\n          template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}\n        };\n        options = extend(defaults, options);\n\n        if (options.view) {\n          result = $templateFactory.fromConfig(options.view, options.params, options.locals);\n        }\n        if (result && options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$viewContentLoading\n         * @eventOf ui.router.state.$view\n         * @eventType broadcast on root scope\n         * @description\n         *\n         * Fired once the view **begins loading**, *before* the DOM is rendered.\n         *\n         * @param {Object} event Event object.\n         * @param {Object} viewConfig The view config properties (template, controller, etc).\n         *\n         * @example\n         *\n         * <pre>\n         * $scope.$on('$viewContentLoading',\n         * function(event, viewConfig){\n         *     // Access to all the view config properties.\n         *     // and one special property 'targetView'\n         *     // viewConfig.targetView\n         * });\n         * </pre>\n         */\n          $rootScope.$broadcast('$viewContentLoading', options);\n        }\n        return result;\n      }\n    };\n  }\n}\n\nangular.module('ui.router.state').provider('$view', $ViewProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$uiViewScrollProvider\n *\n * @description\n * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.\n */\nfunction $ViewScrollProvider() {\n\n  var useAnchorScroll = false;\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll\n   * @methodOf ui.router.state.$uiViewScrollProvider\n   *\n   * @description\n   * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for\n   * scrolling based on the url anchor.\n   */\n  this.useAnchorScroll = function () {\n    useAnchorScroll = true;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$uiViewScroll\n   *\n   * @requires $anchorScroll\n   * @requires $timeout\n   *\n   * @description\n   * When called with a jqLite element, it scrolls the element into view (after a\n   * `$timeout` so the DOM has time to refresh).\n   *\n   * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,\n   * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.\n   */\n  this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {\n    if (useAnchorScroll) {\n      return $anchorScroll;\n    }\n\n    return function ($element) {\n      $timeout(function () {\n        $element[0].scrollIntoView();\n      }, 0, false);\n    };\n  }];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-view\n *\n * @requires ui.router.state.$state\n * @requires $compile\n * @requires $controller\n * @requires $injector\n * @requires ui.router.state.$uiViewScroll\n * @requires $document\n *\n * @restrict ECA\n *\n * @description\n * The ui-view directive tells $state where to place your templates.\n *\n * @param {string=} name A view name. The name should be unique amongst the other views in the\n * same state. You can have views of the same name that live in different states.\n *\n * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window\n * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll\n * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you\n * scroll ui-view elements into view when they are populated during a state activation.\n *\n * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*\n *\n * @param {string=} onload Expression to evaluate whenever the view updates.\n * \n * @example\n * A view can be unnamed or named. \n * <pre>\n * <!-- Unnamed -->\n * <div ui-view></div> \n * \n * <!-- Named -->\n * <div ui-view=\"viewName\"></div>\n * </pre>\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a \n * single view and it is unnamed then you can populate it like so:\n * <pre>\n * <div ui-view></div> \n * $stateProvider.state(\"home\", {\n *   template: \"<h1>HELLO!</h1>\"\n * })\n * </pre>\n * \n * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}\n * config property, by name, in this case an empty name:\n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * But typically you'll only use the views property if you name your view or have more than one view \n * in the same template. There's not really a compelling reason to name a view if its the only one, \n * but you could if you wanted, like so:\n * <pre>\n * <div ui-view=\"main\"></div>\n * </pre> \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"main\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * Really though, you'll use views to set up multiple views:\n * <pre>\n * <div ui-view></div>\n * <div ui-view=\"chart\"></div> \n * <div ui-view=\"data\"></div> \n * </pre>\n * \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     },\n *     \"chart\": {\n *       template: \"<chart_thing/>\"\n *     },\n *     \"data\": {\n *       template: \"<data_thing/>\"\n *     }\n *   }    \n * })\n * </pre>\n *\n * Examples for `autoscroll`:\n *\n * <pre>\n * <!-- If autoscroll present with no expression,\n *      then scroll ui-view into view -->\n * <ui-view autoscroll/>\n *\n * <!-- If autoscroll present with valid expression,\n *      then scroll ui-view into view if expression evaluates to true -->\n * <ui-view autoscroll='true'/>\n * <ui-view autoscroll='false'/>\n * <ui-view autoscroll='scopeVariable'/>\n * </pre>\n */\n$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];\nfunction $ViewDirective(   $state,   $injector,   $uiViewScroll,   $interpolate) {\n\n  function getService() {\n    return ($injector.has) ? function(service) {\n      return $injector.has(service) ? $injector.get(service) : null;\n    } : function(service) {\n      try {\n        return $injector.get(service);\n      } catch (e) {\n        return null;\n      }\n    };\n  }\n\n  var service = getService(),\n      $animator = service('$animator'),\n      $animate = service('$animate');\n\n  // Returns a set of DOM manipulation functions based on which Angular version\n  // it should use\n  function getRenderer(attrs, scope) {\n    var statics = function() {\n      return {\n        enter: function (element, target, cb) { target.after(element); cb(); },\n        leave: function (element, cb) { element.remove(); cb(); }\n      };\n    };\n\n    if ($animate) {\n      return {\n        enter: function(element, target, cb) {\n          var promise = $animate.enter(element, null, target, cb);\n          if (promise && promise.then) promise.then(cb);\n        },\n        leave: function(element, cb) {\n          var promise = $animate.leave(element, cb);\n          if (promise && promise.then) promise.then(cb);\n        }\n      };\n    }\n\n    if ($animator) {\n      var animate = $animator && $animator(scope, attrs);\n\n      return {\n        enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },\n        leave: function(element, cb) { animate.leave(element); cb(); }\n      };\n    }\n\n    return statics();\n  }\n\n  var directive = {\n    restrict: 'ECA',\n    terminal: true,\n    priority: 400,\n    transclude: 'element',\n    compile: function (tElement, tAttrs, $transclude) {\n      return function (scope, $element, attrs) {\n        var previousEl, currentEl, currentScope, latestLocals,\n            onloadExp     = attrs.onload || '',\n            autoScrollExp = attrs.autoscroll,\n            renderer      = getRenderer(attrs, scope);\n\n        scope.$on('$stateChangeSuccess', function() {\n          updateView(false);\n        });\n        scope.$on('$viewContentLoading', function() {\n          updateView(false);\n        });\n\n        updateView(true);\n\n        function cleanupLastView() {\n          if (previousEl) {\n            previousEl.remove();\n            previousEl = null;\n          }\n\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n\n          if (currentEl) {\n            renderer.leave(currentEl, function() {\n              previousEl = null;\n            });\n\n            previousEl = currentEl;\n            currentEl = null;\n          }\n        }\n\n        function updateView(firstTime) {\n          var newScope,\n              name            = getUiViewName(scope, attrs, $element, $interpolate),\n              previousLocals  = name && $state.$current && $state.$current.locals[name];\n\n          if (!firstTime && previousLocals === latestLocals) return; // nothing to do\n          newScope = scope.$new();\n          latestLocals = $state.$current.locals[name];\n\n          var clone = $transclude(newScope, function(clone) {\n            renderer.enter(clone, $element, function onUiViewEnter() {\n              if(currentScope) {\n                currentScope.$emit('$viewContentAnimationEnded');\n              }\n\n              if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {\n                $uiViewScroll(clone);\n              }\n            });\n            cleanupLastView();\n          });\n\n          currentEl = clone;\n          currentScope = newScope;\n          /**\n           * @ngdoc event\n           * @name ui.router.state.directive:ui-view#$viewContentLoaded\n           * @eventOf ui.router.state.directive:ui-view\n           * @eventType emits on ui-view directive scope\n           * @description           *\n           * Fired once the view is **loaded**, *after* the DOM is rendered.\n           *\n           * @param {Object} event Event object.\n           */\n          currentScope.$emit('$viewContentLoaded');\n          currentScope.$eval(onloadExp);\n        }\n      };\n    }\n  };\n\n  return directive;\n}\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];\nfunction $ViewDirectiveFill (  $compile,   $controller,   $state,   $interpolate) {\n  return {\n    restrict: 'ECA',\n    priority: -400,\n    compile: function (tElement) {\n      var initial = tElement.html();\n      return function (scope, $element, attrs) {\n        var current = $state.$current,\n            name = getUiViewName(scope, attrs, $element, $interpolate),\n            locals  = current && current.locals[name];\n\n        if (! locals) {\n          return;\n        }\n\n        $element.data('$uiView', { name: name, state: locals.$$state });\n        $element.html(locals.$template ? locals.$template : initial);\n\n        var link = $compile($element.contents());\n\n        if (locals.$$controller) {\n          locals.$scope = scope;\n          var controller = $controller(locals.$$controller, locals);\n          if (locals.$$controllerAs) {\n            scope[locals.$$controllerAs] = controller;\n          }\n          $element.data('$ngControllerController', controller);\n          $element.children().data('$ngControllerController', controller);\n        }\n\n        link(scope);\n      };\n    }\n  };\n}\n\n/**\n * Shared ui-view code for both directives:\n * Given scope, element, and its attributes, return the view's name\n */\nfunction getUiViewName(scope, attrs, element, $interpolate) {\n  var name = $interpolate(attrs.uiView || attrs.name || '')(scope);\n  var inherited = element.inheritedData('$uiView');\n  return name.indexOf('@') >= 0 ?  name :  (name + '@' + (inherited ? inherited.state.name : ''));\n}\n\nangular.module('ui.router.state').directive('uiView', $ViewDirective);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n\nfunction parseStateRef(ref, current) {\n  var preparsed = ref.match(/^\\s*({[^}]*})\\s*$/), parsed;\n  if (preparsed) ref = current + '(' + preparsed[1] + ')';\n  parsed = ref.replace(/\\n/g, \" \").match(/^([^(]+?)\\s*(\\((.*)\\))?$/);\n  if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n  return { state: parsed[1], paramExpr: parsed[3] || null };\n}\n\nfunction stateContext(el) {\n  var stateData = el.parent().inheritedData('$uiView');\n\n  if (stateData && stateData.state && stateData.state.name) {\n    return stateData.state;\n  }\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref\n *\n * @requires ui.router.state.$state\n * @requires $timeout\n *\n * @restrict A\n *\n * @description\n * A directive that binds a link (`<a>` tag) to a state. If the state has an associated \n * URL, the directive will automatically generate & update the `href` attribute via \n * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking \n * the link will trigger a state transition with optional parameters. \n *\n * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be \n * handled natively by the browser.\n *\n * You can also use relative state paths within ui-sref, just like the relative \n * paths passed to `$state.go()`. You just need to be aware that the path is relative\n * to the state that the link lives in, in other words the state that loaded the \n * template containing the link.\n *\n * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}\n * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,\n * and `reload`.\n *\n * @example\n * Here's an example of how you'd use ui-sref and how it would compile. If you have the \n * following template:\n * <pre>\n * <a ui-sref=\"home\">Home</a> | <a ui-sref=\"about\">About</a> | <a ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a ui-sref=\"contacts.detail({ id: contact.id })\">{{ contact.name }}</a>\n *     </li>\n * </ul>\n * </pre>\n * \n * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):\n * <pre>\n * <a href=\"#/home\" ui-sref=\"home\">Home</a> | <a href=\"#/about\" ui-sref=\"about\">About</a> | <a href=\"#/contacts?page=2\" ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/1\" ui-sref=\"contacts.detail({ id: contact.id })\">Joe</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/2\" ui-sref=\"contacts.detail({ id: contact.id })\">Alice</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/3\" ui-sref=\"contacts.detail({ id: contact.id })\">Bob</a>\n *     </li>\n * </ul>\n *\n * <a ui-sref=\"home\" ui-sref-opts=\"{reload: true}\">Home</a>\n * </pre>\n *\n * @param {string} ui-sref 'stateName' can be any valid absolute or relative state\n * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}\n */\n$StateRefDirective.$inject = ['$state', '$timeout'];\nfunction $StateRefDirective($state, $timeout) {\n  var allowedOptions = ['location', 'inherit', 'reload'];\n\n  return {\n    restrict: 'A',\n    require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n    link: function(scope, element, attrs, uiSrefActive) {\n      var ref = parseStateRef(attrs.uiSref, $state.current.name);\n      var params = null, url = null, base = stateContext(element) || $state.$current;\n      var newHref = null, isAnchor = element.prop(\"tagName\") === \"A\";\n      var isForm = element[0].nodeName === \"FORM\";\n      var attr = isForm ? \"action\" : \"href\", nav = true;\n\n      var options = { relative: base, inherit: true };\n      var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};\n\n      angular.forEach(allowedOptions, function(option) {\n        if (option in optionsOverride) {\n          options[option] = optionsOverride[option];\n        }\n      });\n\n      var update = function(newVal) {\n        if (newVal) params = angular.copy(newVal);\n        if (!nav) return;\n\n        newHref = $state.href(ref.state, params, options);\n\n        var activeDirective = uiSrefActive[1] || uiSrefActive[0];\n        if (activeDirective) {\n          activeDirective.$$setStateInfo(ref.state, params);\n        }\n        if (newHref === null) {\n          nav = false;\n          return false;\n        }\n        attrs.$set(attr, newHref);\n      };\n\n      if (ref.paramExpr) {\n        scope.$watch(ref.paramExpr, function(newVal, oldVal) {\n          if (newVal !== params) update(newVal);\n        }, true);\n        params = angular.copy(scope.$eval(ref.paramExpr));\n      }\n      update();\n\n      if (isForm) return;\n\n      element.bind(\"click\", function(e) {\n        var button = e.which || e.button;\n        if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {\n          // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n          var transition = $timeout(function() {\n            $state.go(ref.state, params, options);\n          });\n          e.preventDefault();\n\n          // if the state has no URL, ignore one preventDefault from the <a> directive.\n          var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;\n          e.preventDefault = function() {\n            if (ignorePreventDefaultCount-- <= 0)\n              $timeout.cancel(transition);\n          };\n        }\n      });\n    }\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * A directive working alongside ui-sref to add classes to an element when the\n * related ui-sref directive's state is active, and removing them when it is inactive.\n * The primary use-case is to simplify the special appearance of navigation menus\n * relying on `ui-sref`, by having the \"active\" state's menu button appear different,\n * distinguishing it from the inactive menu items.\n *\n * ui-sref-active can live on the same element as ui-sref or on a parent element. The first\n * ui-sref-active found at the same level or above the ui-sref will be used.\n *\n * Will activate when the ui-sref's target state or any child state is active. If you\n * need to activate only when the ui-sref target state is active and *not* any of\n * it's children, then you will use\n * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}\n *\n * @example\n * Given the following template:\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item\">\n *     <a href ui-sref=\"app.user({user: 'bilbobaggins'})\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n *\n * When the app state is \"app.user\" (or any children states), and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item active\">\n *     <a ui-sref=\"app.user({user: 'bilbobaggins'})\" href=\"/users/bilbobaggins\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n * The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * Multiple classes may be specified in a space-separated format:\n * <pre>\n * <ul>\n *   <li ui-sref-active='class1 class2 class3'>\n *     <a ui-sref=\"app.user\">link</a>\n *   </li>\n * </ul>\n * </pre>\n */\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active-eq\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate\n * when the exact target state used in the `ui-sref` is active; no child states.\n *\n */\n$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];\nfunction $StateRefActiveDirective($state, $stateParams, $interpolate) {\n  return  {\n    restrict: \"A\",\n    controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {\n      var state, params, activeClass;\n\n      // There probably isn't much point in $observing this\n      // uiSrefActive and uiSrefActiveEq share the same directive object with some\n      // slight difference in logic routing\n      activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);\n\n      // Allow uiSref to communicate with uiSrefActive[Equals]\n      this.$$setStateInfo = function (newState, newParams) {\n        state = $state.get(newState, stateContext($element));\n        params = newParams;\n        update();\n      };\n\n      $scope.$on('$stateChangeSuccess', update);\n\n      // Update route state\n      function update() {\n        if (isMatch()) {\n          $element.addClass(activeClass);\n        } else {\n          $element.removeClass(activeClass);\n        }\n      }\n\n      function isMatch() {\n        if (typeof $attrs.uiSrefActiveEq !== 'undefined') {\n          return state && $state.is(state.name, params);\n        } else {\n          return state && $state.includes(state.name, params);\n        }\n      }\n    }]\n  };\n}\n\nangular.module('ui.router.state')\n  .directive('uiSref', $StateRefDirective)\n  .directive('uiSrefActive', $StateRefActiveDirective)\n  .directive('uiSrefActiveEq', $StateRefActiveDirective);\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:isState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_is $state.is(\"stateName\")}.\n */\n$IsStateFilter.$inject = ['$state'];\nfunction $IsStateFilter($state) {\n  var isFilter = function (state) {\n    return $state.is(state);\n  };\n  isFilter.$stateful = true;\n  return isFilter;\n}\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:includedByState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.\n */\n$IncludedByStateFilter.$inject = ['$state'];\nfunction $IncludedByStateFilter($state) {\n  var includesFilter = function (state) {\n    return $state.includes(state);\n  };\n  includesFilter.$stateful = true;\n  return  includesFilter;\n}\n\nangular.module('ui.router.state')\n  .filter('isState', $IsStateFilter)\n  .filter('includedByState', $IncludedByStateFilter);\n})(window, window.angular);"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/ionic-angular.js",
    "content": "/*!\n * Copyright 2014 Drifty Co.\n * http://drifty.com/\n *\n * Ionic, v1.0.0\n * A powerful HTML5 mobile app framework.\n * http://ionicframework.com/\n *\n * By @maxlynch, @benjsperry, @adamdbradley <3\n *\n * Licensed under the MIT license. Please see LICENSE for more information.\n *\n */\n\n(function() {\n/* eslint no-unused-vars:0 */\nvar IonicModule = angular.module('ionic', ['ngAnimate', 'ngSanitize', 'ui.router']),\n  extend = angular.extend,\n  forEach = angular.forEach,\n  isDefined = angular.isDefined,\n  isNumber = angular.isNumber,\n  isString = angular.isString,\n  jqLite = angular.element,\n  noop = angular.noop;\n\n/**\n * @ngdoc service\n * @name $ionicActionSheet\n * @module ionic\n * @description\n * The Action Sheet is a slide-up pane that lets the user choose from a set of options.\n * Dangerous options are highlighted in red and made obvious.\n *\n * There are easy ways to cancel out of the action sheet, such as tapping the backdrop or even\n * hitting escape on the keyboard for desktop testing.\n *\n * ![Action Sheet](http://ionicframework.com.s3.amazonaws.com/docs/controllers/actionSheet.gif)\n *\n * @usage\n * To trigger an Action Sheet in your code, use the $ionicActionSheet service in your angular controllers:\n *\n * ```js\n * angular.module('mySuperApp', ['ionic'])\n * .controller(function($scope, $ionicActionSheet, $timeout) {\n *\n *  // Triggered on a button click, or some other target\n *  $scope.show = function() {\n *\n *    // Show the action sheet\n *    var hideSheet = $ionicActionSheet.show({\n *      buttons: [\n *        { text: '<b>Share</b> This' },\n *        { text: 'Move' }\n *      ],\n *      destructiveText: 'Delete',\n *      titleText: 'Modify your album',\n *      cancelText: 'Cancel',\n *      cancel: function() {\n          // add cancel code..\n        },\n *      buttonClicked: function(index) {\n *        return true;\n *      }\n *    });\n *\n *    // For example's sake, hide the sheet after two seconds\n *    $timeout(function() {\n *      hideSheet();\n *    }, 2000);\n *\n *  };\n * });\n * ```\n *\n */\nIonicModule\n.factory('$ionicActionSheet', [\n  '$rootScope',\n  '$compile',\n  '$animate',\n  '$timeout',\n  '$ionicTemplateLoader',\n  '$ionicPlatform',\n  '$ionicBody',\n  'IONIC_BACK_PRIORITY',\nfunction($rootScope, $compile, $animate, $timeout, $ionicTemplateLoader, $ionicPlatform, $ionicBody, IONIC_BACK_PRIORITY) {\n\n  return {\n    show: actionSheet\n  };\n\n  /**\n   * @ngdoc method\n   * @name $ionicActionSheet#show\n   * @description\n   * Load and return a new action sheet.\n   *\n   * A new isolated scope will be created for the\n   * action sheet and the new element will be appended into the body.\n   *\n   * @param {object} options The options for this ActionSheet. Properties:\n   *\n   *  - `[Object]` `buttons` Which buttons to show.  Each button is an object with a `text` field.\n   *  - `{string}` `titleText` The title to show on the action sheet.\n   *  - `{string=}` `cancelText` the text for a 'cancel' button on the action sheet.\n   *  - `{string=}` `destructiveText` The text for a 'danger' on the action sheet.\n   *  - `{function=}` `cancel` Called if the cancel button is pressed, the backdrop is tapped or\n   *     the hardware back button is pressed.\n   *  - `{function=}` `buttonClicked` Called when one of the non-destructive buttons is clicked,\n   *     with the index of the button that was clicked and the button object. Return true to close\n   *     the action sheet, or false to keep it opened.\n   *  - `{function=}` `destructiveButtonClicked` Called when the destructive button is clicked.\n   *     Return true to close the action sheet, or false to keep it opened.\n   *  -  `{boolean=}` `cancelOnStateChange` Whether to cancel the actionSheet when navigating\n   *     to a new state.  Default true.\n   *  - `{string}` `cssClass` The custom CSS class name.\n   *\n   * @returns {function} `hideSheet` A function which, when called, hides & cancels the action sheet.\n   */\n  function actionSheet(opts) {\n    var scope = $rootScope.$new(true);\n\n    extend(scope, {\n      cancel: noop,\n      destructiveButtonClicked: noop,\n      buttonClicked: noop,\n      $deregisterBackButton: noop,\n      buttons: [],\n      cancelOnStateChange: true\n    }, opts || {});\n\n    function textForIcon(text) {\n      if (text && /icon/.test(text)) {\n        scope.$actionSheetHasIcon = true;\n      }\n    }\n\n    for (var x = 0; x < scope.buttons.length; x++) {\n      textForIcon(scope.buttons[x].text);\n    }\n    textForIcon(scope.cancelText);\n    textForIcon(scope.destructiveText);\n\n    // Compile the template\n    var element = scope.element = $compile('<ion-action-sheet ng-class=\"cssClass\" buttons=\"buttons\"></ion-action-sheet>')(scope);\n\n    // Grab the sheet element for animation\n    var sheetEl = jqLite(element[0].querySelector('.action-sheet-wrapper'));\n\n    var stateChangeListenDone = scope.cancelOnStateChange ?\n      $rootScope.$on('$stateChangeSuccess', function() { scope.cancel(); }) :\n      noop;\n\n    // removes the actionSheet from the screen\n    scope.removeSheet = function(done) {\n      if (scope.removed) return;\n\n      scope.removed = true;\n      sheetEl.removeClass('action-sheet-up');\n      $timeout(function() {\n        // wait to remove this due to a 300ms delay native\n        // click which would trigging whatever was underneath this\n        $ionicBody.removeClass('action-sheet-open');\n      }, 400);\n      scope.$deregisterBackButton();\n      stateChangeListenDone();\n\n      $animate.removeClass(element, 'active').then(function() {\n        scope.$destroy();\n        element.remove();\n        // scope.cancel.$scope is defined near the bottom\n        scope.cancel.$scope = sheetEl = null;\n        (done || noop)();\n      });\n    };\n\n    scope.showSheet = function(done) {\n      if (scope.removed) return;\n\n      $ionicBody.append(element)\n                .addClass('action-sheet-open');\n\n      $animate.addClass(element, 'active').then(function() {\n        if (scope.removed) return;\n        (done || noop)();\n      });\n      $timeout(function() {\n        if (scope.removed) return;\n        sheetEl.addClass('action-sheet-up');\n      }, 20, false);\n    };\n\n    // registerBackButtonAction returns a callback to deregister the action\n    scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(\n      function() {\n        $timeout(scope.cancel);\n      },\n      IONIC_BACK_PRIORITY.actionSheet\n    );\n\n    // called when the user presses the cancel button\n    scope.cancel = function() {\n      // after the animation is out, call the cancel callback\n      scope.removeSheet(opts.cancel);\n    };\n\n    scope.buttonClicked = function(index) {\n      // Check if the button click event returned true, which means\n      // we can close the action sheet\n      if (opts.buttonClicked(index, opts.buttons[index]) === true) {\n        scope.removeSheet();\n      }\n    };\n\n    scope.destructiveButtonClicked = function() {\n      // Check if the destructive button click event returned true, which means\n      // we can close the action sheet\n      if (opts.destructiveButtonClicked() === true) {\n        scope.removeSheet();\n      }\n    };\n\n    scope.showSheet();\n\n    // Expose the scope on $ionicActionSheet's return value for the sake\n    // of testing it.\n    scope.cancel.$scope = scope;\n\n    return scope.cancel;\n  }\n}]);\n\n\njqLite.prototype.addClass = function(cssClasses) {\n  var x, y, cssClass, el, splitClasses, existingClasses;\n  if (cssClasses && cssClasses != 'ng-scope' && cssClasses != 'ng-isolate-scope') {\n    for (x = 0; x < this.length; x++) {\n      el = this[x];\n      if (el.setAttribute) {\n\n        if (cssClasses.indexOf(' ') < 0 && el.classList.add) {\n          el.classList.add(cssClasses);\n        } else {\n          existingClasses = (' ' + (el.getAttribute('class') || '') + ' ')\n            .replace(/[\\n\\t]/g, \" \");\n          splitClasses = cssClasses.split(' ');\n\n          for (y = 0; y < splitClasses.length; y++) {\n            cssClass = splitClasses[y].trim();\n            if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\n              existingClasses += cssClass + ' ';\n            }\n          }\n          el.setAttribute('class', existingClasses.trim());\n        }\n      }\n    }\n  }\n  return this;\n};\n\njqLite.prototype.removeClass = function(cssClasses) {\n  var x, y, splitClasses, cssClass, el;\n  if (cssClasses) {\n    for (x = 0; x < this.length; x++) {\n      el = this[x];\n      if (el.getAttribute) {\n        if (cssClasses.indexOf(' ') < 0 && el.classList.remove) {\n          el.classList.remove(cssClasses);\n        } else {\n          splitClasses = cssClasses.split(' ');\n\n          for (y = 0; y < splitClasses.length; y++) {\n            cssClass = splitClasses[y];\n            el.setAttribute('class', (\n                (\" \" + (el.getAttribute('class') || '') + \" \")\n                .replace(/[\\n\\t]/g, \" \")\n                .replace(\" \" + cssClass.trim() + \" \", \" \")).trim()\n            );\n          }\n        }\n      }\n    }\n  }\n  return this;\n};\n\n/**\n * @ngdoc service\n * @name $ionicBackdrop\n * @module ionic\n * @description\n * Shows and hides a backdrop over the UI.  Appears behind popups, loading,\n * and other overlays.\n *\n * Often, multiple UI components require a backdrop, but only one backdrop is\n * ever needed in the DOM at a time.\n *\n * Therefore, each component that requires the backdrop to be shown calls\n * `$ionicBackdrop.retain()` when it wants the backdrop, then `$ionicBackdrop.release()`\n * when it is done with the backdrop.\n *\n * For each time `retain` is called, the backdrop will be shown until `release` is called.\n *\n * For example, if `retain` is called three times, the backdrop will be shown until `release`\n * is called three times.\n *\n * @usage\n *\n * ```js\n * function MyController($scope, $ionicBackdrop, $timeout) {\n *   //Show a backdrop for one second\n *   $scope.action = function() {\n *     $ionicBackdrop.retain();\n *     $timeout(function() {\n *       $ionicBackdrop.release();\n *     }, 1000);\n *   };\n * }\n * ```\n */\nIonicModule\n.factory('$ionicBackdrop', [\n  '$document', '$timeout', '$$rAF',\nfunction($document, $timeout, $$rAF) {\n\n  var el = jqLite('<div class=\"backdrop\">');\n  var backdropHolds = 0;\n\n  $document[0].body.appendChild(el[0]);\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicBackdrop#retain\n     * @description Retains the backdrop.\n     */\n    retain: retain,\n    /**\n     * @ngdoc method\n     * @name $ionicBackdrop#release\n     * @description\n     * Releases the backdrop.\n     */\n    release: release,\n\n    getElement: getElement,\n\n    // exposed for testing\n    _element: el\n  };\n\n  function retain() {\n    backdropHolds++;\n    if (backdropHolds === 1) {\n      el.addClass('visible');\n      $$rAF(function() {\n        // If we're still at >0 backdropHolds after async...\n        if (backdropHolds >= 1) el.addClass('active');\n      });\n    }\n  }\n  function release() {\n    if (backdropHolds === 1) {\n      el.removeClass('active');\n      $timeout(function() {\n        // If we're still at 0 backdropHolds after async...\n        if (backdropHolds === 0) el.removeClass('visible');\n      }, 400, false);\n    }\n    backdropHolds = Math.max(0, backdropHolds - 1);\n  }\n\n  function getElement() {\n    return el;\n  }\n\n}]);\n\n/**\n * @private\n */\nIonicModule\n.factory('$ionicBind', ['$parse', '$interpolate', function($parse, $interpolate) {\n  var LOCAL_REGEXP = /^\\s*([@=&])(\\??)\\s*(\\w*)\\s*$/;\n  return function(scope, attrs, bindDefinition) {\n    forEach(bindDefinition || {}, function(definition, scopeName) {\n      //Adapted from angular.js $compile\n      var match = definition.match(LOCAL_REGEXP) || [],\n        attrName = match[3] || scopeName,\n        mode = match[1], // @, =, or &\n        parentGet,\n        unwatch;\n\n      switch (mode) {\n        case '@':\n          if (!attrs[attrName]) {\n            return;\n          }\n          attrs.$observe(attrName, function(value) {\n            scope[scopeName] = value;\n          });\n          // we trigger an interpolation to ensure\n          // the value is there for use immediately\n          if (attrs[attrName]) {\n            scope[scopeName] = $interpolate(attrs[attrName])(scope);\n          }\n          break;\n\n        case '=':\n          if (!attrs[attrName]) {\n            return;\n          }\n          unwatch = scope.$watch(attrs[attrName], function(value) {\n            scope[scopeName] = value;\n          });\n          //Destroy parent scope watcher when this scope is destroyed\n          scope.$on('$destroy', unwatch);\n          break;\n\n        case '&':\n          /* jshint -W044 */\n          if (attrs[attrName] && attrs[attrName].match(RegExp(scopeName + '\\(.*?\\)'))) {\n            throw new Error('& expression binding \"' + scopeName + '\" looks like it will recursively call \"' +\n                          attrs[attrName] + '\" and cause a stack overflow! Please choose a different scopeName.');\n          }\n          parentGet = $parse(attrs[attrName]);\n          scope[scopeName] = function(locals) {\n            return parentGet(scope, locals);\n          };\n          break;\n      }\n    });\n  };\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicBody\n * @module ionic\n * @description An angular utility service to easily and efficiently\n * add and remove CSS classes from the document's body element.\n */\nIonicModule\n.factory('$ionicBody', ['$document', function($document) {\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicBody#add\n     * @description Add a class to the document's body element.\n     * @param {string} class Each argument will be added to the body element.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    addClass: function() {\n      for (var x = 0; x < arguments.length; x++) {\n        $document[0].body.classList.add(arguments[x]);\n      }\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#removeClass\n     * @description Remove a class from the document's body element.\n     * @param {string} class Each argument will be removed from the body element.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    removeClass: function() {\n      for (var x = 0; x < arguments.length; x++) {\n        $document[0].body.classList.remove(arguments[x]);\n      }\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#enableClass\n     * @description Similar to the `add` method, except the first parameter accepts a boolean\n     * value determining if the class should be added or removed. Rather than writing user code,\n     * such as \"if true then add the class, else then remove the class\", this method can be\n     * given a true or false value which reduces redundant code.\n     * @param {boolean} shouldEnableClass A true/false value if the class should be added or removed.\n     * @param {string} class Each remaining argument would be added or removed depending on\n     * the first argument.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    enableClass: function(shouldEnableClass) {\n      var args = Array.prototype.slice.call(arguments).slice(1);\n      if (shouldEnableClass) {\n        this.addClass.apply(this, args);\n      } else {\n        this.removeClass.apply(this, args);\n      }\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#append\n     * @description Append a child to the document's body.\n     * @param {element} element The element to be appended to the body. The passed in element\n     * can be either a jqLite element, or a DOM element.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    append: function(ele) {\n      $document[0].body.appendChild(ele.length ? ele[0] : ele);\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#get\n     * @description Get the document's body element.\n     * @returns {element} Returns the document's body element.\n     */\n    get: function() {\n      return $document[0].body;\n    }\n  };\n}]);\n\nIonicModule\n.factory('$ionicClickBlock', [\n  '$document',\n  '$ionicBody',\n  '$timeout',\nfunction($document, $ionicBody, $timeout) {\n  var CSS_HIDE = 'click-block-hide';\n  var cbEle, fallbackTimer, pendingShow;\n\n  function preventClick(ev) {\n    ev.preventDefault();\n    ev.stopPropagation();\n  }\n\n  function addClickBlock() {\n    if (pendingShow) {\n      if (cbEle) {\n        cbEle.classList.remove(CSS_HIDE);\n      } else {\n        cbEle = $document[0].createElement('div');\n        cbEle.className = 'click-block';\n        $ionicBody.append(cbEle);\n        cbEle.addEventListener('touchstart', preventClick);\n        cbEle.addEventListener('mousedown', preventClick);\n      }\n      pendingShow = false;\n    }\n  }\n\n  function removeClickBlock() {\n    cbEle && cbEle.classList.add(CSS_HIDE);\n  }\n\n  return {\n    show: function(autoExpire) {\n      pendingShow = true;\n      $timeout.cancel(fallbackTimer);\n      fallbackTimer = $timeout(this.hide, autoExpire || 310, false);\n      addClickBlock();\n    },\n    hide: function() {\n      pendingShow = false;\n      $timeout.cancel(fallbackTimer);\n      removeClickBlock();\n    }\n  };\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicGesture\n * @module ionic\n * @description An angular service exposing ionic\n * {@link ionic.utility:ionic.EventController}'s gestures.\n */\nIonicModule\n.factory('$ionicGesture', [function() {\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicGesture#on\n     * @description Add an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#onGesture}.\n     * @param {string} eventType The gesture event to listen for.\n     * @param {function(e)} callback The function to call when the gesture\n     * happens.\n     * @param {element} $element The angular element to listen for the event on.\n     * @param {object} options object.\n     * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).\n     */\n    on: function(eventType, cb, $element, options) {\n      return window.ionic.onGesture(eventType, cb, $element[0], options);\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicGesture#off\n     * @description Remove an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#offGesture}.\n     * @param {ionic.Gesture} gesture The gesture that should be removed.\n     * @param {string} eventType The gesture event to remove the listener for.\n     * @param {function(e)} callback The listener to remove.\n     */\n    off: function(gesture, eventType, cb) {\n      return window.ionic.offGesture(gesture, eventType, cb);\n    }\n  };\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicHistory\n * @module ionic\n * @description\n * $ionicHistory keeps track of views as the user navigates through an app. Similar to the way a\n * browser behaves, an Ionic app is able to keep track of the previous view, the current view, and\n * the forward view (if there is one).  However, a typical web browser only keeps track of one\n * history stack in a linear fashion.\n *\n * Unlike a traditional browser environment, apps and webapps have parallel independent histories,\n * such as with tabs. Should a user navigate few pages deep on one tab, and then switch to a new\n * tab and back, the back button relates not to the previous tab, but to the previous pages\n * visited within _that_ tab.\n *\n * `$ionicHistory` facilitates this parallel history architecture.\n */\n\nIonicModule\n.factory('$ionicHistory', [\n  '$rootScope',\n  '$state',\n  '$location',\n  '$window',\n  '$timeout',\n  '$ionicViewSwitcher',\n  '$ionicNavViewDelegate',\nfunction($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {\n\n  // history actions while navigating views\n  var ACTION_INITIAL_VIEW = 'initialView';\n  var ACTION_NEW_VIEW = 'newView';\n  var ACTION_MOVE_BACK = 'moveBack';\n  var ACTION_MOVE_FORWARD = 'moveForward';\n\n  // direction of navigation\n  var DIRECTION_BACK = 'back';\n  var DIRECTION_FORWARD = 'forward';\n  var DIRECTION_ENTER = 'enter';\n  var DIRECTION_EXIT = 'exit';\n  var DIRECTION_SWAP = 'swap';\n  var DIRECTION_NONE = 'none';\n\n  var stateChangeCounter = 0;\n  var lastStateId, nextViewOptions, nextViewExpireTimer, forcedNav;\n\n  var viewHistory = {\n    histories: { root: { historyId: 'root', parentHistoryId: null, stack: [], cursor: -1 } },\n    views: {},\n    backView: null,\n    forwardView: null,\n    currentView: null\n  };\n\n  var View = function() {};\n  View.prototype.initialize = function(data) {\n    if (data) {\n      for (var name in data) this[name] = data[name];\n      return this;\n    }\n    return null;\n  };\n  View.prototype.go = function() {\n\n    if (this.stateName) {\n      return $state.go(this.stateName, this.stateParams);\n    }\n\n    if (this.url && this.url !== $location.url()) {\n\n      if (viewHistory.backView === this) {\n        return $window.history.go(-1);\n      } else if (viewHistory.forwardView === this) {\n        return $window.history.go(1);\n      }\n\n      $location.url(this.url);\n    }\n\n    return null;\n  };\n  View.prototype.destroy = function() {\n    if (this.scope) {\n      this.scope.$destroy && this.scope.$destroy();\n      this.scope = null;\n    }\n  };\n\n\n  function getViewById(viewId) {\n    return (viewId ? viewHistory.views[ viewId ] : null);\n  }\n\n  function getBackView(view) {\n    return (view ? getViewById(view.backViewId) : null);\n  }\n\n  function getForwardView(view) {\n    return (view ? getViewById(view.forwardViewId) : null);\n  }\n\n  function getHistoryById(historyId) {\n    return (historyId ? viewHistory.histories[ historyId ] : null);\n  }\n\n  function getHistory(scope) {\n    var histObj = getParentHistoryObj(scope);\n\n    if (!viewHistory.histories[ histObj.historyId ]) {\n      // this history object exists in parent scope, but doesn't\n      // exist in the history data yet\n      viewHistory.histories[ histObj.historyId ] = {\n        historyId: histObj.historyId,\n        parentHistoryId: getParentHistoryObj(histObj.scope.$parent).historyId,\n        stack: [],\n        cursor: -1\n      };\n    }\n    return getHistoryById(histObj.historyId);\n  }\n\n  function getParentHistoryObj(scope) {\n    var parentScope = scope;\n    while (parentScope) {\n      if (parentScope.hasOwnProperty('$historyId')) {\n        // this parent scope has a historyId\n        return { historyId: parentScope.$historyId, scope: parentScope };\n      }\n      // nothing found keep climbing up\n      parentScope = parentScope.$parent;\n    }\n    // no history for the parent, use the root\n    return { historyId: 'root', scope: $rootScope };\n  }\n\n  function setNavViews(viewId) {\n    viewHistory.currentView = getViewById(viewId);\n    viewHistory.backView = getBackView(viewHistory.currentView);\n    viewHistory.forwardView = getForwardView(viewHistory.currentView);\n  }\n\n  function getCurrentStateId() {\n    var id;\n    if ($state && $state.current && $state.current.name) {\n      id = $state.current.name;\n      if ($state.params) {\n        for (var key in $state.params) {\n          if ($state.params.hasOwnProperty(key) && $state.params[key]) {\n            id += \"_\" + key + \"=\" + $state.params[key];\n          }\n        }\n      }\n      return id;\n    }\n    // if something goes wrong make sure its got a unique stateId\n    return ionic.Utils.nextUid();\n  }\n\n  function getCurrentStateParams() {\n    var rtn;\n    if ($state && $state.params) {\n      for (var key in $state.params) {\n        if ($state.params.hasOwnProperty(key)) {\n          rtn = rtn || {};\n          rtn[key] = $state.params[key];\n        }\n      }\n    }\n    return rtn;\n  }\n\n\n  return {\n\n    register: function(parentScope, viewLocals) {\n\n      var currentStateId = getCurrentStateId(),\n          hist = getHistory(parentScope),\n          currentView = viewHistory.currentView,\n          backView = viewHistory.backView,\n          forwardView = viewHistory.forwardView,\n          viewId = null,\n          action = null,\n          direction = DIRECTION_NONE,\n          historyId = hist.historyId,\n          url = $location.url(),\n          tmp, x, ele;\n\n      if (lastStateId !== currentStateId) {\n        lastStateId = currentStateId;\n        stateChangeCounter++;\n      }\n\n      if (forcedNav) {\n        // we've previously set exactly what to do\n        viewId = forcedNav.viewId;\n        action = forcedNav.action;\n        direction = forcedNav.direction;\n        forcedNav = null;\n\n      } else if (backView && backView.stateId === currentStateId) {\n        // they went back one, set the old current view as a forward view\n        viewId = backView.viewId;\n        historyId = backView.historyId;\n        action = ACTION_MOVE_BACK;\n        if (backView.historyId === currentView.historyId) {\n          // went back in the same history\n          direction = DIRECTION_BACK;\n\n        } else if (currentView) {\n          direction = DIRECTION_EXIT;\n\n          tmp = getHistoryById(backView.historyId);\n          if (tmp && tmp.parentHistoryId === currentView.historyId) {\n            direction = DIRECTION_ENTER;\n\n          } else {\n            tmp = getHistoryById(currentView.historyId);\n            if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {\n              direction = DIRECTION_SWAP;\n            }\n          }\n        }\n\n      } else if (forwardView && forwardView.stateId === currentStateId) {\n        // they went to the forward one, set the forward view to no longer a forward view\n        viewId = forwardView.viewId;\n        historyId = forwardView.historyId;\n        action = ACTION_MOVE_FORWARD;\n        if (forwardView.historyId === currentView.historyId) {\n          direction = DIRECTION_FORWARD;\n\n        } else if (currentView) {\n          direction = DIRECTION_EXIT;\n\n          if (currentView.historyId === hist.parentHistoryId) {\n            direction = DIRECTION_ENTER;\n\n          } else {\n            tmp = getHistoryById(currentView.historyId);\n            if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {\n              direction = DIRECTION_SWAP;\n            }\n          }\n        }\n\n        tmp = getParentHistoryObj(parentScope);\n        if (forwardView.historyId && tmp.scope) {\n          // if a history has already been created by the forward view then make sure it stays the same\n          tmp.scope.$historyId = forwardView.historyId;\n          historyId = forwardView.historyId;\n        }\n\n      } else if (currentView && currentView.historyId !== historyId &&\n                hist.cursor > -1 && hist.stack.length > 0 && hist.cursor < hist.stack.length &&\n                hist.stack[hist.cursor].stateId === currentStateId) {\n        // they just changed to a different history and the history already has views in it\n        var switchToView = hist.stack[hist.cursor];\n        viewId = switchToView.viewId;\n        historyId = switchToView.historyId;\n        action = ACTION_MOVE_BACK;\n        direction = DIRECTION_SWAP;\n\n        tmp = getHistoryById(currentView.historyId);\n        if (tmp && tmp.parentHistoryId === historyId) {\n          direction = DIRECTION_EXIT;\n\n        } else {\n          tmp = getHistoryById(historyId);\n          if (tmp && tmp.parentHistoryId === currentView.historyId) {\n            direction = DIRECTION_ENTER;\n          }\n        }\n\n        // if switching to a different history, and the history of the view we're switching\n        // to has an existing back view from a different history than itself, then\n        // it's back view would be better represented using the current view as its back view\n        tmp = getViewById(switchToView.backViewId);\n        if (tmp && switchToView.historyId !== tmp.historyId) {\n          hist.stack[hist.cursor].backViewId = currentView.viewId;\n        }\n\n      } else {\n\n        // create an element from the viewLocals template\n        ele = $ionicViewSwitcher.createViewEle(viewLocals);\n        if (this.isAbstractEle(ele, viewLocals)) {\n          void 0;\n          return {\n            action: 'abstractView',\n            direction: DIRECTION_NONE,\n            ele: ele\n          };\n        }\n\n        // set a new unique viewId\n        viewId = ionic.Utils.nextUid();\n\n        if (currentView) {\n          // set the forward view if there is a current view (ie: if its not the first view)\n          currentView.forwardViewId = viewId;\n\n          action = ACTION_NEW_VIEW;\n\n          // check if there is a new forward view within the same history\n          if (forwardView && currentView.stateId !== forwardView.stateId &&\n             currentView.historyId === forwardView.historyId) {\n            // they navigated to a new view but the stack already has a forward view\n            // since its a new view remove any forwards that existed\n            tmp = getHistoryById(forwardView.historyId);\n            if (tmp) {\n              // the forward has a history\n              for (x = tmp.stack.length - 1; x >= forwardView.index; x--) {\n                // starting from the end destroy all forwards in this history from this point\n                var stackItem = tmp.stack[x];\n                stackItem && stackItem.destroy && stackItem.destroy();\n                tmp.stack.splice(x);\n              }\n              historyId = forwardView.historyId;\n            }\n          }\n\n          // its only moving forward if its in the same history\n          if (hist.historyId === currentView.historyId) {\n            direction = DIRECTION_FORWARD;\n\n          } else if (currentView.historyId !== hist.historyId) {\n            direction = DIRECTION_ENTER;\n\n            tmp = getHistoryById(currentView.historyId);\n            if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {\n              direction = DIRECTION_SWAP;\n\n            } else {\n              tmp = getHistoryById(tmp.parentHistoryId);\n              if (tmp && tmp.historyId === hist.historyId) {\n                direction = DIRECTION_EXIT;\n              }\n            }\n          }\n\n        } else {\n          // there's no current view, so this must be the initial view\n          action = ACTION_INITIAL_VIEW;\n        }\n\n        if (stateChangeCounter < 2) {\n          // views that were spun up on the first load should not animate\n          direction = DIRECTION_NONE;\n        }\n\n        // add the new view\n        viewHistory.views[viewId] = this.createView({\n          viewId: viewId,\n          index: hist.stack.length,\n          historyId: hist.historyId,\n          backViewId: (currentView && currentView.viewId ? currentView.viewId : null),\n          forwardViewId: null,\n          stateId: currentStateId,\n          stateName: this.currentStateName(),\n          stateParams: getCurrentStateParams(),\n          url: url,\n          canSwipeBack: canSwipeBack(ele, viewLocals)\n        });\n\n        // add the new view to this history's stack\n        hist.stack.push(viewHistory.views[viewId]);\n      }\n\n      $timeout.cancel(nextViewExpireTimer);\n      if (nextViewOptions) {\n        if (nextViewOptions.disableAnimate) direction = DIRECTION_NONE;\n        if (nextViewOptions.disableBack) viewHistory.views[viewId].backViewId = null;\n        if (nextViewOptions.historyRoot) {\n          for (x = 0; x < hist.stack.length; x++) {\n            if (hist.stack[x].viewId === viewId) {\n              hist.stack[x].index = 0;\n              hist.stack[x].backViewId = hist.stack[x].forwardViewId = null;\n            } else {\n              delete viewHistory.views[hist.stack[x].viewId];\n            }\n          }\n          hist.stack = [viewHistory.views[viewId]];\n        }\n        nextViewOptions = null;\n      }\n\n      setNavViews(viewId);\n\n      if (viewHistory.backView && historyId == viewHistory.backView.historyId && currentStateId == viewHistory.backView.stateId && url == viewHistory.backView.url) {\n        for (x = 0; x < hist.stack.length; x++) {\n          if (hist.stack[x].viewId == viewId) {\n            action = 'dupNav';\n            direction = DIRECTION_NONE;\n            if (x > 0) {\n              hist.stack[x - 1].forwardViewId = null;\n            }\n            viewHistory.forwardView = null;\n            viewHistory.currentView.index = viewHistory.backView.index;\n            viewHistory.currentView.backViewId = viewHistory.backView.backViewId;\n            viewHistory.backView = getBackView(viewHistory.backView);\n            hist.stack.splice(x, 1);\n            break;\n          }\n        }\n      }\n\n      void 0;\n\n      hist.cursor = viewHistory.currentView.index;\n\n      return {\n        viewId: viewId,\n        action: action,\n        direction: direction,\n        historyId: historyId,\n        enableBack: this.enabledBack(viewHistory.currentView),\n        isHistoryRoot: (viewHistory.currentView.index === 0),\n        ele: ele\n      };\n    },\n\n    registerHistory: function(scope) {\n      scope.$historyId = ionic.Utils.nextUid();\n    },\n\n    createView: function(data) {\n      var newView = new View();\n      return newView.initialize(data);\n    },\n\n    getViewById: getViewById,\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#viewHistory\n     * @description The app's view history data, such as all the views and histories, along\n     * with how they are ordered and linked together within the navigation stack.\n     * @returns {object} Returns an object containing the apps view history data.\n     */\n    viewHistory: function() {\n      return viewHistory;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentView\n     * @description The app's current view.\n     * @returns {object} Returns the current view.\n     */\n    currentView: function(view) {\n      if (arguments.length) {\n        viewHistory.currentView = view;\n      }\n      return viewHistory.currentView;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentHistoryId\n     * @description The ID of the history stack which is the parent container of the current view.\n     * @returns {string} Returns the current history ID.\n     */\n    currentHistoryId: function() {\n      return viewHistory.currentView ? viewHistory.currentView.historyId : null;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentTitle\n     * @description Gets and sets the current view's title.\n     * @param {string=} val The title to update the current view with.\n     * @returns {string} Returns the current view's title.\n     */\n    currentTitle: function(val) {\n      if (viewHistory.currentView) {\n        if (arguments.length) {\n          viewHistory.currentView.title = val;\n        }\n        return viewHistory.currentView.title;\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#backView\n     * @description Returns the view that was before the current view in the history stack.\n     * If the user navigated from View A to View B, then View A would be the back view, and\n     * View B would be the current view.\n     * @returns {object} Returns the back view.\n     */\n    backView: function(view) {\n      if (arguments.length) {\n        viewHistory.backView = view;\n      }\n      return viewHistory.backView;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#backTitle\n     * @description Gets the back view's title.\n     * @returns {string} Returns the back view's title.\n     */\n    backTitle: function(view) {\n      var backView = (view && getViewById(view.backViewId)) || viewHistory.backView;\n      return backView && backView.title;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#forwardView\n     * @description Returns the view that was in front of the current view in the history stack.\n     * A forward view would exist if the user navigated from View A to View B, then\n     * navigated back to View A. At this point then View B would be the forward view, and View\n     * A would be the current view.\n     * @returns {object} Returns the forward view.\n     */\n    forwardView: function(view) {\n      if (arguments.length) {\n        viewHistory.forwardView = view;\n      }\n      return viewHistory.forwardView;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentStateName\n     * @description Returns the current state name.\n     * @returns {string}\n     */\n    currentStateName: function() {\n      return ($state && $state.current ? $state.current.name : null);\n    },\n\n    isCurrentStateNavView: function(navView) {\n      return !!($state && $state.current && $state.current.views && $state.current.views[navView]);\n    },\n\n    goToHistoryRoot: function(historyId) {\n      if (historyId) {\n        var hist = getHistoryById(historyId);\n        if (hist && hist.stack.length) {\n          if (viewHistory.currentView && viewHistory.currentView.viewId === hist.stack[0].viewId) {\n            return;\n          }\n          forcedNav = {\n            viewId: hist.stack[0].viewId,\n            action: ACTION_MOVE_BACK,\n            direction: DIRECTION_BACK\n          };\n          hist.stack[0].go();\n        }\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#goBack\n     * @param {number=} backCount Optional negative integer setting how many views to go\n     * back. By default it'll go back one view by using the value `-1`. To go back two\n     * views you would use `-2`. If the number goes farther back than the number of views\n     * in the current history's stack then it'll go to the first view in the current history's\n     * stack. If the number is zero or greater then it'll do nothing. It also does not\n     * cross history stacks, meaning it can only go as far back as the current history.\n     * @description Navigates the app to the back view, if a back view exists.\n     */\n    goBack: function(backCount) {\n      if (isDefined(backCount) && backCount !== -1) {\n        if (backCount > -1) return;\n\n        var currentHistory = viewHistory.histories[this.currentHistoryId()];\n        var newCursor = currentHistory.cursor + backCount + 1;\n        if (newCursor < 1) {\n          newCursor = 1;\n        }\n\n        currentHistory.cursor = newCursor;\n        setNavViews(currentHistory.stack[newCursor].viewId);\n\n        var cursor = newCursor - 1;\n        var clearStateIds = [];\n        var fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);\n        while (fwdView) {\n          clearStateIds.push(fwdView.stateId || fwdView.viewId);\n          cursor++;\n          if (cursor >= currentHistory.stack.length) break;\n          fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);\n        }\n\n        var self = this;\n        if (clearStateIds.length) {\n          $timeout(function() {\n            self.clearCache(clearStateIds);\n          }, 600);\n        }\n      }\n\n      viewHistory.backView && viewHistory.backView.go();\n    },\n\n\n    enabledBack: function(view) {\n      var backView = getBackView(view);\n      return !!(backView && backView.historyId === view.historyId);\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#clearHistory\n     * @description Clears out the app's entire history, except for the current view.\n     */\n    clearHistory: function() {\n      var\n      histories = viewHistory.histories,\n      currentView = viewHistory.currentView;\n\n      if (histories) {\n        for (var historyId in histories) {\n\n          if (histories[historyId].stack) {\n            histories[historyId].stack = [];\n            histories[historyId].cursor = -1;\n          }\n\n          if (currentView && currentView.historyId === historyId) {\n            currentView.backViewId = currentView.forwardViewId = null;\n            histories[historyId].stack.push(currentView);\n          } else if (histories[historyId].destroy) {\n            histories[historyId].destroy();\n          }\n\n        }\n      }\n\n      for (var viewId in viewHistory.views) {\n        if (viewId !== currentView.viewId) {\n          delete viewHistory.views[viewId];\n        }\n      }\n\n      if (currentView) {\n        setNavViews(currentView.viewId);\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#clearCache\n     * @description Removes all cached views within every {@link ionic.directive:ionNavView}.\n     * This both removes the view element from the DOM, and destroy it's scope.\n     */\n    clearCache: function(stateIds) {\n      $timeout(function() {\n        $ionicNavViewDelegate._instances.forEach(function(instance) {\n          instance.clearCache(stateIds);\n        });\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#nextViewOptions\n     * @description Sets options for the next view. This method can be useful to override\n     * certain view/transition defaults right before a view transition happens. For example,\n     * the {@link ionic.directive:menuClose} directive uses this method internally to ensure\n     * an animated view transition does not happen when a side menu is open, and also sets\n     * the next view as the root of its history stack. After the transition these options\n     * are set back to null.\n     *\n     * Available options:\n     *\n     * * `disableAnimate`: Do not animate the next transition.\n     * * `disableBack`: The next view should forget its back view, and set it to null.\n     * * `historyRoot`: The next view should become the root view in its history stack.\n     *\n     * ```js\n     * $ionicHistory.nextViewOptions({\n     *   disableAnimate: true,\n     *   disableBack: true\n     * });\n     * ```\n     */\n    nextViewOptions: function(opts) {\n      if (arguments.length) {\n        $timeout.cancel(nextViewExpireTimer);\n        if (opts === null) {\n          nextViewOptions = opts;\n        } else {\n          nextViewOptions = nextViewOptions || {};\n          extend(nextViewOptions, opts);\n          if (nextViewOptions.expire) {\n            nextViewExpireTimer = $timeout(function() {\n              nextViewOptions = null;\n            }, nextViewOptions.expire);\n          }\n        }\n      }\n      return nextViewOptions;\n    },\n\n    isAbstractEle: function(ele, viewLocals) {\n      if (viewLocals && viewLocals.$$state && viewLocals.$$state.self['abstract']) {\n        return true;\n      }\n      return !!(ele && (isAbstractTag(ele) || isAbstractTag(ele.children())));\n    },\n\n    isActiveScope: function(scope) {\n      if (!scope) return false;\n\n      var climbScope = scope;\n      var currentHistoryId = this.currentHistoryId();\n      var foundHistoryId;\n\n      while (climbScope) {\n        if (climbScope.$$disconnected) {\n          return false;\n        }\n\n        if (!foundHistoryId && climbScope.hasOwnProperty('$historyId')) {\n          foundHistoryId = true;\n        }\n\n        if (currentHistoryId) {\n          if (climbScope.hasOwnProperty('$historyId') && currentHistoryId == climbScope.$historyId) {\n            return true;\n          }\n          if (climbScope.hasOwnProperty('$activeHistoryId')) {\n            if (currentHistoryId == climbScope.$activeHistoryId) {\n              if (climbScope.hasOwnProperty('$historyId')) {\n                return true;\n              }\n              if (!foundHistoryId) {\n                return true;\n              }\n            }\n          }\n        }\n\n        if (foundHistoryId && climbScope.hasOwnProperty('$activeHistoryId')) {\n          foundHistoryId = false;\n        }\n\n        climbScope = climbScope.$parent;\n      }\n\n      return currentHistoryId ? currentHistoryId == 'root' : true;\n    }\n\n  };\n\n  function isAbstractTag(ele) {\n    return ele && ele.length && /ion-side-menus|ion-tabs/i.test(ele[0].tagName);\n  }\n\n  function canSwipeBack(ele, viewLocals) {\n    if (viewLocals && viewLocals.$$state && viewLocals.$$state.self.canSwipeBack === false) {\n      return false;\n    }\n    if (ele && ele.attr('can-swipe-back') === 'false') {\n      return false;\n    }\n    return true;\n  }\n\n}])\n\n.run([\n  '$rootScope',\n  '$state',\n  '$location',\n  '$document',\n  '$ionicPlatform',\n  '$ionicHistory',\n  'IONIC_BACK_PRIORITY',\nfunction($rootScope, $state, $location, $document, $ionicPlatform, $ionicHistory, IONIC_BACK_PRIORITY) {\n\n  // always reset the keyboard state when change stage\n  $rootScope.$on('$ionicView.beforeEnter', function() {\n    ionic.keyboard && ionic.keyboard.hide && ionic.keyboard.hide();\n  });\n\n  $rootScope.$on('$ionicHistory.change', function(e, data) {\n    if (!data) return null;\n\n    var viewHistory = $ionicHistory.viewHistory();\n\n    var hist = (data.historyId ? viewHistory.histories[ data.historyId ] : null);\n    if (hist && hist.cursor > -1 && hist.cursor < hist.stack.length) {\n      // the history they're going to already exists\n      // go to it's last view in its stack\n      var view = hist.stack[ hist.cursor ];\n      return view.go(data);\n    }\n\n    // this history does not have a URL, but it does have a uiSref\n    // figure out its URL from the uiSref\n    if (!data.url && data.uiSref) {\n      data.url = $state.href(data.uiSref);\n    }\n\n    if (data.url) {\n      // don't let it start with a #, messes with $location.url()\n      if (data.url.indexOf('#') === 0) {\n        data.url = data.url.replace('#', '');\n      }\n      if (data.url !== $location.url()) {\n        // we've got a good URL, ready GO!\n        $location.url(data.url);\n      }\n    }\n  });\n\n  $rootScope.$ionicGoBack = function(backCount) {\n    $ionicHistory.goBack(backCount);\n  };\n\n  // Set the document title when a new view is shown\n  $rootScope.$on('$ionicView.afterEnter', function(ev, data) {\n    if (data && data.title) {\n      $document[0].title = data.title;\n    }\n  });\n\n  // Triggered when devices with a hardware back button (Android) is clicked by the user\n  // This is a Cordova/Phonegap platform specifc method\n  function onHardwareBackButton(e) {\n    var backView = $ionicHistory.backView();\n    if (backView) {\n      // there is a back view, go to it\n      backView.go();\n    } else {\n      // there is no back view, so close the app instead\n      ionic.Platform.exitApp();\n    }\n    e.preventDefault();\n    return false;\n  }\n  $ionicPlatform.registerBackButtonAction(\n    onHardwareBackButton,\n    IONIC_BACK_PRIORITY.view\n  );\n\n}]);\n\n/**\n * @ngdoc provider\n * @name $ionicConfigProvider\n * @module ionic\n * @description\n * Ionic automatically takes platform configurations into account to adjust things like what\n * transition style to use and whether tab icons should show on the top or bottom. For example,\n * iOS will move forward by transitioning the entering view from right to center and the leaving\n * view from center to left. However, Android will transition with the entering view going from\n * bottom to center, covering the previous view, which remains stationary. It should be noted\n * that when a platform is not iOS or Android, then it'll default to iOS. So if you are\n * developing on a desktop browser, it's going to take on iOS default configs.\n *\n * These configs can be changed using the `$ionicConfigProvider` during the configuration phase\n * of your app. Additionally, `$ionicConfig` can also set and get config values during the run\n * phase and within the app itself.\n *\n * By default, all base config variables are set to `'platform'`, which means it'll take on the\n * default config of the platform on which it's running. Config variables can be set at this\n * level so all platforms follow the same setting, rather than its platform config.\n * The following code would set the same config variable for all platforms:\n *\n * ```js\n * $ionicConfigProvider.views.maxCache(10);\n * ```\n *\n * Additionally, each platform can have it's own config within the `$ionicConfigProvider.platform`\n * property. The config below would only apply to Android devices.\n *\n * ```js\n * $ionicConfigProvider.platform.android.views.maxCache(5);\n * ```\n *\n * @usage\n * ```js\n * var myApp = angular.module('reallyCoolApp', ['ionic']);\n *\n * myApp.config(function($ionicConfigProvider) {\n *   $ionicConfigProvider.views.maxCache(5);\n *\n *   // note that you can also chain configs\n *   $ionicConfigProvider.backButton.text('Go Back').icon('ion-chevron-left');\n * });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#views.transition\n * @description Animation style when transitioning between views. Default `platform`.\n *\n * @param {string} transition Which style of view transitioning to use.\n *\n * * `platform`: Dynamically choose the correct transition style depending on the platform\n * the app is running from. If the platform is not `ios` or `android` then it will default\n * to `ios`.\n * * `ios`: iOS style transition.\n * * `android`: Android style transition.\n * * `none`: Do not perform animated transitions.\n *\n * @returns {string} value\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#views.maxCache\n * @description  Maximum number of view elements to cache in the DOM. When the max number is\n * exceeded, the view with the longest time period since it was accessed is removed. Views that\n * stay in the DOM cache the view's scope, current state, and scroll position. The scope is\n * disconnected from the `$watch` cycle when it is cached and reconnected when it enters again.\n * When the maximum cache is `0`, the leaving view's element will be removed from the DOM after\n * each view transition, and the next time the same view is shown, it will have to re-compile,\n * attach to the DOM, and link the element again. This disables caching, in effect.\n * @param {number} maxNumber Maximum number of views to retain. Default `10`.\n * @returns {number} How many views Ionic will hold onto until the a view is removed.\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#views.forwardCache\n * @description  By default, when navigating, views that were recently visited are cached, and\n * the same instance data and DOM elements are referenced when navigating back. However, when\n * navigating back in the history, the \"forward\" views are removed from the cache. If you\n * navigate forward to the same view again, it'll create a new DOM element and controller\n * instance. Basically, any forward views are reset each time. Set this config to `true` to have\n * forward views cached and not reset on each load.\n * @param {boolean} value\n * @returns {boolean}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#scrolling.jsScrolling\n * @description  Whether to use JS or Native scrolling. Defaults to JS scrolling. Setting this to\n * `false` has the same effect as setting each `ion-content` to have `overflow-scroll='true'`.\n * @param {boolean} value Defaults to `true`\n * @returns {boolean}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#backButton.icon\n * @description Back button icon.\n * @param {string} value\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#backButton.text\n * @description Back button text.\n * @param {string} value Defaults to `Back`.\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#backButton.previousTitleText\n * @description If the previous title text should become the back button text. This\n * is the default for iOS.\n * @param {boolean} value\n * @returns {boolean}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#form.checkbox\n * @description Checkbox style. Android defaults to `square` and iOS defaults to `circle`.\n * @param {string} value\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#form.toggle\n * @description Toggle item style. Android defaults to `small` and iOS defaults to `large`.\n * @param {string} value\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#tabs.style\n * @description Tab style. Android defaults to `striped` and iOS defaults to `standard`.\n * @param {string} value Available values include `striped` and `standard`.\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#tabs.position\n * @description Tab position. Android defaults to `top` and iOS defaults to `bottom`.\n * @param {string} value Available values include `top` and `bottom`.\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#templates.maxPrefetch\n * @description Sets the maximum number of templates to prefetch from the templateUrls defined in\n * $stateProvider.state. If set to `0`, the user will have to wait\n * for a template to be fetched the first time when navigating to a new page. Default `30`.\n * @param {integer} value Max number of template to prefetch from the templateUrls defined in\n * `$stateProvider.state()`.\n * @returns {integer}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#navBar.alignTitle\n * @description Which side of the navBar to align the title. Default `center`.\n *\n * @param {string} value side of the navBar to align the title.\n *\n * * `platform`: Dynamically choose the correct title style depending on the platform\n * the app is running from. If the platform is `ios`, it will default to `center`.\n * If the platform is `android`, it will default to `left`. If the platform is not\n * `ios` or `android`, it will default to `center`.\n *\n * * `left`: Left align the title in the navBar\n * * `center`: Center align the title in the navBar\n * * `right`: Right align the title in the navBar.\n *\n * @returns {string} value\n */\n\n/**\n  * @ngdoc method\n  * @name $ionicConfigProvider#navBar.positionPrimaryButtons\n  * @description Which side of the navBar to align the primary navBar buttons. Default `left`.\n  *\n  * @param {string} value side of the navBar to align the primary navBar buttons.\n  *\n  * * `platform`: Dynamically choose the correct title style depending on the platform\n  * the app is running from. If the platform is `ios`, it will default to `left`.\n  * If the platform is `android`, it will default to `right`. If the platform is not\n  * `ios` or `android`, it will default to `left`.\n  *\n  * * `left`: Left align the primary navBar buttons in the navBar\n  * * `right`: Right align the primary navBar buttons in the navBar.\n  *\n  * @returns {string} value\n  */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#navBar.positionSecondaryButtons\n * @description Which side of the navBar to align the secondary navBar buttons. Default `right`.\n *\n * @param {string} value side of the navBar to align the secondary navBar buttons.\n *\n * * `platform`: Dynamically choose the correct title style depending on the platform\n * the app is running from. If the platform is `ios`, it will default to `right`.\n * If the platform is `android`, it will default to `right`. If the platform is not\n * `ios` or `android`, it will default to `right`.\n *\n * * `left`: Left align the secondary navBar buttons in the navBar\n * * `right`: Right align the secondary navBar buttons in the navBar.\n *\n * @returns {string} value\n */\n\nIonicModule\n.provider('$ionicConfig', function() {\n\n  var provider = this;\n  provider.platform = {};\n  var PLATFORM = 'platform';\n\n  var configProperties = {\n    views: {\n      maxCache: PLATFORM,\n      forwardCache: PLATFORM,\n      transition: PLATFORM,\n      swipeBackEnabled: PLATFORM,\n      swipeBackHitWidth: PLATFORM\n    },\n    navBar: {\n      alignTitle: PLATFORM,\n      positionPrimaryButtons: PLATFORM,\n      positionSecondaryButtons: PLATFORM,\n      transition: PLATFORM\n    },\n    backButton: {\n      icon: PLATFORM,\n      text: PLATFORM,\n      previousTitleText: PLATFORM\n    },\n    form: {\n      checkbox: PLATFORM,\n      toggle: PLATFORM\n    },\n    scrolling: {\n      jsScrolling: PLATFORM\n    },\n    tabs: {\n      style: PLATFORM,\n      position: PLATFORM\n    },\n    templates: {\n      maxPrefetch: PLATFORM\n    },\n    platform: {}\n  };\n  createConfig(configProperties, provider, '');\n\n\n\n  // Default\n  // -------------------------\n  setPlatformConfig('default', {\n\n    views: {\n      maxCache: 10,\n      forwardCache: false,\n      transition: 'ios',\n      swipeBackEnabled: true,\n      swipeBackHitWidth: 45\n    },\n\n    navBar: {\n      alignTitle: 'center',\n      positionPrimaryButtons: 'left',\n      positionSecondaryButtons: 'right',\n      transition: 'view'\n    },\n\n    backButton: {\n      icon: 'ion-ios-arrow-back',\n      text: 'Back',\n      previousTitleText: true\n    },\n\n    form: {\n      checkbox: 'circle',\n      toggle: 'large'\n    },\n\n    scrolling: {\n      jsScrolling: true\n    },\n\n    tabs: {\n      style: 'standard',\n      position: 'bottom'\n    },\n\n    templates: {\n      maxPrefetch: 30\n    }\n\n  });\n\n\n\n  // iOS (it is the default already)\n  // -------------------------\n  setPlatformConfig('ios', {});\n\n\n\n  // Android\n  // -------------------------\n  setPlatformConfig('android', {\n\n    views: {\n      transition: 'android',\n      swipeBackEnabled: false\n    },\n\n    navBar: {\n      alignTitle: 'left',\n      positionPrimaryButtons: 'right',\n      positionSecondaryButtons: 'right'\n    },\n\n    backButton: {\n      icon: 'ion-android-arrow-back',\n      text: false,\n      previousTitleText: false\n    },\n\n    form: {\n      checkbox: 'square',\n      toggle: 'small'\n    },\n\n    tabs: {\n      style: 'striped',\n      position: 'top'\n    }\n\n  });\n\n  // Windows Phone\n  // -------------------------\n  setPlatformConfig('windowsphone', {\n    //scrolling: {\n    //  jsScrolling: false\n    //}\n  });\n\n\n  provider.transitions = {\n    views: {},\n    navBar: {}\n  };\n\n\n  // iOS Transitions\n  // -----------------------\n  provider.transitions.views.ios = function(enteringEle, leavingEle, direction, shouldAnimate) {\n\n    function setStyles(ele, opacity, x, boxShadowOpacity) {\n      var css = {};\n      css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;\n      css.opacity = opacity;\n      if (boxShadowOpacity > -1) {\n        css.boxShadow = '0 0 10px rgba(0,0,0,' + (d.shouldAnimate ? boxShadowOpacity * 0.45 : 0.3) + ')';\n      }\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';\n      ionic.DomUtil.cachedStyles(ele, css);\n    }\n\n    var d = {\n      run: function(step) {\n        if (direction == 'forward') {\n          setStyles(enteringEle, 1, (1 - step) * 99, 1 - step); // starting at 98% prevents a flicker\n          setStyles(leavingEle, (1 - 0.1 * step), step * -33, -1);\n\n        } else if (direction == 'back') {\n          setStyles(enteringEle, (1 - 0.1 * (1 - step)), (1 - step) * -33, -1);\n          setStyles(leavingEle, 1, step * 100, 1 - step);\n\n        } else {\n          // swap, enter, exit\n          setStyles(enteringEle, 1, 0, -1);\n          setStyles(leavingEle, 0, 0, -1);\n        }\n      },\n      shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')\n    };\n\n    return d;\n  };\n\n  provider.transitions.navBar.ios = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {\n\n    function setStyles(ctrl, opacity, titleX, backTextX) {\n      var css = {};\n      css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : '0ms';\n      css.opacity = opacity === 1 ? '' : opacity;\n\n      ctrl.setCss('buttons-left', css);\n      ctrl.setCss('buttons-right', css);\n      ctrl.setCss('back-button', css);\n\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + backTextX + 'px,0,0)';\n      ctrl.setCss('back-text', css);\n\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + titleX + 'px,0,0)';\n      ctrl.setCss('title', css);\n    }\n\n    function enter(ctrlA, ctrlB, step) {\n      if (!ctrlA || !ctrlB) return;\n      var titleX = (ctrlA.titleTextX() + ctrlA.titleWidth()) * (1 - step);\n      var backTextX = (ctrlB && (ctrlB.titleTextX() - ctrlA.backButtonTextLeft()) * (1 - step)) || 0;\n      setStyles(ctrlA, step, titleX, backTextX);\n    }\n\n    function leave(ctrlA, ctrlB, step) {\n      if (!ctrlA || !ctrlB) return;\n      var titleX = (-(ctrlA.titleTextX() - ctrlB.backButtonTextLeft()) - (ctrlA.titleLeftRight())) * step;\n      setStyles(ctrlA, 1 - step, titleX, 0);\n    }\n\n    var d = {\n      run: function(step) {\n        var enteringHeaderCtrl = enteringHeaderBar.controller();\n        var leavingHeaderCtrl = leavingHeaderBar && leavingHeaderBar.controller();\n        if (d.direction == 'back') {\n          leave(enteringHeaderCtrl, leavingHeaderCtrl, 1 - step);\n          enter(leavingHeaderCtrl, enteringHeaderCtrl, 1 - step);\n        } else {\n          enter(enteringHeaderCtrl, leavingHeaderCtrl, step);\n          leave(leavingHeaderCtrl, enteringHeaderCtrl, step);\n        }\n      },\n      direction: direction,\n      shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')\n    };\n\n    return d;\n  };\n\n\n  // Android Transitions\n  // -----------------------\n\n  provider.transitions.views.android = function(enteringEle, leavingEle, direction, shouldAnimate) {\n    shouldAnimate = shouldAnimate && (direction == 'forward' || direction == 'back');\n\n    function setStyles(ele, x) {\n      var css = {};\n      css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';\n      ionic.DomUtil.cachedStyles(ele, css);\n    }\n\n    var d = {\n      run: function(step) {\n        if (direction == 'forward') {\n          setStyles(enteringEle, (1 - step) * 99); // starting at 98% prevents a flicker\n          setStyles(leavingEle, step * -100);\n\n        } else if (direction == 'back') {\n          setStyles(enteringEle, (1 - step) * -100);\n          setStyles(leavingEle, step * 100);\n\n        } else {\n          // swap, enter, exit\n          setStyles(enteringEle, 0);\n          setStyles(leavingEle, 0);\n        }\n      },\n      shouldAnimate: shouldAnimate\n    };\n\n    return d;\n  };\n\n  provider.transitions.navBar.android = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {\n\n    function setStyles(ctrl, opacity) {\n      if (!ctrl) return;\n      var css = {};\n      css.opacity = opacity === 1 ? '' : opacity;\n\n      ctrl.setCss('buttons-left', css);\n      ctrl.setCss('buttons-right', css);\n      ctrl.setCss('back-button', css);\n      ctrl.setCss('back-text', css);\n      ctrl.setCss('title', css);\n    }\n\n    return {\n      run: function(step) {\n        setStyles(enteringHeaderBar.controller(), step);\n        setStyles(leavingHeaderBar && leavingHeaderBar.controller(), 1 - step);\n      },\n      shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')\n    };\n  };\n\n\n  // No Transition\n  // -----------------------\n\n  provider.transitions.views.none = function(enteringEle, leavingEle) {\n    return {\n      run: function(step) {\n        provider.transitions.views.android(enteringEle, leavingEle, false, false).run(step);\n      },\n      shouldAnimate: false\n    };\n  };\n\n  provider.transitions.navBar.none = function(enteringHeaderBar, leavingHeaderBar) {\n    return {\n      run: function(step) {\n        provider.transitions.navBar.ios(enteringHeaderBar, leavingHeaderBar, false, false).run(step);\n        provider.transitions.navBar.android(enteringHeaderBar, leavingHeaderBar, false, false).run(step);\n      },\n      shouldAnimate: false\n    };\n  };\n\n\n  // private: used to set platform configs\n  function setPlatformConfig(platformName, platformConfigs) {\n    configProperties.platform[platformName] = platformConfigs;\n    provider.platform[platformName] = {};\n\n    addConfig(configProperties, configProperties.platform[platformName]);\n\n    createConfig(configProperties.platform[platformName], provider.platform[platformName], '');\n  }\n\n\n  // private: used to recursively add new platform configs\n  function addConfig(configObj, platformObj) {\n    for (var n in configObj) {\n      if (n != PLATFORM && configObj.hasOwnProperty(n)) {\n        if (angular.isObject(configObj[n])) {\n          if (!isDefined(platformObj[n])) {\n            platformObj[n] = {};\n          }\n          addConfig(configObj[n], platformObj[n]);\n\n        } else if (!isDefined(platformObj[n])) {\n          platformObj[n] = null;\n        }\n      }\n    }\n  }\n\n\n  // private: create methods for each config to get/set\n  function createConfig(configObj, providerObj, platformPath) {\n    forEach(configObj, function(value, namespace) {\n\n      if (angular.isObject(configObj[namespace])) {\n        // recursively drill down the config object so we can create a method for each one\n        providerObj[namespace] = {};\n        createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);\n\n      } else {\n        // create a method for the provider/config methods that will be exposed\n        providerObj[namespace] = function(newValue) {\n          if (arguments.length) {\n            configObj[namespace] = newValue;\n            return providerObj;\n          }\n          if (configObj[namespace] == PLATFORM) {\n            // if the config is set to 'platform', then get this config's platform value\n            var platformConfig = stringObj(configProperties.platform, ionic.Platform.platform() + platformPath + '.' + namespace);\n            if (platformConfig || platformConfig === false) {\n              return platformConfig;\n            }\n            // didnt find a specific platform config, now try the default\n            return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);\n          }\n          return configObj[namespace];\n        };\n      }\n\n    });\n  }\n\n  function stringObj(obj, str) {\n    str = str.split(\".\");\n    for (var i = 0; i < str.length; i++) {\n      if (obj && isDefined(obj[str[i]])) {\n        obj = obj[str[i]];\n      } else {\n        return null;\n      }\n    }\n    return obj;\n  }\n\n  provider.setPlatformConfig = setPlatformConfig;\n\n\n  // private: Service definition for internal Ionic use\n  /**\n   * @ngdoc service\n   * @name $ionicConfig\n   * @module ionic\n   * @private\n   */\n  provider.$get = function() {\n    return provider;\n  };\n})\n// Fix for URLs in Cordova apps on Windows Phone\n// http://blogs.msdn.com/b/msdn_answers/archive/2015/02/10/\n// running-cordova-apps-on-windows-and-windows-phone-8-1-using-ionic-angularjs-and-other-frameworks.aspx\n.config(['$compileProvider', function($compileProvider) {\n  $compileProvider.aHrefSanitizationWhitelist(/^\\s*(https?|tel|ftp|mailto|file|ghttps?|ms-appx|x-wmapp0):/);\n  $compileProvider.imgSrcSanitizationWhitelist(/^\\s*(https?|tel|ftp|file|blob|ms-appx|x-wmapp0):|data:image\\//);\n}]);\n\n\nvar LOADING_TPL =\n  '<div class=\"loading-container\">' +\n    '<div class=\"loading\">' +\n    '</div>' +\n  '</div>';\n\nvar LOADING_HIDE_DEPRECATED = '$ionicLoading instance.hide() has been deprecated. Use $ionicLoading.hide().';\nvar LOADING_SHOW_DEPRECATED = '$ionicLoading instance.show() has been deprecated. Use $ionicLoading.show().';\nvar LOADING_SET_DEPRECATED = '$ionicLoading instance.setContent() has been deprecated. Use $ionicLoading.show({ template: \\'my content\\' }).';\n\n/**\n * @ngdoc service\n * @name $ionicLoading\n * @module ionic\n * @description\n * An overlay that can be used to indicate activity while blocking user\n * interaction.\n *\n * @usage\n * ```js\n * angular.module('LoadingApp', ['ionic'])\n * .controller('LoadingCtrl', function($scope, $ionicLoading) {\n *   $scope.show = function() {\n *     $ionicLoading.show({\n *       template: 'Loading...'\n *     });\n *   };\n *   $scope.hide = function(){\n *     $ionicLoading.hide();\n *   };\n * });\n * ```\n */\n/**\n * @ngdoc object\n * @name $ionicLoadingConfig\n * @module ionic\n * @description\n * Set the default options to be passed to the {@link ionic.service:$ionicLoading} service.\n *\n * @usage\n * ```js\n * var app = angular.module('myApp', ['ionic'])\n * app.constant('$ionicLoadingConfig', {\n *   template: 'Default Loading Template...'\n * });\n * app.controller('AppCtrl', function($scope, $ionicLoading) {\n *   $scope.showLoading = function() {\n *     $ionicLoading.show(); //options default to values in $ionicLoadingConfig\n *   };\n * });\n * ```\n */\nIonicModule\n.constant('$ionicLoadingConfig', {\n  template: '<ion-spinner></ion-spinner>'\n})\n.factory('$ionicLoading', [\n  '$ionicLoadingConfig',\n  '$ionicBody',\n  '$ionicTemplateLoader',\n  '$ionicBackdrop',\n  '$timeout',\n  '$q',\n  '$log',\n  '$compile',\n  '$ionicPlatform',\n  '$rootScope',\n  'IONIC_BACK_PRIORITY',\nfunction($ionicLoadingConfig, $ionicBody, $ionicTemplateLoader, $ionicBackdrop, $timeout, $q, $log, $compile, $ionicPlatform, $rootScope, IONIC_BACK_PRIORITY) {\n\n  var loaderInstance;\n  //default values\n  var deregisterBackAction = noop;\n  var deregisterStateListener1 = noop;\n  var deregisterStateListener2 = noop;\n  var loadingShowDelay = $q.when();\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicLoading#show\n     * @description Shows a loading indicator. If the indicator is already shown,\n     * it will set the options given and keep the indicator shown.\n     * @param {object} opts The options for the loading indicator. Available properties:\n     *  - `{string=}` `template` The html content of the indicator.\n     *  - `{string=}` `templateUrl` The url of an html template to load as the content of the indicator.\n     *  - `{object=}` `scope` The scope to be a child of. Default: creates a child of $rootScope.\n     *  - `{boolean=}` `noBackdrop` Whether to hide the backdrop. By default it will be shown.\n     *  - `{boolean=}` `hideOnStateChange` Whether to hide the loading spinner when navigating\n     *    to a new state. Default false.\n     *  - `{number=}` `delay` How many milliseconds to delay showing the indicator. By default there is no delay.\n     *  - `{number=}` `duration` How many milliseconds to wait until automatically\n     *  hiding the indicator. By default, the indicator will be shown until `.hide()` is called.\n     */\n    show: showLoader,\n    /**\n     * @ngdoc method\n     * @name $ionicLoading#hide\n     * @description Hides the loading indicator, if shown.\n     */\n    hide: hideLoader,\n    /**\n     * @private for testing\n     */\n    _getLoader: getLoader\n  };\n\n  function getLoader() {\n    if (!loaderInstance) {\n      loaderInstance = $ionicTemplateLoader.compile({\n        template: LOADING_TPL,\n        appendTo: $ionicBody.get()\n      })\n      .then(function(self) {\n        self.show = function(options) {\n          var templatePromise = options.templateUrl ?\n            $ionicTemplateLoader.load(options.templateUrl) :\n            //options.content: deprecated\n            $q.when(options.template || options.content || '');\n\n          self.scope = options.scope || self.scope;\n\n          if (!self.isShown) {\n            //options.showBackdrop: deprecated\n            self.hasBackdrop = !options.noBackdrop && options.showBackdrop !== false;\n            if (self.hasBackdrop) {\n              $ionicBackdrop.retain();\n              $ionicBackdrop.getElement().addClass('backdrop-loading');\n            }\n          }\n\n          if (options.duration) {\n            $timeout.cancel(self.durationTimeout);\n            self.durationTimeout = $timeout(\n              angular.bind(self, self.hide),\n              +options.duration\n            );\n          }\n\n          deregisterBackAction();\n          //Disable hardware back button while loading\n          deregisterBackAction = $ionicPlatform.registerBackButtonAction(\n            noop,\n            IONIC_BACK_PRIORITY.loading\n          );\n\n          templatePromise.then(function(html) {\n            if (html) {\n              var loading = self.element.children();\n              loading.html(html);\n              $compile(loading.contents())(self.scope);\n            }\n\n            //Don't show until template changes\n            if (self.isShown) {\n              self.element.addClass('visible');\n              ionic.requestAnimationFrame(function() {\n                if (self.isShown) {\n                  self.element.addClass('active');\n                  $ionicBody.addClass('loading-active');\n                }\n              });\n            }\n          });\n\n          self.isShown = true;\n        };\n        self.hide = function() {\n\n          deregisterBackAction();\n          if (self.isShown) {\n            if (self.hasBackdrop) {\n              $ionicBackdrop.release();\n              $ionicBackdrop.getElement().removeClass('backdrop-loading');\n            }\n            self.element.removeClass('active');\n            $ionicBody.removeClass('loading-active');\n            setTimeout(function() {\n              !self.isShown && self.element.removeClass('visible');\n            }, 200);\n          }\n          $timeout.cancel(self.durationTimeout);\n          self.isShown = false;\n        };\n\n        return self;\n      });\n    }\n    return loaderInstance;\n  }\n\n  function showLoader(options) {\n    options = extend({}, $ionicLoadingConfig || {}, options || {});\n    var delay = options.delay || options.showDelay || 0;\n\n    deregisterStateListener1();\n    deregisterStateListener2();\n    if (options.hideOnStateChange) {\n      deregisterStateListener1 = $rootScope.$on('$stateChangeSuccess', hideLoader);\n      deregisterStateListener2 = $rootScope.$on('$stateChangeError', hideLoader);\n    }\n\n    //If loading.show() was called previously, cancel it and show with our new options\n    $timeout.cancel(loadingShowDelay);\n    loadingShowDelay = $timeout(noop, delay);\n    loadingShowDelay.then(getLoader).then(function(loader) {\n      return loader.show(options);\n    });\n\n    return {\n      hide: function deprecatedHide() {\n        $log.error(LOADING_HIDE_DEPRECATED);\n        return hideLoader.apply(this, arguments);\n      },\n      show: function deprecatedShow() {\n        $log.error(LOADING_SHOW_DEPRECATED);\n        return showLoader.apply(this, arguments);\n      },\n      setContent: function deprecatedSetContent(content) {\n        $log.error(LOADING_SET_DEPRECATED);\n        return getLoader().then(function(loader) {\n          loader.show({ template: content });\n        });\n      }\n    };\n  }\n\n  function hideLoader() {\n    deregisterStateListener1();\n    deregisterStateListener2();\n    $timeout.cancel(loadingShowDelay);\n    getLoader().then(function(loader) {\n      loader.hide();\n    });\n  }\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicModal\n * @module ionic\n * @description\n *\n * Related: {@link ionic.controller:ionicModal ionicModal controller}.\n *\n * The Modal is a content pane that can go over the user's main view\n * temporarily.  Usually used for making a choice or editing an item.\n *\n * Put the content of the modal inside of an `<ion-modal-view>` element.\n *\n * **Notes:**\n * - A modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating\n * scope, passing in itself as an event argument. Both the modal.removed and modal.hidden events are\n * called when the modal is removed.\n *\n * - This example assumes your modal is in your main index file or another template file. If it is in its own\n * template file, remove the script tags and call it by file name.\n *\n * @usage\n * ```html\n * <script id=\"my-modal.html\" type=\"text/ng-template\">\n *   <ion-modal-view>\n *     <ion-header-bar>\n *       <h1 class=\"title\">My Modal title</h1>\n *     </ion-header-bar>\n *     <ion-content>\n *       Hello!\n *     </ion-content>\n *   </ion-modal-view>\n * </script>\n * ```\n * ```js\n * angular.module('testApp', ['ionic'])\n * .controller('MyController', function($scope, $ionicModal) {\n *   $ionicModal.fromTemplateUrl('my-modal.html', {\n *     scope: $scope,\n *     animation: 'slide-in-up'\n *   }).then(function(modal) {\n *     $scope.modal = modal;\n *   });\n *   $scope.openModal = function() {\n *     $scope.modal.show();\n *   };\n *   $scope.closeModal = function() {\n *     $scope.modal.hide();\n *   };\n *   //Cleanup the modal when we're done with it!\n *   $scope.$on('$destroy', function() {\n *     $scope.modal.remove();\n *   });\n *   // Execute action on hide modal\n *   $scope.$on('modal.hidden', function() {\n *     // Execute action\n *   });\n *   // Execute action on remove modal\n *   $scope.$on('modal.removed', function() {\n *     // Execute action\n *   });\n * });\n * ```\n */\nIonicModule\n.factory('$ionicModal', [\n  '$rootScope',\n  '$ionicBody',\n  '$compile',\n  '$timeout',\n  '$ionicPlatform',\n  '$ionicTemplateLoader',\n  '$$q',\n  '$log',\n  '$ionicClickBlock',\n  '$window',\n  'IONIC_BACK_PRIORITY',\nfunction($rootScope, $ionicBody, $compile, $timeout, $ionicPlatform, $ionicTemplateLoader, $$q, $log, $ionicClickBlock, $window, IONIC_BACK_PRIORITY) {\n\n  /**\n   * @ngdoc controller\n   * @name ionicModal\n   * @module ionic\n   * @description\n   * Instantiated by the {@link ionic.service:$ionicModal} service.\n   *\n   * Be sure to call [remove()](#remove) when you are done with each modal\n   * to clean it up and avoid memory leaks.\n   *\n   * Note: a modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating\n   * scope, passing in itself as an event argument. Note: both modal.removed and modal.hidden are\n   * called when the modal is removed.\n   */\n  var ModalView = ionic.views.Modal.inherit({\n    /**\n     * @ngdoc method\n     * @name ionicModal#initialize\n     * @description Creates a new modal controller instance.\n     * @param {object} options An options object with the following properties:\n     *  - `{object=}` `scope` The scope to be a child of.\n     *    Default: creates a child of $rootScope.\n     *  - `{string=}` `animation` The animation to show & hide with.\n     *    Default: 'slide-in-up'\n     *  - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of\n     *    the modal when shown. Will only show the keyboard on iOS, to force the keyboard to show\n     *    on Android, please use the [Ionic keyboard plugin](https://github.com/driftyco/ionic-plugin-keyboard#keyboardshow).\n     *    Default: false.\n     *  - `{boolean=}` `backdropClickToClose` Whether to close the modal on clicking the backdrop.\n     *    Default: true.\n     *  - `{boolean=}` `hardwareBackButtonClose` Whether the modal can be closed using the hardware\n     *    back button on Android and similar devices.  Default: true.\n     */\n    initialize: function(opts) {\n      ionic.views.Modal.prototype.initialize.call(this, opts);\n      this.animation = opts.animation || 'slide-in-up';\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#show\n     * @description Show this modal instance.\n     * @returns {promise} A promise which is resolved when the modal is finished animating in.\n     */\n    show: function(target) {\n      var self = this;\n\n      if (self.scope.$$destroyed) {\n        $log.error('Cannot call ' + self.viewType + '.show() after remove(). Please create a new ' + self.viewType + ' instance.');\n        return $$q.when();\n      }\n\n      // on iOS, clicks will sometimes bleed through/ghost click on underlying\n      // elements\n      $ionicClickBlock.show(600);\n\n      var modalEl = jqLite(self.modalEl);\n\n      self.el.classList.remove('hide');\n      $timeout(function() {\n        if (!self._isShown) return;\n        $ionicBody.addClass(self.viewType + '-open');\n      }, 400, false);\n\n      if (!self.el.parentElement) {\n        modalEl.addClass(self.animation);\n        $ionicBody.append(self.el);\n      }\n\n      // if modal was closed while the keyboard was up, reset scroll view on\n      // next show since we can only resize it once it's visible\n      var scrollCtrl = modalEl.data('$$ionicScrollController');\n      scrollCtrl && scrollCtrl.resize();\n\n      if (target && self.positionView) {\n        self.positionView(target, modalEl);\n        // set up a listener for in case the window size changes\n\n        self._onWindowResize = function() {\n          if (self._isShown) self.positionView(target, modalEl);\n        };\n        ionic.on('resize', self._onWindowResize, window);\n      }\n\n      modalEl.addClass('ng-enter active')\n             .removeClass('ng-leave ng-leave-active');\n\n      self._isShown = true;\n      self._deregisterBackButton = $ionicPlatform.registerBackButtonAction(\n        self.hardwareBackButtonClose ? angular.bind(self, self.hide) : noop,\n        IONIC_BACK_PRIORITY.modal\n      );\n\n      ionic.views.Modal.prototype.show.call(self);\n\n      $timeout(function() {\n        if (!self._isShown) return;\n        modalEl.addClass('ng-enter-active');\n        ionic.trigger('resize');\n        self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.shown', self);\n        self.el.classList.add('active');\n        self.scope.$broadcast('$ionicHeader.align');\n      }, 20);\n\n      return $timeout(function() {\n        if (!self._isShown) return;\n        //After animating in, allow hide on backdrop click\n        self.$el.on('click', function(e) {\n          if (self.backdropClickToClose && e.target === self.el) {\n            self.hide();\n          }\n        });\n      }, 400);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#hide\n     * @description Hide this modal instance.\n     * @returns {promise} A promise which is resolved when the modal is finished animating out.\n     */\n    hide: function() {\n      var self = this;\n      var modalEl = jqLite(self.modalEl);\n\n      // on iOS, clicks will sometimes bleed through/ghost click on underlying\n      // elements\n      $ionicClickBlock.show(600);\n\n      self.el.classList.remove('active');\n      modalEl.addClass('ng-leave');\n\n      $timeout(function() {\n        if (self._isShown) return;\n        modalEl.addClass('ng-leave-active')\n               .removeClass('ng-enter ng-enter-active active');\n      }, 20, false);\n\n      self.$el.off('click');\n      self._isShown = false;\n      self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.hidden', self);\n      self._deregisterBackButton && self._deregisterBackButton();\n\n      ionic.views.Modal.prototype.hide.call(self);\n\n      // clean up event listeners\n      if (self.positionView) {\n        ionic.off('resize', self._onWindowResize, window);\n      }\n\n      return $timeout(function() {\n        $ionicBody.removeClass(self.viewType + '-open');\n        self.el.classList.add('hide');\n      }, self.hideDelay || 320);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#remove\n     * @description Remove this modal instance from the DOM and clean up.\n     * @returns {promise} A promise which is resolved when the modal is finished animating out.\n     */\n    remove: function() {\n      var self = this;\n      self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.removed', self);\n\n      return self.hide().then(function() {\n        self.scope.$destroy();\n        self.$el.remove();\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#isShown\n     * @returns boolean Whether this modal is currently shown.\n     */\n    isShown: function() {\n      return !!this._isShown;\n    }\n  });\n\n  var createModal = function(templateString, options) {\n    // Create a new scope for the modal\n    var scope = options.scope && options.scope.$new() || $rootScope.$new(true);\n\n    options.viewType = options.viewType || 'modal';\n\n    extend(scope, {\n      $hasHeader: false,\n      $hasSubheader: false,\n      $hasFooter: false,\n      $hasSubfooter: false,\n      $hasTabs: false,\n      $hasTabsTop: false\n    });\n\n    // Compile the template\n    var element = $compile('<ion-' + options.viewType + '>' + templateString + '</ion-' + options.viewType + '>')(scope);\n\n    options.$el = element;\n    options.el = element[0];\n    options.modalEl = options.el.querySelector('.' + options.viewType);\n    var modal = new ModalView(options);\n\n    modal.scope = scope;\n\n    // If this wasn't a defined scope, we can assign the viewType to the isolated scope\n    // we created\n    if (!options.scope) {\n      scope[ options.viewType ] = modal;\n    }\n\n    return modal;\n  };\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicModal#fromTemplate\n     * @param {string} templateString The template string to use as the modal's\n     * content.\n     * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.\n     * @returns {object} An instance of an {@link ionic.controller:ionicModal}\n     * controller.\n     */\n    fromTemplate: function(templateString, options) {\n      var modal = createModal(templateString, options || {});\n      return modal;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicModal#fromTemplateUrl\n     * @param {string} templateUrl The url to load the template from.\n     * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.\n     * options object.\n     * @returns {promise} A promise that will be resolved with an instance of\n     * an {@link ionic.controller:ionicModal} controller.\n     */\n    fromTemplateUrl: function(url, options, _) {\n      var cb;\n      //Deprecated: allow a callback as second parameter. Now we return a promise.\n      if (angular.isFunction(options)) {\n        cb = options;\n        options = _;\n      }\n      return $ionicTemplateLoader.load(url).then(function(templateString) {\n        var modal = createModal(templateString, options || {});\n        cb && cb(modal);\n        return modal;\n      });\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc service\n * @name $ionicNavBarDelegate\n * @module ionic\n * @description\n * Delegate for controlling the {@link ionic.directive:ionNavBar} directive.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MyCtrl\">\n *   <ion-nav-bar>\n *     <button ng-click=\"setNavTitle('banana')\">\n *       Set title to banana!\n *     </button>\n *   </ion-nav-bar>\n * </body>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicNavBarDelegate) {\n *   $scope.setNavTitle = function(title) {\n *     $ionicNavBarDelegate.title(title);\n *   }\n * }\n * ```\n */\nIonicModule\n.service('$ionicNavBarDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#align\n   * @description Aligns the title with the buttons in a given direction.\n   * @param {string=} direction The direction to the align the title text towards.\n   * Available: 'left', 'right', 'center'. Default: 'center'.\n   */\n  'align',\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#showBackButton\n   * @description\n   * Set/get whether the {@link ionic.directive:ionNavBackButton} is shown\n   * (if it exists and there is a previous view that can be navigated to).\n   * @param {boolean=} show Whether to show the back button.\n   * @returns {boolean} Whether the back button is shown.\n   */\n  'showBackButton',\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#showBar\n   * @description\n   * Set/get whether the {@link ionic.directive:ionNavBar} is shown.\n   * @param {boolean} show Whether to show the bar.\n   * @returns {boolean} Whether the bar is shown.\n   */\n  'showBar',\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#title\n   * @description\n   * Set the title for the {@link ionic.directive:ionNavBar}.\n   * @param {string} title The new title to show.\n   */\n  'title',\n\n  // DEPRECATED, as of v1.0.0-beta14 -------\n  'changeTitle',\n  'setTitle',\n  'getTitle',\n  'back',\n  'getPreviousTitle'\n  // END DEPRECATED -------\n]));\n\n\nIonicModule\n.service('$ionicNavViewDelegate', ionic.DelegateService([\n  'clearCache'\n]));\n\n\n\n/**\n * @ngdoc service\n * @name $ionicPlatform\n * @module ionic\n * @description\n * An angular abstraction of {@link ionic.utility:ionic.Platform}.\n *\n * Used to detect the current platform, as well as do things like override the\n * Android back button in PhoneGap/Cordova.\n */\nIonicModule\n.constant('IONIC_BACK_PRIORITY', {\n  view: 100,\n  sideMenu: 150,\n  modal: 200,\n  actionSheet: 300,\n  popup: 400,\n  loading: 500\n})\n.provider('$ionicPlatform', function() {\n  return {\n    $get: ['$q', function($q) {\n      var self = {\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#onHardwareBackButton\n         * @description\n         * Some platforms have a hardware back button, so this is one way to\n         * bind to it.\n         * @param {function} callback the callback to trigger when this event occurs\n         */\n        onHardwareBackButton: function(cb) {\n          ionic.Platform.ready(function() {\n            document.addEventListener('backbutton', cb, false);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#offHardwareBackButton\n         * @description\n         * Remove an event listener for the backbutton.\n         * @param {function} callback The listener function that was\n         * originally bound.\n         */\n        offHardwareBackButton: function(fn) {\n          ionic.Platform.ready(function() {\n            document.removeEventListener('backbutton', fn);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#registerBackButtonAction\n         * @description\n         * Register a hardware back button action. Only one action will execute\n         * when the back button is clicked, so this method decides which of\n         * the registered back button actions has the highest priority.\n         *\n         * For example, if an actionsheet is showing, the back button should\n         * close the actionsheet, but it should not also go back a page view\n         * or close a modal which may be open.\n         *\n         * The priorities for the existing back button hooks are as follows:\n         *   Return to previous view = 100\n         *   Close side menu = 150\n         *   Dismiss modal = 200\n         *   Close action sheet = 300\n         *   Dismiss popup = 400\n         *   Dismiss loading overlay = 500\n         *\n         * Your back button action will override each of the above actions\n         * whose priority is less than the priority you provide. For example,\n         * an action assigned a priority of 101 will override the 'return to\n         * previous view' action, but not any of the other actions.\n         *\n         * @param {function} callback Called when the back button is pressed,\n         * if this listener is the highest priority.\n         * @param {number} priority Only the highest priority will execute.\n         * @param {*=} actionId The id to assign this action. Default: a\n         * random unique id.\n         * @returns {function} A function that, when called, will deregister\n         * this backButtonAction.\n         */\n        $backButtonActions: {},\n        registerBackButtonAction: function(fn, priority, actionId) {\n\n          if (!self._hasBackButtonHandler) {\n            // add a back button listener if one hasn't been setup yet\n            self.$backButtonActions = {};\n            self.onHardwareBackButton(self.hardwareBackButtonClick);\n            self._hasBackButtonHandler = true;\n          }\n\n          var action = {\n            id: (actionId ? actionId : ionic.Utils.nextUid()),\n            priority: (priority ? priority : 0),\n            fn: fn\n          };\n          self.$backButtonActions[action.id] = action;\n\n          // return a function to de-register this back button action\n          return function() {\n            delete self.$backButtonActions[action.id];\n          };\n        },\n\n        /**\n         * @private\n         */\n        hardwareBackButtonClick: function(e) {\n          // loop through all the registered back button actions\n          // and only run the last one of the highest priority\n          var priorityAction, actionId;\n          for (actionId in self.$backButtonActions) {\n            if (!priorityAction || self.$backButtonActions[actionId].priority >= priorityAction.priority) {\n              priorityAction = self.$backButtonActions[actionId];\n            }\n          }\n          if (priorityAction) {\n            priorityAction.fn(e);\n            return priorityAction;\n          }\n        },\n\n        is: function(type) {\n          return ionic.Platform.is(type);\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#on\n         * @description\n         * Add Cordova event listeners, such as `pause`, `resume`, `volumedownbutton`, `batterylow`,\n         * `offline`, etc. More information about available event types can be found in\n         * [Cordova's event documentation](https://cordova.apache.org/docs/en/edge/cordova_events_events.md.html#Events).\n         * @param {string} type Cordova [event type](https://cordova.apache.org/docs/en/edge/cordova_events_events.md.html#Events).\n         * @param {function} callback Called when the Cordova event is fired.\n         * @returns {function} Returns a deregistration function to remove the event listener.\n         */\n        on: function(type, cb) {\n          ionic.Platform.ready(function() {\n            document.addEventListener(type, cb, false);\n          });\n          return function() {\n            ionic.Platform.ready(function() {\n              document.removeEventListener(type, cb);\n            });\n          };\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#ready\n         * @description\n         * Trigger a callback once the device is ready,\n         * or immediately if the device is already ready.\n         * @param {function=} callback The function to call.\n         * @returns {promise} A promise which is resolved when the device is ready.\n         */\n        ready: function(cb) {\n          var q = $q.defer();\n\n          ionic.Platform.ready(function() {\n            q.resolve();\n            cb && cb();\n          });\n\n          return q.promise;\n        }\n      };\n      return self;\n    }]\n  };\n\n});\n\n/**\n * @ngdoc service\n * @name $ionicPopover\n * @module ionic\n * @description\n *\n * Related: {@link ionic.controller:ionicPopover ionicPopover controller}.\n *\n * The Popover is a view that floats above an app’s content. Popovers provide an\n * easy way to present or gather information from the user and are\n * commonly used in the following situations:\n *\n * - Show more info about the current view\n * - Select a commonly used tool or configuration\n * - Present a list of actions to perform inside one of your views\n *\n * Put the content of the popover inside of an `<ion-popover-view>` element.\n *\n * @usage\n * ```html\n * <p>\n *   <button ng-click=\"openPopover($event)\">Open Popover</button>\n * </p>\n *\n * <script id=\"my-popover.html\" type=\"text/ng-template\">\n *   <ion-popover-view>\n *     <ion-header-bar>\n *       <h1 class=\"title\">My Popover Title</h1>\n *     </ion-header-bar>\n *     <ion-content>\n *       Hello!\n *     </ion-content>\n *   </ion-popover-view>\n * </script>\n * ```\n * ```js\n * angular.module('testApp', ['ionic'])\n * .controller('MyController', function($scope, $ionicPopover) {\n *\n *   // .fromTemplate() method\n *   var template = '<ion-popover-view><ion-header-bar> <h1 class=\"title\">My Popover Title</h1> </ion-header-bar> <ion-content> Hello! </ion-content></ion-popover-view>';\n *\n *   $scope.popover = $ionicPopover.fromTemplate(template, {\n *     scope: $scope\n *   });\n *\n *   // .fromTemplateUrl() method\n *   $ionicPopover.fromTemplateUrl('my-popover.html', {\n *     scope: $scope\n *   }).then(function(popover) {\n *     $scope.popover = popover;\n *   });\n *\n *\n *   $scope.openPopover = function($event) {\n *     $scope.popover.show($event);\n *   };\n *   $scope.closePopover = function() {\n *     $scope.popover.hide();\n *   };\n *   //Cleanup the popover when we're done with it!\n *   $scope.$on('$destroy', function() {\n *     $scope.popover.remove();\n *   });\n *   // Execute action on hide popover\n *   $scope.$on('popover.hidden', function() {\n *     // Execute action\n *   });\n *   // Execute action on remove popover\n *   $scope.$on('popover.removed', function() {\n *     // Execute action\n *   });\n * });\n * ```\n */\n\n\nIonicModule\n.factory('$ionicPopover', ['$ionicModal', '$ionicPosition', '$document', '$window',\nfunction($ionicModal, $ionicPosition, $document, $window) {\n\n  var POPOVER_BODY_PADDING = 6;\n\n  var POPOVER_OPTIONS = {\n    viewType: 'popover',\n    hideDelay: 1,\n    animation: 'none',\n    positionView: positionView\n  };\n\n  function positionView(target, popoverEle) {\n    var targetEle = jqLite(target.target || target);\n    var buttonOffset = $ionicPosition.offset(targetEle);\n    var popoverWidth = popoverEle.prop('offsetWidth');\n    var popoverHeight = popoverEle.prop('offsetHeight');\n    // Use innerWidth and innerHeight, because clientWidth and clientHeight\n    // doesn't work consistently for body on all platforms\n    var bodyWidth = $window.innerWidth;\n    var bodyHeight = $window.innerHeight;\n\n    var popoverCSS = {\n      left: buttonOffset.left + buttonOffset.width / 2 - popoverWidth / 2\n    };\n    var arrowEle = jqLite(popoverEle[0].querySelector('.popover-arrow'));\n\n    if (popoverCSS.left < POPOVER_BODY_PADDING) {\n      popoverCSS.left = POPOVER_BODY_PADDING;\n    } else if (popoverCSS.left + popoverWidth + POPOVER_BODY_PADDING > bodyWidth) {\n      popoverCSS.left = bodyWidth - popoverWidth - POPOVER_BODY_PADDING;\n    }\n\n    // If the popover when popped down stretches past bottom of screen,\n    // make it pop up if there's room above\n    if (buttonOffset.top + buttonOffset.height + popoverHeight > bodyHeight &&\n        buttonOffset.top - popoverHeight > 0) {\n      popoverCSS.top = buttonOffset.top - popoverHeight;\n      popoverEle.addClass('popover-bottom');\n    } else {\n      popoverCSS.top = buttonOffset.top + buttonOffset.height;\n      popoverEle.removeClass('popover-bottom');\n    }\n\n    arrowEle.css({\n      left: buttonOffset.left + buttonOffset.width / 2 -\n        arrowEle.prop('offsetWidth') / 2 - popoverCSS.left + 'px'\n    });\n\n    popoverEle.css({\n      top: popoverCSS.top + 'px',\n      left: popoverCSS.left + 'px',\n      marginLeft: '0',\n      opacity: '1'\n    });\n\n  }\n\n  /**\n   * @ngdoc controller\n   * @name ionicPopover\n   * @module ionic\n   * @description\n   * Instantiated by the {@link ionic.service:$ionicPopover} service.\n   *\n   * Be sure to call [remove()](#remove) when you are done with each popover\n   * to clean it up and avoid memory leaks.\n   *\n   * Note: a popover will broadcast 'popover.shown', 'popover.hidden', and 'popover.removed' events from its originating\n   * scope, passing in itself as an event argument. Both the popover.removed and popover.hidden events are\n   * called when the popover is removed.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#initialize\n   * @description Creates a new popover controller instance.\n   * @param {object} options An options object with the following properties:\n   *  - `{object=}` `scope` The scope to be a child of.\n   *    Default: creates a child of $rootScope.\n   *  - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of\n   *    the popover when shown.  Default: false.\n   *  - `{boolean=}` `backdropClickToClose` Whether to close the popover on clicking the backdrop.\n   *    Default: true.\n   *  - `{boolean=}` `hardwareBackButtonClose` Whether the popover can be closed using the hardware\n   *    back button on Android and similar devices.  Default: true.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#show\n   * @description Show this popover instance.\n   * @param {$event} $event The $event or target element which the popover should align\n   * itself next to.\n   * @returns {promise} A promise which is resolved when the popover is finished animating in.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#hide\n   * @description Hide this popover instance.\n   * @returns {promise} A promise which is resolved when the popover is finished animating out.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#remove\n   * @description Remove this popover instance from the DOM and clean up.\n   * @returns {promise} A promise which is resolved when the popover is finished animating out.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#isShown\n   * @returns boolean Whether this popover is currently shown.\n   */\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicPopover#fromTemplate\n     * @param {string} templateString The template string to use as the popovers's\n     * content.\n     * @param {object} options Options to be passed to the initialize method.\n     * @returns {object} An instance of an {@link ionic.controller:ionicPopover}\n     * controller (ionicPopover is built on top of $ionicPopover).\n     */\n    fromTemplate: function(templateString, options) {\n      return $ionicModal.fromTemplate(templateString, ionic.Utils.extend(POPOVER_OPTIONS, options || {}));\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicPopover#fromTemplateUrl\n     * @param {string} templateUrl The url to load the template from.\n     * @param {object} options Options to be passed to the initialize method.\n     * @returns {promise} A promise that will be resolved with an instance of\n     * an {@link ionic.controller:ionicPopover} controller (ionicPopover is built on top of $ionicPopover).\n     */\n    fromTemplateUrl: function(url, options) {\n      return $ionicModal.fromTemplateUrl(url, ionic.Utils.extend(POPOVER_OPTIONS, options || {}));\n    }\n  };\n\n}]);\n\n\nvar POPUP_TPL =\n  '<div class=\"popup-container\" ng-class=\"cssClass\">' +\n    '<div class=\"popup\">' +\n      '<div class=\"popup-head\">' +\n        '<h3 class=\"popup-title\" ng-bind-html=\"title\"></h3>' +\n        '<h5 class=\"popup-sub-title\" ng-bind-html=\"subTitle\" ng-if=\"subTitle\"></h5>' +\n      '</div>' +\n      '<div class=\"popup-body\">' +\n      '</div>' +\n      '<div class=\"popup-buttons\" ng-show=\"buttons.length\">' +\n        '<button ng-repeat=\"button in buttons\" ng-click=\"$buttonTapped(button, $event)\" class=\"button\" ng-class=\"button.type || \\'button-default\\'\" ng-bind-html=\"button.text\"></button>' +\n      '</div>' +\n    '</div>' +\n  '</div>';\n\n/**\n * @ngdoc service\n * @name $ionicPopup\n * @module ionic\n * @restrict E\n * @codepen zkmhJ\n * @description\n *\n * The Ionic Popup service allows programmatically creating and showing popup\n * windows that require the user to respond in order to continue.\n *\n * The popup system has support for more flexible versions of the built in `alert()`, `prompt()`,\n * and `confirm()` functions that users are used to, in addition to allowing popups with completely\n * custom content and look.\n *\n * An input can be given an `autofocus` attribute so it automatically receives focus when\n * the popup first shows. However, depending on certain use-cases this can cause issues with\n * the tap/click system, which is why Ionic prefers using the `autofocus` attribute as\n * an opt-in feature and not the default.\n *\n * @usage\n * A few basic examples, see below for details about all of the options available.\n *\n * ```js\n *angular.module('mySuperApp', ['ionic'])\n *.controller('PopupCtrl',function($scope, $ionicPopup, $timeout) {\n *\n * // Triggered on a button click, or some other target\n * $scope.showPopup = function() {\n *   $scope.data = {}\n *\n *   // An elaborate, custom popup\n *   var myPopup = $ionicPopup.show({\n *     template: '<input type=\"password\" ng-model=\"data.wifi\">',\n *     title: 'Enter Wi-Fi Password',\n *     subTitle: 'Please use normal things',\n *     scope: $scope,\n *     buttons: [\n *       { text: 'Cancel' },\n *       {\n *         text: '<b>Save</b>',\n *         type: 'button-positive',\n *         onTap: function(e) {\n *           if (!$scope.data.wifi) {\n *             //don't allow the user to close unless he enters wifi password\n *             e.preventDefault();\n *           } else {\n *             return $scope.data.wifi;\n *           }\n *         }\n *       }\n *     ]\n *   });\n *   myPopup.then(function(res) {\n *     console.log('Tapped!', res);\n *   });\n *   $timeout(function() {\n *      myPopup.close(); //close the popup after 3 seconds for some reason\n *   }, 3000);\n *  };\n *  // A confirm dialog\n *  $scope.showConfirm = function() {\n *    var confirmPopup = $ionicPopup.confirm({\n *      title: 'Consume Ice Cream',\n *      template: 'Are you sure you want to eat this ice cream?'\n *    });\n *    confirmPopup.then(function(res) {\n *      if(res) {\n *        console.log('You are sure');\n *      } else {\n *        console.log('You are not sure');\n *      }\n *    });\n *  };\n *\n *  // An alert dialog\n *  $scope.showAlert = function() {\n *    var alertPopup = $ionicPopup.alert({\n *      title: 'Don\\'t eat that!',\n *      template: 'It might taste good'\n *    });\n *    alertPopup.then(function(res) {\n *      console.log('Thank you for not eating my delicious ice cream cone');\n *    });\n *  };\n *});\n *```\n */\n\nIonicModule\n.factory('$ionicPopup', [\n  '$ionicTemplateLoader',\n  '$ionicBackdrop',\n  '$q',\n  '$timeout',\n  '$rootScope',\n  '$ionicBody',\n  '$compile',\n  '$ionicPlatform',\n  'IONIC_BACK_PRIORITY',\nfunction($ionicTemplateLoader, $ionicBackdrop, $q, $timeout, $rootScope, $ionicBody, $compile, $ionicPlatform, IONIC_BACK_PRIORITY) {\n  //TODO allow this to be configured\n  var config = {\n    stackPushDelay: 75\n  };\n  var popupStack = [];\n\n  var $ionicPopup = {\n    /**\n     * @ngdoc method\n     * @description\n     * Show a complex popup. This is the master show function for all popups.\n     *\n     * A complex popup has a `buttons` array, with each button having a `text` and `type`\n     * field, in addition to an `onTap` function.  The `onTap` function, called when\n     * the corresponding button on the popup is tapped, will by default close the popup\n     * and resolve the popup promise with its return value.  If you wish to prevent the\n     * default and keep the popup open on button tap, call `event.preventDefault()` on the\n     * passed in tap event.  Details below.\n     *\n     * @name $ionicPopup#show\n     * @param {object} options The options for the new popup, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   scope: null, // Scope (optional). A scope to link to the popup content.\n     *   buttons: [{ // Array[Object] (optional). Buttons to place in the popup footer.\n     *     text: 'Cancel',\n     *     type: 'button-default',\n     *     onTap: function(e) {\n     *       // e.preventDefault() will stop the popup from closing when tapped.\n     *       e.preventDefault();\n     *     }\n     *   }, {\n     *     text: 'OK',\n     *     type: 'button-positive',\n     *     onTap: function(e) {\n     *       // Returning a value will cause the promise to resolve with the given value.\n     *       return scope.data.response;\n     *     }\n     *   }]\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has an additional\n     * `close` function, which can be used to programmatically close the popup.\n     */\n    show: showPopup,\n\n    /**\n     * @ngdoc method\n     * @name $ionicPopup#alert\n     * @description Show a simple alert popup with a message and one button that the user can\n     * tap to close the popup.\n     *\n     * @param {object} options The options for showing the alert, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   okText: '', // String (default: 'OK'). The text of the OK button.\n     *   okType: '', // String (default: 'button-positive'). The type of the OK button.\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has one additional\n     * function `close`, which can be called with any value to programmatically close the popup\n     * with the given value.\n     */\n    alert: showAlert,\n\n    /**\n     * @ngdoc method\n     * @name $ionicPopup#confirm\n     * @description\n     * Show a simple confirm popup with a Cancel and OK button.\n     *\n     * Resolves the promise with true if the user presses the OK button, and false if the\n     * user presses the Cancel button.\n     *\n     * @param {object} options The options for showing the confirm popup, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   cancelText: '', // String (default: 'Cancel'). The text of the Cancel button.\n     *   cancelType: '', // String (default: 'button-default'). The type of the Cancel button.\n     *   okText: '', // String (default: 'OK'). The text of the OK button.\n     *   okType: '', // String (default: 'button-positive'). The type of the OK button.\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has one additional\n     * function `close`, which can be called with any value to programmatically close the popup\n     * with the given value.\n     */\n    confirm: showConfirm,\n\n    /**\n     * @ngdoc method\n     * @name $ionicPopup#prompt\n     * @description Show a simple prompt popup, which has an input, OK button, and Cancel button.\n     * Resolves the promise with the value of the input if the user presses OK, and with undefined\n     * if the user presses Cancel.\n     *\n     * ```javascript\n     *  $ionicPopup.prompt({\n     *    title: 'Password Check',\n     *    template: 'Enter your secret password',\n     *    inputType: 'password',\n     *    inputPlaceholder: 'Your password'\n     *  }).then(function(res) {\n     *    console.log('Your password is', res);\n     *  });\n     * ```\n     * @param {object} options The options for showing the prompt popup, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   inputType: // String (default: 'text'). The type of input to use\n     *   inputPlaceholder: // String (default: ''). A placeholder to use for the input.\n     *   cancelText: // String (default: 'Cancel'. The text of the Cancel button.\n     *   cancelType: // String (default: 'button-default'). The type of the Cancel button.\n     *   okText: // String (default: 'OK'). The text of the OK button.\n     *   okType: // String (default: 'button-positive'). The type of the OK button.\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has one additional\n     * function `close`, which can be called with any value to programmatically close the popup\n     * with the given value.\n     */\n    prompt: showPrompt,\n    /**\n     * @private for testing\n     */\n    _createPopup: createPopup,\n    _popupStack: popupStack\n  };\n\n  return $ionicPopup;\n\n  function createPopup(options) {\n    options = extend({\n      scope: null,\n      title: '',\n      buttons: []\n    }, options || {});\n\n    var self = {};\n    self.scope = (options.scope || $rootScope).$new();\n    self.element = jqLite(POPUP_TPL);\n    self.responseDeferred = $q.defer();\n\n    $ionicBody.get().appendChild(self.element[0]);\n    $compile(self.element)(self.scope);\n\n    extend(self.scope, {\n      title: options.title,\n      buttons: options.buttons,\n      subTitle: options.subTitle,\n      cssClass: options.cssClass,\n      $buttonTapped: function(button, event) {\n        var result = (button.onTap || noop)(event);\n        event = event.originalEvent || event; //jquery events\n\n        if (!event.defaultPrevented) {\n          self.responseDeferred.resolve(result);\n        }\n      }\n    });\n\n    $q.when(\n      options.templateUrl ?\n      $ionicTemplateLoader.load(options.templateUrl) :\n        (options.template || options.content || '')\n    ).then(function(template) {\n      var popupBody = jqLite(self.element[0].querySelector('.popup-body'));\n      if (template) {\n        popupBody.html(template);\n        $compile(popupBody.contents())(self.scope);\n      } else {\n        popupBody.remove();\n      }\n    });\n\n    self.show = function() {\n      if (self.isShown || self.removed) return;\n\n      self.isShown = true;\n      ionic.requestAnimationFrame(function() {\n        //if hidden while waiting for raf, don't show\n        if (!self.isShown) return;\n\n        self.element.removeClass('popup-hidden');\n        self.element.addClass('popup-showing active');\n        focusInput(self.element);\n      });\n    };\n\n    self.hide = function(callback) {\n      callback = callback || noop;\n      if (!self.isShown) return callback();\n\n      self.isShown = false;\n      self.element.removeClass('active');\n      self.element.addClass('popup-hidden');\n      $timeout(callback, 250, false);\n    };\n\n    self.remove = function() {\n      if (self.removed) return;\n\n      self.hide(function() {\n        self.element.remove();\n        self.scope.$destroy();\n      });\n\n      self.removed = true;\n    };\n\n    return self;\n  }\n\n  function onHardwareBackButton() {\n    var last = popupStack[popupStack.length - 1];\n    last && last.responseDeferred.resolve();\n  }\n\n  function showPopup(options) {\n    var popup = $ionicPopup._createPopup(options);\n    var showDelay = 0;\n\n    if (popupStack.length > 0) {\n      popupStack[popupStack.length - 1].hide();\n      showDelay = config.stackPushDelay;\n    } else {\n      //Add popup-open & backdrop if this is first popup\n      $ionicBody.addClass('popup-open');\n      $ionicBackdrop.retain();\n      //only show the backdrop on the first popup\n      $ionicPopup._backButtonActionDone = $ionicPlatform.registerBackButtonAction(\n        onHardwareBackButton,\n        IONIC_BACK_PRIORITY.popup\n      );\n    }\n\n    // Expose a 'close' method on the returned promise\n    popup.responseDeferred.promise.close = function popupClose(result) {\n      if (!popup.removed) popup.responseDeferred.resolve(result);\n    };\n    //DEPRECATED: notify the promise with an object with a close method\n    popup.responseDeferred.notify({ close: popup.responseDeferred.close });\n\n    doShow();\n\n    return popup.responseDeferred.promise;\n\n    function doShow() {\n      popupStack.push(popup);\n      $timeout(popup.show, showDelay, false);\n\n      popup.responseDeferred.promise.then(function(result) {\n        var index = popupStack.indexOf(popup);\n        if (index !== -1) {\n          popupStack.splice(index, 1);\n        }\n\n        if (popupStack.length > 0) {\n          popupStack[popupStack.length - 1].show();\n        } else {\n          $ionicBackdrop.release();\n          //Remove popup-open & backdrop if this is last popup\n          $timeout(function() {\n            // wait to remove this due to a 300ms delay native\n            // click which would trigging whatever was underneath this\n            if (!popupStack.length) {\n              $ionicBody.removeClass('popup-open');\n            }\n          }, 400, false);\n          ($ionicPopup._backButtonActionDone || noop)();\n        }\n\n        popup.remove();\n\n        return result;\n      });\n\n    }\n\n  }\n\n  function focusInput(element) {\n    var focusOn = element[0].querySelector('[autofocus]');\n    if (focusOn) {\n      focusOn.focus();\n    }\n  }\n\n  function showAlert(opts) {\n    return showPopup(extend({\n      buttons: [{\n        text: opts.okText || 'OK',\n        type: opts.okType || 'button-positive',\n        onTap: function() {\n          return true;\n        }\n      }]\n    }, opts || {}));\n  }\n\n  function showConfirm(opts) {\n    return showPopup(extend({\n      buttons: [{\n        text: opts.cancelText || 'Cancel',\n        type: opts.cancelType || 'button-default',\n        onTap: function() { return false; }\n      }, {\n        text: opts.okText || 'OK',\n        type: opts.okType || 'button-positive',\n        onTap: function() { return true; }\n      }]\n    }, opts || {}));\n  }\n\n  function showPrompt(opts) {\n    var scope = $rootScope.$new(true);\n    scope.data = {};\n    var text = '';\n    if (opts.template && /<[a-z][\\s\\S]*>/i.test(opts.template) === false) {\n      text = '<span>' + opts.template + '</span>';\n      delete opts.template;\n    }\n    return showPopup(extend({\n      template: text + '<input ng-model=\"data.response\" type=\"' + (opts.inputType || 'text') +\n        '\" placeholder=\"' + (opts.inputPlaceholder || '') + '\">',\n      scope: scope,\n      buttons: [{\n        text: opts.cancelText || 'Cancel',\n        type: opts.cancelType || 'button-default',\n        onTap: function() {}\n      }, {\n        text: opts.okText || 'OK',\n        type: opts.okType || 'button-positive',\n        onTap: function() {\n          return scope.data.response || '';\n        }\n      }]\n    }, opts || {}));\n  }\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicPosition\n * @module ionic\n * @description\n * A set of utility methods that can be use to retrieve position of DOM elements.\n * It is meant to be used where we need to absolute-position DOM elements in\n * relation to other, existing elements (this is the case for tooltips, popovers, etc.).\n *\n * Adapted from [AngularUI Bootstrap](https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js),\n * ([license](https://github.com/angular-ui/bootstrap/blob/master/LICENSE))\n */\nIonicModule\n.factory('$ionicPosition', ['$document', '$window', function($document, $window) {\n\n  function getStyle(el, cssprop) {\n    if (el.currentStyle) { //IE\n      return el.currentStyle[cssprop];\n    } else if ($window.getComputedStyle) {\n      return $window.getComputedStyle(el)[cssprop];\n    }\n    // finally try and get inline style\n    return el.style[cssprop];\n  }\n\n  /**\n   * Checks if a given element is statically positioned\n   * @param element - raw DOM element\n   */\n  function isStaticPositioned(element) {\n    return (getStyle(element, 'position') || 'static') === 'static';\n  }\n\n  /**\n   * returns the closest, non-statically positioned parentOffset of a given element\n   * @param element\n   */\n  var parentOffsetEl = function(element) {\n    var docDomEl = $document[0];\n    var offsetParent = element.offsetParent || docDomEl;\n    while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent)) {\n      offsetParent = offsetParent.offsetParent;\n    }\n    return offsetParent || docDomEl;\n  };\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicPosition#position\n     * @description Get the current coordinates of the element, relative to the offset parent.\n     * Read-only equivalent of [jQuery's position function](http://api.jquery.com/position/).\n     * @param {element} element The element to get the position of.\n     * @returns {object} Returns an object containing the properties top, left, width and height.\n     */\n    position: function(element) {\n      var elBCR = this.offset(element);\n      var offsetParentBCR = { top: 0, left: 0 };\n      var offsetParentEl = parentOffsetEl(element[0]);\n      if (offsetParentEl != $document[0]) {\n        offsetParentBCR = this.offset(jqLite(offsetParentEl));\n        offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;\n        offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;\n      }\n\n      var boundingClientRect = element[0].getBoundingClientRect();\n      return {\n        width: boundingClientRect.width || element.prop('offsetWidth'),\n        height: boundingClientRect.height || element.prop('offsetHeight'),\n        top: elBCR.top - offsetParentBCR.top,\n        left: elBCR.left - offsetParentBCR.left\n      };\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicPosition#offset\n     * @description Get the current coordinates of the element, relative to the document.\n     * Read-only equivalent of [jQuery's offset function](http://api.jquery.com/offset/).\n     * @param {element} element The element to get the offset of.\n     * @returns {object} Returns an object containing the properties top, left, width and height.\n     */\n    offset: function(element) {\n      var boundingClientRect = element[0].getBoundingClientRect();\n      return {\n        width: boundingClientRect.width || element.prop('offsetWidth'),\n        height: boundingClientRect.height || element.prop('offsetHeight'),\n        top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),\n        left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)\n      };\n    }\n\n  };\n}]);\n\n\n/**\n * @ngdoc service\n * @name $ionicScrollDelegate\n * @module ionic\n * @description\n * Delegate for controlling scrollViews (created by\n * {@link ionic.directive:ionContent} and\n * {@link ionic.directive:ionScroll} directives).\n *\n * Methods called directly on the $ionicScrollDelegate service will control all scroll\n * views.  Use the {@link ionic.service:$ionicScrollDelegate#$getByHandle $getByHandle}\n * method to control specific scrollViews.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MainCtrl\">\n *   <ion-content>\n *     <button ng-click=\"scrollTop()\">Scroll to Top!</button>\n *   </ion-content>\n * </body>\n * ```\n * ```js\n * function MainCtrl($scope, $ionicScrollDelegate) {\n *   $scope.scrollTop = function() {\n *     $ionicScrollDelegate.scrollTop();\n *   };\n * }\n * ```\n *\n * Example of advanced usage, with two scroll areas using `delegate-handle`\n * for fine control.\n *\n * ```html\n * <body ng-controller=\"MainCtrl\">\n *   <ion-content delegate-handle=\"mainScroll\">\n *     <button ng-click=\"scrollMainToTop()\">\n *       Scroll content to top!\n *     </button>\n *     <ion-scroll delegate-handle=\"small\" style=\"height: 100px;\">\n *       <button ng-click=\"scrollSmallToTop()\">\n *         Scroll small area to top!\n *       </button>\n *     </ion-scroll>\n *   </ion-content>\n * </body>\n * ```\n * ```js\n * function MainCtrl($scope, $ionicScrollDelegate) {\n *   $scope.scrollMainToTop = function() {\n *     $ionicScrollDelegate.$getByHandle('mainScroll').scrollTop();\n *   };\n *   $scope.scrollSmallToTop = function() {\n *     $ionicScrollDelegate.$getByHandle('small').scrollTop();\n *   };\n * }\n * ```\n */\nIonicModule\n.service('$ionicScrollDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#resize\n   * @description Tell the scrollView to recalculate the size of its container.\n   */\n  'resize',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollTop\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollTop',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollBottom\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollBottom',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollTo\n   * @param {number} left The x-value to scroll to.\n   * @param {number} top The y-value to scroll to.\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollTo',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollBy\n   * @param {number} left The x-offset to scroll by.\n   * @param {number} top The y-offset to scroll by.\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollBy',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#zoomTo\n   * @param {number} level Level to zoom to.\n   * @param {boolean=} animate Whether to animate the zoom.\n   * @param {number=} originLeft Zoom in at given left coordinate.\n   * @param {number=} originTop Zoom in at given top coordinate.\n   */\n  'zoomTo',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#zoomBy\n   * @param {number} factor The factor to zoom by.\n   * @param {boolean=} animate Whether to animate the zoom.\n   * @param {number=} originLeft Zoom in at given left coordinate.\n   * @param {number=} originTop Zoom in at given top coordinate.\n   */\n  'zoomBy',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#getScrollPosition\n   * @returns {object} The scroll position of this view, with the following properties:\n   *  - `{number}` `left` The distance the user has scrolled from the left (starts at 0).\n   *  - `{number}` `top` The distance the user has scrolled from the top (starts at 0).\n   */\n  'getScrollPosition',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#anchorScroll\n   * @description Tell the scrollView to scroll to the element with an id\n   * matching window.location.hash.\n   *\n   * If no matching element is found, it will scroll to top.\n   *\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'anchorScroll',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#freezeScroll\n   * @description Does not allow this scroll view to scroll either x or y.\n   * @param {boolean=} shouldFreeze Should this scroll view be prevented from scrolling or not.\n   * @returns {object} If the scroll view is being prevented from scrolling or not.\n   */\n  'freezeScroll',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#freezeAllScrolls\n   * @description Does not allow any of the app's scroll views to scroll either x or y.\n   * @param {boolean=} shouldFreeze Should all app scrolls be prevented from scrolling or not.\n   */\n  'freezeAllScrolls',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#getScrollView\n   * @returns {object} The scrollView associated with this delegate.\n   */\n  'getScrollView'\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * scrollViews with `delegate-handle` matching the given handle.\n   *\n   * Example: `$ionicScrollDelegate.$getByHandle('my-handle').scrollTop();`\n   */\n]));\n\n\n/**\n * @ngdoc service\n * @name $ionicSideMenuDelegate\n * @module ionic\n *\n * @description\n * Delegate for controlling the {@link ionic.directive:ionSideMenus} directive.\n *\n * Methods called directly on the $ionicSideMenuDelegate service will control all side\n * menus.  Use the {@link ionic.service:$ionicSideMenuDelegate#$getByHandle $getByHandle}\n * method to control specific ionSideMenus instances.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MainCtrl\">\n *   <ion-side-menus>\n *     <ion-side-menu-content>\n *       Content!\n *       <button ng-click=\"toggleLeftSideMenu()\">\n *         Toggle Left Side Menu\n *       </button>\n *     </ion-side-menu-content>\n *     <ion-side-menu side=\"left\">\n *       Left Menu!\n *     <ion-side-menu>\n *   </ion-side-menus>\n * </body>\n * ```\n * ```js\n * function MainCtrl($scope, $ionicSideMenuDelegate) {\n *   $scope.toggleLeftSideMenu = function() {\n *     $ionicSideMenuDelegate.toggleLeft();\n *   };\n * }\n * ```\n */\nIonicModule\n.service('$ionicSideMenuDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#toggleLeft\n   * @description Toggle the left side menu (if it exists).\n   * @param {boolean=} isOpen Whether to open or close the menu.\n   * Default: Toggles the menu.\n   */\n  'toggleLeft',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#toggleRight\n   * @description Toggle the right side menu (if it exists).\n   * @param {boolean=} isOpen Whether to open or close the menu.\n   * Default: Toggles the menu.\n   */\n  'toggleRight',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#getOpenRatio\n   * @description Gets the ratio of open amount over menu width. For example, a\n   * menu of width 100 that is opened by 50 pixels is 50% opened, and would return\n   * a ratio of 0.5.\n   *\n   * @returns {float} 0 if nothing is open, between 0 and 1 if left menu is\n   * opened/opening, and between 0 and -1 if right menu is opened/opening.\n   */\n  'getOpenRatio',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#isOpen\n   * @returns {boolean} Whether either the left or right menu is currently opened.\n   */\n  'isOpen',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#isOpenLeft\n   * @returns {boolean} Whether the left menu is currently opened.\n   */\n  'isOpenLeft',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#isOpenRight\n   * @returns {boolean} Whether the right menu is currently opened.\n   */\n  'isOpenRight',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#canDragContent\n   * @param {boolean=} canDrag Set whether the content can or cannot be dragged to open\n   * side menus.\n   * @returns {boolean} Whether the content can be dragged to open side menus.\n   */\n  'canDragContent',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#edgeDragThreshold\n   * @param {boolean|number=} value Set whether the content drag can only start if it is below a certain threshold distance from the edge of the screen. Accepts three different values:\n   *  - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.\n   *  - If true is given, the default number of pixels (25) is used as the maximum allowed distance.\n   *  - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.\n   * @returns {boolean} Whether the drag can start only from within the edge of screen threshold.\n   */\n  'edgeDragThreshold'\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionSideMenus} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicSideMenuDelegate.$getByHandle('my-handle').toggleLeft();`\n   */\n]));\n\n\n/**\n * @ngdoc service\n * @name $ionicSlideBoxDelegate\n * @module ionic\n * @description\n * Delegate that controls the {@link ionic.directive:ionSlideBox} directive.\n *\n * Methods called directly on the $ionicSlideBoxDelegate service will control all slide boxes.  Use the {@link ionic.service:$ionicSlideBoxDelegate#$getByHandle $getByHandle}\n * method to control specific slide box instances.\n *\n * @usage\n *\n * ```html\n * <ion-view>\n *   <ion-slide-box>\n *     <ion-slide>\n *       <div class=\"box blue\">\n *         <button ng-click=\"nextSlide()\">Next slide!</button>\n *       </div>\n *     </ion-slide>\n *     <ion-slide>\n *       <div class=\"box red\">\n *         Slide 2!\n *       </div>\n *     </ion-slide>\n *   </ion-slide-box>\n * </ion-view>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicSlideBoxDelegate) {\n *   $scope.nextSlide = function() {\n *     $ionicSlideBoxDelegate.next();\n *   }\n * }\n * ```\n */\nIonicModule\n.service('$ionicSlideBoxDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#update\n   * @description\n   * Update the slidebox (for example if using Angular with ng-repeat,\n   * resize it for the elements inside).\n   */\n  'update',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#slide\n   * @param {number} to The index to slide to.\n   * @param {number=} speed The number of milliseconds the change should take.\n   */\n  'slide',\n  'select',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#enableSlide\n   * @param {boolean=} shouldEnable Whether to enable sliding the slidebox.\n   * @returns {boolean} Whether sliding is enabled.\n   */\n  'enableSlide',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#previous\n   * @param {number=} speed The number of milliseconds the change should take.\n   * @description Go to the previous slide. Wraps around if at the beginning.\n   */\n  'previous',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#next\n   * @param {number=} speed The number of milliseconds the change should take.\n   * @description Go to the next slide. Wraps around if at the end.\n   */\n  'next',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#stop\n   * @description Stop sliding. The slideBox will not move again until\n   * explicitly told to do so.\n   */\n  'stop',\n  'autoPlay',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#start\n   * @description Start sliding again if the slideBox was stopped.\n   */\n  'start',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#currentIndex\n   * @returns number The index of the current slide.\n   */\n  'currentIndex',\n  'selected',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#slidesCount\n   * @returns number The number of slides there are currently.\n   */\n  'slidesCount',\n  'count',\n  'loop'\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionSlideBox} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicSlideBoxDelegate.$getByHandle('my-handle').stop();`\n   */\n]));\n\n\n/**\n * @ngdoc service\n * @name $ionicTabsDelegate\n * @module ionic\n *\n * @description\n * Delegate for controlling the {@link ionic.directive:ionTabs} directive.\n *\n * Methods called directly on the $ionicTabsDelegate service will control all ionTabs\n * directives. Use the {@link ionic.service:$ionicTabsDelegate#$getByHandle $getByHandle}\n * method to control specific ionTabs instances.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MyCtrl\">\n *   <ion-tabs>\n *\n *     <ion-tab title=\"Tab 1\">\n *       Hello tab 1!\n *       <button ng-click=\"selectTabWithIndex(1)\">Select tab 2!</button>\n *     </ion-tab>\n *     <ion-tab title=\"Tab 2\">Hello tab 2!</ion-tab>\n *\n *   </ion-tabs>\n * </body>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicTabsDelegate) {\n *   $scope.selectTabWithIndex = function(index) {\n *     $ionicTabsDelegate.select(index);\n *   }\n * }\n * ```\n */\nIonicModule\n.service('$ionicTabsDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicTabsDelegate#select\n   * @description Select the tab matching the given index.\n   *\n   * @param {number} index Index of the tab to select.\n   */\n  'select',\n  /**\n   * @ngdoc method\n   * @name $ionicTabsDelegate#selectedIndex\n   * @returns `number` The index of the selected tab, or -1.\n   */\n  'selectedIndex'\n  /**\n   * @ngdoc method\n   * @name $ionicTabsDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionTabs} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicTabsDelegate.$getByHandle('my-handle').select(0);`\n   */\n]));\n\n\n// closure to keep things neat\n(function() {\n  var templatesToCache = [];\n\n/**\n * @ngdoc service\n * @name $ionicTemplateCache\n * @module ionic\n * @description A service that preemptively caches template files to eliminate transition flicker and boost performance.\n * @usage\n * State templates are cached automatically, but you can optionally cache other templates.\n *\n * ```js\n * $ionicTemplateCache('myNgIncludeTemplate.html');\n * ```\n *\n * Optionally disable all preemptive caching with the `$ionicConfigProvider` or individual states by setting `prefetchTemplate`\n * in the `$state` definition\n *\n * ```js\n *   angular.module('myApp', ['ionic'])\n *   .config(function($stateProvider, $ionicConfigProvider) {\n *\n *     // disable preemptive template caching globally\n *     $ionicConfigProvider.templates.prefetch(false);\n *\n *     // disable individual states\n *     $stateProvider\n *       .state('tabs', {\n *         url: \"/tab\",\n *         abstract: true,\n *         prefetchTemplate: false,\n *         templateUrl: \"tabs-templates/tabs.html\"\n *       })\n *       .state('tabs.home', {\n *         url: \"/home\",\n *         views: {\n *           'home-tab': {\n *             prefetchTemplate: false,\n *             templateUrl: \"tabs-templates/home.html\",\n *             controller: 'HomeTabCtrl'\n *           }\n *         }\n *       });\n *   });\n * ```\n */\nIonicModule\n.factory('$ionicTemplateCache', [\n'$http',\n'$templateCache',\n'$timeout',\nfunction($http, $templateCache, $timeout) {\n  var toCache = templatesToCache,\n      hasRun;\n\n  function $ionicTemplateCache(templates) {\n    if (typeof templates === 'undefined') {\n      return run();\n    }\n    if (isString(templates)) {\n      templates = [templates];\n    }\n    forEach(templates, function(template) {\n      toCache.push(template);\n    });\n    if (hasRun) {\n      run();\n    }\n  }\n\n  // run through methods - internal method\n  function run() {\n    var template;\n    $ionicTemplateCache._runCount++;\n\n    hasRun = true;\n    // ignore if race condition already zeroed out array\n    if (toCache.length === 0) return;\n\n    var i = 0;\n    while (i < 4 && (template = toCache.pop())) {\n      // note that inline templates are ignored by this request\n      if (isString(template)) $http.get(template, { cache: $templateCache });\n      i++;\n    }\n    // only preload 3 templates a second\n    if (toCache.length) {\n      $timeout(run, 1000);\n    }\n  }\n\n  // exposing for testing\n  $ionicTemplateCache._runCount = 0;\n  // default method\n  return $ionicTemplateCache;\n}])\n\n// Intercepts the $stateprovider.state() command to look for templateUrls that can be cached\n.config([\n'$stateProvider',\n'$ionicConfigProvider',\nfunction($stateProvider, $ionicConfigProvider) {\n  var stateProviderState = $stateProvider.state;\n  $stateProvider.state = function(stateName, definition) {\n    // don't even bother if it's disabled. note, another config may run after this, so it's not a catch-all\n    if (typeof definition === 'object') {\n      var enabled = definition.prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();\n      if (enabled && isString(definition.templateUrl)) templatesToCache.push(definition.templateUrl);\n      if (angular.isObject(definition.views)) {\n        for (var key in definition.views) {\n          enabled = definition.views[key].prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();\n          if (enabled && isString(definition.views[key].templateUrl)) templatesToCache.push(definition.views[key].templateUrl);\n        }\n      }\n    }\n    return stateProviderState.call($stateProvider, stateName, definition);\n  };\n}])\n\n// process the templateUrls collected by the $stateProvider, adding them to the cache\n.run(['$ionicTemplateCache', function($ionicTemplateCache) {\n  $ionicTemplateCache();\n}]);\n\n})();\n\nIonicModule\n.factory('$ionicTemplateLoader', [\n  '$compile',\n  '$controller',\n  '$http',\n  '$q',\n  '$rootScope',\n  '$templateCache',\nfunction($compile, $controller, $http, $q, $rootScope, $templateCache) {\n\n  return {\n    load: fetchTemplate,\n    compile: loadAndCompile\n  };\n\n  function fetchTemplate(url) {\n    return $http.get(url, {cache: $templateCache})\n    .then(function(response) {\n      return response.data && response.data.trim();\n    });\n  }\n\n  function loadAndCompile(options) {\n    options = extend({\n      template: '',\n      templateUrl: '',\n      scope: null,\n      controller: null,\n      locals: {},\n      appendTo: null\n    }, options || {});\n\n    var templatePromise = options.templateUrl ?\n      this.load(options.templateUrl) :\n      $q.when(options.template);\n\n    return templatePromise.then(function(template) {\n      var controller;\n      var scope = options.scope || $rootScope.$new();\n\n      //Incase template doesn't have just one root element, do this\n      var element = jqLite('<div>').html(template).contents();\n\n      if (options.controller) {\n        controller = $controller(\n          options.controller,\n          extend(options.locals, {\n            $scope: scope\n          })\n        );\n        element.children().data('$ngControllerController', controller);\n      }\n      if (options.appendTo) {\n        jqLite(options.appendTo).append(element);\n      }\n\n      $compile(element)(scope);\n\n      return {\n        element: element,\n        scope: scope\n      };\n    });\n  }\n\n}]);\n\n/**\n * @private\n * DEPRECATED, as of v1.0.0-beta14 -------\n */\nIonicModule\n.factory('$ionicViewService', ['$ionicHistory', '$log', function($ionicHistory, $log) {\n\n  function warn(oldMethod, newMethod) {\n    $log.warn('$ionicViewService' + oldMethod + ' is deprecated, please use $ionicHistory' + newMethod + ' instead: http://ionicframework.com/docs/nightly/api/service/$ionicHistory/');\n  }\n\n  warn('', '');\n\n  var methodsMap = {\n    getCurrentView: 'currentView',\n    getBackView: 'backView',\n    getForwardView: 'forwardView',\n    getCurrentStateName: 'currentStateName',\n    nextViewOptions: 'nextViewOptions',\n    clearHistory: 'clearHistory'\n  };\n\n  forEach(methodsMap, function(newMethod, oldMethod) {\n    methodsMap[oldMethod] = function() {\n      warn('.' + oldMethod, '.' + newMethod);\n      return $ionicHistory[newMethod].apply(this, arguments);\n    };\n  });\n\n  return methodsMap;\n\n}]);\n\n/**\n * @private\n * TODO document\n */\n\nIonicModule.factory('$ionicViewSwitcher', [\n  '$timeout',\n  '$document',\n  '$q',\n  '$ionicClickBlock',\n  '$ionicConfig',\n  '$ionicNavBarDelegate',\nfunction($timeout, $document, $q, $ionicClickBlock, $ionicConfig, $ionicNavBarDelegate) {\n\n  var TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';\n  var DATA_NO_CACHE = '$noCache';\n  var DATA_DESTROY_ELE = '$destroyEle';\n  var DATA_ELE_IDENTIFIER = '$eleId';\n  var DATA_VIEW_ACCESSED = '$accessed';\n  var DATA_FALLBACK_TIMER = '$fallbackTimer';\n  var DATA_VIEW = '$viewData';\n  var NAV_VIEW_ATTR = 'nav-view';\n  var VIEW_STATUS_ACTIVE = 'active';\n  var VIEW_STATUS_CACHED = 'cached';\n  var VIEW_STATUS_STAGED = 'stage';\n\n  var transitionCounter = 0;\n  var nextTransition, nextDirection;\n  ionic.transition = ionic.transition || {};\n  ionic.transition.isActive = false;\n  var isActiveTimer;\n  var cachedAttr = ionic.DomUtil.cachedAttr;\n  var transitionPromises = [];\n  var defaultTimeout = 1100;\n\n  var ionicViewSwitcher = {\n\n    create: function(navViewCtrl, viewLocals, enteringView, leavingView, renderStart, renderEnd) {\n      // get a reference to an entering/leaving element if they exist\n      // loop through to see if the view is already in the navViewElement\n      var enteringEle, leavingEle;\n      var transitionId = ++transitionCounter;\n      var alreadyInDom;\n\n      var switcher = {\n\n        init: function(registerData, callback) {\n          ionicViewSwitcher.isTransitioning(true);\n\n          switcher.loadViewElements(registerData);\n\n          switcher.render(registerData, function() {\n            callback && callback();\n          });\n        },\n\n        loadViewElements: function(registerData) {\n          var x, l, viewEle;\n          var viewElements = navViewCtrl.getViewElements();\n          var enteringEleIdentifier = getViewElementIdentifier(viewLocals, enteringView);\n          var navViewActiveEleId = navViewCtrl.activeEleId();\n\n          for (x = 0, l = viewElements.length; x < l; x++) {\n            viewEle = viewElements.eq(x);\n\n            if (viewEle.data(DATA_ELE_IDENTIFIER) === enteringEleIdentifier) {\n              // we found an existing element in the DOM that should be entering the view\n              if (viewEle.data(DATA_NO_CACHE)) {\n                // the existing element should not be cached, don't use it\n                viewEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier + ionic.Utils.nextUid());\n                viewEle.data(DATA_DESTROY_ELE, true);\n\n              } else {\n                enteringEle = viewEle;\n              }\n\n            } else if (isDefined(navViewActiveEleId) && viewEle.data(DATA_ELE_IDENTIFIER) === navViewActiveEleId) {\n              leavingEle = viewEle;\n            }\n\n            if (enteringEle && leavingEle) break;\n          }\n\n          alreadyInDom = !!enteringEle;\n\n          if (!alreadyInDom) {\n            // still no existing element to use\n            // create it using existing template/scope/locals\n            enteringEle = registerData.ele || ionicViewSwitcher.createViewEle(viewLocals);\n\n            // existing elements in the DOM are looked up by their state name and state id\n            enteringEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier);\n          }\n\n          if (renderEnd) {\n            navViewCtrl.activeEleId(enteringEleIdentifier);\n          }\n\n          registerData.ele = null;\n        },\n\n        render: function(registerData, callback) {\n          if (alreadyInDom) {\n            // it was already found in the DOM, just reconnect the scope\n            ionic.Utils.reconnectScope(enteringEle.scope());\n\n          } else {\n            // the entering element is not already in the DOM\n            // set that the entering element should be \"staged\" and its\n            // styles of where this element will go before it hits the DOM\n            navViewAttr(enteringEle, VIEW_STATUS_STAGED);\n\n            var enteringData = getTransitionData(viewLocals, enteringEle, registerData.direction, enteringView);\n            var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;\n            transitionFn(enteringEle, null, enteringData.direction, true).run(0);\n\n            enteringEle.data(DATA_VIEW, {\n              viewId: enteringData.viewId,\n              historyId: enteringData.historyId,\n              stateName: enteringData.stateName,\n              stateParams: enteringData.stateParams\n            });\n\n            // if the current state has cache:false\n            // or the element has cache-view=\"false\" attribute\n            if (viewState(viewLocals).cache === false || viewState(viewLocals).cache === 'false' ||\n                enteringEle.attr('cache-view') == 'false' || $ionicConfig.views.maxCache() === 0) {\n              enteringEle.data(DATA_NO_CACHE, true);\n            }\n\n            // append the entering element to the DOM, create a new scope and run link\n            var viewScope = navViewCtrl.appendViewElement(enteringEle, viewLocals);\n\n            delete enteringData.direction;\n            delete enteringData.transition;\n            viewScope.$emit('$ionicView.loaded', enteringData);\n          }\n\n          // update that this view was just accessed\n          enteringEle.data(DATA_VIEW_ACCESSED, Date.now());\n\n          callback && callback();\n        },\n\n        transition: function(direction, enableBack, allowAnimate) {\n          var deferred;\n          var enteringData = getTransitionData(viewLocals, enteringEle, direction, enteringView);\n          var leavingData = extend(extend({}, enteringData), getViewData(leavingView));\n          enteringData.transitionId = leavingData.transitionId = transitionId;\n          enteringData.fromCache = !!alreadyInDom;\n          enteringData.enableBack = !!enableBack;\n          enteringData.renderStart = renderStart;\n          enteringData.renderEnd = renderEnd;\n\n          cachedAttr(enteringEle.parent(), 'nav-view-transition', enteringData.transition);\n          cachedAttr(enteringEle.parent(), 'nav-view-direction', enteringData.direction);\n\n          // cancel any previous transition complete fallbacks\n          $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));\n\n          // get the transition ready and see if it'll animate\n          var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;\n          var viewTransition = transitionFn(enteringEle, leavingEle, enteringData.direction,\n                                            enteringData.shouldAnimate && allowAnimate && renderEnd);\n\n          if (viewTransition.shouldAnimate) {\n            // attach transitionend events (and fallback timer)\n            enteringEle.on(TRANSITIONEND_EVENT, completeOnTransitionEnd);\n            enteringEle.data(DATA_FALLBACK_TIMER, $timeout(transitionComplete, defaultTimeout));\n            $ionicClickBlock.show(defaultTimeout);\n          }\n\n          if (renderStart) {\n            // notify the views \"before\" the transition starts\n            switcher.emit('before', enteringData, leavingData);\n\n            // stage entering element, opacity 0, no transition duration\n            navViewAttr(enteringEle, VIEW_STATUS_STAGED);\n\n            // render the elements in the correct location for their starting point\n            viewTransition.run(0);\n          }\n\n          if (renderEnd) {\n            // create a promise so we can keep track of when all transitions finish\n            // only required if this transition should complete\n            deferred = $q.defer();\n            transitionPromises.push(deferred.promise);\n          }\n\n          if (renderStart && renderEnd) {\n            // CSS \"auto\" transitioned, not manually transitioned\n            // wait a frame so the styles apply before auto transitioning\n            $timeout(onReflow, 16);\n\n          } else if (!renderEnd) {\n            // just the start of a manual transition\n            // but it will not render the end of the transition\n            navViewAttr(enteringEle, 'entering');\n            navViewAttr(leavingEle, 'leaving');\n\n            // return the transition run method so each step can be ran manually\n            return {\n              run: viewTransition.run,\n              cancel: function(shouldAnimate) {\n                if (shouldAnimate) {\n                  enteringEle.on(TRANSITIONEND_EVENT, cancelOnTransitionEnd);\n                  enteringEle.data(DATA_FALLBACK_TIMER, $timeout(cancelTransition, defaultTimeout));\n                  $ionicClickBlock.show(defaultTimeout);\n                } else {\n                  cancelTransition();\n                }\n                viewTransition.shouldAnimate = shouldAnimate;\n                viewTransition.run(0);\n                viewTransition = null;\n              }\n            };\n\n          } else if (renderEnd) {\n            // just the end of a manual transition\n            // happens after the manual transition has completed\n            // and a full history change has happened\n            onReflow();\n          }\n\n\n          function onReflow() {\n            // remove that we're staging the entering element so it can auto transition\n            navViewAttr(enteringEle, viewTransition.shouldAnimate ? 'entering' : VIEW_STATUS_ACTIVE);\n            navViewAttr(leavingEle, viewTransition.shouldAnimate ? 'leaving' : VIEW_STATUS_CACHED);\n\n            // start the auto transition and let the CSS take over\n            viewTransition.run(1);\n\n            // trigger auto transitions on the associated nav bars\n            $ionicNavBarDelegate._instances.forEach(function(instance) {\n              instance.triggerTransitionStart(transitionId);\n            });\n\n            if (!viewTransition.shouldAnimate) {\n              // no animated auto transition\n              transitionComplete();\n            }\n          }\n\n          // Make sure that transitionend events bubbling up from children won't fire\n          // transitionComplete. Will only go forward if ev.target == the element listening.\n          function completeOnTransitionEnd(ev) {\n            if (ev.target !== this) return;\n            transitionComplete();\n          }\n          function transitionComplete() {\n            if (transitionComplete.x) return;\n            transitionComplete.x = true;\n\n            enteringEle.off(TRANSITIONEND_EVENT, completeOnTransitionEnd);\n            $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));\n            leavingEle && $timeout.cancel(leavingEle.data(DATA_FALLBACK_TIMER));\n\n            // emit that the views have finished transitioning\n            // each parent nav-view will update which views are active and cached\n            switcher.emit('after', enteringData, leavingData);\n\n            // resolve that this one transition (there could be many w/ nested views)\n            deferred && deferred.resolve(navViewCtrl);\n\n            // the most recent transition added has completed and all the active\n            // transition promises should be added to the services array of promises\n            if (transitionId === transitionCounter) {\n              $q.all(transitionPromises).then(ionicViewSwitcher.transitionEnd);\n              switcher.cleanup(enteringData);\n            }\n\n            // tell the nav bars that the transition has ended\n            $ionicNavBarDelegate._instances.forEach(function(instance) {\n              instance.triggerTransitionEnd();\n            });\n\n            // remove any references that could cause memory issues\n            nextTransition = nextDirection = enteringView = leavingView = enteringEle = leavingEle = null;\n          }\n\n          // Make sure that transitionend events bubbling up from children won't fire\n          // transitionComplete. Will only go forward if ev.target == the element listening.\n          function cancelOnTransitionEnd(ev) {\n            if (ev.target !== this) return;\n            cancelTransition();\n          }\n          function cancelTransition() {\n            navViewAttr(enteringEle, VIEW_STATUS_CACHED);\n            navViewAttr(leavingEle, VIEW_STATUS_ACTIVE);\n            enteringEle.off(TRANSITIONEND_EVENT, cancelOnTransitionEnd);\n            $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));\n            ionicViewSwitcher.transitionEnd([navViewCtrl]);\n          }\n\n        },\n\n        emit: function(step, enteringData, leavingData) {\n          var scope = enteringEle.scope();\n          if (scope) {\n            scope.$emit('$ionicView.' + step + 'Enter', enteringData);\n            if (step == 'after') {\n              scope.$emit('$ionicView.enter', enteringData);\n            }\n          }\n\n          if (leavingEle) {\n            scope = leavingEle.scope();\n            if (scope) {\n              scope.$emit('$ionicView.' + step + 'Leave', leavingData);\n              if (step == 'after') {\n                scope.$emit('$ionicView.leave', leavingData);\n              }\n            }\n\n          } else if (scope && leavingData && leavingData.viewId) {\n            scope.$emit('$ionicNavView.' + step + 'Leave', leavingData);\n            if (step == 'after') {\n              scope.$emit('$ionicNavView.leave', leavingData);\n            }\n          }\n        },\n\n        cleanup: function(transData) {\n          // check if any views should be removed\n          if (leavingEle && transData.direction == 'back' && !$ionicConfig.views.forwardCache()) {\n            // if they just navigated back we can destroy the forward view\n            // do not remove forward views if cacheForwardViews config is true\n            destroyViewEle(leavingEle);\n          }\n\n          var viewElements = navViewCtrl.getViewElements();\n          var viewElementsLength = viewElements.length;\n          var x, viewElement;\n          var removeOldestAccess = (viewElementsLength - 1) > $ionicConfig.views.maxCache();\n          var removableEle;\n          var oldestAccess = Date.now();\n\n          for (x = 0; x < viewElementsLength; x++) {\n            viewElement = viewElements.eq(x);\n\n            if (removeOldestAccess && viewElement.data(DATA_VIEW_ACCESSED) < oldestAccess) {\n              // remember what was the oldest element to be accessed so it can be destroyed\n              oldestAccess = viewElement.data(DATA_VIEW_ACCESSED);\n              removableEle = viewElements.eq(x);\n\n            } else if (viewElement.data(DATA_DESTROY_ELE) && navViewAttr(viewElement) != VIEW_STATUS_ACTIVE) {\n              destroyViewEle(viewElement);\n            }\n          }\n\n          destroyViewEle(removableEle);\n\n          if (enteringEle.data(DATA_NO_CACHE)) {\n            enteringEle.data(DATA_DESTROY_ELE, true);\n          }\n        },\n\n        enteringEle: function() { return enteringEle; },\n        leavingEle: function() { return leavingEle; }\n\n      };\n\n      return switcher;\n    },\n\n    transitionEnd: function(navViewCtrls) {\n      forEach(navViewCtrls, function(navViewCtrl) {\n        navViewCtrl.transitionEnd();\n      });\n\n      ionicViewSwitcher.isTransitioning(false);\n      $ionicClickBlock.hide();\n      transitionPromises = [];\n    },\n\n    nextTransition: function(val) {\n      nextTransition = val;\n    },\n\n    nextDirection: function(val) {\n      nextDirection = val;\n    },\n\n    isTransitioning: function(val) {\n      if (arguments.length) {\n        ionic.transition.isActive = !!val;\n        $timeout.cancel(isActiveTimer);\n        if (val) {\n          isActiveTimer = $timeout(function() {\n            ionicViewSwitcher.isTransitioning(false);\n          }, 999);\n        }\n      }\n      return ionic.transition.isActive;\n    },\n\n    createViewEle: function(viewLocals) {\n      var containerEle = $document[0].createElement('div');\n      if (viewLocals && viewLocals.$template) {\n        containerEle.innerHTML = viewLocals.$template;\n        if (containerEle.children.length === 1) {\n          containerEle.children[0].classList.add('pane');\n          return jqLite(containerEle.children[0]);\n        }\n      }\n      containerEle.className = \"pane\";\n      return jqLite(containerEle);\n    },\n\n    viewEleIsActive: function(viewEle, isActiveAttr) {\n      navViewAttr(viewEle, isActiveAttr ? VIEW_STATUS_ACTIVE : VIEW_STATUS_CACHED);\n    },\n\n    getTransitionData: getTransitionData,\n    navViewAttr: navViewAttr,\n    destroyViewEle: destroyViewEle\n\n  };\n\n  return ionicViewSwitcher;\n\n\n  function getViewElementIdentifier(locals, view) {\n    if (viewState(locals)['abstract']) return viewState(locals).name;\n    if (view) return view.stateId || view.viewId;\n    return ionic.Utils.nextUid();\n  }\n\n  function viewState(locals) {\n    return locals && locals.$$state && locals.$$state.self || {};\n  }\n\n  function getTransitionData(viewLocals, enteringEle, direction, view) {\n    // Priority\n    // 1) attribute directive on the button/link to this view\n    // 2) entering element's attribute\n    // 3) entering view's $state config property\n    // 4) view registration data\n    // 5) global config\n    // 6) fallback value\n\n    var state = viewState(viewLocals);\n    var viewTransition = nextTransition || cachedAttr(enteringEle, 'view-transition') || state.viewTransition || $ionicConfig.views.transition() || 'ios';\n    var navBarTransition = $ionicConfig.navBar.transition();\n    direction = nextDirection || cachedAttr(enteringEle, 'view-direction') || state.viewDirection || direction || 'none';\n\n    return extend(getViewData(view), {\n      transition: viewTransition,\n      navBarTransition: navBarTransition === 'view' ? viewTransition : navBarTransition,\n      direction: direction,\n      shouldAnimate: (viewTransition !== 'none' && direction !== 'none')\n    });\n  }\n\n  function getViewData(view) {\n    view = view || {};\n    return {\n      viewId: view.viewId,\n      historyId: view.historyId,\n      stateId: view.stateId,\n      stateName: view.stateName,\n      stateParams: view.stateParams\n    };\n  }\n\n  function navViewAttr(ele, value) {\n    if (arguments.length > 1) {\n      cachedAttr(ele, NAV_VIEW_ATTR, value);\n    } else {\n      return cachedAttr(ele, NAV_VIEW_ATTR);\n    }\n  }\n\n  function destroyViewEle(ele) {\n    // we found an element that should be removed\n    // destroy its scope, then remove the element\n    if (ele && ele.length) {\n      var viewScope = ele.scope();\n      if (viewScope) {\n        viewScope.$emit('$ionicView.unloaded', ele.data(DATA_VIEW));\n        viewScope.$destroy();\n      }\n      ele.remove();\n    }\n  }\n\n}]);\n\n/**\n * @private\n * Parts of Ionic requires that $scope data is attached to the element.\n * We do not want to disable adding $scope data to the $element when\n * $compileProvider.debugInfoEnabled(false) is used.\n */\nIonicModule.config(['$provide', function($provide) {\n  $provide.decorator('$compile', ['$delegate', function($compile) {\n     $compile.$$addScopeInfo = function $$addScopeInfo($element, scope, isolated, noTemplate) {\n       var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n       $element.data(dataName, scope);\n     };\n     return $compile;\n  }]);\n}]);\n\n/**\n * @private\n */\nIonicModule.config([\n  '$provide',\nfunction($provide) {\n  function $LocationDecorator($location, $timeout) {\n\n    $location.__hash = $location.hash;\n    //Fix: when window.location.hash is set, the scrollable area\n    //found nearest to body's scrollTop is set to scroll to an element\n    //with that ID.\n    $location.hash = function(value) {\n      if (isDefined(value)) {\n        $timeout(function() {\n          var scroll = document.querySelector('.scroll-content');\n          if (scroll) {\n            scroll.scrollTop = 0;\n          }\n        }, 0, false);\n      }\n      return $location.__hash(value);\n    };\n\n    return $location;\n  }\n\n  $provide.decorator('$location', ['$delegate', '$timeout', $LocationDecorator]);\n}]);\n\nIonicModule\n\n.controller('$ionicHeaderBar', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$q',\n  '$ionicConfig',\n  '$ionicHistory',\nfunction($scope, $element, $attrs, $q, $ionicConfig, $ionicHistory) {\n  var TITLE = 'title';\n  var BACK_TEXT = 'back-text';\n  var BACK_BUTTON = 'back-button';\n  var DEFAULT_TITLE = 'default-title';\n  var PREVIOUS_TITLE = 'previous-title';\n  var HIDE = 'hide';\n\n  var self = this;\n  var titleText = '';\n  var previousTitleText = '';\n  var titleLeft = 0;\n  var titleRight = 0;\n  var titleCss = '';\n  var isBackEnabled = false;\n  var isBackShown = true;\n  var isNavBackShown = true;\n  var isBackElementShown = false;\n  var titleTextWidth = 0;\n\n\n  self.beforeEnter = function(viewData) {\n    $scope.$broadcast('$ionicView.beforeEnter', viewData);\n  };\n\n\n  self.title = function(newTitleText) {\n    if (arguments.length && newTitleText !== titleText) {\n      getEle(TITLE).innerHTML = newTitleText;\n      titleText = newTitleText;\n      titleTextWidth = 0;\n    }\n    return titleText;\n  };\n\n\n  self.enableBack = function(shouldEnable, disableReset) {\n    // whether or not the back button show be visible, according\n    // to the navigation and history\n    if (arguments.length) {\n      isBackEnabled = shouldEnable;\n      if (!disableReset) self.updateBackButton();\n    }\n    return isBackEnabled;\n  };\n\n\n  self.showBack = function(shouldShow, disableReset) {\n    // different from enableBack() because this will always have the back\n    // visually hidden if false, even if the history says it should show\n    if (arguments.length) {\n      isBackShown = shouldShow;\n      if (!disableReset) self.updateBackButton();\n    }\n    return isBackShown;\n  };\n\n\n  self.showNavBack = function(shouldShow) {\n    // different from showBack() because this is for the entire nav bar's\n    // setting for all of it's child headers. For internal use.\n    isNavBackShown = shouldShow;\n    self.updateBackButton();\n  };\n\n\n  self.updateBackButton = function() {\n    var ele;\n    if ((isBackShown && isNavBackShown && isBackEnabled) !== isBackElementShown) {\n      isBackElementShown = isBackShown && isNavBackShown && isBackEnabled;\n      ele = getEle(BACK_BUTTON);\n      ele && ele.classList[ isBackElementShown ? 'remove' : 'add' ](HIDE);\n    }\n\n    if (isBackEnabled) {\n      ele = ele || getEle(BACK_BUTTON);\n      if (ele) {\n        if (self.backButtonIcon !== $ionicConfig.backButton.icon()) {\n          ele = getEle(BACK_BUTTON + ' .icon');\n          if (ele) {\n            self.backButtonIcon = $ionicConfig.backButton.icon();\n            ele.className = 'icon ' + self.backButtonIcon;\n          }\n        }\n\n        if (self.backButtonText !== $ionicConfig.backButton.text()) {\n          ele = getEle(BACK_BUTTON + ' .back-text');\n          if (ele) {\n            ele.textContent = self.backButtonText = $ionicConfig.backButton.text();\n          }\n        }\n      }\n    }\n  };\n\n\n  self.titleTextWidth = function() {\n    if (!titleTextWidth) {\n      var bounds = ionic.DomUtil.getTextBounds(getEle(TITLE));\n      titleTextWidth = Math.min(bounds && bounds.width || 30);\n    }\n    return titleTextWidth;\n  };\n\n\n  self.titleWidth = function() {\n    var titleWidth = self.titleTextWidth();\n    var offsetWidth = getEle(TITLE).offsetWidth;\n    if (offsetWidth < titleWidth) {\n      titleWidth = offsetWidth + (titleLeft - titleRight - 5);\n    }\n    return titleWidth;\n  };\n\n\n  self.titleTextX = function() {\n    return ($element[0].offsetWidth / 2) - (self.titleWidth() / 2);\n  };\n\n\n  self.titleLeftRight = function() {\n    return titleLeft - titleRight;\n  };\n\n\n  self.backButtonTextLeft = function() {\n    var offsetLeft = 0;\n    var ele = getEle(BACK_TEXT);\n    while (ele) {\n      offsetLeft += ele.offsetLeft;\n      ele = ele.parentElement;\n    }\n    return offsetLeft;\n  };\n\n\n  self.resetBackButton = function(viewData) {\n    if ($ionicConfig.backButton.previousTitleText()) {\n      var previousTitleEle = getEle(PREVIOUS_TITLE);\n      if (previousTitleEle) {\n        previousTitleEle.classList.remove(HIDE);\n\n        var view = (viewData && $ionicHistory.getViewById(viewData.viewId));\n        var newPreviousTitleText = $ionicHistory.backTitle(view);\n\n        if (newPreviousTitleText !== previousTitleText) {\n          previousTitleText = previousTitleEle.innerHTML = newPreviousTitleText;\n        }\n      }\n      var defaultTitleEle = getEle(DEFAULT_TITLE);\n      if (defaultTitleEle) {\n        defaultTitleEle.classList.remove(HIDE);\n      }\n    }\n  };\n\n\n  self.align = function(textAlign) {\n    var titleEle = getEle(TITLE);\n\n    textAlign = textAlign || $attrs.alignTitle || $ionicConfig.navBar.alignTitle();\n\n    var widths = self.calcWidths(textAlign, false);\n\n    if (isBackShown && previousTitleText && $ionicConfig.backButton.previousTitleText()) {\n      var previousTitleWidths = self.calcWidths(textAlign, true);\n\n      var availableTitleWidth = $element[0].offsetWidth - previousTitleWidths.titleLeft - previousTitleWidths.titleRight;\n\n      if (self.titleTextWidth() <= availableTitleWidth) {\n        widths = previousTitleWidths;\n      }\n    }\n\n    return self.updatePositions(titleEle, widths.titleLeft, widths.titleRight, widths.buttonsLeft, widths.buttonsRight, widths.css, widths.showPrevTitle);\n  };\n\n\n  self.calcWidths = function(textAlign, isPreviousTitle) {\n    var titleEle = getEle(TITLE);\n    var backBtnEle = getEle(BACK_BUTTON);\n    var x, y, z, b, c, d, childSize, bounds;\n    var childNodes = $element[0].childNodes;\n    var buttonsLeft = 0;\n    var buttonsRight = 0;\n    var isCountRightOfTitle;\n    var updateTitleLeft = 0;\n    var updateTitleRight = 0;\n    var updateCss = '';\n    var backButtonWidth = 0;\n\n    // Compute how wide the left children are\n    // Skip all titles (there may still be two titles, one leaving the dom)\n    // Once we encounter a titleEle, realize we are now counting the right-buttons, not left\n    for (x = 0; x < childNodes.length; x++) {\n      c = childNodes[x];\n\n      childSize = 0;\n      if (c.nodeType == 1) {\n        // element node\n        if (c === titleEle) {\n          isCountRightOfTitle = true;\n          continue;\n        }\n\n        if (c.classList.contains(HIDE)) {\n          continue;\n        }\n\n        if (isBackShown && c === backBtnEle) {\n\n          for (y = 0; y < c.childNodes.length; y++) {\n            b = c.childNodes[y];\n\n            if (b.nodeType == 1) {\n\n              if (b.classList.contains(BACK_TEXT)) {\n                for (z = 0; z < b.children.length; z++) {\n                  d = b.children[z];\n\n                  if (isPreviousTitle) {\n                    if (d.classList.contains(DEFAULT_TITLE)) continue;\n                    backButtonWidth += d.offsetWidth;\n                  } else {\n                    if (d.classList.contains(PREVIOUS_TITLE)) continue;\n                    backButtonWidth += d.offsetWidth;\n                  }\n                }\n\n              } else {\n                backButtonWidth += b.offsetWidth;\n              }\n\n            } else if (b.nodeType == 3 && b.nodeValue.trim()) {\n              bounds = ionic.DomUtil.getTextBounds(b);\n              backButtonWidth += bounds && bounds.width || 0;\n            }\n\n          }\n          childSize = backButtonWidth || c.offsetWidth;\n\n        } else {\n          // not the title, not the back button, not a hidden element\n          childSize = c.offsetWidth;\n        }\n\n      } else if (c.nodeType == 3 && c.nodeValue.trim()) {\n        // text node\n        bounds = ionic.DomUtil.getTextBounds(c);\n        childSize = bounds && bounds.width || 0;\n      }\n\n      if (isCountRightOfTitle) {\n        buttonsRight += childSize;\n      } else {\n        buttonsLeft += childSize;\n      }\n    }\n\n    // Size and align the header titleEle based on the sizes of the left and\n    // right children, and the desired alignment mode\n    if (textAlign == 'left') {\n      updateCss = 'title-left';\n      if (buttonsLeft) {\n        updateTitleLeft = buttonsLeft + 15;\n      }\n      if (buttonsRight) {\n        updateTitleRight = buttonsRight + 15;\n      }\n\n    } else if (textAlign == 'right') {\n      updateCss = 'title-right';\n      if (buttonsLeft) {\n        updateTitleLeft = buttonsLeft + 15;\n      }\n      if (buttonsRight) {\n        updateTitleRight = buttonsRight + 15;\n      }\n\n    } else {\n      // center the default\n      var margin = Math.max(buttonsLeft, buttonsRight) + 10;\n      if (margin > 10) {\n        updateTitleLeft = updateTitleRight = margin;\n      }\n    }\n\n    return {\n      backButtonWidth: backButtonWidth,\n      buttonsLeft: buttonsLeft,\n      buttonsRight: buttonsRight,\n      titleLeft: updateTitleLeft,\n      titleRight: updateTitleRight,\n      showPrevTitle: isPreviousTitle,\n      css: updateCss\n    };\n  };\n\n\n  self.updatePositions = function(titleEle, updateTitleLeft, updateTitleRight, buttonsLeft, buttonsRight, updateCss, showPreviousTitle) {\n    var deferred = $q.defer();\n\n    // only make DOM updates when there are actual changes\n    if (titleEle) {\n      if (updateTitleLeft !== titleLeft) {\n        titleEle.style.left = updateTitleLeft ? updateTitleLeft + 'px' : '';\n        titleLeft = updateTitleLeft;\n      }\n      if (updateTitleRight !== titleRight) {\n        titleEle.style.right = updateTitleRight ? updateTitleRight + 'px' : '';\n        titleRight = updateTitleRight;\n      }\n\n      if (updateCss !== titleCss) {\n        updateCss && titleEle.classList.add(updateCss);\n        titleCss && titleEle.classList.remove(titleCss);\n        titleCss = updateCss;\n      }\n    }\n\n    if ($ionicConfig.backButton.previousTitleText()) {\n      var prevTitle = getEle(PREVIOUS_TITLE);\n      var defaultTitle = getEle(DEFAULT_TITLE);\n\n      prevTitle && prevTitle.classList[ showPreviousTitle ? 'remove' : 'add'](HIDE);\n      defaultTitle && defaultTitle.classList[ showPreviousTitle ? 'add' : 'remove'](HIDE);\n    }\n\n    ionic.requestAnimationFrame(function() {\n      if (titleEle && titleEle.offsetWidth + 10 < titleEle.scrollWidth) {\n        var minRight = buttonsRight + 5;\n        var testRight = $element[0].offsetWidth - titleLeft - self.titleTextWidth() - 20;\n        updateTitleRight = testRight < minRight ? minRight : testRight;\n        if (updateTitleRight !== titleRight) {\n          titleEle.style.right = updateTitleRight + 'px';\n          titleRight = updateTitleRight;\n        }\n      }\n      deferred.resolve();\n    });\n\n    return deferred.promise;\n  };\n\n\n  self.setCss = function(elementClassname, css) {\n    ionic.DomUtil.cachedStyles(getEle(elementClassname), css);\n  };\n\n\n  var eleCache = {};\n  function getEle(className) {\n    if (!eleCache[className]) {\n      eleCache[className] = $element[0].querySelector('.' + className);\n    }\n    return eleCache[className];\n  }\n\n\n  $scope.$on('$destroy', function() {\n    for (var n in eleCache) eleCache[n] = null;\n  });\n\n}]);\n\nIonicModule\n.controller('$ionInfiniteScroll', [\n  '$scope',\n  '$attrs',\n  '$element',\n  '$timeout',\nfunction($scope, $attrs, $element, $timeout) {\n  var self = this;\n  self.isLoading = false;\n\n  $scope.icon = function() {\n    return isDefined($attrs.icon) ? $attrs.icon : 'ion-load-d';\n  };\n\n  $scope.spinner = function() {\n    return isDefined($attrs.spinner) ? $attrs.spinner : '';\n  };\n\n  $scope.$on('scroll.infiniteScrollComplete', function() {\n    finishInfiniteScroll();\n  });\n\n  $scope.$on('$destroy', function() {\n    if (self.scrollCtrl && self.scrollCtrl.$element) self.scrollCtrl.$element.off('scroll', self.checkBounds);\n    if (self.scrollEl && self.scrollEl.removeEventListener) {\n      self.scrollEl.removeEventListener('scroll', self.checkBounds);\n    }\n  });\n\n  // debounce checking infinite scroll events\n  self.checkBounds = ionic.Utils.throttle(checkInfiniteBounds, 300);\n\n  function onInfinite() {\n    ionic.requestAnimationFrame(function() {\n      $element[0].classList.add('active');\n    });\n    self.isLoading = true;\n    $scope.$parent && $scope.$parent.$apply($attrs.onInfinite || '');\n  }\n\n  function finishInfiniteScroll() {\n    ionic.requestAnimationFrame(function() {\n      $element[0].classList.remove('active');\n    });\n    $timeout(function() {\n      if (self.jsScrolling) self.scrollView.resize();\n      // only check bounds again immediately if the page isn't cached (scroll el has height)\n      if ((self.jsScrolling && self.scrollView.__container && self.scrollView.__container.offsetHeight > 0) ||\n      !self.jsScrolling) {\n        self.checkBounds();\n      }\n    }, 30, false);\n    self.isLoading = false;\n  }\n\n  // check if we've scrolled far enough to trigger an infinite scroll\n  function checkInfiniteBounds() {\n    if (self.isLoading) return;\n    var maxScroll = {};\n\n    if (self.jsScrolling) {\n      maxScroll = self.getJSMaxScroll();\n      var scrollValues = self.scrollView.getValues();\n      if ((maxScroll.left !== -1 && scrollValues.left >= maxScroll.left) ||\n        (maxScroll.top !== -1 && scrollValues.top >= maxScroll.top)) {\n        onInfinite();\n      }\n    } else {\n      maxScroll = self.getNativeMaxScroll();\n      if ((\n        maxScroll.left !== -1 &&\n        self.scrollEl.scrollLeft >= maxScroll.left - self.scrollEl.clientWidth\n        ) || (\n        maxScroll.top !== -1 &&\n        self.scrollEl.scrollTop >= maxScroll.top - self.scrollEl.clientHeight\n        )) {\n        onInfinite();\n      }\n    }\n  }\n\n  // determine the threshold at which we should fire an infinite scroll\n  // note: this gets processed every scroll event, can it be cached?\n  self.getJSMaxScroll = function() {\n    var maxValues = self.scrollView.getScrollMax();\n    return {\n      left: self.scrollView.options.scrollingX ?\n        calculateMaxValue(maxValues.left) :\n        -1,\n      top: self.scrollView.options.scrollingY ?\n        calculateMaxValue(maxValues.top) :\n        -1\n    };\n  };\n\n  self.getNativeMaxScroll = function() {\n    var maxValues = {\n      left: self.scrollEl.scrollWidth,\n      top: self.scrollEl.scrollHeight\n    };\n    var computedStyle = window.getComputedStyle(self.scrollEl) || {};\n    return {\n      left: computedStyle.overflowX === 'scroll' ||\n      computedStyle.overflowX === 'auto' ||\n      self.scrollEl.style['overflow-x'] === 'scroll' ?\n        calculateMaxValue(maxValues.left) : -1,\n      top: computedStyle.overflowY === 'scroll' ||\n      computedStyle.overflowY === 'auto' ||\n      self.scrollEl.style['overflow-y'] === 'scroll' ?\n        calculateMaxValue(maxValues.top) : -1\n    };\n  };\n\n  // determine pixel refresh distance based on % or value\n  function calculateMaxValue(maximum) {\n    var distance = ($attrs.distance || '2.5%').trim();\n    var isPercent = distance.indexOf('%') !== -1;\n    return isPercent ?\n    maximum * (1 - parseFloat(distance) / 100) :\n    maximum - parseFloat(distance);\n  }\n\n  //for testing\n  self.__finishInfiniteScroll = finishInfiniteScroll;\n\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicListDelegate\n * @module ionic\n *\n * @description\n * Delegate for controlling the {@link ionic.directive:ionList} directive.\n *\n * Methods called directly on the $ionicListDelegate service will control all lists.\n * Use the {@link ionic.service:$ionicListDelegate#$getByHandle $getByHandle}\n * method to control specific ionList instances.\n *\n * @usage\n *\n * ````html\n * <ion-content ng-controller=\"MyCtrl\">\n *   <button class=\"button\" ng-click=\"showDeleteButtons()\"></button>\n *   <ion-list>\n *     <ion-item ng-repeat=\"i in items\">\n *       {% raw %}Hello, {{i}}!{% endraw %}\n *       <ion-delete-button class=\"ion-minus-circled\"></ion-delete-button>\n *     </ion-item>\n *   </ion-list>\n * </ion-content>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicListDelegate) {\n *   $scope.showDeleteButtons = function() {\n *     $ionicListDelegate.showDelete(true);\n *   };\n * }\n * ```\n */\nIonicModule.service('$ionicListDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#showReorder\n   * @param {boolean=} showReorder Set whether or not this list is showing its reorder buttons.\n   * @returns {boolean} Whether the reorder buttons are shown.\n   */\n  'showReorder',\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#showDelete\n   * @param {boolean=} showDelete Set whether or not this list is showing its delete buttons.\n   * @returns {boolean} Whether the delete buttons are shown.\n   */\n  'showDelete',\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#canSwipeItems\n   * @param {boolean=} canSwipeItems Set whether or not this list is able to swipe to show\n   * option buttons.\n   * @returns {boolean} Whether the list is able to swipe to show option buttons.\n   */\n  'canSwipeItems',\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#closeOptionButtons\n   * @description Closes any option buttons on the list that are swiped open.\n   */\n  'closeOptionButtons'\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionList} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicListDelegate.$getByHandle('my-handle').showReorder(true);`\n   */\n]))\n\n.controller('$ionicList', [\n  '$scope',\n  '$attrs',\n  '$ionicListDelegate',\n  '$ionicHistory',\nfunction($scope, $attrs, $ionicListDelegate, $ionicHistory) {\n  var self = this;\n  var isSwipeable = true;\n  var isReorderShown = false;\n  var isDeleteShown = false;\n\n  var deregisterInstance = $ionicListDelegate._registerInstance(\n    self, $attrs.delegateHandle, function() {\n      return $ionicHistory.isActiveScope($scope);\n    }\n  );\n  $scope.$on('$destroy', deregisterInstance);\n\n  self.showReorder = function(show) {\n    if (arguments.length) {\n      isReorderShown = !!show;\n    }\n    return isReorderShown;\n  };\n\n  self.showDelete = function(show) {\n    if (arguments.length) {\n      isDeleteShown = !!show;\n    }\n    return isDeleteShown;\n  };\n\n  self.canSwipeItems = function(can) {\n    if (arguments.length) {\n      isSwipeable = !!can;\n    }\n    return isSwipeable;\n  };\n\n  self.closeOptionButtons = function() {\n    self.listView && self.listView.clearDragEffects();\n  };\n}]);\n\nIonicModule\n\n.controller('$ionicNavBar', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$compile',\n  '$timeout',\n  '$ionicNavBarDelegate',\n  '$ionicConfig',\n  '$ionicHistory',\nfunction($scope, $element, $attrs, $compile, $timeout, $ionicNavBarDelegate, $ionicConfig, $ionicHistory) {\n\n  var CSS_HIDE = 'hide';\n  var DATA_NAV_BAR_CTRL = '$ionNavBarController';\n  var PRIMARY_BUTTONS = 'primaryButtons';\n  var SECONDARY_BUTTONS = 'secondaryButtons';\n  var BACK_BUTTON = 'backButton';\n  var ITEM_TYPES = 'primaryButtons secondaryButtons leftButtons rightButtons title'.split(' ');\n\n  var self = this;\n  var headerBars = [];\n  var navElementHtml = {};\n  var isVisible = true;\n  var queuedTransitionStart, queuedTransitionEnd, latestTransitionId;\n\n  $element.parent().data(DATA_NAV_BAR_CTRL, self);\n\n  var delegateHandle = $attrs.delegateHandle || 'navBar' + ionic.Utils.nextUid();\n\n  var deregisterInstance = $ionicNavBarDelegate._registerInstance(self, delegateHandle);\n\n\n  self.init = function() {\n    $element.addClass('nav-bar-container');\n    ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', $ionicConfig.views.transition());\n\n    // create two nav bar blocks which will trade out which one is shown\n    self.createHeaderBar(false);\n    self.createHeaderBar(true);\n\n    $scope.$emit('ionNavBar.init', delegateHandle);\n  };\n\n\n  self.createHeaderBar = function(isActive) {\n    var containerEle = jqLite('<div class=\"nav-bar-block\">');\n    ionic.DomUtil.cachedAttr(containerEle, 'nav-bar', isActive ? 'active' : 'cached');\n\n    var alignTitle = $attrs.alignTitle || $ionicConfig.navBar.alignTitle();\n    var headerBarEle = jqLite('<ion-header-bar>').addClass($attrs['class']).attr('align-title', alignTitle);\n    if (isDefined($attrs.noTapScroll)) headerBarEle.attr('no-tap-scroll', $attrs.noTapScroll);\n    var titleEle = jqLite('<div class=\"title title-' + alignTitle + '\">');\n    var navEle = {};\n    var lastViewItemEle = {};\n    var leftButtonsEle, rightButtonsEle;\n\n    navEle[BACK_BUTTON] = createNavElement(BACK_BUTTON);\n    navEle[BACK_BUTTON] && headerBarEle.append(navEle[BACK_BUTTON]);\n\n    // append title in the header, this is the rock to where buttons append\n    headerBarEle.append(titleEle);\n\n    forEach(ITEM_TYPES, function(itemType) {\n      // create default button elements\n      navEle[itemType] = createNavElement(itemType);\n      // append and position buttons\n      positionItem(navEle[itemType], itemType);\n    });\n\n    // add header-item to the root children\n    for (var x = 0; x < headerBarEle[0].children.length; x++) {\n      headerBarEle[0].children[x].classList.add('header-item');\n    }\n\n    // compile header and append to the DOM\n    containerEle.append(headerBarEle);\n    $element.append($compile(containerEle)($scope.$new()));\n\n    var headerBarCtrl = headerBarEle.data('$ionHeaderBarController');\n    headerBarCtrl.backButtonIcon = $ionicConfig.backButton.icon();\n    headerBarCtrl.backButtonText = $ionicConfig.backButton.text();\n\n    var headerBarInstance = {\n      isActive: isActive,\n      title: function(newTitleText) {\n        headerBarCtrl.title(newTitleText);\n      },\n      setItem: function(navBarItemEle, itemType) {\n        // first make sure any exiting nav bar item has been removed\n        headerBarInstance.removeItem(itemType);\n\n        if (navBarItemEle) {\n          if (itemType === 'title') {\n            // clear out the text based title\n            headerBarInstance.title(\"\");\n          }\n\n          // there's a custom nav bar item\n          positionItem(navBarItemEle, itemType);\n\n          if (navEle[itemType]) {\n            // make sure the default on this itemType is hidden\n            navEle[itemType].addClass(CSS_HIDE);\n          }\n          lastViewItemEle[itemType] = navBarItemEle;\n\n        } else if (navEle[itemType]) {\n          // there's a default button for this side and no view button\n          navEle[itemType].removeClass(CSS_HIDE);\n        }\n      },\n      removeItem: function(itemType) {\n        if (lastViewItemEle[itemType]) {\n          lastViewItemEle[itemType].scope().$destroy();\n          lastViewItemEle[itemType].remove();\n          lastViewItemEle[itemType] = null;\n        }\n      },\n      containerEle: function() {\n        return containerEle;\n      },\n      headerBarEle: function() {\n        return headerBarEle;\n      },\n      afterLeave: function() {\n        forEach(ITEM_TYPES, function(itemType) {\n          headerBarInstance.removeItem(itemType);\n        });\n        headerBarCtrl.resetBackButton();\n      },\n      controller: function() {\n        return headerBarCtrl;\n      },\n      destroy: function() {\n        forEach(ITEM_TYPES, function(itemType) {\n          headerBarInstance.removeItem(itemType);\n        });\n        containerEle.scope().$destroy();\n        for (var n in navEle) {\n          if (navEle[n]) {\n            navEle[n].removeData();\n            navEle[n] = null;\n          }\n        }\n        leftButtonsEle && leftButtonsEle.removeData();\n        rightButtonsEle && rightButtonsEle.removeData();\n        titleEle.removeData();\n        headerBarEle.removeData();\n        containerEle.remove();\n        containerEle = headerBarEle = titleEle = leftButtonsEle = rightButtonsEle = null;\n      }\n    };\n\n    function positionItem(ele, itemType) {\n      if (!ele) return;\n\n      if (itemType === 'title') {\n        // title element\n        titleEle.append(ele);\n\n      } else if (itemType == 'rightButtons' ||\n                (itemType == SECONDARY_BUTTONS && $ionicConfig.navBar.positionSecondaryButtons() != 'left') ||\n                (itemType == PRIMARY_BUTTONS && $ionicConfig.navBar.positionPrimaryButtons() == 'right')) {\n        // right side\n        if (!rightButtonsEle) {\n          rightButtonsEle = jqLite('<div class=\"buttons buttons-right\">');\n          headerBarEle.append(rightButtonsEle);\n        }\n        if (itemType == SECONDARY_BUTTONS) {\n          rightButtonsEle.append(ele);\n        } else {\n          rightButtonsEle.prepend(ele);\n        }\n\n      } else {\n        // left side\n        if (!leftButtonsEle) {\n          leftButtonsEle = jqLite('<div class=\"buttons buttons-left\">');\n          if (navEle[BACK_BUTTON]) {\n            navEle[BACK_BUTTON].after(leftButtonsEle);\n          } else {\n            headerBarEle.prepend(leftButtonsEle);\n          }\n        }\n        if (itemType == SECONDARY_BUTTONS) {\n          leftButtonsEle.append(ele);\n        } else {\n          leftButtonsEle.prepend(ele);\n        }\n      }\n\n    }\n\n    headerBars.push(headerBarInstance);\n\n    return headerBarInstance;\n  };\n\n\n  self.navElement = function(type, html) {\n    if (isDefined(html)) {\n      navElementHtml[type] = html;\n    }\n    return navElementHtml[type];\n  };\n\n\n  self.update = function(viewData) {\n    var showNavBar = !viewData.hasHeaderBar && viewData.showNavBar;\n    viewData.transition = $ionicConfig.views.transition();\n\n    if (!showNavBar) {\n      viewData.direction = 'none';\n    }\n\n    self.enable(showNavBar);\n    var enteringHeaderBar = self.isInitialized ? getOffScreenHeaderBar() : getOnScreenHeaderBar();\n    var leavingHeaderBar = self.isInitialized ? getOnScreenHeaderBar() : null;\n    var enteringHeaderCtrl = enteringHeaderBar.controller();\n\n    // update if the entering header should show the back button or not\n    enteringHeaderCtrl.enableBack(viewData.enableBack, true);\n    enteringHeaderCtrl.showBack(viewData.showBack, true);\n    enteringHeaderCtrl.updateBackButton();\n\n    // update the entering header bar's title\n    self.title(viewData.title, enteringHeaderBar);\n\n    self.showBar(showNavBar);\n\n    // update the nav bar items, depending if the view has their own or not\n    if (viewData.navBarItems) {\n      forEach(ITEM_TYPES, function(itemType) {\n        enteringHeaderBar.setItem(viewData.navBarItems[itemType], itemType);\n      });\n    }\n\n    // begin transition of entering and leaving header bars\n    self.transition(enteringHeaderBar, leavingHeaderBar, viewData);\n\n    self.isInitialized = true;\n    navSwipeAttr('');\n  };\n\n\n  self.transition = function(enteringHeaderBar, leavingHeaderBar, viewData) {\n    var enteringHeaderBarCtrl = enteringHeaderBar.controller();\n    var transitionFn = $ionicConfig.transitions.navBar[viewData.navBarTransition] || $ionicConfig.transitions.navBar.none;\n    var transitionId = viewData.transitionId;\n\n    enteringHeaderBarCtrl.beforeEnter(viewData);\n\n    var navBarTransition = transitionFn(enteringHeaderBar, leavingHeaderBar, viewData.direction, viewData.shouldAnimate && self.isInitialized);\n\n    ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', viewData.navBarTransition);\n    ionic.DomUtil.cachedAttr($element, 'nav-bar-direction', viewData.direction);\n\n    if (navBarTransition.shouldAnimate && viewData.renderEnd) {\n      navBarAttr(enteringHeaderBar, 'stage');\n    } else {\n      navBarAttr(enteringHeaderBar, 'entering');\n      navBarAttr(leavingHeaderBar, 'leaving');\n    }\n\n    enteringHeaderBarCtrl.resetBackButton(viewData);\n\n    navBarTransition.run(0);\n\n    self.activeTransition = {\n      run: function(step) {\n        navBarTransition.shouldAnimate = false;\n        navBarTransition.direction = 'back';\n        navBarTransition.run(step);\n      },\n      cancel: function(shouldAnimate, speed, cancelData) {\n        navSwipeAttr(speed);\n        navBarAttr(leavingHeaderBar, 'active');\n        navBarAttr(enteringHeaderBar, 'cached');\n        navBarTransition.shouldAnimate = shouldAnimate;\n        navBarTransition.run(0);\n        self.activeTransition = navBarTransition = null;\n\n        var runApply;\n        if (cancelData.showBar !== self.showBar()) {\n          self.showBar(cancelData.showBar);\n        }\n        if (cancelData.showBackButton !== self.showBackButton()) {\n          self.showBackButton(cancelData.showBackButton);\n        }\n        if (runApply) {\n          $scope.$apply();\n        }\n      },\n      complete: function(shouldAnimate, speed) {\n        navSwipeAttr(speed);\n        navBarTransition.shouldAnimate = shouldAnimate;\n        navBarTransition.run(1);\n        queuedTransitionEnd = transitionEnd;\n      }\n    };\n\n    $timeout(enteringHeaderBarCtrl.align, 16);\n\n    queuedTransitionStart = function() {\n      if (latestTransitionId !== transitionId) return;\n\n      navBarAttr(enteringHeaderBar, 'entering');\n      navBarAttr(leavingHeaderBar, 'leaving');\n\n      navBarTransition.run(1);\n\n      queuedTransitionEnd = function() {\n        if (latestTransitionId == transitionId || !navBarTransition.shouldAnimate) {\n          transitionEnd();\n        }\n      };\n\n      queuedTransitionStart = null;\n    };\n\n    function transitionEnd() {\n      for (var x = 0; x < headerBars.length; x++) {\n        headerBars[x].isActive = false;\n      }\n      enteringHeaderBar.isActive = true;\n\n      navBarAttr(enteringHeaderBar, 'active');\n      navBarAttr(leavingHeaderBar, 'cached');\n\n      self.activeTransition = navBarTransition = queuedTransitionEnd = null;\n    }\n\n    queuedTransitionStart();\n  };\n\n\n  self.triggerTransitionStart = function(triggerTransitionId) {\n    latestTransitionId = triggerTransitionId;\n    queuedTransitionStart && queuedTransitionStart();\n  };\n\n\n  self.triggerTransitionEnd = function() {\n    queuedTransitionEnd && queuedTransitionEnd();\n  };\n\n\n  self.showBar = function(shouldShow) {\n    if (arguments.length) {\n      self.visibleBar(shouldShow);\n      $scope.$parent.$hasHeader = !!shouldShow;\n    }\n    return !!$scope.$parent.$hasHeader;\n  };\n\n\n  self.visibleBar = function(shouldShow) {\n    if (shouldShow && !isVisible) {\n      $element.removeClass(CSS_HIDE);\n      self.align();\n    } else if (!shouldShow && isVisible) {\n      $element.addClass(CSS_HIDE);\n    }\n    isVisible = shouldShow;\n  };\n\n\n  self.enable = function(val) {\n    // set primary to show first\n    self.visibleBar(val);\n\n    // set non primary to hide second\n    for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {\n      if ($ionicNavBarDelegate._instances[x] !== self) $ionicNavBarDelegate._instances[x].visibleBar(false);\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavBar#showBackButton\n   * @description Show/hide the nav bar back button when there is a\n   * back view. If the back button is not possible, for example, the\n   * first view in the stack, then this will not force the back button\n   * to show.\n   */\n  self.showBackButton = function(shouldShow) {\n    if (arguments.length) {\n      for (var x = 0; x < headerBars.length; x++) {\n        headerBars[x].controller().showNavBack(!!shouldShow);\n      }\n      $scope.$isBackButtonShown = !!shouldShow;\n    }\n    return $scope.$isBackButtonShown;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavBar#showActiveBackButton\n   * @description Show/hide only the active header bar's back button.\n   */\n  self.showActiveBackButton = function(shouldShow) {\n    var headerBar = getOnScreenHeaderBar();\n    if (headerBar) {\n      if (arguments.length) {\n        return headerBar.controller().showBack(shouldShow);\n      }\n      return headerBar.controller().showBack();\n    }\n  };\n\n\n  self.title = function(newTitleText, headerBar) {\n    if (isDefined(newTitleText)) {\n      newTitleText = newTitleText || '';\n      headerBar = headerBar || getOnScreenHeaderBar();\n      headerBar && headerBar.title(newTitleText);\n      $scope.$title = newTitleText;\n      $ionicHistory.currentTitle(newTitleText);\n    }\n    return $scope.$title;\n  };\n\n\n  self.align = function(val, headerBar) {\n    headerBar = headerBar || getOnScreenHeaderBar();\n    headerBar && headerBar.controller().align(val);\n  };\n\n\n  self.hasTabsTop = function(isTabsTop) {\n    $element[isTabsTop ? 'addClass' : 'removeClass']('nav-bar-tabs-top');\n  };\n\n  self.hasBarSubheader = function(isBarSubheader) {\n    $element[isBarSubheader ? 'addClass' : 'removeClass']('nav-bar-has-subheader');\n  };\n\n  // DEPRECATED, as of v1.0.0-beta14 -------\n  self.changeTitle = function(val) {\n    deprecatedWarning('changeTitle(val)', 'title(val)');\n    self.title(val);\n  };\n  self.setTitle = function(val) {\n    deprecatedWarning('setTitle(val)', 'title(val)');\n    self.title(val);\n  };\n  self.getTitle = function() {\n    deprecatedWarning('getTitle()', 'title()');\n    return self.title();\n  };\n  self.back = function() {\n    deprecatedWarning('back()', '$ionicHistory.goBack()');\n    $ionicHistory.goBack();\n  };\n  self.getPreviousTitle = function() {\n    deprecatedWarning('getPreviousTitle()', '$ionicHistory.backTitle()');\n    $ionicHistory.goBack();\n  };\n  function deprecatedWarning(oldMethod, newMethod) {\n    var warn = console.warn || console.log;\n    warn && warn.call(console, 'navBarController.' + oldMethod + ' is deprecated, please use ' + newMethod + ' instead');\n  }\n  // END DEPRECATED -------\n\n\n  function createNavElement(type) {\n    if (navElementHtml[type]) {\n      return jqLite(navElementHtml[type]);\n    }\n  }\n\n\n  function getOnScreenHeaderBar() {\n    for (var x = 0; x < headerBars.length; x++) {\n      if (headerBars[x].isActive) return headerBars[x];\n    }\n  }\n\n\n  function getOffScreenHeaderBar() {\n    for (var x = 0; x < headerBars.length; x++) {\n      if (!headerBars[x].isActive) return headerBars[x];\n    }\n  }\n\n\n  function navBarAttr(ctrl, val) {\n    ctrl && ionic.DomUtil.cachedAttr(ctrl.containerEle(), 'nav-bar', val);\n  }\n\n  function navSwipeAttr(val) {\n    ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);\n  }\n\n\n  $scope.$on('$destroy', function() {\n    $scope.$parent.$hasHeader = false;\n    $element.parent().removeData(DATA_NAV_BAR_CTRL);\n    for (var x = 0; x < headerBars.length; x++) {\n      headerBars[x].destroy();\n    }\n    $element.remove();\n    $element = headerBars = null;\n    deregisterInstance();\n  });\n\n}]);\n\nIonicModule\n.controller('$ionicNavView', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$compile',\n  '$controller',\n  '$ionicNavBarDelegate',\n  '$ionicNavViewDelegate',\n  '$ionicHistory',\n  '$ionicViewSwitcher',\n  '$ionicConfig',\n  '$ionicScrollDelegate',\nfunction($scope, $element, $attrs, $compile, $controller, $ionicNavBarDelegate, $ionicNavViewDelegate, $ionicHistory, $ionicViewSwitcher, $ionicConfig, $ionicScrollDelegate) {\n\n  var DATA_ELE_IDENTIFIER = '$eleId';\n  var DATA_DESTROY_ELE = '$destroyEle';\n  var DATA_NO_CACHE = '$noCache';\n  var VIEW_STATUS_ACTIVE = 'active';\n  var VIEW_STATUS_CACHED = 'cached';\n\n  var self = this;\n  var direction;\n  var isPrimary = false;\n  var navBarDelegate;\n  var activeEleId;\n  var navViewAttr = $ionicViewSwitcher.navViewAttr;\n  var disableRenderStartViewId, disableAnimation;\n\n  self.scope = $scope;\n  self.element = $element;\n\n  self.init = function() {\n    var navViewName = $attrs.name || '';\n\n    // Find the details of the parent view directive (if any) and use it\n    // to derive our own qualified view name, then hang our own details\n    // off the DOM so child directives can find it.\n    var parent = $element.parent().inheritedData('$uiView');\n    var parentViewName = ((parent && parent.state) ? parent.state.name : '');\n    if (navViewName.indexOf('@') < 0) navViewName = navViewName + '@' + parentViewName;\n\n    var viewData = { name: navViewName, state: null };\n    $element.data('$uiView', viewData);\n\n    var deregisterInstance = $ionicNavViewDelegate._registerInstance(self, $attrs.delegateHandle);\n    $scope.$on('$destroy', function() {\n      deregisterInstance();\n\n      // ensure no scrolls have been left frozen\n      if (self.isSwipeFreeze) {\n        $ionicScrollDelegate.freezeAllScrolls(false);\n      }\n    });\n\n    $scope.$on('$ionicHistory.deselect', self.cacheCleanup);\n    $scope.$on('$ionicTabs.top', onTabsTop);\n    $scope.$on('$ionicSubheader', onBarSubheader);\n\n    $scope.$on('$ionicTabs.beforeLeave', onTabsLeave);\n    $scope.$on('$ionicTabs.afterLeave', onTabsLeave);\n    $scope.$on('$ionicTabs.leave', onTabsLeave);\n\n    ionic.Platform.ready(function() {\n      if (ionic.Platform.isWebView() && $ionicConfig.views.swipeBackEnabled()) {\n        self.initSwipeBack();\n      }\n    });\n\n    return viewData;\n  };\n\n\n  self.register = function(viewLocals) {\n    var leavingView = extend({}, $ionicHistory.currentView());\n\n    // register that a view is coming in and get info on how it should transition\n    var registerData = $ionicHistory.register($scope, viewLocals);\n\n    // update which direction\n    self.update(registerData);\n\n    // begin rendering and transitioning\n    var enteringView = $ionicHistory.getViewById(registerData.viewId) || {};\n\n    var renderStart = (disableRenderStartViewId !== registerData.viewId);\n    self.render(registerData, viewLocals, enteringView, leavingView, renderStart, true);\n  };\n\n\n  self.update = function(registerData) {\n    // always reset that this is the primary navView\n    isPrimary = true;\n\n    // remember what direction this navView should use\n    // this may get updated later by a child navView\n    direction = registerData.direction;\n\n    var parentNavViewCtrl = $element.parent().inheritedData('$ionNavViewController');\n    if (parentNavViewCtrl) {\n      // this navView is nested inside another one\n      // update the parent to use this direction and not\n      // the other it originally was set to\n\n      // inform the parent navView that it is not the primary navView\n      parentNavViewCtrl.isPrimary(false);\n\n      if (direction === 'enter' || direction === 'exit') {\n        // they're entering/exiting a history\n        // find parent navViewController\n        parentNavViewCtrl.direction(direction);\n\n        if (direction === 'enter') {\n          // reset the direction so this navView doesn't animate\n          // because it's parent will\n          direction = 'none';\n        }\n      }\n    }\n  };\n\n\n  self.render = function(registerData, viewLocals, enteringView, leavingView, renderStart, renderEnd) {\n    // register the view and figure out where it lives in the various\n    // histories and nav stacks, along with how views should enter/leave\n    var switcher = $ionicViewSwitcher.create(self, viewLocals, enteringView, leavingView, renderStart, renderEnd);\n\n    // init the rendering of views for this navView directive\n    switcher.init(registerData, function() {\n      // the view is now compiled, in the dom and linked, now lets transition the views.\n      // this uses a callback incase THIS nav-view has a nested nav-view, and after the NESTED\n      // nav-view links, the NESTED nav-view would update which direction THIS nav-view should use\n\n      // kick off the transition of views\n      switcher.transition(self.direction(), registerData.enableBack, !disableAnimation);\n\n      // reset private vars for next time\n      disableRenderStartViewId = disableAnimation = null;\n    });\n\n  };\n\n\n  self.beforeEnter = function(transitionData) {\n    if (isPrimary) {\n      // only update this nav-view's nav-bar if this is the primary nav-view\n      navBarDelegate = transitionData.navBarDelegate;\n      var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n      associatedNavBarCtrl && associatedNavBarCtrl.update(transitionData);\n      navSwipeAttr('');\n    }\n  };\n\n\n  self.activeEleId = function(eleId) {\n    if (arguments.length) {\n      activeEleId = eleId;\n    }\n    return activeEleId;\n  };\n\n\n  self.transitionEnd = function() {\n    var viewElements = $element.children();\n    var x, l, viewElement;\n\n    for (x = 0, l = viewElements.length; x < l; x++) {\n      viewElement = viewElements.eq(x);\n\n      if (viewElement.data(DATA_ELE_IDENTIFIER) === activeEleId) {\n        // this is the active element\n        navViewAttr(viewElement, VIEW_STATUS_ACTIVE);\n\n      } else if (navViewAttr(viewElement) === 'leaving' || navViewAttr(viewElement) === VIEW_STATUS_ACTIVE || navViewAttr(viewElement) === VIEW_STATUS_CACHED) {\n        // this is a leaving element or was the former active element, or is an cached element\n        if (viewElement.data(DATA_DESTROY_ELE) || viewElement.data(DATA_NO_CACHE)) {\n          // this element shouldn't stay cached\n          $ionicViewSwitcher.destroyViewEle(viewElement);\n\n        } else {\n          // keep in the DOM, mark as cached\n          navViewAttr(viewElement, VIEW_STATUS_CACHED);\n\n          // disconnect the leaving scope\n          ionic.Utils.disconnectScope(viewElement.scope());\n        }\n      }\n    }\n\n    navSwipeAttr('');\n\n    // ensure no scrolls have been left frozen\n    if (self.isSwipeFreeze) {\n      $ionicScrollDelegate.freezeAllScrolls(false);\n    }\n  };\n\n\n  function onTabsLeave(ev, data) {\n    var viewElements = $element.children();\n    var viewElement, viewScope;\n\n    for (var x = 0, l = viewElements.length; x < l; x++) {\n      viewElement = viewElements.eq(x);\n      if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {\n        viewScope = viewElement.scope();\n        viewScope && viewScope.$emit(ev.name.replace('Tabs', 'View'), data);\n        break;\n      }\n    }\n  }\n\n\n  self.cacheCleanup = function() {\n    var viewElements = $element.children();\n    for (var x = 0, l = viewElements.length; x < l; x++) {\n      if (viewElements.eq(x).data(DATA_DESTROY_ELE)) {\n        $ionicViewSwitcher.destroyViewEle(viewElements.eq(x));\n      }\n    }\n  };\n\n\n  self.clearCache = function(stateIds) {\n    var viewElements = $element.children();\n    var viewElement, viewScope, x, l, y, eleIdentifier;\n\n    for (x = 0, l = viewElements.length; x < l; x++) {\n      viewElement = viewElements.eq(x);\n\n      if (stateIds) {\n        eleIdentifier = viewElement.data(DATA_ELE_IDENTIFIER);\n\n        for (y = 0; y < stateIds.length; y++) {\n          if (eleIdentifier === stateIds[y]) {\n            $ionicViewSwitcher.destroyViewEle(viewElement);\n          }\n        }\n        continue;\n      }\n\n      if (navViewAttr(viewElement) == VIEW_STATUS_CACHED) {\n        $ionicViewSwitcher.destroyViewEle(viewElement);\n\n      } else if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {\n        viewScope = viewElement.scope();\n        viewScope && viewScope.$broadcast('$ionicView.clearCache');\n      }\n\n    }\n  };\n\n\n  self.getViewElements = function() {\n    return $element.children();\n  };\n\n\n  self.appendViewElement = function(viewEle, viewLocals) {\n    // compile the entering element and get the link function\n    var linkFn = $compile(viewEle);\n\n    $element.append(viewEle);\n\n    var viewScope = $scope.$new();\n\n    if (viewLocals && viewLocals.$$controller) {\n      viewLocals.$scope = viewScope;\n      var controller = $controller(viewLocals.$$controller, viewLocals);\n      $element.children().data('$ngControllerController', controller);\n    }\n\n    linkFn(viewScope);\n\n    return viewScope;\n  };\n\n\n  self.title = function(val) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.title(val);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavView#enableBackButton\n   * @description Enable/disable if the back button can be shown or not. For\n   * example, the very first view in the navigation stack would not have a\n   * back view, so the back button would be disabled.\n   */\n  self.enableBackButton = function(shouldEnable) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.enableBackButton(shouldEnable);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavView#showBackButton\n   * @description Show/hide the nav bar active back button. If the back button\n   * is not possible this will not force the back button to show. The\n   * `enableBackButton()` method handles if a back button is even possible or not.\n   */\n  self.showBackButton = function(shouldShow) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    if (associatedNavBarCtrl) {\n      if (arguments.length) {\n        return associatedNavBarCtrl.showActiveBackButton(shouldShow);\n      }\n      return associatedNavBarCtrl.showActiveBackButton();\n    }\n    return true;\n  };\n\n\n  self.showBar = function(val) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    if (associatedNavBarCtrl) {\n      if (arguments.length) {\n        return associatedNavBarCtrl.showBar(val);\n      }\n      return associatedNavBarCtrl.showBar();\n    }\n    return true;\n  };\n\n\n  self.isPrimary = function(val) {\n    if (arguments.length) {\n      isPrimary = val;\n    }\n    return isPrimary;\n  };\n\n\n  self.direction = function(val) {\n    if (arguments.length) {\n      direction = val;\n    }\n    return direction;\n  };\n\n\n  self.initSwipeBack = function() {\n    var swipeBackHitWidth = $ionicConfig.views.swipeBackHitWidth();\n    var viewTransition, associatedNavBarCtrl, backView;\n    var deregDragStart, deregDrag, deregRelease;\n    var windowWidth, startDragX, dragPoints;\n    var cancelData = {};\n\n    function onDragStart(ev) {\n      if (!isPrimary) return;\n\n      startDragX = getDragX(ev);\n      if (startDragX > swipeBackHitWidth) return;\n\n      backView = $ionicHistory.backView();\n\n      var currentView = $ionicHistory.currentView();\n\n      if (!backView || backView.historyId !== currentView.historyId || currentView.canSwipeBack === false) return;\n\n      if (!windowWidth) windowWidth = window.innerWidth;\n\n      self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(true);\n\n      var registerData = {\n        direction: 'back'\n      };\n\n      dragPoints = [];\n\n      cancelData = {\n        showBar: self.showBar(),\n        showBackButton: self.showBackButton()\n      };\n\n      var switcher = $ionicViewSwitcher.create(self, registerData, backView, currentView, true, false);\n      switcher.loadViewElements(registerData);\n      switcher.render(registerData);\n\n      viewTransition = switcher.transition('back', $ionicHistory.enabledBack(backView), true);\n\n      associatedNavBarCtrl = getAssociatedNavBarCtrl();\n\n      deregDrag = ionic.onGesture('drag', onDrag, $element[0]);\n      deregRelease = ionic.onGesture('release', onRelease, $element[0]);\n    }\n\n    function onDrag(ev) {\n      if (isPrimary && viewTransition) {\n        var dragX = getDragX(ev);\n\n        dragPoints.push({\n          t: Date.now(),\n          x: dragX\n        });\n\n        if (dragX >= windowWidth - 15) {\n          onRelease(ev);\n\n        } else {\n          var step = Math.min(Math.max(getSwipeCompletion(dragX), 0), 1);\n          viewTransition.run(step);\n          associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.run(step);\n        }\n\n      }\n    }\n\n    function onRelease(ev) {\n      if (isPrimary && viewTransition && dragPoints && dragPoints.length > 1) {\n\n        var now = Date.now();\n        var releaseX = getDragX(ev);\n        var startDrag = dragPoints[dragPoints.length - 1];\n\n        for (var x = dragPoints.length - 2; x >= 0; x--) {\n          if (now - startDrag.t > 200) {\n            break;\n          }\n          startDrag = dragPoints[x];\n        }\n\n        var isSwipingRight = (releaseX >= dragPoints[dragPoints.length - 2].x);\n        var releaseSwipeCompletion = getSwipeCompletion(releaseX);\n        var velocity = Math.abs(startDrag.x - releaseX) / (now - startDrag.t);\n\n        // private variables because ui-router has no way to pass custom data using $state.go\n        disableRenderStartViewId = backView.viewId;\n        disableAnimation = (releaseSwipeCompletion < 0.03 || releaseSwipeCompletion > 0.97);\n\n        if (isSwipingRight && (releaseSwipeCompletion > 0.5 || velocity > 0.1)) {\n          // complete view transition on release\n          var speed = (velocity > 0.5 || velocity < 0.05 || releaseX > windowWidth - 45) ? 'fast' : 'slow';\n          navSwipeAttr(disableAnimation ? '' : speed);\n          backView.go();\n          associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.complete(!disableAnimation, speed);\n\n        } else {\n          // cancel view transition on release\n          navSwipeAttr(disableAnimation ? '' : 'fast');\n          disableRenderStartViewId = null;\n          viewTransition.cancel(!disableAnimation);\n          associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.cancel(!disableAnimation, 'fast', cancelData);\n          disableAnimation = null;\n        }\n\n      }\n\n      ionic.offGesture(deregDrag, 'drag', onDrag);\n      ionic.offGesture(deregRelease, 'release', onRelease);\n\n      windowWidth = viewTransition = dragPoints = null;\n\n      self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(false);\n    }\n\n    function getDragX(ev) {\n      return ionic.tap.pointerCoord(ev.gesture.srcEvent).x;\n    }\n\n    function getSwipeCompletion(dragX) {\n      return (dragX - startDragX) / windowWidth;\n    }\n\n    deregDragStart = ionic.onGesture('dragstart', onDragStart, $element[0]);\n\n    $scope.$on('$destroy', function() {\n      ionic.offGesture(deregDragStart, 'dragstart', onDragStart);\n      ionic.offGesture(deregDrag, 'drag', onDrag);\n      ionic.offGesture(deregRelease, 'release', onRelease);\n      self.element = viewTransition = associatedNavBarCtrl = null;\n    });\n  };\n\n\n  function navSwipeAttr(val) {\n    ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);\n  }\n\n\n  function onTabsTop(ev, isTabsTop) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.hasTabsTop(isTabsTop);\n  }\n\n  function onBarSubheader(ev, isBarSubheader) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.hasBarSubheader(isBarSubheader);\n  }\n\n  function getAssociatedNavBarCtrl() {\n    if (navBarDelegate) {\n      for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {\n        if ($ionicNavBarDelegate._instances[x].$$delegateHandle == navBarDelegate) {\n          return $ionicNavBarDelegate._instances[x];\n        }\n      }\n    }\n    return $element.inheritedData('$ionNavBarController');\n  }\n\n}]);\n\nIonicModule\n.controller('$ionicRefresher', [\n  '$scope',\n  '$attrs',\n  '$element',\n  '$ionicBind',\n  '$timeout',\n  function($scope, $attrs, $element, $ionicBind, $timeout) {\n    var self = this,\n        isDragging = false,\n        isOverscrolling = false,\n        dragOffset = 0,\n        lastOverscroll = 0,\n        ptrThreshold = 60,\n        activated = false,\n        scrollTime = 500,\n        startY = null,\n        deltaY = null,\n        canOverscroll = true,\n        scrollParent,\n        scrollChild;\n\n    if (!isDefined($attrs.pullingIcon)) {\n      $attrs.$set('pullingIcon', 'ion-android-arrow-down');\n    }\n\n    $scope.showSpinner = !isDefined($attrs.refreshingIcon) && $attrs.spinner != 'none';\n\n    $scope.showIcon = isDefined($attrs.refreshingIcon);\n\n    $ionicBind($scope, $attrs, {\n      pullingIcon: '@',\n      pullingText: '@',\n      refreshingIcon: '@',\n      refreshingText: '@',\n      spinner: '@',\n      disablePullingRotation: '@',\n      $onRefresh: '&onRefresh',\n      $onPulling: '&onPulling'\n    });\n\n    function handleTouchend() {\n      // if this wasn't an overscroll, get out immediately\n      if (!canOverscroll && !isDragging) {\n        return;\n      }\n      // reset Y\n      startY = null;\n      // the user has overscrolled but went back to native scrolling\n      if (!isDragging) {\n        dragOffset = 0;\n        isOverscrolling = false;\n        setScrollLock(false);\n      } else {\n        isDragging = false;\n        dragOffset = 0;\n\n        // the user has scroll far enough to trigger a refresh\n        if (lastOverscroll > ptrThreshold) {\n          start();\n          scrollTo(ptrThreshold, scrollTime);\n\n        // the user has overscrolled but not far enough to trigger a refresh\n        } else {\n          scrollTo(0, scrollTime, deactivate);\n          isOverscrolling = false;\n        }\n      }\n    }\n\n    function handleTouchmove(e) {\n      // if multitouch or regular scroll event, get out immediately\n      if (!canOverscroll || e.touches.length > 1) {\n        return;\n      }\n      //if this is a new drag, keep track of where we start\n      if (startY === null) {\n        startY = parseInt(e.touches[0].screenY, 10);\n      }\n\n      // kitkat fix for touchcancel events http://updates.html5rocks.com/2014/05/A-More-Compatible-Smoother-Touch\n      if (ionic.Platform.isAndroid() && ionic.Platform.version() === 4.4 && scrollParent.scrollTop === 0) {\n        isDragging = true;\n        e.preventDefault();\n      }\n\n      // how far have we dragged so far?\n      deltaY = parseInt(e.touches[0].screenY, 10) - startY;\n\n      // if we've dragged up and back down in to native scroll territory\n      if (deltaY - dragOffset <= 0 || scrollParent.scrollTop !== 0) {\n\n        if (isOverscrolling) {\n          isOverscrolling = false;\n          setScrollLock(false);\n        }\n\n        if (isDragging) {\n          nativescroll(scrollParent, parseInt(deltaY - dragOffset, 10) * -1);\n        }\n\n        // if we're not at overscroll 0 yet, 0 out\n        if (lastOverscroll !== 0) {\n          overscroll(0);\n        }\n        return;\n\n      } else if (deltaY > 0 && scrollParent.scrollTop === 0 && !isOverscrolling) {\n        // starting overscroll, but drag started below scrollTop 0, so we need to offset the position\n        dragOffset = deltaY;\n      }\n\n      // prevent native scroll events while overscrolling\n      e.preventDefault();\n\n      // if not overscrolling yet, initiate overscrolling\n      if (!isOverscrolling) {\n        isOverscrolling = true;\n        setScrollLock(true);\n      }\n\n      isDragging = true;\n      // overscroll according to the user's drag so far\n      overscroll(parseInt((deltaY - dragOffset) / 3, 10));\n\n      // update the icon accordingly\n      if (!activated && lastOverscroll > ptrThreshold) {\n        activated = true;\n        ionic.requestAnimationFrame(activate);\n\n      } else if (activated && lastOverscroll < ptrThreshold) {\n        activated = false;\n        ionic.requestAnimationFrame(deactivate);\n      }\n    }\n\n    function handleScroll(e) {\n      // canOverscrol is used to greatly simplify the drag handler during normal scrolling\n      canOverscroll = (e.target.scrollTop === 0) || isDragging;\n    }\n\n    function overscroll(val) {\n      scrollChild.style[ionic.CSS.TRANSFORM] = 'translateY(' + val + 'px)';\n      lastOverscroll = val;\n    }\n\n    function nativescroll(target, newScrollTop) {\n      // creates a scroll event that bubbles, can be cancelled, and with its view\n      // and detail property initialized to window and 1, respectively\n      target.scrollTop = newScrollTop;\n      var e = document.createEvent(\"UIEvents\");\n      e.initUIEvent(\"scroll\", true, true, window, 1);\n      target.dispatchEvent(e);\n    }\n\n    function setScrollLock(enabled) {\n      // set the scrollbar to be position:fixed in preparation to overscroll\n      // or remove it so the app can be natively scrolled\n      if (enabled) {\n        ionic.requestAnimationFrame(function() {\n          scrollChild.classList.add('overscroll');\n          show();\n        });\n\n      } else {\n        ionic.requestAnimationFrame(function() {\n          scrollChild.classList.remove('overscroll');\n          hide();\n          deactivate();\n        });\n      }\n    }\n\n    $scope.$on('scroll.refreshComplete', function() {\n      // prevent the complete from firing before the scroll has started\n      $timeout(function() {\n\n        ionic.requestAnimationFrame(tail);\n\n        // scroll back to home during tail animation\n        scrollTo(0, scrollTime, deactivate);\n\n        // return to native scrolling after tail animation has time to finish\n        $timeout(function() {\n\n          if (isOverscrolling) {\n            isOverscrolling = false;\n            setScrollLock(false);\n          }\n\n        }, scrollTime);\n\n      }, scrollTime);\n    });\n\n    function scrollTo(Y, duration, callback) {\n      // scroll animation loop w/ easing\n      // credit https://gist.github.com/dezinezync/5487119\n      var start = Date.now(),\n          from = lastOverscroll;\n\n      if (from === Y) {\n        callback();\n        return; /* Prevent scrolling to the Y point if already there */\n      }\n\n      // decelerating to zero velocity\n      function easeOutCubic(t) {\n        return (--t) * t * t + 1;\n      }\n\n      // scroll loop\n      function scroll() {\n        var currentTime = Date.now(),\n          time = Math.min(1, ((currentTime - start) / duration)),\n          // where .5 would be 50% of time on a linear scale easedT gives a\n          // fraction based on the easing method\n          easedT = easeOutCubic(time);\n\n        overscroll(parseInt((easedT * (Y - from)) + from, 10));\n\n        if (time < 1) {\n          ionic.requestAnimationFrame(scroll);\n\n        } else {\n\n          if (Y < 5 && Y > -5) {\n            isOverscrolling = false;\n            setScrollLock(false);\n          }\n\n          callback && callback();\n        }\n      }\n\n      // start scroll loop\n      ionic.requestAnimationFrame(scroll);\n    }\n\n\n    self.init = function() {\n      scrollParent = $element.parent().parent()[0];\n      scrollChild = $element.parent()[0];\n\n      if (!scrollParent || !scrollParent.classList.contains('ionic-scroll') ||\n        !scrollChild || !scrollChild.classList.contains('scroll')) {\n        throw new Error('Refresher must be immediate child of ion-content or ion-scroll');\n      }\n\n      ionic.on('touchmove', handleTouchmove, scrollChild);\n      ionic.on('touchend', handleTouchend, scrollChild);\n      ionic.on('scroll', handleScroll, scrollParent);\n\n      // cleanup when done\n      $scope.$on('$destroy', destroy);\n    };\n\n    function destroy() {\n      ionic.off('touchmove', handleTouchmove, scrollChild);\n      ionic.off('touchend', handleTouchend, scrollChild);\n      ionic.off('scroll', handleScroll, scrollParent);\n      scrollParent = null;\n      scrollChild = null;\n    }\n\n    // DOM manipulation and broadcast methods shared by JS and Native Scrolling\n    // getter used by JS Scrolling\n    self.getRefresherDomMethods = function() {\n      return {\n        activate: activate,\n        deactivate: deactivate,\n        start: start,\n        show: show,\n        hide: hide,\n        tail: tail\n      };\n    };\n\n    function activate() {\n      $element[0].classList.add('active');\n      $scope.$onPulling();\n    }\n\n    function deactivate() {\n      // give tail 150ms to finish\n      $timeout(function() {\n        // deactivateCallback\n        $element.removeClass('active refreshing refreshing-tail');\n        if (activated) activated = false;\n      }, 150);\n    }\n\n    function start() {\n      // startCallback\n      $element[0].classList.add('refreshing');\n      $scope.$onRefresh();\n    }\n\n    function show() {\n      // showCallback\n      $element[0].classList.remove('invisible');\n    }\n\n    function hide() {\n      // showCallback\n      $element[0].classList.add('invisible');\n    }\n\n    function tail() {\n      // tailCallback\n      $element[0].classList.add('refreshing-tail');\n    }\n\n    // for testing\n    self.__handleTouchmove = handleTouchmove;\n    self.__getScrollChild = function() { return scrollChild; };\n    self.__getScrollParent = function() { return scrollParent; };\n  }\n]);\n\n/**\n * @private\n */\nIonicModule\n\n.controller('$ionicScroll', [\n  '$scope',\n  'scrollViewOptions',\n  '$timeout',\n  '$window',\n  '$location',\n  '$document',\n  '$ionicScrollDelegate',\n  '$ionicHistory',\nfunction($scope,\n         scrollViewOptions,\n         $timeout,\n         $window,\n         $location,\n         $document,\n         $ionicScrollDelegate,\n         $ionicHistory) {\n\n  var self = this;\n  // for testing\n  self.__timeout = $timeout;\n\n  self._scrollViewOptions = scrollViewOptions; //for testing\n  self.isNative = function() {\n    return !!scrollViewOptions.nativeScrolling;\n  };\n\n  var element = self.element = scrollViewOptions.el;\n  var $element = self.$element = jqLite(element);\n  var scrollView;\n  if (self.isNative()) {\n    scrollView = self.scrollView = new ionic.views.ScrollNative(scrollViewOptions);\n  } else {\n    scrollView = self.scrollView = new ionic.views.Scroll(scrollViewOptions);\n  }\n\n\n  //Attach self to element as a controller so other directives can require this controller\n  //through `require: '$ionicScroll'\n  //Also attach to parent so that sibling elements can require this\n  ($element.parent().length ? $element.parent() : $element)\n    .data('$$ionicScrollController', self);\n\n  var deregisterInstance = $ionicScrollDelegate._registerInstance(\n    self, scrollViewOptions.delegateHandle, function() {\n      return $ionicHistory.isActiveScope($scope);\n    }\n  );\n\n  if (!isDefined(scrollViewOptions.bouncing)) {\n    ionic.Platform.ready(function() {\n      if (scrollView.options) {\n        scrollView.options.bouncing = true;\n        if (ionic.Platform.isAndroid()) {\n          // No bouncing by default on Android\n          scrollView.options.bouncing = false;\n          // Faster scroll decel\n          scrollView.options.deceleration = 0.95;\n        }\n      }\n    });\n  }\n\n  var resize = angular.bind(scrollView, scrollView.resize);\n  angular.element($window).on('resize', resize);\n\n  var scrollFunc = function(e) {\n    var detail = (e.originalEvent || e).detail || {};\n    $scope.$onScroll && $scope.$onScroll({\n      event: e,\n      scrollTop: detail.scrollTop || 0,\n      scrollLeft: detail.scrollLeft || 0\n    });\n  };\n\n  $element.on('scroll', scrollFunc);\n\n  $scope.$on('$destroy', function() {\n    deregisterInstance();\n    scrollView && scrollView.__cleanup && scrollView.__cleanup();\n    angular.element($window).off('resize', resize);\n    $element.off('scroll', scrollFunc);\n    scrollView = self.scrollView = scrollViewOptions = self._scrollViewOptions = scrollViewOptions.el = self._scrollViewOptions.el = $element = self.$element = element = null;\n  });\n\n  $timeout(function() {\n    scrollView && scrollView.run && scrollView.run();\n  });\n\n  self.getScrollView = function() {\n    return scrollView;\n  };\n\n  self.getScrollPosition = function() {\n    return scrollView.getValues();\n  };\n\n  self.resize = function() {\n    return $timeout(resize, 0, false).then(function() {\n      $element && $element.triggerHandler('scroll-resize');\n    });\n  };\n\n  self.scrollTop = function(shouldAnimate) {\n    self.resize().then(function() {\n      scrollView.scrollTo(0, 0, !!shouldAnimate);\n    });\n  };\n\n  self.scrollBottom = function(shouldAnimate) {\n    self.resize().then(function() {\n      var max = scrollView.getScrollMax();\n      scrollView.scrollTo(max.left, max.top, !!shouldAnimate);\n    });\n  };\n\n  self.scrollTo = function(left, top, shouldAnimate) {\n    self.resize().then(function() {\n      scrollView.scrollTo(left, top, !!shouldAnimate);\n    });\n  };\n\n  self.zoomTo = function(zoom, shouldAnimate, originLeft, originTop) {\n    self.resize().then(function() {\n      scrollView.zoomTo(zoom, !!shouldAnimate, originLeft, originTop);\n    });\n  };\n\n  self.zoomBy = function(zoom, shouldAnimate, originLeft, originTop) {\n    self.resize().then(function() {\n      scrollView.zoomBy(zoom, !!shouldAnimate, originLeft, originTop);\n    });\n  };\n\n  self.scrollBy = function(left, top, shouldAnimate) {\n    self.resize().then(function() {\n      scrollView.scrollBy(left, top, !!shouldAnimate);\n    });\n  };\n\n  self.anchorScroll = function(shouldAnimate) {\n    self.resize().then(function() {\n      var hash = $location.hash();\n      var elm = hash && $document[0].getElementById(hash);\n      if (!(hash && elm)) {\n        scrollView.scrollTo(0, 0, !!shouldAnimate);\n        return;\n      }\n      var curElm = elm;\n      var scrollLeft = 0, scrollTop = 0;\n      do {\n        if (curElm !== null) scrollLeft += curElm.offsetLeft;\n        if (curElm !== null) scrollTop += curElm.offsetTop;\n        curElm = curElm.offsetParent;\n      } while (curElm.attributes != self.element.attributes && curElm.offsetParent);\n      scrollView.scrollTo(scrollLeft, scrollTop, !!shouldAnimate);\n    });\n  };\n\n  self.freezeScroll = scrollView.freeze;\n\n  self.freezeAllScrolls = function(shouldFreeze) {\n    for (var i = 0; i < $ionicScrollDelegate._instances.length; i++) {\n      $ionicScrollDelegate._instances[i].freezeScroll(shouldFreeze);\n    }\n  };\n\n\n  /**\n   * @private\n   */\n  self._setRefresher = function(refresherScope, refresherElement, refresherMethods) {\n    self.refresher = refresherElement;\n    var refresherHeight = self.refresher.clientHeight || 60;\n    scrollView.activatePullToRefresh(\n      refresherHeight,\n      refresherMethods\n    );\n  };\n\n}]);\n\nIonicModule\n.controller('$ionicSideMenus', [\n  '$scope',\n  '$attrs',\n  '$ionicSideMenuDelegate',\n  '$ionicPlatform',\n  '$ionicBody',\n  '$ionicHistory',\n  '$ionicScrollDelegate',\n  'IONIC_BACK_PRIORITY',\nfunction($scope, $attrs, $ionicSideMenuDelegate, $ionicPlatform, $ionicBody, $ionicHistory, $ionicScrollDelegate, IONIC_BACK_PRIORITY) {\n  var self = this;\n  var rightShowing, leftShowing, isDragging;\n  var startX, lastX, offsetX, isAsideExposed;\n  var enableMenuWithBackViews = true;\n\n  self.$scope = $scope;\n\n  self.initialize = function(options) {\n    self.left = options.left;\n    self.right = options.right;\n    self.setContent(options.content);\n    self.dragThresholdX = options.dragThresholdX || 10;\n    $ionicHistory.registerHistory(self.$scope);\n  };\n\n  /**\n   * Set the content view controller if not passed in the constructor options.\n   *\n   * @param {object} content\n   */\n  self.setContent = function(content) {\n    if (content) {\n      self.content = content;\n\n      self.content.onDrag = function(e) {\n        self._handleDrag(e);\n      };\n\n      self.content.endDrag = function(e) {\n        self._endDrag(e);\n      };\n    }\n  };\n\n  self.isOpenLeft = function() {\n    return self.getOpenAmount() > 0;\n  };\n\n  self.isOpenRight = function() {\n    return self.getOpenAmount() < 0;\n  };\n\n  /**\n   * Toggle the left menu to open 100%\n   */\n  self.toggleLeft = function(shouldOpen) {\n    if (isAsideExposed || !self.left.isEnabled) return;\n    var openAmount = self.getOpenAmount();\n    if (arguments.length === 0) {\n      shouldOpen = openAmount <= 0;\n    }\n    self.content.enableAnimation();\n    if (!shouldOpen) {\n      self.openPercentage(0);\n    } else {\n      self.openPercentage(100);\n    }\n  };\n\n  /**\n   * Toggle the right menu to open 100%\n   */\n  self.toggleRight = function(shouldOpen) {\n    if (isAsideExposed || !self.right.isEnabled) return;\n    var openAmount = self.getOpenAmount();\n    if (arguments.length === 0) {\n      shouldOpen = openAmount >= 0;\n    }\n    self.content.enableAnimation();\n    if (!shouldOpen) {\n      self.openPercentage(0);\n    } else {\n      self.openPercentage(-100);\n    }\n  };\n\n  self.toggle = function(side) {\n    if (side == 'right') {\n      self.toggleRight();\n    } else {\n      self.toggleLeft();\n    }\n  };\n\n  /**\n   * Close all menus.\n   */\n  self.close = function() {\n    self.openPercentage(0);\n  };\n\n  /**\n   * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative)\n   */\n  self.getOpenAmount = function() {\n    return self.content && self.content.getTranslateX() || 0;\n  };\n\n  /**\n   * @return {float} The ratio of open amount over menu width. For example, a\n   * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative\n   * for right menu.\n   */\n  self.getOpenRatio = function() {\n    var amount = self.getOpenAmount();\n    if (amount >= 0) {\n      return amount / self.left.width;\n    }\n    return amount / self.right.width;\n  };\n\n  self.isOpen = function() {\n    return self.getOpenAmount() !== 0;\n  };\n\n  /**\n   * @return {float} The percentage of open amount over menu width. For example, a\n   * menu of width 100 open 50 pixels would be open 50%. Value is negative\n   * for right menu.\n   */\n  self.getOpenPercentage = function() {\n    return self.getOpenRatio() * 100;\n  };\n\n  /**\n   * Open the menu with a given percentage amount.\n   * @param {float} percentage The percentage (positive or negative for left/right) to open the menu.\n   */\n  self.openPercentage = function(percentage) {\n    var p = percentage / 100;\n\n    if (self.left && percentage >= 0) {\n      self.openAmount(self.left.width * p);\n    } else if (self.right && percentage < 0) {\n      self.openAmount(self.right.width * p);\n    }\n\n    // add the CSS class \"menu-open\" if the percentage does not\n    // equal 0, otherwise remove the class from the body element\n    $ionicBody.enableClass((percentage !== 0), 'menu-open');\n\n    freezeAllScrolls(false);\n  };\n\n  function freezeAllScrolls(shouldFreeze) {\n    if (shouldFreeze && !self.isScrollFreeze) {\n      $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);\n\n    } else if (!shouldFreeze && self.isScrollFreeze) {\n      $ionicScrollDelegate.freezeAllScrolls(false);\n    }\n    self.isScrollFreeze = shouldFreeze;\n  }\n\n  /**\n   * Open the menu the given pixel amount.\n   * @param {float} amount the pixel amount to open the menu. Positive value for left menu,\n   * negative value for right menu (only one menu will be visible at a time).\n   */\n  self.openAmount = function(amount) {\n    var maxLeft = self.left && self.left.width || 0;\n    var maxRight = self.right && self.right.width || 0;\n\n    // Check if we can move to that side, depending if the left/right panel is enabled\n    if (!(self.left && self.left.isEnabled) && amount > 0) {\n      self.content.setTranslateX(0);\n      return;\n    }\n\n    if (!(self.right && self.right.isEnabled) && amount < 0) {\n      self.content.setTranslateX(0);\n      return;\n    }\n\n    if (leftShowing && amount > maxLeft) {\n      self.content.setTranslateX(maxLeft);\n      return;\n    }\n\n    if (rightShowing && amount < -maxRight) {\n      self.content.setTranslateX(-maxRight);\n      return;\n    }\n\n    self.content.setTranslateX(amount);\n\n    if (amount >= 0) {\n      leftShowing = true;\n      rightShowing = false;\n\n      if (amount > 0) {\n        // Push the z-index of the right menu down\n        self.right && self.right.pushDown && self.right.pushDown();\n        // Bring the z-index of the left menu up\n        self.left && self.left.bringUp && self.left.bringUp();\n      }\n    } else {\n      rightShowing = true;\n      leftShowing = false;\n\n      // Bring the z-index of the right menu up\n      self.right && self.right.bringUp && self.right.bringUp();\n      // Push the z-index of the left menu down\n      self.left && self.left.pushDown && self.left.pushDown();\n    }\n  };\n\n  /**\n   * Given an event object, find the final resting position of this side\n   * menu. For example, if the user \"throws\" the content to the right and\n   * releases the touch, the left menu should snap open (animated, of course).\n   *\n   * @param {Event} e the gesture event to use for snapping\n   */\n  self.snapToRest = function(e) {\n    // We want to animate at the end of this\n    self.content.enableAnimation();\n    isDragging = false;\n\n    // Check how much the panel is open after the drag, and\n    // what the drag velocity is\n    var ratio = self.getOpenRatio();\n\n    if (ratio === 0) {\n      // Just to be safe\n      self.openPercentage(0);\n      return;\n    }\n\n    var velocityThreshold = 0.3;\n    var velocityX = e.gesture.velocityX;\n    var direction = e.gesture.direction;\n\n    // Going right, less than half, too slow (snap back)\n    if (ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {\n      self.openPercentage(0);\n    }\n\n    // Going left, more than half, too slow (snap back)\n    else if (ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) {\n      self.openPercentage(100);\n    }\n\n    // Going left, less than half, too slow (snap back)\n    else if (ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) {\n      self.openPercentage(0);\n    }\n\n    // Going right, more than half, too slow (snap back)\n    else if (ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {\n      self.openPercentage(-100);\n    }\n\n    // Going right, more than half, or quickly (snap open)\n    else if (direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) {\n      self.openPercentage(100);\n    }\n\n    // Going left, more than half, or quickly (span open)\n    else if (direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) {\n      self.openPercentage(-100);\n    }\n\n    // Snap back for safety\n    else {\n      self.openPercentage(0);\n    }\n  };\n\n  self.enableMenuWithBackViews = function(val) {\n    if (arguments.length) {\n      enableMenuWithBackViews = !!val;\n    }\n    return enableMenuWithBackViews;\n  };\n\n  self.isAsideExposed = function() {\n    return !!isAsideExposed;\n  };\n\n  self.exposeAside = function(shouldExposeAside) {\n    if (!(self.left && self.left.isEnabled) && !(self.right && self.right.isEnabled)) return;\n    self.close();\n\n    isAsideExposed = shouldExposeAside;\n    if (self.left && self.left.isEnabled) {\n      // set the left marget width if it should be exposed\n      // otherwise set false so there's no left margin\n      self.content.setMarginLeft(isAsideExposed ? self.left.width : 0);\n    } else if (self.right && self.right.isEnabled) {\n      self.content.setMarginRight(isAsideExposed ? self.right.width : 0);\n    }\n\n    self.$scope.$emit('$ionicExposeAside', isAsideExposed);\n  };\n\n  self.activeAsideResizing = function(isResizing) {\n    $ionicBody.enableClass(isResizing, 'aside-resizing');\n  };\n\n  // End a drag with the given event\n  self._endDrag = function(e) {\n    freezeAllScrolls(false);\n\n    if (isAsideExposed) return;\n\n    if (isDragging) {\n      self.snapToRest(e);\n    }\n    startX = null;\n    lastX = null;\n    offsetX = null;\n  };\n\n  // Handle a drag event\n  self._handleDrag = function(e) {\n    if (isAsideExposed || !$scope.dragContent) return;\n\n    // If we don't have start coords, grab and store them\n    if (!startX) {\n      startX = e.gesture.touches[0].pageX;\n      lastX = startX;\n    } else {\n      // Grab the current tap coords\n      lastX = e.gesture.touches[0].pageX;\n    }\n\n    // Calculate difference from the tap points\n    if (!isDragging && Math.abs(lastX - startX) > self.dragThresholdX) {\n      // if the difference is greater than threshold, start dragging using the current\n      // point as the starting point\n      startX = lastX;\n\n      isDragging = true;\n      // Initialize dragging\n      self.content.disableAnimation();\n      offsetX = self.getOpenAmount();\n    }\n\n    if (isDragging) {\n      self.openAmount(offsetX + (lastX - startX));\n      freezeAllScrolls(true);\n    }\n  };\n\n  self.canDragContent = function(canDrag) {\n    if (arguments.length) {\n      $scope.dragContent = !!canDrag;\n    }\n    return $scope.dragContent;\n  };\n\n  self.edgeThreshold = 25;\n  self.edgeThresholdEnabled = false;\n  self.edgeDragThreshold = function(value) {\n    if (arguments.length) {\n      if (isNumber(value) && value > 0) {\n        self.edgeThreshold = value;\n        self.edgeThresholdEnabled = true;\n      } else {\n        self.edgeThresholdEnabled = !!value;\n      }\n    }\n    return self.edgeThresholdEnabled;\n  };\n\n  self.isDraggableTarget = function(e) {\n    //Only restrict edge when sidemenu is closed and restriction is enabled\n    var shouldOnlyAllowEdgeDrag = self.edgeThresholdEnabled && !self.isOpen();\n    var startX = e.gesture.startEvent && e.gesture.startEvent.center &&\n      e.gesture.startEvent.center.pageX;\n\n    var dragIsWithinBounds = !shouldOnlyAllowEdgeDrag ||\n      startX <= self.edgeThreshold ||\n      startX >= self.content.element.offsetWidth - self.edgeThreshold;\n\n    var backView = $ionicHistory.backView();\n    var menuEnabled = enableMenuWithBackViews ? true : !backView;\n    if (!menuEnabled) {\n      var currentView = $ionicHistory.currentView() || {};\n      return backView.historyId !== currentView.historyId;\n    }\n\n    return ($scope.dragContent || self.isOpen()) &&\n      dragIsWithinBounds &&\n      !e.gesture.srcEvent.defaultPrevented &&\n      menuEnabled &&\n      !e.target.tagName.match(/input|textarea|select|object|embed/i) &&\n      !e.target.isContentEditable &&\n      !(e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll') == 'true');\n  };\n\n  $scope.sideMenuContentTranslateX = 0;\n\n  var deregisterBackButtonAction = noop;\n  var closeSideMenu = angular.bind(self, self.close);\n\n  $scope.$watch(function() {\n    return self.getOpenAmount() !== 0;\n  }, function(isOpen) {\n    deregisterBackButtonAction();\n    if (isOpen) {\n      deregisterBackButtonAction = $ionicPlatform.registerBackButtonAction(\n        closeSideMenu,\n        IONIC_BACK_PRIORITY.sideMenu\n      );\n    }\n  });\n\n  var deregisterInstance = $ionicSideMenuDelegate._registerInstance(\n    self, $attrs.delegateHandle, function() {\n      return $ionicHistory.isActiveScope($scope);\n    }\n  );\n\n  $scope.$on('$destroy', function() {\n    deregisterInstance();\n    deregisterBackButtonAction();\n    self.$scope = null;\n    if (self.content) {\n      self.content.element = null;\n      self.content = null;\n    }\n\n    // ensure scrolls are unfrozen\n    freezeAllScrolls(false);\n  });\n\n  self.initialize({\n    left: {\n      width: 275\n    },\n    right: {\n      width: 275\n    }\n  });\n\n}]);\n\n(function(ionic) {\n\n  var TRANSLATE32 = 'translate(32,32)';\n  var STROKE_OPACITY = 'stroke-opacity';\n  var ROUND = 'round';\n  var INDEFINITE = 'indefinite';\n  var DURATION = '750ms';\n  var NONE = 'none';\n  var SHORTCUTS = {\n    a: 'animate',\n    an: 'attributeName',\n    at: 'animateTransform',\n    c: 'circle',\n    da: 'stroke-dasharray',\n    os: 'stroke-dashoffset',\n    f: 'fill',\n    lc: 'stroke-linecap',\n    rc: 'repeatCount',\n    sw: 'stroke-width',\n    t: 'transform',\n    v: 'values'\n  };\n\n  var SPIN_ANIMATION = {\n    v: '0,32,32;360,32,32',\n    an: 'transform',\n    type: 'rotate',\n    rc: INDEFINITE,\n    dur: DURATION\n  };\n\n  function createSvgElement(tagName, data, parent, spinnerName) {\n    var ele = document.createElement(SHORTCUTS[tagName] || tagName);\n    var k, x, y;\n\n    for (k in data) {\n\n      if (angular.isArray(data[k])) {\n        for (x = 0; x < data[k].length; x++) {\n          if (data[k][x].fn) {\n            for (y = 0; y < data[k][x].t; y++) {\n              createSvgElement(k, data[k][x].fn(y, spinnerName), ele, spinnerName);\n            }\n          } else {\n            createSvgElement(k, data[k][x], ele, spinnerName);\n          }\n        }\n\n      } else {\n        setSvgAttribute(ele, k, data[k]);\n      }\n    }\n\n    parent.appendChild(ele);\n  }\n\n  function setSvgAttribute(ele, k, v) {\n    ele.setAttribute(SHORTCUTS[k] || k, v);\n  }\n\n  function animationValues(strValues, i) {\n    var values = strValues.split(';');\n    var back = values.slice(i);\n    var front = values.slice(0, values.length - back.length);\n    values = back.concat(front).reverse();\n    return values.join(';') + ';' + values[0];\n  }\n\n  var IOS_SPINNER = {\n    sw: 4,\n    lc: ROUND,\n    line: [{\n      fn: function(i, spinnerName) {\n        return {\n          y1: spinnerName == 'ios' ? 17 : 12,\n          y2: spinnerName == 'ios' ? 29 : 20,\n          t: TRANSLATE32 + ' rotate(' + (30 * i + (i < 6 ? 180 : -180)) + ')',\n          a: [{\n            fn: function() {\n              return {\n                an: STROKE_OPACITY,\n                dur: DURATION,\n                v: animationValues('0;.1;.15;.25;.35;.45;.55;.65;.7;.85;1', i),\n                rc: INDEFINITE\n              };\n            },\n            t: 1\n          }]\n        };\n      },\n      t: 12\n    }]\n  };\n\n  var spinners = {\n\n    android: {\n      c: [{\n        sw: 6,\n        da: 128,\n        os: 82,\n        r: 26,\n        cx: 32,\n        cy: 32,\n        f: NONE\n      }]\n    },\n\n    ios: IOS_SPINNER,\n\n    'ios-small': IOS_SPINNER,\n\n    bubbles: {\n      sw: 0,\n      c: [{\n        fn: function(i) {\n          return {\n            cx: 24 * Math.cos(2 * Math.PI * i / 8),\n            cy: 24 * Math.sin(2 * Math.PI * i / 8),\n            t: TRANSLATE32,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'r',\n                  dur: DURATION,\n                  v: animationValues('1;2;3;4;5;6;7;8', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 8\n      }]\n    },\n\n    circles: {\n\n      c: [{\n        fn: function(i) {\n          return {\n            r: 5,\n            cx: 24 * Math.cos(2 * Math.PI * i / 8),\n            cy: 24 * Math.sin(2 * Math.PI * i / 8),\n            t: TRANSLATE32,\n            sw: 0,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'fill-opacity',\n                  dur: DURATION,\n                  v: animationValues('.3;.3;.3;.4;.7;.85;.9;1', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 8\n      }]\n    },\n\n    crescent: {\n      c: [{\n        sw: 4,\n        da: 128,\n        os: 82,\n        r: 26,\n        cx: 32,\n        cy: 32,\n        f: NONE,\n        at: [SPIN_ANIMATION]\n      }]\n    },\n\n    dots: {\n\n      c: [{\n        fn: function(i) {\n          return {\n            cx: 16 + (16 * i),\n            cy: 32,\n            sw: 0,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'fill-opacity',\n                  dur: DURATION,\n                  v: animationValues('.5;.6;.8;1;.8;.6;.5', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: 'r',\n                  dur: DURATION,\n                  v: animationValues('4;5;6;5;4;3;3', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 3\n      }]\n    },\n\n    lines: {\n      sw: 7,\n      lc: ROUND,\n      line: [{\n        fn: function(i) {\n          return {\n            x1: 10 + (i * 14),\n            x2: 10 + (i * 14),\n            a: [{\n              fn: function() {\n                return {\n                  an: 'y1',\n                  dur: DURATION,\n                  v: animationValues('16;18;28;18;16', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: 'y2',\n                  dur: DURATION,\n                  v: animationValues('48;44;36;46;48', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: STROKE_OPACITY,\n                  dur: DURATION,\n                  v: animationValues('1;.8;.5;.4;1', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 4\n      }]\n    },\n\n    ripple: {\n      f: NONE,\n      'fill-rule': 'evenodd',\n      sw: 3,\n      circle: [{\n        fn: function(i) {\n          return {\n            cx: 32,\n            cy: 32,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'r',\n                  begin: (i * -1) + 's',\n                  dur: '2s',\n                  v: '0;24',\n                  keyTimes: '0;1',\n                  keySplines: '0.1,0.2,0.3,1',\n                  calcMode: 'spline',\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: STROKE_OPACITY,\n                  begin: (i * -1) + 's',\n                  dur: '2s',\n                  v: '.2;1;.2;0',\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 2\n      }]\n    },\n\n    spiral: {\n      defs: [{\n        linearGradient: [{\n          id: 'sGD',\n          gradientUnits: 'userSpaceOnUse',\n          x1: 55, y1: 46, x2: 2, y2: 46,\n          stop: [{\n            offset: 0.1,\n            class: 'stop1'\n          }, {\n            offset: 1,\n            class: 'stop2'\n          }]\n        }]\n      }],\n      g: [{\n        sw: 4,\n        lc: ROUND,\n        f: NONE,\n        path: [{\n          stroke: 'url(#sGD)',\n          d: 'M4,32 c0,15,12,28,28,28c8,0,16-4,21-9'\n        }, {\n          d: 'M60,32 C60,16,47.464,4,32,4S4,16,4,32'\n        }],\n        at: [SPIN_ANIMATION]\n      }]\n    }\n\n  };\n\n  var animations = {\n\n    android: function(ele) {\n      var rIndex = 0;\n      var rotateCircle = 0;\n      var startTime;\n      var svgEle = ele.querySelector('g');\n      var circleEle = ele.querySelector('circle');\n\n      function run() {\n        var v = easeInOutCubic(Date.now() - startTime, 650);\n        var scaleX = 1;\n        var translateX = 0;\n        var dasharray = (188 - (58 * v));\n        var dashoffset = (182 - (182 * v));\n\n        if (rIndex % 2) {\n          scaleX = -1;\n          translateX = -64;\n          dasharray = (128 - (-58 * v));\n          dashoffset = (182 * v);\n        }\n\n        var rotateLine = [0, -101, -90, -11, -180, 79, -270, -191][rIndex];\n\n        setSvgAttribute(circleEle, 'da', Math.max(Math.min(dasharray, 188), 128));\n        setSvgAttribute(circleEle, 'os', Math.max(Math.min(dashoffset, 182), 0));\n        setSvgAttribute(circleEle, 't', 'scale(' + scaleX + ',1) translate(' + translateX + ',0) rotate(' + rotateLine + ',32,32)');\n\n        rotateCircle += 4.1;\n        if (rotateCircle > 359) rotateCircle = 0;\n        setSvgAttribute(svgEle, 't', 'rotate(' + rotateCircle + ',32,32)');\n\n        if (v >= 1) {\n          rIndex++;\n          if (rIndex > 7) rIndex = 0;\n          startTime = Date.now();\n        }\n\n        ionic.requestAnimationFrame(run);\n      }\n\n      return function() {\n        startTime = Date.now();\n        run();\n      };\n\n    }\n\n  };\n\n  function easeInOutCubic(t, c) {\n    t /= c / 2;\n    if (t < 1) return 1 / 2 * t * t * t;\n    t -= 2;\n    return 1 / 2 * (t * t * t + 2);\n  }\n\n\n  IonicModule\n  .controller('$ionicSpinner', [\n    '$element',\n    '$attrs',\n  function($element, $attrs) {\n    var spinnerName, spinner;\n\n    this.init = function() {\n      var override = null;\n      if (ionic.Platform.platform() === 'windowsphone') {\n        override = 'android';\n      }\n      spinnerName = $attrs.icon || override || ionic.Platform.platform();\n      spinner = spinners[spinnerName];\n      if (!spinner) {\n        spinnerName = 'ios';\n        spinner = spinners.ios;\n      }\n\n      var container = document.createElement('div');\n      createSvgElement('svg', {\n        viewBox: '0 0 64 64',\n        g: [spinners[spinnerName]]\n      }, container, spinnerName);\n\n      // Specifically for animations to work,\n      // Android 4.3 and below requires the element to be\n      // added as an html string, rather than dynmically\n      // building up the svg element and appending it.\n      $element.html(container.innerHTML);\n\n      this.start();\n\n      return spinnerName;\n    };\n\n    this.start = function() {\n      animations[spinnerName] && animations[spinnerName]($element[0])();\n    };\n\n  }]);\n\n})(ionic);\n\nIonicModule\n.controller('$ionicTab', [\n  '$scope',\n  '$ionicHistory',\n  '$attrs',\n  '$location',\n  '$state',\nfunction($scope, $ionicHistory, $attrs, $location, $state) {\n  this.$scope = $scope;\n\n  //All of these exposed for testing\n  this.hrefMatchesState = function() {\n    return $attrs.href && $location.path().indexOf(\n      $attrs.href.replace(/^#/, '').replace(/\\/$/, '')\n    ) === 0;\n  };\n  this.srefMatchesState = function() {\n    return $attrs.uiSref && $state.includes($attrs.uiSref.split('(')[0]);\n  };\n  this.navNameMatchesState = function() {\n    return this.navViewName && $ionicHistory.isCurrentStateNavView(this.navViewName);\n  };\n\n  this.tabMatchesState = function() {\n    return this.hrefMatchesState() || this.srefMatchesState() || this.navNameMatchesState();\n  };\n}]);\n\nIonicModule\n.controller('$ionicTabs', [\n  '$scope',\n  '$element',\n  '$ionicHistory',\nfunction($scope, $element, $ionicHistory) {\n  var self = this;\n  var selectedTab = null;\n  var previousSelectedTab = null;\n  var selectedTabIndex;\n  self.tabs = [];\n\n  self.selectedIndex = function() {\n    return self.tabs.indexOf(selectedTab);\n  };\n  self.selectedTab = function() {\n    return selectedTab;\n  };\n  self.previousSelectedTab = function() {\n    return previousSelectedTab;\n  };\n\n  self.add = function(tab) {\n    $ionicHistory.registerHistory(tab);\n    self.tabs.push(tab);\n  };\n\n  self.remove = function(tab) {\n    var tabIndex = self.tabs.indexOf(tab);\n    if (tabIndex === -1) {\n      return;\n    }\n    //Use a field like '$tabSelected' so developers won't accidentally set it in controllers etc\n    if (tab.$tabSelected) {\n      self.deselect(tab);\n      //Try to select a new tab if we're removing a tab\n      if (self.tabs.length === 1) {\n        //Do nothing if there are no other tabs to select\n      } else {\n        //Select previous tab if it's the last tab, else select next tab\n        var newTabIndex = tabIndex === self.tabs.length - 1 ? tabIndex - 1 : tabIndex + 1;\n        self.select(self.tabs[newTabIndex]);\n      }\n    }\n    self.tabs.splice(tabIndex, 1);\n  };\n\n  self.deselect = function(tab) {\n    if (tab.$tabSelected) {\n      previousSelectedTab = selectedTab;\n      selectedTab = selectedTabIndex = null;\n      tab.$tabSelected = false;\n      (tab.onDeselect || noop)();\n      tab.$broadcast && tab.$broadcast('$ionicHistory.deselect');\n    }\n  };\n\n  self.select = function(tab, shouldEmitEvent) {\n    var tabIndex;\n    if (isNumber(tab)) {\n      tabIndex = tab;\n      if (tabIndex >= self.tabs.length) return;\n      tab = self.tabs[tabIndex];\n    } else {\n      tabIndex = self.tabs.indexOf(tab);\n    }\n\n    if (arguments.length === 1) {\n      shouldEmitEvent = !!(tab.navViewName || tab.uiSref);\n    }\n\n    if (selectedTab && selectedTab.$historyId == tab.$historyId) {\n      if (shouldEmitEvent) {\n        $ionicHistory.goToHistoryRoot(tab.$historyId);\n      }\n\n    } else if (selectedTabIndex !== tabIndex) {\n      forEach(self.tabs, function(tab) {\n        self.deselect(tab);\n      });\n\n      selectedTab = tab;\n      selectedTabIndex = tabIndex;\n\n      if (self.$scope && self.$scope.$parent) {\n        self.$scope.$parent.$activeHistoryId = tab.$historyId;\n      }\n\n      //Use a funny name like $tabSelected so the developer doesn't overwrite the var in a child scope\n      tab.$tabSelected = true;\n      (tab.onSelect || noop)();\n\n      if (shouldEmitEvent) {\n        $scope.$emit('$ionicHistory.change', {\n          type: 'tab',\n          tabIndex: tabIndex,\n          historyId: tab.$historyId,\n          navViewName: tab.navViewName,\n          hasNavView: !!tab.navViewName,\n          title: tab.title,\n          url: tab.href,\n          uiSref: tab.uiSref\n        });\n      }\n    }\n  };\n\n  self.hasActiveScope = function() {\n    for (var x = 0; x < self.tabs.length; x++) {\n      if ($ionicHistory.isActiveScope(self.tabs[x])) {\n        return true;\n      }\n    }\n    return false;\n  };\n\n}]);\n\nIonicModule\n.controller('$ionicView', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$compile',\n  '$rootScope',\nfunction($scope, $element, $attrs, $compile, $rootScope) {\n  var self = this;\n  var navElementHtml = {};\n  var navViewCtrl;\n  var navBarDelegateHandle;\n  var hasViewHeaderBar;\n  var deregisters = [];\n  var viewTitle;\n\n  var deregIonNavBarInit = $scope.$on('ionNavBar.init', function(ev, delegateHandle) {\n    // this view has its own ion-nav-bar, remember the navBarDelegateHandle for this view\n    ev.stopPropagation();\n    navBarDelegateHandle = delegateHandle;\n  });\n\n\n  self.init = function() {\n    deregIonNavBarInit();\n\n    var modalCtrl = $element.inheritedData('$ionModalController');\n    navViewCtrl = $element.inheritedData('$ionNavViewController');\n\n    // don't bother if inside a modal or there's no parent navView\n    if (!navViewCtrl || modalCtrl) return;\n\n    // add listeners for when this view changes\n    $scope.$on('$ionicView.beforeEnter', self.beforeEnter);\n    $scope.$on('$ionicView.afterEnter', afterEnter);\n    $scope.$on('$ionicView.beforeLeave', deregisterFns);\n  };\n\n  self.beforeEnter = function(ev, transData) {\n    // this event was emitted, starting at intial ion-view, then bubbles up\n    // only the first ion-view should do something with it, parent ion-views should ignore\n    if (transData && !transData.viewNotified) {\n      transData.viewNotified = true;\n\n      if (!$rootScope.$$phase) $scope.$digest();\n      viewTitle = isDefined($attrs.viewTitle) ? $attrs.viewTitle : $attrs.title;\n\n      var navBarItems = {};\n      for (var n in navElementHtml) {\n        navBarItems[n] = generateNavBarItem(navElementHtml[n]);\n      }\n\n      navViewCtrl.beforeEnter(extend(transData, {\n        title: viewTitle,\n        showBack: !attrTrue('hideBackButton'),\n        navBarItems: navBarItems,\n        navBarDelegate: navBarDelegateHandle || null,\n        showNavBar: !attrTrue('hideNavBar'),\n        hasHeaderBar: !!hasViewHeaderBar\n      }));\n\n      // make sure any existing observers are cleaned up\n      deregisterFns();\n    }\n  };\n\n\n  function afterEnter() {\n    // only listen for title updates after it has entered\n    // but also deregister the observe before it leaves\n    var viewTitleAttr = isDefined($attrs.viewTitle) && 'viewTitle' || isDefined($attrs.title) && 'title';\n    if (viewTitleAttr) {\n      titleUpdate($attrs[viewTitleAttr]);\n      deregisters.push($attrs.$observe(viewTitleAttr, titleUpdate));\n    }\n\n    if (isDefined($attrs.hideBackButton)) {\n      deregisters.push($scope.$watch($attrs.hideBackButton, function(val) {\n        navViewCtrl.showBackButton(!val);\n      }));\n    }\n\n    if (isDefined($attrs.hideNavBar)) {\n      deregisters.push($scope.$watch($attrs.hideNavBar, function(val) {\n        navViewCtrl.showBar(!val);\n      }));\n    }\n  }\n\n\n  function titleUpdate(newTitle) {\n    if (isDefined(newTitle) && newTitle !== viewTitle) {\n      viewTitle = newTitle;\n      navViewCtrl.title(viewTitle);\n    }\n  }\n\n\n  function deregisterFns() {\n    // remove all existing $attrs.$observe's\n    for (var x = 0; x < deregisters.length; x++) {\n      deregisters[x]();\n    }\n    deregisters = [];\n  }\n\n\n  function generateNavBarItem(html) {\n    if (html) {\n      // every time a view enters we need to recreate its view buttons if they exist\n      return $compile(html)($scope.$new());\n    }\n  }\n\n\n  function attrTrue(key) {\n    return !!$scope.$eval($attrs[key]);\n  }\n\n\n  self.navElement = function(type, html) {\n    navElementHtml[type] = html;\n  };\n\n}]);\n\n/*\n * We don't document the ionActionSheet directive, we instead document\n * the $ionicActionSheet service\n */\nIonicModule\n.directive('ionActionSheet', ['$document', function($document) {\n  return {\n    restrict: 'E',\n    scope: true,\n    replace: true,\n    link: function($scope, $element) {\n\n      var keyUp = function(e) {\n        if (e.which == 27) {\n          $scope.cancel();\n          $scope.$apply();\n        }\n      };\n\n      var backdropClick = function(e) {\n        if (e.target == $element[0]) {\n          $scope.cancel();\n          $scope.$apply();\n        }\n      };\n      $scope.$on('$destroy', function() {\n        $element.remove();\n        $document.unbind('keyup', keyUp);\n      });\n\n      $document.bind('keyup', keyUp);\n      $element.bind('click', backdropClick);\n    },\n    template: '<div class=\"action-sheet-backdrop\">' +\n                '<div class=\"action-sheet-wrapper\">' +\n                  '<div class=\"action-sheet\" ng-class=\"{\\'action-sheet-has-icons\\': $actionSheetHasIcon}\">' +\n                    '<div class=\"action-sheet-group action-sheet-options\">' +\n                      '<div class=\"action-sheet-title\" ng-if=\"titleText\" ng-bind-html=\"titleText\"></div>' +\n                      '<button class=\"button action-sheet-option\" ng-click=\"buttonClicked($index)\" ng-repeat=\"b in buttons\" ng-bind-html=\"b.text\"></button>' +\n                      '<button class=\"button destructive action-sheet-destructive\" ng-if=\"destructiveText\" ng-click=\"destructiveButtonClicked()\" ng-bind-html=\"destructiveText\"></button>' +\n                    '</div>' +\n                    '<div class=\"action-sheet-group action-sheet-cancel\" ng-if=\"cancelText\">' +\n                      '<button class=\"button\" ng-click=\"cancel()\" ng-bind-html=\"cancelText\"></button>' +\n                    '</div>' +\n                  '</div>' +\n                '</div>' +\n              '</div>'\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @name ionCheckbox\n * @module ionic\n * @restrict E\n * @codepen hqcju\n * @description\n * The checkbox is no different than the HTML checkbox input, except it's styled differently.\n *\n * The checkbox behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]).\n *\n * @usage\n * ```html\n * <ion-checkbox ng-model=\"isChecked\">Checkbox Label</ion-checkbox>\n * ```\n */\n\nIonicModule\n.directive('ionCheckbox', ['$ionicConfig', function($ionicConfig) {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '?ngModel',\n    transclude: true,\n    template:\n      '<label class=\"item item-checkbox\">' +\n        '<div class=\"checkbox checkbox-input-hidden disable-pointer-events\">' +\n          '<input type=\"checkbox\">' +\n          '<i class=\"checkbox-icon\"></i>' +\n        '</div>' +\n        '<div class=\"item-content disable-pointer-events\" ng-transclude></div>' +\n      '</label>',\n    compile: function(element, attr) {\n      var input = element.find('input');\n      forEach({\n        'name': attr.name,\n        'ng-value': attr.ngValue,\n        'ng-model': attr.ngModel,\n        'ng-checked': attr.ngChecked,\n        'ng-disabled': attr.ngDisabled,\n        'ng-true-value': attr.ngTrueValue,\n        'ng-false-value': attr.ngFalseValue,\n        'ng-change': attr.ngChange,\n        'ng-required': attr.ngRequired,\n        'required': attr.required\n      }, function(value, name) {\n        if (isDefined(value)) {\n          input.attr(name, value);\n        }\n      });\n      var checkboxWrapper = element[0].querySelector('.checkbox');\n      checkboxWrapper.classList.add('checkbox-' + $ionicConfig.form.checkbox());\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @restrict A\n * @name collectionRepeat\n * @module ionic\n * @codepen 7ec1ec58f2489ab8f359fa1a0fe89c15\n * @description\n * `collection-repeat` allows an app to show huge lists of items much more performantly than\n * `ng-repeat`.\n *\n * It renders into the DOM only as many items as are currently visible.\n *\n * This means that on a phone screen that can fit eight items, only the eight items matching\n * the current scroll position will be rendered.\n *\n * **The Basics**:\n *\n * - The data given to collection-repeat must be an array.\n * - If the `item-height` and `item-width` attributes are not supplied, it will be assumed that\n *   every item in the list has the same dimensions as the first item.\n * - Don't use angular one-time binding (`::`) with collection-repeat. The scope of each item is\n *   assigned new data and re-digested as you scroll. Bindings need to update, and one-time bindings\n *   won't.\n *\n * **Performance Tips**:\n *\n * - The iOS webview has a performance bottleneck when switching out `<img src>` attributes.\n *   To increase performance of images on iOS, cache your images in advance and,\n *   if possible, lower the number of unique images. We're working on [a solution](https://github.com/driftyco/ionic/issues/3194).\n *\n * @usage\n * #### Basic Item List ([codepen](http://codepen.io/ionic/pen/0c2c35a34a8b18ad4d793fef0b081693))\n * ```html\n * <ion-content>\n *   <ion-item collection-repeat=\"item in items\">\n *     {% raw %}{{item}}{% endraw %}\n *   </ion-item>\n * </ion-content>\n * ```\n *\n * #### Grid of Images ([codepen](http://codepen.io/ionic/pen/5515d4efd9d66f780e96787387f41664))\n * ```html\n * <ion-content>\n *   <img collection-repeat=\"photo in photos\"\n *     item-width=\"33%\"\n *     item-height=\"200px\"\n *     ng-src=\"{% raw %}{{photo.url}}{% endraw %}\">\n * </ion-content>\n * ```\n *\n * #### Horizontal Scroller, Dynamic Item Width ([codepen](http://codepen.io/ionic/pen/67cc56b349124a349acb57a0740e030e))\n * ```html\n * <ion-content>\n *   <h2>Available Kittens:</h2>\n *   <ion-scroll direction=\"x\" class=\"available-scroller\">\n *     <div class=\"photo\" collection-repeat=\"photo in main.photos\"\n *        item-height=\"250\" item-width=\"photo.width + 30\">\n *        <img ng-src=\"{{photo.src}}\">\n *     </div>\n *   </ion-scroll>\n * </ion-content>\n * ```\n *\n * @param {expression} collection-repeat The expression indicating how to enumerate a collection,\n *   of the format  `variable in expression` – where variable is the user defined loop variable\n *   and `expression` is a scope expression giving the collection to enumerate.\n *   For example: `album in artist.albums` or `album in artist.albums | orderBy:'name'`.\n * @param {expression=} item-width The width of the repeated element. The expression must return\n *   a number (pixels) or a percentage. Defaults to the width of the first item in the list.\n *   (previously named collection-item-width)\n * @param {expression=} item-height The height of the repeated element. The expression must return\n *   a number (pixels) or a percentage. Defaults to the height of the first item in the list.\n *   (previously named collection-item-height)\n * @param {number=} item-render-buffer The number of items to load before and after the visible\n *   items in the list. Default 3. Tip: set this higher if you have lots of images to preload, but\n *   don't set it too high or you'll see performance loss.\n * @param {boolean=} force-refresh-images Force images to refresh as you scroll. This fixes a problem\n *   where, when an element is interchanged as scrolling, its image will still have the old src\n *   while the new src loads. Setting this to true comes with a small performance loss.\n */\n\nIonicModule\n.directive('collectionRepeat', CollectionRepeatDirective)\n.factory('$ionicCollectionManager', RepeatManagerFactory);\n\nvar ONE_PX_TRANSPARENT_IMG_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';\nvar WIDTH_HEIGHT_REGEX = /height:.*?px;\\s*width:.*?px/;\nvar DEFAULT_RENDER_BUFFER = 3;\n\nCollectionRepeatDirective.$inject = ['$ionicCollectionManager', '$parse', '$window', '$$rAF', '$rootScope', '$timeout'];\nfunction CollectionRepeatDirective($ionicCollectionManager, $parse, $window, $$rAF, $rootScope, $timeout) {\n  return {\n    restrict: 'A',\n    priority: 1000,\n    transclude: 'element',\n    $$tlb: true,\n    require: '^^$ionicScroll',\n    link: postLink\n  };\n\n  function postLink(scope, element, attr, scrollCtrl, transclude) {\n    var scrollView = scrollCtrl.scrollView;\n    var node = element[0];\n    var containerNode = angular.element('<div class=\"collection-repeat-container\">')[0];\n    node.parentNode.replaceChild(containerNode, node);\n\n    if (scrollView.options.scrollingX && scrollView.options.scrollingY) {\n      throw new Error(\"collection-repeat expected a parent x or y scrollView, not \" +\n                      \"an xy scrollView.\");\n    }\n\n    var repeatExpr = attr.collectionRepeat;\n    var match = repeatExpr.match(/^\\s*([\\s\\S]+?)\\s+in\\s+([\\s\\S]+?)(?:\\s+track\\s+by\\s+([\\s\\S]+?))?\\s*$/);\n    if (!match) {\n      throw new Error(\"collection-repeat expected expression in form of '_item_ in \" +\n                      \"_collection_[ track by _id_]' but got '\" + attr.collectionRepeat + \"'.\");\n    }\n    var keyExpr = match[1];\n    var listExpr = match[2];\n    var listGetter = $parse(listExpr);\n    var heightData = {};\n    var widthData = {};\n    var computedStyleDimensions = {};\n    var data = [];\n    var repeatManager;\n\n    // attr.collectionBufferSize is deprecated\n    var renderBufferExpr = attr.itemRenderBuffer || attr.collectionBufferSize;\n    var renderBuffer = angular.isDefined(renderBufferExpr) ?\n      parseInt(renderBufferExpr) :\n      DEFAULT_RENDER_BUFFER;\n\n    // attr.collectionItemHeight is deprecated\n    var heightExpr = attr.itemHeight || attr.collectionItemHeight;\n    // attr.collectionItemWidth is deprecated\n    var widthExpr = attr.itemWidth || attr.collectionItemWidth;\n\n    var afterItemsContainer = initAfterItemsContainer();\n\n    var changeValidator = makeChangeValidator();\n    initDimensions();\n\n    // Dimensions are refreshed on resize or data change.\n    scrollCtrl.$element.on('scroll-resize', refreshDimensions);\n\n    angular.element($window).on('resize', onResize);\n    var unlistenToExposeAside = $rootScope.$on('$ionicExposeAside', ionic.animationFrameThrottle(function() {\n      scrollCtrl.scrollView.resize();\n      onResize();\n    }));\n    $timeout(refreshDimensions, 0, false);\n\n    function onResize() {\n      if (changeValidator.resizeRequiresRefresh(scrollView.__clientWidth, scrollView.__clientHeight)) {\n        refreshDimensions();\n      }\n    }\n\n    scope.$watchCollection(listGetter, function(newValue) {\n      data = newValue || (newValue = []);\n      if (!angular.isArray(newValue)) {\n        throw new Error(\"collection-repeat expected an array for '\" + listExpr + \"', \" +\n          \"but got a \" + typeof value);\n      }\n      // Wait for this digest to end before refreshing everything.\n      scope.$$postDigest(function() {\n        getRepeatManager().setData(data);\n        if (changeValidator.dataChangeRequiresRefresh(data)) refreshDimensions();\n      });\n    });\n\n    scope.$on('$destroy', function() {\n      angular.element($window).off('resize', onResize);\n      unlistenToExposeAside();\n      scrollCtrl.$element && scrollCtrl.$element.off('scroll-resize', refreshDimensions);\n\n      computedStyleNode && computedStyleNode.parentNode &&\n        computedStyleNode.parentNode.removeChild(computedStyleNode);\n      computedStyleScope && computedStyleScope.$destroy();\n      computedStyleScope = computedStyleNode = null;\n\n      repeatManager && repeatManager.destroy();\n      repeatManager = null;\n    });\n\n    function makeChangeValidator() {\n      var self;\n      return (self = {\n        dataLength: 0,\n        width: 0,\n        height: 0,\n        // A resize triggers a refresh only if we have data, the scrollView has size,\n        // and the size has changed.\n        resizeRequiresRefresh: function(newWidth, newHeight) {\n          var requiresRefresh = self.dataLength && newWidth && newHeight &&\n            (newWidth !== self.width || newHeight !== self.height);\n\n          self.width = newWidth;\n          self.height = newHeight;\n\n          return !!requiresRefresh;\n        },\n        // A change in data only triggers a refresh if the data has length, or if the data's\n        // length is less than before.\n        dataChangeRequiresRefresh: function(newData) {\n          var requiresRefresh = newData.length > 0 || newData.length < self.dataLength;\n\n          self.dataLength = newData.length;\n\n          return !!requiresRefresh;\n        }\n      });\n    }\n\n    function getRepeatManager() {\n      return repeatManager || (repeatManager = new $ionicCollectionManager({\n        afterItemsNode: afterItemsContainer[0],\n        containerNode: containerNode,\n        heightData: heightData,\n        widthData: widthData,\n        forceRefreshImages: !!(isDefined(attr.forceRefreshImages) && attr.forceRefreshImages !== 'false'),\n        keyExpression: keyExpr,\n        renderBuffer: renderBuffer,\n        scope: scope,\n        scrollView: scrollCtrl.scrollView,\n        transclude: transclude\n      }));\n    }\n\n    function initAfterItemsContainer() {\n      var container = angular.element(\n        scrollView.__content.querySelector('.collection-repeat-after-container')\n      );\n      // Put everything in the view after the repeater into a container.\n      if (!container.length) {\n        var elementIsAfterRepeater = false;\n        var afterNodes = [].filter.call(scrollView.__content.childNodes, function(node) {\n          if (ionic.DomUtil.contains(node, containerNode)) {\n            elementIsAfterRepeater = true;\n            return false;\n          }\n          return elementIsAfterRepeater;\n        });\n        container = angular.element('<span class=\"collection-repeat-after-container\">');\n        if (scrollView.options.scrollingX) {\n          container.addClass('horizontal');\n        }\n        container.append(afterNodes);\n        scrollView.__content.appendChild(container[0]);\n      }\n      return container;\n    }\n\n    function initDimensions() {\n      //Height and width have four 'modes':\n      //1) Computed Mode\n      //  - Nothing is supplied, so we getComputedStyle() on one element in the list and use\n      //    that width and height value for the width and height of every item. This is re-computed\n      //    every resize.\n      //2) Constant Mode, Static Integer\n      //  - The user provides a constant number for width or height, in pixels. We parse it,\n      //    store it on the `value` field, and it never changes\n      //3) Constant Mode, Percent\n      //  - The user provides a percent string for width or height. The getter for percent is\n      //    stored on the `getValue()` field, and is re-evaluated once every resize. The result\n      //    is stored on the `value` field.\n      //4) Dynamic Mode\n      //  - The user provides a dynamic expression for the width or height.  This is re-evaluated\n      //    for every item, stored on the `.getValue()` field.\n      if (heightExpr) {\n        parseDimensionAttr(heightExpr, heightData);\n      } else {\n        heightData.computed = true;\n      }\n      if (widthExpr) {\n        parseDimensionAttr(widthExpr, widthData);\n      } else {\n        widthData.computed = true;\n      }\n    }\n\n    function refreshDimensions() {\n      var hasData = data.length > 0;\n\n      if (hasData && (heightData.computed || widthData.computed)) {\n        computeStyleDimensions();\n      }\n\n      if (hasData && heightData.computed) {\n        heightData.value = computedStyleDimensions.height;\n        if (!heightData.value) {\n          throw new Error('collection-repeat tried to compute the height of repeated elements \"' +\n            repeatExpr + '\", but was unable to. Please provide the \"item-height\" attribute. ' +\n            'http://ionicframework.com/docs/api/directive/collectionRepeat/');\n        }\n      } else if (!heightData.dynamic && heightData.getValue) {\n        // If it's a constant with a getter (eg percent), we just refresh .value after resize\n        heightData.value = heightData.getValue();\n      }\n\n      if (hasData && widthData.computed) {\n        widthData.value = computedStyleDimensions.width;\n        if (!widthData.value) {\n          throw new Error('collection-repeat tried to compute the width of repeated elements \"' +\n            repeatExpr + '\", but was unable to. Please provide the \"item-width\" attribute. ' +\n            'http://ionicframework.com/docs/api/directive/collectionRepeat/');\n        }\n      } else if (!widthData.dynamic && widthData.getValue) {\n        // If it's a constant with a getter (eg percent), we just refresh .value after resize\n        widthData.value = widthData.getValue();\n      }\n      // Dynamic dimensions aren't updated on resize. Since they're already dynamic anyway,\n      // .getValue() will be used.\n\n      getRepeatManager().refreshLayout();\n    }\n\n    function parseDimensionAttr(attrValue, dimensionData) {\n      if (!attrValue) return;\n\n      var parsedValue;\n      // Try to just parse the plain attr value\n      try {\n        parsedValue = $parse(attrValue);\n      } catch (e) {\n        // If the parse fails and the value has `px` or `%` in it, surround the attr in\n        // quotes, to attempt to let the user provide a simple `attr=\"100%\"` or `attr=\"100px\"`\n        if (attrValue.trim().match(/\\d+(px|%)$/)) {\n          attrValue = '\"' + attrValue + '\"';\n        }\n        parsedValue = $parse(attrValue);\n      }\n\n      var constantAttrValue = attrValue.replace(/(\\'|\\\"|px|%)/g, '').trim();\n      var isConstant = constantAttrValue.length && !/([a-zA-Z]|\\$|:|\\?)/.test(constantAttrValue);\n      dimensionData.attrValue = attrValue;\n\n      // If it's a constant, it's either a percent or just a constant pixel number.\n      if (isConstant) {\n        var intValue = parseInt(parsedValue());\n\n        // For percents, store the percent getter on .getValue()\n        if (attrValue.indexOf('%') > -1) {\n          var decimalValue = intValue / 100;\n          dimensionData.getValue = dimensionData === heightData ?\n            function() { return Math.floor(decimalValue * scrollView.__clientHeight); } :\n            function() { return Math.floor(decimalValue * scrollView.__clientWidth); };\n        } else {\n          // For static constants, just store the static constant.\n          dimensionData.value = intValue;\n        }\n\n      } else {\n        dimensionData.dynamic = true;\n        dimensionData.getValue = dimensionData === heightData ?\n          function heightGetter(scope, locals) {\n            var result = parsedValue(scope, locals);\n            if (result.charAt && result.charAt(result.length - 1) === '%') {\n              return Math.floor(parseInt(result) / 100 * scrollView.__clientHeight);\n            }\n            return parseInt(result);\n          } :\n          function widthGetter(scope, locals) {\n            var result = parsedValue(scope, locals);\n            if (result.charAt && result.charAt(result.length - 1) === '%') {\n              return Math.floor(parseInt(result) / 100 * scrollView.__clientWidth);\n            }\n            return parseInt(result);\n          };\n      }\n    }\n\n    var computedStyleNode;\n    var computedStyleScope;\n    function computeStyleDimensions() {\n      if (!computedStyleNode) {\n        transclude(computedStyleScope = scope.$new(), function(clone) {\n          clone[0].removeAttribute('collection-repeat'); // remove absolute position styling\n          computedStyleNode = clone[0];\n        });\n      }\n\n      computedStyleScope[keyExpr] = (listGetter(scope) || [])[0];\n      if (!$rootScope.$$phase) computedStyleScope.$digest();\n      containerNode.appendChild(computedStyleNode);\n\n      var style = $window.getComputedStyle(computedStyleNode);\n      computedStyleDimensions.width = parseInt(style.width);\n      computedStyleDimensions.height = parseInt(style.height);\n\n      containerNode.removeChild(computedStyleNode);\n    }\n\n  }\n\n}\n\nRepeatManagerFactory.$inject = ['$rootScope', '$window', '$$rAF'];\nfunction RepeatManagerFactory($rootScope, $window, $$rAF) {\n  var EMPTY_DIMENSION = { primaryPos: 0, secondaryPos: 0, primarySize: 0, secondarySize: 0, rowPrimarySize: 0 };\n\n  return function RepeatController(options) {\n    var afterItemsNode = options.afterItemsNode;\n    var containerNode = options.containerNode;\n    var forceRefreshImages = options.forceRefreshImages;\n    var heightData = options.heightData;\n    var widthData = options.widthData;\n    var keyExpression = options.keyExpression;\n    var renderBuffer = options.renderBuffer;\n    var scope = options.scope;\n    var scrollView = options.scrollView;\n    var transclude = options.transclude;\n\n    var data = [];\n\n    var getterLocals = {};\n    var heightFn = heightData.getValue || function() { return heightData.value; };\n    var heightGetter = function(index, value) {\n      getterLocals[keyExpression] = value;\n      getterLocals.$index = index;\n      return heightFn(scope, getterLocals);\n    };\n\n    var widthFn = widthData.getValue || function() { return widthData.value; };\n    var widthGetter = function(index, value) {\n      getterLocals[keyExpression] = value;\n      getterLocals.$index = index;\n      return widthFn(scope, getterLocals);\n    };\n\n    var isVertical = !!scrollView.options.scrollingY;\n\n    // We say it's a grid view if we're either dynamic or not 100% width\n    var isGridView = isVertical ?\n      (widthData.dynamic || widthData.value !== scrollView.__clientWidth) :\n      (heightData.dynamic || heightData.value !== scrollView.__clientHeight);\n\n    var isStaticView = !heightData.dynamic && !widthData.dynamic;\n\n    var PRIMARY = 'PRIMARY';\n    var SECONDARY = 'SECONDARY';\n    var TRANSLATE_TEMPLATE_STR = isVertical ?\n      'translate3d(SECONDARYpx,PRIMARYpx,0)' :\n      'translate3d(PRIMARYpx,SECONDARYpx,0)';\n    var WIDTH_HEIGHT_TEMPLATE_STR = isVertical ?\n      'height: PRIMARYpx; width: SECONDARYpx;' :\n      'height: SECONDARYpx; width: PRIMARYpx;';\n\n    var estimatedHeight;\n    var estimatedWidth;\n\n    var repeaterBeforeSize = 0;\n    var repeaterAfterSize = 0;\n\n    var renderStartIndex = -1;\n    var renderEndIndex = -1;\n    var renderAfterBoundary = -1;\n    var renderBeforeBoundary = -1;\n\n    var itemsPool = [];\n    var itemsLeaving = [];\n    var itemsEntering = [];\n    var itemsShownMap = {};\n    var nextItemId = 0;\n\n    var scrollViewSetDimensions = isVertical ?\n      function() { scrollView.setDimensions(null, null, null, view.getContentSize(), true); } :\n      function() { scrollView.setDimensions(null, null, view.getContentSize(), null, true); };\n\n    // view is a mix of list/grid methods + static/dynamic methods.\n    // See bottom for implementations. Available methods:\n    //\n    // getEstimatedPrimaryPos(i), getEstimatedSecondaryPos(i), getEstimatedIndex(scrollTop),\n    // calculateDimensions(toIndex), getDimensions(index),\n    // updateRenderRange(scrollTop, scrollValueEnd), onRefreshLayout(), onRefreshData()\n    var view = isVertical ? new VerticalViewType() : new HorizontalViewType();\n    (isGridView ? GridViewType : ListViewType).call(view);\n    (isStaticView ? StaticViewType : DynamicViewType).call(view);\n\n    var contentSizeStr = isVertical ? 'getContentHeight' : 'getContentWidth';\n    var originalGetContentSize = scrollView.options[contentSizeStr];\n    scrollView.options[contentSizeStr] = angular.bind(view, view.getContentSize);\n\n    scrollView.__$callback = scrollView.__callback;\n    scrollView.__callback = function(transformLeft, transformTop, zoom, wasResize) {\n      var scrollValue = view.getScrollValue();\n      if (renderStartIndex === -1 ||\n          scrollValue + view.scrollPrimarySize > renderAfterBoundary ||\n          scrollValue < renderBeforeBoundary) {\n        render();\n      }\n      scrollView.__$callback(transformLeft, transformTop, zoom, wasResize);\n    };\n\n    var isLayoutReady = false;\n    var isDataReady = false;\n    this.refreshLayout = function() {\n      if (data.length) {\n        estimatedHeight = heightGetter(0, data[0]);\n        estimatedWidth = widthGetter(0, data[0]);\n      } else {\n        // If we don't have any data in our array, just guess.\n        estimatedHeight = 100;\n        estimatedWidth = 100;\n      }\n\n      // Get the size of every element AFTER the repeater. We have to get the margin before and\n      // after the first/last element to fix a browser bug with getComputedStyle() not counting\n      // the first/last child's margins into height.\n      var style = getComputedStyle(afterItemsNode) || {};\n      var firstStyle = afterItemsNode.firstElementChild && getComputedStyle(afterItemsNode.firstElementChild) || {};\n      var lastStyle = afterItemsNode.lastElementChild && getComputedStyle(afterItemsNode.lastElementChild) || {};\n      repeaterAfterSize = (parseInt(style[isVertical ? 'height' : 'width']) || 0) +\n        (firstStyle && parseInt(firstStyle[isVertical ? 'marginTop' : 'marginLeft']) || 0) +\n        (lastStyle && parseInt(lastStyle[isVertical ? 'marginBottom' : 'marginRight']) || 0);\n\n      // Get the offsetTop of the repeater.\n      repeaterBeforeSize = 0;\n      var current = containerNode;\n      do {\n        repeaterBeforeSize += current[isVertical ? 'offsetTop' : 'offsetLeft'];\n      } while ( ionic.DomUtil.contains(scrollView.__content, current = current.offsetParent) );\n\n      var containerPrevNode = containerNode.previousElementSibling;\n      var beforeStyle = containerPrevNode ? $window.getComputedStyle(containerPrevNode) : {};\n      var beforeMargin = parseInt(beforeStyle[isVertical ? 'marginBottom' : 'marginRight'] || 0);\n\n      // Because we position the collection container with position: relative, it doesn't take\n      // into account where to position itself relative to the previous element's marginBottom.\n      // To compensate, we translate the container up by the previous element's margin.\n      containerNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR\n        .replace(PRIMARY, -beforeMargin)\n        .replace(SECONDARY, 0);\n      repeaterBeforeSize -= beforeMargin;\n\n      if (!scrollView.__clientHeight || !scrollView.__clientWidth) {\n        scrollView.__clientWidth = scrollView.__container.clientWidth;\n        scrollView.__clientHeight = scrollView.__container.clientHeight;\n      }\n\n      (view.onRefreshLayout || angular.noop)();\n      view.refreshDirection();\n      scrollViewSetDimensions();\n\n      // Create the pool of items for reuse, setting the size to (estimatedItemsOnScreen) * 2,\n      // plus the size of the renderBuffer.\n      if (!isLayoutReady) {\n        var poolSize = Math.max(20, renderBuffer * 3);\n        for (var i = 0; i < poolSize; i++) {\n          itemsPool.push(new RepeatItem());\n        }\n      }\n\n      isLayoutReady = true;\n      if (isLayoutReady && isDataReady) {\n        // If the resize or latest data change caused the scrollValue to\n        // now be out of bounds, resize the scrollView.\n        if (scrollView.__scrollLeft > scrollView.__maxScrollLeft ||\n            scrollView.__scrollTop > scrollView.__maxScrollTop) {\n          scrollView.resize();\n        }\n        forceRerender(true);\n      }\n    };\n\n    this.setData = function(newData) {\n      data = newData;\n      (view.onRefreshData || angular.noop)();\n      isDataReady = true;\n    };\n\n    this.destroy = function() {\n      render.destroyed = true;\n\n      itemsPool.forEach(function(item) {\n        item.scope.$destroy();\n        item.scope = item.element = item.node = item.images = null;\n      });\n      itemsPool.length = itemsEntering.length = itemsLeaving.length = 0;\n      itemsShownMap = {};\n\n      //Restore the scrollView's normal behavior and resize it to normal size.\n      scrollView.options[contentSizeStr] = originalGetContentSize;\n      scrollView.__callback = scrollView.__$callback;\n      scrollView.resize();\n\n      (view.onDestroy || angular.noop)();\n    };\n\n    function forceRerender() {\n      return render(true);\n    }\n    function render(forceRerender) {\n      if (render.destroyed) return;\n      var i;\n      var ii;\n      var item;\n      var dim;\n      var scope;\n      var scrollValue = view.getScrollValue();\n      var scrollValueEnd = scrollValue + view.scrollPrimarySize;\n\n      view.updateRenderRange(scrollValue, scrollValueEnd);\n\n      renderStartIndex = Math.max(0, renderStartIndex - renderBuffer);\n      renderEndIndex = Math.min(data.length - 1, renderEndIndex + renderBuffer);\n\n      for (i in itemsShownMap) {\n        if (i < renderStartIndex || i > renderEndIndex) {\n          item = itemsShownMap[i];\n          delete itemsShownMap[i];\n          itemsLeaving.push(item);\n          item.isShown = false;\n        }\n      }\n\n      // Render indicies that aren't shown yet\n      //\n      // NOTE(ajoslin): this may sound crazy, but calling any other functions during this render\n      // loop will often push the render time over the edge from less than one frame to over\n      // one frame, causing visible jank.\n      // DON'T call any other functions inside this loop unless it's vital.\n      for (i = renderStartIndex; i <= renderEndIndex; i++) {\n        // We only go forward with render if the index is in data, the item isn't already shown,\n        // or forceRerender is on.\n        if (i >= data.length || (itemsShownMap[i] && !forceRerender)) continue;\n\n        item = itemsShownMap[i] || (itemsShownMap[i] = itemsLeaving.length ? itemsLeaving.pop() :\n                                    itemsPool.length ? itemsPool.shift() :\n                                    new RepeatItem());\n        itemsEntering.push(item);\n        item.isShown = true;\n\n        scope = item.scope;\n        scope.$index = i;\n        scope[keyExpression] = data[i];\n        scope.$first = (i === 0);\n        scope.$last = (i === (data.length - 1));\n        scope.$middle = !(scope.$first || scope.$last);\n        scope.$odd = !(scope.$even = (i & 1) === 0);\n\n        if (scope.$$disconnected) ionic.Utils.reconnectScope(item.scope);\n\n        dim = view.getDimensions(i);\n        if (item.secondaryPos !== dim.secondaryPos || item.primaryPos !== dim.primaryPos) {\n          item.node.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR\n            .replace(PRIMARY, (item.primaryPos = dim.primaryPos))\n            .replace(SECONDARY, (item.secondaryPos = dim.secondaryPos));\n        }\n        if (item.secondarySize !== dim.secondarySize || item.primarySize !== dim.primarySize) {\n          item.node.style.cssText = item.node.style.cssText\n            .replace(WIDTH_HEIGHT_REGEX, WIDTH_HEIGHT_TEMPLATE_STR\n              //TODO fix item.primarySize + 1 hack\n              .replace(PRIMARY, (item.primarySize = dim.primarySize) + 1)\n              .replace(SECONDARY, (item.secondarySize = dim.secondarySize))\n            );\n        }\n\n      }\n\n      // If we reach the end of the list, render the afterItemsNode - this contains all the\n      // elements the developer placed after the collection-repeat\n      if (renderEndIndex === data.length - 1) {\n        dim = view.getDimensions(data.length - 1) || EMPTY_DIMENSION;\n        afterItemsNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR\n          .replace(PRIMARY, dim.primaryPos + dim.primarySize)\n          .replace(SECONDARY, 0);\n      }\n\n      while (itemsLeaving.length) {\n        item = itemsLeaving.pop();\n        item.scope.$broadcast('$collectionRepeatLeave');\n        ionic.Utils.disconnectScope(item.scope);\n        itemsPool.push(item);\n        item.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';\n        item.primaryPos = item.secondaryPos = null;\n      }\n\n      if (forceRefreshImages) {\n        for (i = 0, ii = itemsEntering.length; i < ii && (item = itemsEntering[i]); i++) {\n          if (!item.images) continue;\n          for (var j = 0, jj = item.images.length, img; j < jj && (img = item.images[j]); j++) {\n            var src = img.src;\n            img.src = ONE_PX_TRANSPARENT_IMG_SRC;\n            img.src = src;\n          }\n        }\n      }\n      if (forceRerender) {\n        var rootScopePhase = $rootScope.$$phase;\n        while (itemsEntering.length) {\n          item = itemsEntering.pop();\n          if (!rootScopePhase) item.scope.$digest();\n        }\n      } else {\n        digestEnteringItems();\n      }\n    }\n\n    function digestEnteringItems() {\n      var item;\n      if (digestEnteringItems.running) return;\n      digestEnteringItems.running = true;\n\n      $$rAF(function process() {\n        var rootScopePhase = $rootScope.$$phase;\n        while (itemsEntering.length) {\n          item = itemsEntering.pop();\n          if (item.isShown) {\n            if (!rootScopePhase) item.scope.$digest();\n          }\n        }\n        digestEnteringItems.running = false;\n      });\n    }\n\n    function RepeatItem() {\n      var self = this;\n      this.scope = scope.$new();\n      this.id = 'item' + (nextItemId++);\n      transclude(this.scope, function(clone) {\n        self.element = clone;\n        self.element.data('$$collectionRepeatItem', self);\n        // TODO destroy\n        self.node = clone[0];\n        // Batch style setting to lower repaints\n        self.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';\n        self.node.style.cssText += ' height: 0px; width: 0px;';\n        ionic.Utils.disconnectScope(self.scope);\n        containerNode.appendChild(self.node);\n        self.images = clone[0].getElementsByTagName('img');\n      });\n    }\n\n    function VerticalViewType() {\n      this.getItemPrimarySize = heightGetter;\n      this.getItemSecondarySize = widthGetter;\n\n      this.getScrollValue = function() {\n        return Math.max(0, Math.min(scrollView.__scrollTop - repeaterBeforeSize,\n          scrollView.__maxScrollTop - repeaterBeforeSize - repeaterAfterSize));\n      };\n\n      this.refreshDirection = function() {\n        this.scrollPrimarySize = scrollView.__clientHeight;\n        this.scrollSecondarySize = scrollView.__clientWidth;\n\n        this.estimatedPrimarySize = estimatedHeight;\n        this.estimatedSecondarySize = estimatedWidth;\n        this.estimatedItemsAcross = isGridView &&\n          Math.floor(scrollView.__clientWidth / estimatedWidth) ||\n          1;\n      };\n    }\n    function HorizontalViewType() {\n      this.getItemPrimarySize = widthGetter;\n      this.getItemSecondarySize = heightGetter;\n\n      this.getScrollValue = function() {\n        return Math.max(0, Math.min(scrollView.__scrollLeft - repeaterBeforeSize,\n          scrollView.__maxScrollLeft - repeaterBeforeSize - repeaterAfterSize));\n      };\n\n      this.refreshDirection = function() {\n        this.scrollPrimarySize = scrollView.__clientWidth;\n        this.scrollSecondarySize = scrollView.__clientHeight;\n\n        this.estimatedPrimarySize = estimatedWidth;\n        this.estimatedSecondarySize = estimatedHeight;\n        this.estimatedItemsAcross = isGridView &&\n          Math.floor(scrollView.__clientHeight / estimatedHeight) ||\n          1;\n      };\n    }\n\n    function GridViewType() {\n      this.getEstimatedSecondaryPos = function(index) {\n        return (index % this.estimatedItemsAcross) * this.estimatedSecondarySize;\n      };\n      this.getEstimatedPrimaryPos = function(index) {\n        return Math.floor(index / this.estimatedItemsAcross) * this.estimatedPrimarySize;\n      };\n      this.getEstimatedIndex = function(scrollValue) {\n        return Math.floor(scrollValue / this.estimatedPrimarySize) *\n          this.estimatedItemsAcross;\n      };\n    }\n\n    function ListViewType() {\n      this.getEstimatedSecondaryPos = function() {\n        return 0;\n      };\n      this.getEstimatedPrimaryPos = function(index) {\n        return index * this.estimatedPrimarySize;\n      };\n      this.getEstimatedIndex = function(scrollValue) {\n        return Math.floor((scrollValue) / this.estimatedPrimarySize);\n      };\n    }\n\n    function StaticViewType() {\n      this.getContentSize = function() {\n        return this.getEstimatedPrimaryPos(data.length - 1) + this.estimatedPrimarySize +\n          repeaterBeforeSize + repeaterAfterSize;\n      };\n      // static view always returns the same object for getDimensions, to avoid memory allocation\n      // while scrolling. This could be dangerous if this was a public function, but it's not.\n      // Only we use it.\n      var dim = {};\n      this.getDimensions = function(index) {\n        dim.primaryPos = this.getEstimatedPrimaryPos(index);\n        dim.secondaryPos = this.getEstimatedSecondaryPos(index);\n        dim.primarySize = this.estimatedPrimarySize;\n        dim.secondarySize = this.estimatedSecondarySize;\n        return dim;\n      };\n      this.updateRenderRange = function(scrollValue, scrollValueEnd) {\n        renderStartIndex = Math.max(0, this.getEstimatedIndex(scrollValue));\n\n        // Make sure the renderEndIndex takes into account all the items on the row\n        renderEndIndex = Math.min(data.length - 1,\n          this.getEstimatedIndex(scrollValueEnd) + this.estimatedItemsAcross - 1);\n\n        renderBeforeBoundary = Math.max(0,\n          this.getEstimatedPrimaryPos(renderStartIndex));\n        renderAfterBoundary = this.getEstimatedPrimaryPos(renderEndIndex) +\n          this.estimatedPrimarySize;\n      };\n    }\n\n    function DynamicViewType() {\n      var self = this;\n      var debouncedScrollViewSetDimensions = ionic.debounce(scrollViewSetDimensions, 25, true);\n      var calculateDimensions = isGridView ? calculateDimensionsGrid : calculateDimensionsList;\n      var dimensionsIndex;\n      var dimensions = [];\n\n\n      // Get the dimensions at index. {width, height, left, top}.\n      // We start with no dimensions calculated, then any time dimensions are asked for at an\n      // index we calculate dimensions up to there.\n      function calculateDimensionsList(toIndex) {\n        var i, prevDimension, dim;\n        for (i = Math.max(0, dimensionsIndex); i <= toIndex && (dim = dimensions[i]); i++) {\n          prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;\n          dim.primarySize = self.getItemPrimarySize(i, data[i]);\n          dim.secondarySize = self.scrollSecondarySize;\n          dim.primaryPos = prevDimension.primaryPos + prevDimension.primarySize;\n          dim.secondaryPos = 0;\n        }\n      }\n      function calculateDimensionsGrid(toIndex) {\n        var i, prevDimension, dim;\n        for (i = Math.max(dimensionsIndex, 0); i <= toIndex && (dim = dimensions[i]); i++) {\n          prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;\n          dim.secondarySize = Math.min(\n            self.getItemSecondarySize(i, data[i]),\n            self.scrollSecondarySize\n          );\n          dim.secondaryPos = prevDimension.secondaryPos + prevDimension.secondarySize;\n\n          if (i === 0 || dim.secondaryPos + dim.secondarySize > self.scrollSecondarySize) {\n            dim.secondaryPos = 0;\n            dim.primarySize = self.getItemPrimarySize(i, data[i]);\n            dim.primaryPos = prevDimension.primaryPos + prevDimension.rowPrimarySize;\n\n            dim.rowStartIndex = i;\n            dim.rowPrimarySize = dim.primarySize;\n          } else {\n            dim.primarySize = self.getItemPrimarySize(i, data[i]);\n            dim.primaryPos = prevDimension.primaryPos;\n            dim.rowStartIndex = prevDimension.rowStartIndex;\n\n            dimensions[dim.rowStartIndex].rowPrimarySize = dim.rowPrimarySize = Math.max(\n              dimensions[dim.rowStartIndex].rowPrimarySize,\n              dim.primarySize\n            );\n            dim.rowPrimarySize = Math.max(dim.primarySize, dim.rowPrimarySize);\n          }\n        }\n      }\n\n      this.getContentSize = function() {\n        var dim = dimensions[dimensionsIndex] || EMPTY_DIMENSION;\n        return ((dim.primaryPos + dim.primarySize) || 0) +\n          this.getEstimatedPrimaryPos(data.length - dimensionsIndex - 1) +\n          repeaterBeforeSize + repeaterAfterSize;\n      };\n      this.onDestroy = function() {\n        dimensions.length = 0;\n      };\n\n      this.onRefreshData = function() {\n        var i;\n        var ii;\n        // Make sure dimensions has as many items as data.length.\n        // This is to be sure we don't have to allocate objects while scrolling.\n        for (i = dimensions.length, ii = data.length; i < ii; i++) {\n          dimensions.push({});\n        }\n        dimensionsIndex = -1;\n      };\n      this.onRefreshLayout = function() {\n        dimensionsIndex = -1;\n      };\n      this.getDimensions = function(index) {\n        index = Math.min(index, data.length - 1);\n\n        if (dimensionsIndex < index) {\n          // Once we start asking for dimensions near the end of the list, go ahead and calculate\n          // everything. This is to make sure when the user gets to the end of the list, the\n          // scroll height of the list is 100% accurate (not estimated anymore).\n          if (index > data.length * 0.9) {\n            calculateDimensions(data.length - 1);\n            dimensionsIndex = data.length - 1;\n            scrollViewSetDimensions();\n          } else {\n            calculateDimensions(index);\n            dimensionsIndex = index;\n            debouncedScrollViewSetDimensions();\n          }\n\n        }\n        return dimensions[index];\n      };\n\n      var oldRenderStartIndex = -1;\n      var oldScrollValue = -1;\n      this.updateRenderRange = function(scrollValue, scrollValueEnd) {\n        var i;\n        var len;\n        var dim;\n\n        // Calculate more dimensions than we estimate we'll need, to be sure.\n        this.getDimensions( this.getEstimatedIndex(scrollValueEnd) * 2 );\n\n        // -- Calculate renderStartIndex\n        // base case: start at 0\n        if (oldRenderStartIndex === -1 || scrollValue === 0) {\n          i = 0;\n        // scrolling down\n        } else if (scrollValue >= oldScrollValue) {\n          for (i = oldRenderStartIndex, len = data.length; i < len; i++) {\n            if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize >= scrollValue) {\n              break;\n            }\n          }\n        // scrolling up\n        } else {\n          for (i = oldRenderStartIndex; i >= 0; i--) {\n            if ((dim = this.getDimensions(i)) && dim.primaryPos <= scrollValue) {\n              // when grid view, make sure the render starts at the beginning of a row.\n              i = isGridView ? dim.rowStartIndex : i;\n              break;\n            }\n          }\n        }\n\n        renderStartIndex = Math.min(Math.max(0, i), data.length - 1);\n        renderBeforeBoundary = renderStartIndex !== -1 ? this.getDimensions(renderStartIndex).primaryPos : -1;\n\n        // -- Calculate renderEndIndex\n        var lastRowDim;\n        for (i = renderStartIndex + 1, len = data.length; i < len; i++) {\n          if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize > scrollValueEnd) {\n\n            // Go all the way to the end of the row if we're in a grid\n            if (isGridView) {\n              lastRowDim = dim;\n              while (i < len - 1 &&\n                    (dim = this.getDimensions(i + 1)).primaryPos === lastRowDim.primaryPos) {\n                i++;\n              }\n            }\n            break;\n          }\n        }\n\n        renderEndIndex = Math.min(i, data.length - 1);\n        renderAfterBoundary = renderEndIndex !== -1 ?\n          ((dim = this.getDimensions(renderEndIndex)).primaryPos + (dim.rowPrimarySize || dim.primarySize)) :\n          -1;\n\n        oldScrollValue = scrollValue;\n        oldRenderStartIndex = renderStartIndex;\n      };\n    }\n\n\n  };\n\n}\n\n/**\n * @ngdoc directive\n * @name ionContent\n * @module ionic\n * @delegate ionic.service:$ionicScrollDelegate\n * @restrict E\n *\n * @description\n * The ionContent directive provides an easy to use content area that can be configured\n * to use Ionic's custom Scroll View, or the built in overflow scrolling of the browser.\n *\n * While we recommend using the custom Scroll features in Ionic in most cases, sometimes\n * (for performance reasons) only the browser's native overflow scrolling will suffice,\n * and so we've made it easy to toggle between the Ionic scroll implementation and\n * overflow scrolling.\n *\n * You can implement pull-to-refresh with the {@link ionic.directive:ionRefresher}\n * directive, and infinite scrolling with the {@link ionic.directive:ionInfiniteScroll}\n * directive.\n *\n * If there is any dynamic content inside the ion-content, be sure to call `.resize()` with {@link ionic.service:$ionicScrollDelegate}\n * after the content has been added.\n *\n * Be aware that this directive gets its own child scope. If you do not understand why this\n * is important, you can read [https://docs.angularjs.org/guide/scope](https://docs.angularjs.org/guide/scope).\n *\n * @param {string=} delegate-handle The handle used to identify this scrollView\n * with {@link ionic.service:$ionicScrollDelegate}.\n * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.\n * @param {boolean=} locking Whether to lock scrolling in one direction at a time. Useful to set to false when zoomed in or scrolling in two directions. Default true.\n * @param {boolean=} padding Whether to add padding to the content.\n * of the content.  Defaults to true on iOS, false on Android.\n * @param {boolean=} scroll Whether to allow scrolling of content.  Defaults to true.\n * @param {boolean=} overflow-scroll Whether to use overflow-scrolling instead of\n * Ionic scroll. See {@link ionic.provider:$ionicConfigProvider} to set this as the global default.\n * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.\n * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.\n * @param {string=} start-x Initial horizontal scroll position. Default 0.\n * @param {string=} start-y Initial vertical scroll position. Default 0.\n * @param {expression=} on-scroll Expression to evaluate when the content is scrolled.\n * @param {expression=} on-scroll-complete Expression to evaluate when a scroll action completes. Has access to 'scrollLeft' and 'scrollTop' locals.\n * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges\n * of the content.  Defaults to true on iOS, false on Android.\n * @param {number=} scroll-event-interval Number of milliseconds between each firing of the 'on-scroll' expression. Default 10.\n */\nIonicModule\n.directive('ionContent', [\n  '$timeout',\n  '$controller',\n  '$ionicBind',\n  '$ionicConfig',\nfunction($timeout, $controller, $ionicBind, $ionicConfig) {\n  return {\n    restrict: 'E',\n    require: '^?ionNavView',\n    scope: true,\n    priority: 800,\n    compile: function(element, attr) {\n      var innerElement;\n      var scrollCtrl;\n\n      element.addClass('scroll-content ionic-scroll');\n\n      if (attr.scroll != 'false') {\n        //We cannot use normal transclude here because it breaks element.data()\n        //inheritance on compile\n        innerElement = jqLite('<div class=\"scroll\"></div>');\n        innerElement.append(element.contents());\n        element.append(innerElement);\n      } else {\n        element.addClass('scroll-content-false');\n      }\n\n      var nativeScrolling = attr.overflowScroll === \"true\" || !$ionicConfig.scrolling.jsScrolling();\n\n      // collection-repeat requires JS scrolling\n      if (nativeScrolling) {\n        nativeScrolling = !element[0].querySelector('[collection-repeat]');\n      }\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attr) {\n        var parentScope = $scope.$parent;\n        $scope.$watch(function() {\n          return (parentScope.$hasHeader ? ' has-header' : '') +\n            (parentScope.$hasSubheader ? ' has-subheader' : '') +\n            (parentScope.$hasFooter ? ' has-footer' : '') +\n            (parentScope.$hasSubfooter ? ' has-subfooter' : '') +\n            (parentScope.$hasTabs ? ' has-tabs' : '') +\n            (parentScope.$hasTabsTop ? ' has-tabs-top' : '');\n        }, function(className, oldClassName) {\n          $element.removeClass(oldClassName);\n          $element.addClass(className);\n        });\n\n        //Only this ionContent should use these variables from parent scopes\n        $scope.$hasHeader = $scope.$hasSubheader =\n          $scope.$hasFooter = $scope.$hasSubfooter =\n          $scope.$hasTabs = $scope.$hasTabsTop =\n          false;\n        $ionicBind($scope, $attr, {\n          $onScroll: '&onScroll',\n          $onScrollComplete: '&onScrollComplete',\n          hasBouncing: '@',\n          padding: '@',\n          direction: '@',\n          scrollbarX: '@',\n          scrollbarY: '@',\n          startX: '@',\n          startY: '@',\n          scrollEventInterval: '@'\n        });\n        $scope.direction = $scope.direction || 'y';\n\n        if (isDefined($attr.padding)) {\n          $scope.$watch($attr.padding, function(newVal) {\n              (innerElement || $element).toggleClass('padding', !!newVal);\n          });\n        }\n\n        if ($attr.scroll === \"false\") {\n          //do nothing\n        } else {\n          var scrollViewOptions = {};\n\n          // determined in compile phase above\n          if (nativeScrolling) {\n            // use native scrolling\n            $element.addClass('overflow-scroll');\n\n            scrollViewOptions = {\n              el: $element[0],\n              delegateHandle: attr.delegateHandle,\n              startX: $scope.$eval($scope.startX) || 0,\n              startY: $scope.$eval($scope.startY) || 0,\n              nativeScrolling: true\n            };\n\n          } else {\n            // Use JS scrolling\n            scrollViewOptions = {\n              el: $element[0],\n              delegateHandle: attr.delegateHandle,\n              locking: (attr.locking || 'true') === 'true',\n              bouncing: $scope.$eval($scope.hasBouncing),\n              startX: $scope.$eval($scope.startX) || 0,\n              startY: $scope.$eval($scope.startY) || 0,\n              scrollbarX: $scope.$eval($scope.scrollbarX) !== false,\n              scrollbarY: $scope.$eval($scope.scrollbarY) !== false,\n              scrollingX: $scope.direction.indexOf('x') >= 0,\n              scrollingY: $scope.direction.indexOf('y') >= 0,\n              scrollEventInterval: parseInt($scope.scrollEventInterval, 10) || 10,\n              scrollingComplete: onScrollComplete\n            };\n          }\n\n          // init scroll controller with appropriate options\n          scrollCtrl = $controller('$ionicScroll', {\n            $scope: $scope,\n            scrollViewOptions: scrollViewOptions\n          });\n\n          $scope.$on('$destroy', function() {\n            if (scrollViewOptions) {\n              scrollViewOptions.scrollingComplete = noop;\n              delete scrollViewOptions.el;\n            }\n            innerElement = null;\n            $element = null;\n            attr.$$element = null;\n          });\n        }\n\n        function onScrollComplete() {\n          $scope.$onScrollComplete({\n            scrollTop: scrollCtrl.scrollView.__scrollTop,\n            scrollLeft: scrollCtrl.scrollView.__scrollLeft\n          });\n        }\n\n      }\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name exposeAsideWhen\n * @module ionic\n * @restrict A\n * @parent ionic.directive:ionSideMenus\n *\n * @description\n * It is common for a tablet application to hide a menu when in portrait mode, but to show the\n * same menu on the left side when the tablet is in landscape mode. The `exposeAsideWhen` attribute\n * directive can be used to accomplish a similar interface.\n *\n * By default, side menus are hidden underneath its side menu content, and can be opened by either\n * swiping the content left or right, or toggling a button to show the side menu. However, by adding the\n * `exposeAsideWhen` attribute directive to an {@link ionic.directive:ionSideMenu} element directive,\n * a side menu can be given instructions on \"when\" the menu should be exposed (always viewable). For\n * example, the `expose-aside-when=\"large\"` attribute will keep the side menu hidden when the viewport's\n * width is less than `768px`, but when the viewport's width is `768px` or greater, the menu will then\n * always be shown and can no longer be opened or closed like it could when it was hidden for smaller\n * viewports.\n *\n * Using `large` as the attribute's value is a shortcut value to `(min-width:768px)` since it is\n * the most common use-case. However, for added flexibility, any valid media query could be added\n * as the value, such as `(min-width:600px)` or even multiple queries such as\n * `(min-width:750px) and (max-width:1200px)`.\n\n * @usage\n * ```html\n * <ion-side-menus>\n *   <!-- Center content -->\n *   <ion-side-menu-content>\n *   </ion-side-menu-content>\n *\n *   <!-- Left menu -->\n *   <ion-side-menu expose-aside-when=\"large\">\n *   </ion-side-menu>\n * </ion-side-menus>\n * ```\n * For a complete side menu example, see the\n * {@link ionic.directive:ionSideMenus} documentation.\n */\nIonicModule.directive('exposeAsideWhen', ['$window', function($window) {\n  return {\n    restrict: 'A',\n    require: '^ionSideMenus',\n    link: function($scope, $element, $attr, sideMenuCtrl) {\n\n      function checkAsideExpose() {\n        var mq = $attr.exposeAsideWhen == 'large' ? '(min-width:768px)' : $attr.exposeAsideWhen;\n        sideMenuCtrl.exposeAside($window.matchMedia(mq).matches);\n        sideMenuCtrl.activeAsideResizing(false);\n      }\n\n      function onResize() {\n        sideMenuCtrl.activeAsideResizing(true);\n        debouncedCheck();\n      }\n\n      var debouncedCheck = ionic.debounce(function() {\n        $scope.$apply(checkAsideExpose);\n      }, 300, false);\n\n      $scope.$evalAsync(checkAsideExpose);\n\n      ionic.on('resize', onResize, $window);\n\n      $scope.$on('$destroy', function() {\n        ionic.off('resize', onResize, $window);\n      });\n\n    }\n  };\n}]);\n\n\nvar GESTURE_DIRECTIVES = 'onHold onTap onDoubleTap onTouch onRelease onDrag onDragUp onDragRight onDragDown onDragLeft onSwipe onSwipeUp onSwipeRight onSwipeDown onSwipeLeft'.split(' ');\n\nGESTURE_DIRECTIVES.forEach(function(name) {\n  IonicModule.directive(name, gestureDirective(name));\n});\n\n\n/**\n * @ngdoc directive\n * @name onHold\n * @module ionic\n * @restrict A\n *\n * @description\n * Touch stays at the same location for 500ms. Similar to long touch events available for AngularJS and jQuery.\n *\n * @usage\n * ```html\n * <button on-hold=\"onHold()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onTap\n * @module ionic\n * @restrict A\n *\n * @description\n * Quick touch at a location. If the duration of the touch goes\n * longer than 250ms it is no longer a tap gesture.\n *\n * @usage\n * ```html\n * <button on-tap=\"onTap()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDoubleTap\n * @module ionic\n * @restrict A\n *\n * @description\n * Double tap touch at a location.\n *\n * @usage\n * ```html\n * <button on-double-tap=\"onDoubleTap()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onTouch\n * @module ionic\n * @restrict A\n *\n * @description\n * Called immediately when the user first begins a touch. This\n * gesture does not wait for a touchend/mouseup.\n *\n * @usage\n * ```html\n * <button on-touch=\"onTouch()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onRelease\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the user ends a touch.\n *\n * @usage\n * ```html\n * <button on-release=\"onRelease()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDrag\n * @module ionic\n * @restrict A\n *\n * @description\n * Move with one touch around on the page. Blocking the scrolling when\n * moving left and right is a good practice. When all the drag events are\n * blocking you disable scrolling on that area.\n *\n * @usage\n * ```html\n * <button on-drag=\"onDrag()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragUp\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged up.\n *\n * @usage\n * ```html\n * <button on-drag-up=\"onDragUp()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragRight\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged to the right.\n *\n * @usage\n * ```html\n * <button on-drag-right=\"onDragRight()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragDown\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged down.\n *\n * @usage\n * ```html\n * <button on-drag-down=\"onDragDown()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragLeft\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged to the left.\n *\n * @usage\n * ```html\n * <button on-drag-left=\"onDragLeft()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipe\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity in any direction.\n *\n * @usage\n * ```html\n * <button on-swipe=\"onSwipe()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeUp\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving up.\n *\n * @usage\n * ```html\n * <button on-swipe-up=\"onSwipeUp()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeRight\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving to the right.\n *\n * @usage\n * ```html\n * <button on-swipe-right=\"onSwipeRight()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeDown\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving down.\n *\n * @usage\n * ```html\n * <button on-swipe-down=\"onSwipeDown()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeLeft\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving to the left.\n *\n * @usage\n * ```html\n * <button on-swipe-left=\"onSwipeLeft()\" class=\"button\">Test</button>\n * ```\n */\n\n\nfunction gestureDirective(directiveName) {\n  return ['$ionicGesture', '$parse', function($ionicGesture, $parse) {\n    var eventType = directiveName.substr(2).toLowerCase();\n\n    return function(scope, element, attr) {\n      var fn = $parse( attr[directiveName] );\n\n      var listener = function(ev) {\n        scope.$apply(function() {\n          fn(scope, {\n            $event: ev\n          });\n        });\n      };\n\n      var gesture = $ionicGesture.on(eventType, listener, element);\n\n      scope.$on('$destroy', function() {\n        $ionicGesture.off(gesture, eventType, listener);\n      });\n    };\n  }];\n}\n\n\nIonicModule\n.directive('ionHeaderBar', tapScrollToTopDirective())\n\n/**\n * @ngdoc directive\n * @name ionHeaderBar\n * @module ionic\n * @restrict E\n *\n * @description\n * Adds a fixed header bar above some content.\n *\n * Can also be a subheader (lower down) if the 'bar-subheader' class is applied.\n * See [the header CSS docs](/docs/components/#subheader).\n *\n * @param {string=} align-title How to align the title. By default the title\n * will be aligned the same as how the platform aligns its titles (iOS centers\n * titles, Android aligns them left).\n * Available: 'left', 'right', or 'center'.  Defaults to the same as the platform.\n * @param {boolean=} no-tap-scroll By default, the header bar will scroll the\n * content to the top when tapped.  Set no-tap-scroll to true to disable this\n * behavior.\n * Available: true or false.  Defaults to false.\n *\n * @usage\n * ```html\n * <ion-header-bar align-title=\"left\" class=\"bar-positive\">\n *   <div class=\"buttons\">\n *     <button class=\"button\" ng-click=\"doSomething()\">Left Button</button>\n *   </div>\n *   <h1 class=\"title\">Title!</h1>\n *   <div class=\"buttons\">\n *     <button class=\"button\">Right Button</button>\n *   </div>\n * </ion-header-bar>\n * <ion-content>\n *   Some content!\n * </ion-content>\n * ```\n */\n.directive('ionHeaderBar', headerFooterBarDirective(true))\n\n/**\n * @ngdoc directive\n * @name ionFooterBar\n * @module ionic\n * @restrict E\n *\n * @description\n * Adds a fixed footer bar below some content.\n *\n * Can also be a subfooter (higher up) if the 'bar-subfooter' class is applied.\n * See [the footer CSS docs](/docs/components/#footer).\n *\n * Note: If you use ionFooterBar in combination with ng-if, the surrounding content\n * will not align correctly.  This will be fixed soon.\n *\n * @param {string=} align-title Where to align the title.\n * Available: 'left', 'right', or 'center'.  Defaults to 'center'.\n *\n * @usage\n * ```html\n * <ion-content>\n *   Some content!\n * </ion-content>\n * <ion-footer-bar align-title=\"left\" class=\"bar-assertive\">\n *   <div class=\"buttons\">\n *     <button class=\"button\">Left Button</button>\n *   </div>\n *   <h1 class=\"title\">Title!</h1>\n *   <div class=\"buttons\" ng-click=\"doSomething()\">\n *     <button class=\"button\">Right Button</button>\n *   </div>\n * </ion-footer-bar>\n * ```\n */\n.directive('ionFooterBar', headerFooterBarDirective(false));\n\nfunction tapScrollToTopDirective() {\n  return ['$ionicScrollDelegate', function($ionicScrollDelegate) {\n    return {\n      restrict: 'E',\n      link: function($scope, $element, $attr) {\n        if ($attr.noTapScroll == 'true') {\n          return;\n        }\n        ionic.on('tap', onTap, $element[0]);\n        $scope.$on('$destroy', function() {\n          ionic.off('tap', onTap, $element[0]);\n        });\n\n        function onTap(e) {\n          var depth = 3;\n          var current = e.target;\n          //Don't scroll to top in certain cases\n          while (depth-- && current) {\n            if (current.classList.contains('button') ||\n                current.tagName.match(/input|textarea|select/i) ||\n                current.isContentEditable) {\n              return;\n            }\n            current = current.parentNode;\n          }\n          var touch = e.gesture && e.gesture.touches[0] || e.detail.touches[0];\n          var bounds = $element[0].getBoundingClientRect();\n          if (ionic.DomUtil.rectContains(\n            touch.pageX, touch.pageY,\n            bounds.left, bounds.top - 20,\n            bounds.left + bounds.width, bounds.top + bounds.height\n          )) {\n            $ionicScrollDelegate.scrollTop(true);\n          }\n        }\n      }\n    };\n  }];\n}\n\nfunction headerFooterBarDirective(isHeader) {\n  return ['$document', '$timeout', function($document, $timeout) {\n    return {\n      restrict: 'E',\n      controller: '$ionicHeaderBar',\n      compile: function(tElement) {\n        tElement.addClass(isHeader ? 'bar bar-header' : 'bar bar-footer');\n        // top style tabs? if so, remove bottom border for seamless display\n        $timeout(function() {\n          if (isHeader && $document[0].getElementsByClassName('tabs-top').length) tElement.addClass('has-tabs-top');\n        });\n\n        return { pre: prelink };\n        function prelink($scope, $element, $attr, ctrl) {\n          if (isHeader) {\n            $scope.$watch(function() { return $element[0].className; }, function(value) {\n              var isShown = value.indexOf('ng-hide') === -1;\n              var isSubheader = value.indexOf('bar-subheader') !== -1;\n              $scope.$hasHeader = isShown && !isSubheader;\n              $scope.$hasSubheader = isShown && isSubheader;\n              $scope.$emit('$ionicSubheader', $scope.$hasSubheader);\n            });\n            $scope.$on('$destroy', function() {\n              delete $scope.$hasHeader;\n              delete $scope.$hasSubheader;\n            });\n            ctrl.align();\n            $scope.$on('$ionicHeader.align', function() {\n              ionic.requestAnimationFrame(function() {\n                ctrl.align();\n              });\n            });\n\n          } else {\n            $scope.$watch(function() { return $element[0].className; }, function(value) {\n              var isShown = value.indexOf('ng-hide') === -1;\n              var isSubfooter = value.indexOf('bar-subfooter') !== -1;\n              $scope.$hasFooter = isShown && !isSubfooter;\n              $scope.$hasSubfooter = isShown && isSubfooter;\n            });\n            $scope.$on('$destroy', function() {\n              delete $scope.$hasFooter;\n              delete $scope.$hasSubfooter;\n            });\n            $scope.$watch('$hasTabs', function(val) {\n              $element.toggleClass('has-tabs', !!val);\n            });\n          }\n        }\n      }\n    };\n  }];\n}\n\n/**\n * @ngdoc directive\n * @name ionInfiniteScroll\n * @module ionic\n * @parent ionic.directive:ionContent, ionic.directive:ionScroll\n * @restrict E\n *\n * @description\n * The ionInfiniteScroll directive allows you to call a function whenever\n * the user gets to the bottom of the page or near the bottom of the page.\n *\n * The expression you pass in for `on-infinite` is called when the user scrolls\n * greater than `distance` away from the bottom of the content.  Once `on-infinite`\n * is done loading new data, it should broadcast the `scroll.infiniteScrollComplete`\n * event from your controller (see below example).\n *\n * @param {expression} on-infinite What to call when the scroller reaches the\n * bottom.\n * @param {string=} distance The distance from the bottom that the scroll must\n * reach to trigger the on-infinite expression. Default: 1%.\n * @param {string=} spinner The {@link ionic.directive:ionSpinner} to show while loading. The SVG\n * {@link ionic.directive:ionSpinner} is now the default, replacing rotating font icons.\n * @param {string=} icon The icon to show while loading. Default: 'ion-load-d'.  This is depreicated\n * in favor of the SVG {@link ionic.directive:ionSpinner}.\n * @param {boolean=} immediate-check Whether to check the infinite scroll bounds immediately on load.\n *\n * @usage\n * ```html\n * <ion-content ng-controller=\"MyController\">\n *   <ion-list>\n *   ....\n *   ....\n *   </ion-list>\n *\n *   <ion-infinite-scroll\n *     on-infinite=\"loadMore()\"\n *     distance=\"1%\">\n *   </ion-infinite-scroll>\n * </ion-content>\n * ```\n * ```js\n * function MyController($scope, $http) {\n *   $scope.items = [];\n *   $scope.loadMore = function() {\n *     $http.get('/more-items').success(function(items) {\n *       useItems(items);\n *       $scope.$broadcast('scroll.infiniteScrollComplete');\n *     });\n *   };\n *\n *   $scope.$on('$stateChangeSuccess', function() {\n *     $scope.loadMore();\n *   });\n * }\n * ```\n *\n * An easy to way to stop infinite scroll once there is no more data to load\n * is to use angular's `ng-if` directive:\n *\n * ```html\n * <ion-infinite-scroll\n *   ng-if=\"moreDataCanBeLoaded()\"\n *   icon=\"ion-loading-c\"\n *   on-infinite=\"loadMoreData()\">\n * </ion-infinite-scroll>\n * ```\n */\nIonicModule\n.directive('ionInfiniteScroll', ['$timeout', function($timeout) {\n  return {\n    restrict: 'E',\n    require: ['?^$ionicScroll', 'ionInfiniteScroll'],\n    template: function($element, $attrs) {\n      if ($attrs.icon) return '<i class=\"icon {{icon()}} icon-refreshing {{scrollingType}}\"></i>';\n      return '<ion-spinner icon=\"{{spinner()}}\"></ion-spinner>';\n    },\n    scope: true,\n    controller: '$ionInfiniteScroll',\n    link: function($scope, $element, $attrs, ctrls) {\n      var infiniteScrollCtrl = ctrls[1];\n      var scrollCtrl = infiniteScrollCtrl.scrollCtrl = ctrls[0];\n      var jsScrolling = infiniteScrollCtrl.jsScrolling = !scrollCtrl.isNative();\n\n      // if this view is not beneath a scrollCtrl, it can't be injected, proceed w/ native scrolling\n      if (jsScrolling) {\n        infiniteScrollCtrl.scrollView = scrollCtrl.scrollView;\n        $scope.scrollingType = 'js-scrolling';\n        //bind to JS scroll events\n        scrollCtrl.$element.on('scroll', infiniteScrollCtrl.checkBounds);\n      } else {\n        // grabbing the scrollable element, to determine dimensions, and current scroll pos\n        var scrollEl = ionic.DomUtil.getParentOrSelfWithClass($element[0].parentNode, 'overflow-scroll');\n        infiniteScrollCtrl.scrollEl = scrollEl;\n        // if there's no scroll controller, and no overflow scroll div, infinite scroll wont work\n        if (!scrollEl) {\n          throw 'Infinite scroll must be used inside a scrollable div';\n        }\n        //bind to native scroll events\n        infiniteScrollCtrl.scrollEl.addEventListener('scroll', infiniteScrollCtrl.checkBounds);\n      }\n\n      // Optionally check bounds on start after scrollView is fully rendered\n      var doImmediateCheck = isDefined($attrs.immediateCheck) ? $scope.$eval($attrs.immediateCheck) : true;\n      if (doImmediateCheck) {\n        $timeout(function() { infiniteScrollCtrl.checkBounds(); });\n      }\n    }\n  };\n}]);\n\n/**\n* @ngdoc directive\n* @name ionItem\n* @parent ionic.directive:ionList\n* @module ionic\n* @restrict E\n* Creates a list-item that can easily be swiped,\n* deleted, reordered, edited, and more.\n*\n* See {@link ionic.directive:ionList} for a complete example & explanation.\n*\n* Can be assigned any item class name. See the\n* [list CSS documentation](/docs/components/#list).\n*\n* @usage\n*\n* ```html\n* <ion-list>\n*   <ion-item>Hello!</ion-item>\n*   <ion-item href=\"#/detail\">\n*     Link to detail page\n*   </ion-item>\n* </ion-list>\n* ```\n*/\nIonicModule\n.directive('ionItem', ['$$rAF', function($$rAF) {\n  return {\n    restrict: 'E',\n    controller: ['$scope', '$element', function($scope, $element) {\n      this.$scope = $scope;\n      this.$element = $element;\n    }],\n    scope: true,\n    compile: function($element, $attrs) {\n      var isAnchor = isDefined($attrs.href) ||\n                     isDefined($attrs.ngHref) ||\n                     isDefined($attrs.uiSref);\n      var isComplexItem = isAnchor ||\n        //Lame way of testing, but we have to know at compile what to do with the element\n        /ion-(delete|option|reorder)-button/i.test($element.html());\n\n      if (isComplexItem) {\n        var innerElement = jqLite(isAnchor ? '<a></a>' : '<div></div>');\n        innerElement.addClass('item-content');\n\n        if (isDefined($attrs.href) || isDefined($attrs.ngHref)) {\n          innerElement.attr('ng-href', '{{$href()}}');\n          if (isDefined($attrs.target)) {\n            innerElement.attr('target', '{{$target()}}');\n          }\n        }\n\n        innerElement.append($element.contents());\n\n        $element.addClass('item item-complex')\n                .append(innerElement);\n      } else {\n        $element.addClass('item');\n      }\n\n      return function link($scope, $element, $attrs) {\n        $scope.$href = function() {\n          return $attrs.href || $attrs.ngHref;\n        };\n        $scope.$target = function() {\n          return $attrs.target;\n        };\n\n        var content = $element[0].querySelector('.item-content');\n        if (content) {\n          $scope.$on('$collectionRepeatLeave', function() {\n            if (content && content.$$ionicOptionsOpen) {\n              content.style[ionic.CSS.TRANSFORM] = '';\n              content.style[ionic.CSS.TRANSITION] = 'none';\n              $$rAF(function() {\n                content.style[ionic.CSS.TRANSITION] = '';\n              });\n              content.$$ionicOptionsOpen = false;\n            }\n          });\n        }\n      };\n\n    }\n  };\n}]);\n\nvar ITEM_TPL_DELETE_BUTTON =\n  '<div class=\"item-left-edit item-delete enable-pointer-events\">' +\n  '</div>';\n/**\n* @ngdoc directive\n* @name ionDeleteButton\n* @parent ionic.directive:ionItem\n* @module ionic\n* @restrict E\n* Creates a delete button inside a list item, that is visible when the\n* {@link ionic.directive:ionList ionList parent's} `show-delete` evaluates to true or\n* `$ionicListDelegate.showDelete(true)` is called.\n*\n* Takes any ionicon as a class.\n*\n* See {@link ionic.directive:ionList} for a complete example & explanation.\n*\n* @usage\n*\n* ```html\n* <ion-list show-delete=\"shouldShowDelete\">\n*   <ion-item>\n*     <ion-delete-button class=\"ion-minus-circled\"></ion-delete-button>\n*     Hello, list item!\n*   </ion-item>\n* </ion-list>\n* <ion-toggle ng-model=\"shouldShowDelete\">\n*   Show Delete?\n* </ion-toggle>\n* ```\n*/\nIonicModule\n.directive('ionDeleteButton', function() {\n\n  function stopPropagation(ev) {\n    ev.stopPropagation();\n  }\n\n  return {\n    restrict: 'E',\n    require: ['^^ionItem', '^?ionList'],\n    //Run before anything else, so we can move it before other directives process\n    //its location (eg ngIf relies on the location of the directive in the dom)\n    priority: Number.MAX_VALUE,\n    compile: function($element, $attr) {\n      //Add the classes we need during the compile phase, so that they stay\n      //even if something else like ngIf removes the element and re-addss it\n      $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);\n      return function($scope, $element, $attr, ctrls) {\n        var itemCtrl = ctrls[0];\n        var listCtrl = ctrls[1];\n        var container = jqLite(ITEM_TPL_DELETE_BUTTON);\n        container.append($element);\n        itemCtrl.$element.append(container).addClass('item-left-editable');\n\n        //Don't bubble click up to main .item\n        $element.on('click', stopPropagation);\n\n        init();\n        $scope.$on('$ionic.reconnectScope', init);\n        function init() {\n          listCtrl = listCtrl || $element.controller('ionList');\n          if (listCtrl && listCtrl.showDelete()) {\n            container.addClass('visible active');\n          }\n        }\n      };\n    }\n  };\n});\n\n\nIonicModule\n.directive('itemFloatingLabel', function() {\n  return {\n    restrict: 'C',\n    link: function(scope, element) {\n      var el = element[0];\n      var input = el.querySelector('input, textarea');\n      var inputLabel = el.querySelector('.input-label');\n\n      if (!input || !inputLabel) return;\n\n      var onInput = function() {\n        if (input.value) {\n          inputLabel.classList.add('has-input');\n        } else {\n          inputLabel.classList.remove('has-input');\n        }\n      };\n\n      input.addEventListener('input', onInput);\n\n      var ngModelCtrl = jqLite(input).controller('ngModel');\n      if (ngModelCtrl) {\n        ngModelCtrl.$render = function() {\n          input.value = ngModelCtrl.$viewValue || '';\n          onInput();\n        };\n      }\n\n      scope.$on('$destroy', function() {\n        input.removeEventListener('input', onInput);\n      });\n    }\n  };\n});\n\nvar ITEM_TPL_OPTION_BUTTONS =\n  '<div class=\"item-options invisible\">' +\n  '</div>';\n/**\n* @ngdoc directive\n* @name ionOptionButton\n* @parent ionic.directive:ionItem\n* @module ionic\n* @restrict E\n* Creates an option button inside a list item, that is visible when the item is swiped\n* to the left by the user.  Swiped open option buttons can be hidden with\n* {@link ionic.service:$ionicListDelegate#closeOptionButtons $ionicListDelegate#closeOptionButtons}.\n*\n* Can be assigned any button class.\n*\n* See {@link ionic.directive:ionList} for a complete example & explanation.\n*\n* @usage\n*\n* ```html\n* <ion-list>\n*   <ion-item>\n*     I love kittens!\n*     <ion-option-button class=\"button-positive\">Share</ion-option-button>\n*     <ion-option-button class=\"button-assertive\">Edit</ion-option-button>\n*   </ion-item>\n* </ion-list>\n* ```\n*/\nIonicModule.directive('ionOptionButton', [function() {\n  function stopPropagation(e) {\n    e.stopPropagation();\n  }\n  return {\n    restrict: 'E',\n    require: '^ionItem',\n    priority: Number.MAX_VALUE,\n    compile: function($element, $attr) {\n      $attr.$set('class', ($attr['class'] || '') + ' button', true);\n      return function($scope, $element, $attr, itemCtrl) {\n        if (!itemCtrl.optionsContainer) {\n          itemCtrl.optionsContainer = jqLite(ITEM_TPL_OPTION_BUTTONS);\n          itemCtrl.$element.append(itemCtrl.optionsContainer);\n        }\n        itemCtrl.optionsContainer.append($element);\n\n        itemCtrl.$element.addClass('item-right-editable');\n\n        //Don't bubble click up to main .item\n        $element.on('click', stopPropagation);\n      };\n    }\n  };\n}]);\n\nvar ITEM_TPL_REORDER_BUTTON =\n  '<div data-prevent-scroll=\"true\" class=\"item-right-edit item-reorder enable-pointer-events\">' +\n  '</div>';\n\n/**\n* @ngdoc directive\n* @name ionReorderButton\n* @parent ionic.directive:ionItem\n* @module ionic\n* @restrict E\n* Creates a reorder button inside a list item, that is visible when the\n* {@link ionic.directive:ionList ionList parent's} `show-reorder` evaluates to true or\n* `$ionicListDelegate.showReorder(true)` is called.\n*\n* Can be dragged to reorder items in the list. Takes any ionicon class.\n*\n* Note: Reordering works best when used with `ng-repeat`.  Be sure that all `ion-item` children of an `ion-list` are part of the same `ng-repeat` expression.\n*\n* When an item reorder is complete, the expression given in the `on-reorder` attribute is called. The `on-reorder` expression is given two locals that can be used: `$fromIndex` and `$toIndex`.  See below for an example.\n*\n* Look at {@link ionic.directive:ionList} for more examples.\n*\n* @usage\n*\n* ```html\n* <ion-list ng-controller=\"MyCtrl\" show-reorder=\"true\">\n*   <ion-item ng-repeat=\"item in items\">\n*     Item {{item}}\n*     <ion-reorder-button class=\"ion-navicon\"\n*                         on-reorder=\"moveItem(item, $fromIndex, $toIndex)\">\n*     </ion-reorder-button>\n*   </ion-item>\n* </ion-list>\n* ```\n* ```js\n* function MyCtrl($scope) {\n*   $scope.items = [1, 2, 3, 4];\n*   $scope.moveItem = function(item, fromIndex, toIndex) {\n*     //Move the item in the array\n*     $scope.items.splice(fromIndex, 1);\n*     $scope.items.splice(toIndex, 0, item);\n*   };\n* }\n* ```\n*\n* @param {expression=} on-reorder Expression to call when an item is reordered.\n* Parameters given: $fromIndex, $toIndex.\n*/\nIonicModule\n.directive('ionReorderButton', ['$parse', function($parse) {\n  return {\n    restrict: 'E',\n    require: ['^ionItem', '^?ionList'],\n    priority: Number.MAX_VALUE,\n    compile: function($element, $attr) {\n      $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);\n      $element[0].setAttribute('data-prevent-scroll', true);\n      return function($scope, $element, $attr, ctrls) {\n        var itemCtrl = ctrls[0];\n        var listCtrl = ctrls[1];\n        var onReorderFn = $parse($attr.onReorder);\n\n        $scope.$onReorder = function(oldIndex, newIndex) {\n          onReorderFn($scope, {\n            $fromIndex: oldIndex,\n            $toIndex: newIndex\n          });\n        };\n\n        // prevent clicks from bubbling up to the item\n        if (!$attr.ngClick && !$attr.onClick && !$attr.onclick) {\n          $element[0].onclick = function(e) {\n            e.stopPropagation();\n            return false;\n          };\n        }\n\n        var container = jqLite(ITEM_TPL_REORDER_BUTTON);\n        container.append($element);\n        itemCtrl.$element.append(container).addClass('item-right-editable');\n\n        if (listCtrl && listCtrl.showReorder()) {\n          container.addClass('visible active');\n        }\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name keyboardAttach\n * @module ionic\n * @restrict A\n *\n * @description\n * keyboard-attach is an attribute directive which will cause an element to float above\n * the keyboard when the keyboard shows. Currently only supports the\n * [ion-footer-bar]({{ page.versionHref }}/api/directive/ionFooterBar/) directive.\n *\n * ### Notes\n * - This directive requires the\n * [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard).\n * - On Android not in fullscreen mode, i.e. you have\n *   `<preference name=\"Fullscreen\" value=\"false\" />` or no preference in your `config.xml` file,\n *   this directive is unnecessary since it is the default behavior.\n * - On iOS, if there is an input in your footer, you will need to set\n *   `cordova.plugins.Keyboard.disableScroll(true)`.\n *\n * @usage\n *\n * ```html\n *  <ion-footer-bar align-title=\"left\" keyboard-attach class=\"bar-assertive\">\n *    <h1 class=\"title\">Title!</h1>\n *  </ion-footer-bar>\n * ```\n */\n\nIonicModule\n.directive('keyboardAttach', function() {\n  return function(scope, element) {\n    ionic.on('native.keyboardshow', onShow, window);\n    ionic.on('native.keyboardhide', onHide, window);\n\n    //deprecated\n    ionic.on('native.showkeyboard', onShow, window);\n    ionic.on('native.hidekeyboard', onHide, window);\n\n\n    var scrollCtrl;\n\n    function onShow(e) {\n      if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {\n        return;\n      }\n\n      //for testing\n      var keyboardHeight = e.keyboardHeight || e.detail.keyboardHeight;\n      element.css('bottom', keyboardHeight + \"px\");\n      scrollCtrl = element.controller('$ionicScroll');\n      if (scrollCtrl) {\n        scrollCtrl.scrollView.__container.style.bottom = keyboardHeight + keyboardAttachGetClientHeight(element[0]) + \"px\";\n      }\n    }\n\n    function onHide() {\n      if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {\n        return;\n      }\n\n      element.css('bottom', '');\n      if (scrollCtrl) {\n        scrollCtrl.scrollView.__container.style.bottom = '';\n      }\n    }\n\n    scope.$on('$destroy', function() {\n      ionic.off('native.keyboardshow', onShow, window);\n      ionic.off('native.keyboardhide', onHide, window);\n\n      //deprecated\n      ionic.off('native.showkeyboard', onShow, window);\n      ionic.off('native.hidekeyboard', onHide, window);\n    });\n  };\n});\n\nfunction keyboardAttachGetClientHeight(element) {\n  return element.clientHeight;\n}\n\n/**\n* @ngdoc directive\n* @name ionList\n* @module ionic\n* @delegate ionic.service:$ionicListDelegate\n* @codepen JsHjf\n* @restrict E\n* @description\n* The List is a widely used interface element in almost any mobile app, and can include\n* content ranging from basic text all the way to buttons, toggles, icons, and thumbnails.\n*\n* Both the list, which contains items, and the list items themselves can be any HTML\n* element. The containing element requires the `list` class and each list item requires\n* the `item` class.\n*\n* However, using the ionList and ionItem directives make it easy to support various\n* interaction modes such as swipe to edit, drag to reorder, and removing items.\n*\n* Related: {@link ionic.directive:ionItem}, {@link ionic.directive:ionOptionButton}\n* {@link ionic.directive:ionReorderButton}, {@link ionic.directive:ionDeleteButton}, [`list CSS documentation`](/docs/components/#list).\n*\n* @usage\n*\n* Basic Usage:\n*\n* ```html\n* <ion-list>\n*   <ion-item ng-repeat=\"item in items\">\n*     {% raw %}Hello, {{item}}!{% endraw %}\n*   </ion-item>\n* </ion-list>\n* ```\n*\n* Advanced Usage: Thumbnails, Delete buttons, Reordering, Swiping\n*\n* ```html\n* <ion-list ng-controller=\"MyCtrl\"\n*           show-delete=\"shouldShowDelete\"\n*           show-reorder=\"shouldShowReorder\"\n*           can-swipe=\"listCanSwipe\">\n*   <ion-item ng-repeat=\"item in items\"\n*             class=\"item-thumbnail-left\">\n*\n*     {% raw %}<img ng-src=\"{{item.img}}\">\n*     <h2>{{item.title}}</h2>\n*     <p>{{item.description}}</p>{% endraw %}\n*     <ion-option-button class=\"button-positive\"\n*                        ng-click=\"share(item)\">\n*       Share\n*     </ion-option-button>\n*     <ion-option-button class=\"button-info\"\n*                        ng-click=\"edit(item)\">\n*       Edit\n*     </ion-option-button>\n*     <ion-delete-button class=\"ion-minus-circled\"\n*                        ng-click=\"items.splice($index, 1)\">\n*     </ion-delete-button>\n*     <ion-reorder-button class=\"ion-navicon\"\n*                         on-reorder=\"reorderItem(item, $fromIndex, $toIndex)\">\n*     </ion-reorder-button>\n*\n*   </ion-item>\n* </ion-list>\n* ```\n*\n*```javascript\n* app.controller('MyCtrl', function($scope) {\n*  $scope.shouldShowDelete = false;\n*  $scope.shouldShowReorder = false;\n*  $scope.listCanSwipe = true\n* });\n*```\n*\n* @param {string=} delegate-handle The handle used to identify this list with\n* {@link ionic.service:$ionicListDelegate}.\n* @param type {string=} The type of list to use (list-inset or card)\n* @param show-delete {boolean=} Whether the delete buttons for the items in the list are\n* currently shown or hidden.\n* @param show-reorder {boolean=} Whether the reorder buttons for the items in the list are\n* currently shown or hidden.\n* @param can-swipe {boolean=} Whether the items in the list are allowed to be swiped to reveal\n* option buttons. Default: true.\n*/\nIonicModule\n.directive('ionList', [\n  '$timeout',\nfunction($timeout) {\n  return {\n    restrict: 'E',\n    require: ['ionList', '^?$ionicScroll'],\n    controller: '$ionicList',\n    compile: function($element, $attr) {\n      var listEl = jqLite('<div class=\"list\">')\n        .append($element.contents())\n        .addClass($attr.type);\n\n      $element.append(listEl);\n\n      return function($scope, $element, $attrs, ctrls) {\n        var listCtrl = ctrls[0];\n        var scrollCtrl = ctrls[1];\n\n        // Wait for child elements to render...\n        $timeout(init);\n\n        function init() {\n          var listView = listCtrl.listView = new ionic.views.ListView({\n            el: $element[0],\n            listEl: $element.children()[0],\n            scrollEl: scrollCtrl && scrollCtrl.element,\n            scrollView: scrollCtrl && scrollCtrl.scrollView,\n            onReorder: function(el, oldIndex, newIndex) {\n              var itemScope = jqLite(el).scope();\n              if (itemScope && itemScope.$onReorder) {\n                // Make sure onReorder is called in apply cycle,\n                // but also make sure it has no conflicts by doing\n                // $evalAsync\n                $timeout(function() {\n                  itemScope.$onReorder(oldIndex, newIndex);\n                });\n              }\n            },\n            canSwipe: function() {\n              return listCtrl.canSwipeItems();\n            }\n          });\n\n          $scope.$on('$destroy', function() {\n            if (listView) {\n              listView.deregister && listView.deregister();\n              listView = null;\n            }\n          });\n\n          if (isDefined($attr.canSwipe)) {\n            $scope.$watch('!!(' + $attr.canSwipe + ')', function(value) {\n              listCtrl.canSwipeItems(value);\n            });\n          }\n          if (isDefined($attr.showDelete)) {\n            $scope.$watch('!!(' + $attr.showDelete + ')', function(value) {\n              listCtrl.showDelete(value);\n            });\n          }\n          if (isDefined($attr.showReorder)) {\n            $scope.$watch('!!(' + $attr.showReorder + ')', function(value) {\n              listCtrl.showReorder(value);\n            });\n          }\n\n          $scope.$watch(function() {\n            return listCtrl.showDelete();\n          }, function(isShown, wasShown) {\n            //Only use isShown=false if it was already shown\n            if (!isShown && !wasShown) { return; }\n\n            if (isShown) listCtrl.closeOptionButtons();\n            listCtrl.canSwipeItems(!isShown);\n\n            $element.children().toggleClass('list-left-editing', isShown);\n            $element.toggleClass('disable-pointer-events', isShown);\n\n            var deleteButton = jqLite($element[0].getElementsByClassName('item-delete'));\n            setButtonShown(deleteButton, listCtrl.showDelete);\n          });\n\n          $scope.$watch(function() {\n            return listCtrl.showReorder();\n          }, function(isShown, wasShown) {\n            //Only use isShown=false if it was already shown\n            if (!isShown && !wasShown) { return; }\n\n            if (isShown) listCtrl.closeOptionButtons();\n            listCtrl.canSwipeItems(!isShown);\n\n            $element.children().toggleClass('list-right-editing', isShown);\n            $element.toggleClass('disable-pointer-events', isShown);\n\n            var reorderButton = jqLite($element[0].getElementsByClassName('item-reorder'));\n            setButtonShown(reorderButton, listCtrl.showReorder);\n          });\n\n          function setButtonShown(el, shown) {\n            shown() && el.addClass('visible') || el.removeClass('active');\n            ionic.requestAnimationFrame(function() {\n              shown() && el.addClass('active') || el.removeClass('visible');\n            });\n          }\n        }\n\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name menuClose\n * @module ionic\n * @restrict AC\n *\n * @description\n * `menu-close` is an attribute directive that closes a currently opened side menu.\n * Note that by default, navigation transitions will not animate between views when\n * the menu is open. Additionally, this directive will reset the entering view's\n * history stack, making the new page the root of the history stack. This is done\n * to replicate the user experience seen in most side menu implementations, which is\n * to not show the back button at the root of the stack and show only the\n * menu button. We recommend that you also use the `enable-menu-with-back-views=\"false\"`\n * {@link ionic.directive:ionSideMenus} attribute when using the menuClose directive.\n *\n * @usage\n * Below is an example of a link within a side menu. Tapping this link would\n * automatically close the currently opened menu.\n *\n * ```html\n * <a menu-close href=\"#/home\" class=\"item\">Home</a>\n * ```\n */\nIonicModule\n.directive('menuClose', ['$ionicHistory', function($ionicHistory) {\n  return {\n    restrict: 'AC',\n    link: function($scope, $element) {\n      $element.bind('click', function() {\n        var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');\n        if (sideMenuCtrl) {\n          $ionicHistory.nextViewOptions({\n            historyRoot: true,\n            disableAnimate: true,\n            expire: 300\n          });\n          sideMenuCtrl.close();\n        }\n      });\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name menuToggle\n * @module ionic\n * @restrict AC\n *\n * @description\n * Toggle a side menu on the given side.\n *\n * @usage\n * Below is an example of a link within a nav bar. Tapping this button\n * would open the given side menu, and tapping it again would close it.\n *\n * ```html\n * <ion-nav-bar>\n *   <ion-nav-buttons side=\"left\">\n *    <button menu-toggle=\"left\" class=\"button button-icon icon ion-navicon\"></button>\n *   </ion-nav-buttons>\n * </ion-nav-bar>\n * ```\n *\n * ### Button Hidden On Child Views\n * By default, the menu toggle button will only appear on a root\n * level side-menu page. Navigating in to child views will hide the menu-\n * toggle button. They can be made visible on child pages by setting the\n * enable-menu-with-back-views attribute of the {@link ionic.directive:ionSideMenus}\n * directive to true.\n *\n * ```html\n * <ion-side-menus enable-menu-with-back-views=\"true\">\n * ```\n */\nIonicModule\n.directive('menuToggle', function() {\n  return {\n    restrict: 'AC',\n    link: function($scope, $element, $attr) {\n      $scope.$on('$ionicView.beforeEnter', function(ev, viewData) {\n        if (viewData.enableBack) {\n          var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');\n          if (!sideMenuCtrl.enableMenuWithBackViews()) {\n            $element.addClass('hide');\n          }\n        } else {\n          $element.removeClass('hide');\n        }\n      });\n\n      $element.bind('click', function() {\n        var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');\n        sideMenuCtrl && sideMenuCtrl.toggle($attr.menuToggle);\n      });\n    }\n  };\n});\n\n/*\n * We don't document the ionModal directive, we instead document\n * the $ionicModal service\n */\nIonicModule\n.directive('ionModal', [function() {\n  return {\n    restrict: 'E',\n    transclude: true,\n    replace: true,\n    controller: [function() {}],\n    template: '<div class=\"modal-backdrop\">' +\n                '<div class=\"modal-backdrop-bg\"></div>' +\n                '<div class=\"modal-wrapper\" ng-transclude></div>' +\n              '</div>'\n  };\n}]);\n\nIonicModule\n.directive('ionModalView', function() {\n  return {\n    restrict: 'E',\n    compile: function(element) {\n      element.addClass('modal');\n    }\n  };\n});\n\n/**\n * @ngdoc directive\n * @name ionNavBackButton\n * @module ionic\n * @restrict E\n * @parent ionNavBar\n * @description\n * Creates a back button inside an {@link ionic.directive:ionNavBar}.\n *\n * The back button will appear when the user is able to go back in the current navigation stack. By\n * default, the markup of the back button is automatically built using platform-appropriate defaults\n * (iOS back button icon on iOS and Android icon on Android).\n *\n * Additionally, the button is automatically set to `$ionicGoBack()` on click/tap. By default, the\n * app will navigate back one view when the back button is clicked.  More advanced behavior is also\n * possible, as outlined below.\n *\n * @usage\n *\n * Recommended markup for default settings:\n *\n * ```html\n * <ion-nav-bar>\n *   <ion-nav-back-button>\n *   </ion-nav-back-button>\n * </ion-nav-bar>\n * ```\n *\n * With custom inner markup, and automatically adds a default click action:\n *\n * ```html\n * <ion-nav-bar>\n *   <ion-nav-back-button class=\"button-clear\">\n *     <i class=\"ion-arrow-left-c\"></i> Back\n *   </ion-nav-back-button>\n * </ion-nav-bar>\n * ```\n *\n * With custom inner markup and custom click action, using {@link ionic.service:$ionicHistory}:\n *\n * ```html\n * <ion-nav-bar ng-controller=\"MyCtrl\">\n *   <ion-nav-back-button class=\"button-clear\"\n *     ng-click=\"myGoBack()\">\n *     <i class=\"ion-arrow-left-c\"></i> Back\n *   </ion-nav-back-button>\n * </ion-nav-bar>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicHistory) {\n *   $scope.myGoBack = function() {\n *     $ionicHistory.goBack();\n *   };\n * }\n * ```\n */\nIonicModule\n.directive('ionNavBackButton', ['$ionicConfig', '$document', function($ionicConfig, $document) {\n  return {\n    restrict: 'E',\n    require: '^ionNavBar',\n    compile: function(tElement, tAttrs) {\n\n      // clone the back button, but as a <div>\n      var buttonEle = $document[0].createElement('button');\n      for (var n in tAttrs.$attr) {\n        buttonEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);\n      }\n\n      if (!tAttrs.ngClick) {\n        buttonEle.setAttribute('ng-click', '$ionicGoBack()');\n      }\n\n      buttonEle.className = 'button back-button hide buttons ' + (tElement.attr('class') || '');\n      buttonEle.innerHTML = tElement.html() || '';\n\n      var childNode;\n      var hasIcon = hasIconClass(tElement[0]);\n      var hasInnerText;\n      var hasButtonText;\n      var hasPreviousTitle;\n\n      for (var x = 0; x < tElement[0].childNodes.length; x++) {\n        childNode = tElement[0].childNodes[x];\n        if (childNode.nodeType === 1) {\n          if (hasIconClass(childNode)) {\n            hasIcon = true;\n          } else if (childNode.classList.contains('default-title')) {\n            hasButtonText = true;\n          } else if (childNode.classList.contains('previous-title')) {\n            hasPreviousTitle = true;\n          }\n        } else if (!hasInnerText && childNode.nodeType === 3) {\n          hasInnerText = !!childNode.nodeValue.trim();\n        }\n      }\n\n      function hasIconClass(ele) {\n        return /ion-|icon/.test(ele.className);\n      }\n\n      var defaultIcon = $ionicConfig.backButton.icon();\n      if (!hasIcon && defaultIcon && defaultIcon !== 'none') {\n        buttonEle.innerHTML = '<i class=\"icon ' + defaultIcon + '\"></i> ' + buttonEle.innerHTML;\n        buttonEle.className += ' button-clear';\n      }\n\n      if (!hasInnerText) {\n        var buttonTextEle = $document[0].createElement('span');\n        buttonTextEle.className = 'back-text';\n\n        if (!hasButtonText && $ionicConfig.backButton.text()) {\n          buttonTextEle.innerHTML += '<span class=\"default-title\">' + $ionicConfig.backButton.text() + '</span>';\n        }\n        if (!hasPreviousTitle && $ionicConfig.backButton.previousTitleText()) {\n          buttonTextEle.innerHTML += '<span class=\"previous-title\"></span>';\n        }\n        buttonEle.appendChild(buttonTextEle);\n\n      }\n\n      tElement.attr('class', 'hide');\n      tElement.empty();\n\n      return {\n        pre: function($scope, $element, $attr, navBarCtrl) {\n          // only register the plain HTML, the navBarCtrl takes care of scope/compile/link\n          navBarCtrl.navElement('backButton', buttonEle.outerHTML);\n          buttonEle = null;\n        }\n      };\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @name ionNavBar\n * @module ionic\n * @delegate ionic.service:$ionicNavBarDelegate\n * @restrict E\n *\n * @description\n * If we have an {@link ionic.directive:ionNavView} directive, we can also create an\n * `<ion-nav-bar>`, which will create a topbar that updates as the application state changes.\n *\n * We can add a back button by putting an {@link ionic.directive:ionNavBackButton} inside.\n *\n * We can add buttons depending on the currently visible view using\n * {@link ionic.directive:ionNavButtons}.\n *\n * Note that the ion-nav-bar element will only work correctly if your content has an\n * ionView around it.\n *\n * @usage\n *\n * ```html\n * <body ng-app=\"starter\">\n *   <!-- The nav bar that will be updated as we navigate -->\n *   <ion-nav-bar class=\"bar-positive\">\n *   </ion-nav-bar>\n *\n *   <!-- where the initial view template will be rendered -->\n *   <ion-nav-view>\n *     <ion-view>\n *       <ion-content>Hello!</ion-content>\n *     </ion-view>\n *   </ion-nav-view>\n * </body>\n * ```\n *\n * @param {string=} delegate-handle The handle used to identify this navBar\n * with {@link ionic.service:$ionicNavBarDelegate}.\n * @param align-title {string=} Where to align the title of the navbar.\n * Available: 'left', 'right', 'center'. Defaults to 'center'.\n * @param {boolean=} no-tap-scroll By default, the navbar will scroll the content\n * to the top when tapped.  Set no-tap-scroll to true to disable this behavior.\n *\n * </table><br/>\n */\nIonicModule\n.directive('ionNavBar', function() {\n  return {\n    restrict: 'E',\n    controller: '$ionicNavBar',\n    scope: true,\n    link: function($scope, $element, $attr, ctrl) {\n      ctrl.init();\n    }\n  };\n});\n\n\n/**\n * @ngdoc directive\n * @name ionNavButtons\n * @module ionic\n * @restrict E\n * @parent ionNavView\n *\n * @description\n * Use nav buttons to set the buttons on your {@link ionic.directive:ionNavBar}\n * from within an {@link ionic.directive:ionView}. This gives each\n * view template the ability to specify which buttons should show in the nav bar,\n * overriding any default buttons already placed in the nav bar.\n *\n * Any buttons you declare will be positioned on the navbar's corresponding side. Primary\n * buttons generally map to the left side of the header, and secondary buttons are\n * generally on the right side. However, their exact locations are platform-specific.\n * For example, in iOS, the primary buttons are on the far left of the header, and\n * secondary buttons are on the far right, with the header title centered between them.\n * For Android, however, both groups of buttons are on the far right of the header,\n * with the header title aligned left.\n *\n * We recommend always using `primary` and `secondary`, so the buttons correctly map\n * to the side familiar to users of each platform. However, in cases where buttons should\n * always be on an exact side, both `left` and `right` sides are still available. For\n * example, a toggle button for a left side menu should be on the left side; in this case,\n * we'd recommend using `side=\"left\"`, so it's always on the left, no matter the platform.\n *\n * ***Note*** that `ion-nav-buttons` must be immediate descendants of the `ion-view` or\n * `ion-nav-bar` element (basically, don't wrap it in another div).\n *\n * @usage\n * ```html\n * <ion-nav-bar>\n * </ion-nav-bar>\n * <ion-nav-view>\n *   <ion-view>\n *     <ion-nav-buttons side=\"primary\">\n *       <button class=\"button\" ng-click=\"doSomething()\">\n *         I'm a button on the primary of the navbar!\n *       </button>\n *     </ion-nav-buttons>\n *     <ion-content>\n *       Some super content here!\n *     </ion-content>\n *   </ion-view>\n * </ion-nav-view>\n * ```\n *\n * @param {string} side The side to place the buttons in the\n * {@link ionic.directive:ionNavBar}. Available sides: `primary`, `secondary`, `left`, and `right`.\n */\nIonicModule\n.directive('ionNavButtons', ['$document', function($document) {\n  return {\n    require: '^ionNavBar',\n    restrict: 'E',\n    compile: function(tElement, tAttrs) {\n      var side = 'left';\n\n      if (/^primary|secondary|right$/i.test(tAttrs.side || '')) {\n        side = tAttrs.side.toLowerCase();\n      }\n\n      var spanEle = $document[0].createElement('span');\n      spanEle.className = side + '-buttons';\n      spanEle.innerHTML = tElement.html();\n\n      var navElementType = side + 'Buttons';\n\n      tElement.attr('class', 'hide');\n      tElement.empty();\n\n      return {\n        pre: function($scope, $element, $attrs, navBarCtrl) {\n          // only register the plain HTML, the navBarCtrl takes care of scope/compile/link\n\n          var parentViewCtrl = $element.parent().data('$ionViewController');\n          if (parentViewCtrl) {\n            // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view\n            parentViewCtrl.navElement(navElementType, spanEle.outerHTML);\n\n          } else {\n            // these are buttons for all views that do not have their own ion-nav-buttons\n            navBarCtrl.navElement(navElementType, spanEle.outerHTML);\n          }\n\n          spanEle = null;\n        }\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name navDirection\n * @module ionic\n * @restrict A\n *\n * @description\n * The direction which the nav view transition should animate. Available options\n * are: `forward`, `back`, `enter`, `exit`, `swap`.\n *\n * @usage\n *\n * ```html\n * <a nav-direction=\"forward\" href=\"#/home\">Home</a>\n * ```\n */\nIonicModule\n.directive('navDirection', ['$ionicViewSwitcher', function($ionicViewSwitcher) {\n  return {\n    restrict: 'A',\n    priority: 1000,\n    link: function($scope, $element, $attr) {\n      $element.bind('click', function() {\n        $ionicViewSwitcher.nextDirection($attr.navDirection);\n      });\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionNavTitle\n * @module ionic\n * @restrict E\n * @parent ionNavView\n *\n * @description\n *\n * The nav title directive replaces an {@link ionic.directive:ionNavBar} title text with\n * custom HTML from within an {@link ionic.directive:ionView} template. This gives each\n * view the ability to specify its own custom title element, such as an image or any HTML,\n * rather than being text-only. Alternatively, text-only titles can be updated using the\n * `view-title` {@link ionic.directive:ionView} attribute.\n *\n * Note that `ion-nav-title` must be an immediate descendant of the `ion-view` or\n * `ion-nav-bar` element (basically don't wrap it in another div).\n *\n * @usage\n * ```html\n * <ion-nav-bar>\n * </ion-nav-bar>\n * <ion-nav-view>\n *   <ion-view>\n *     <ion-nav-title>\n *       <img src=\"logo.svg\">\n *     </ion-nav-title>\n *     <ion-content>\n *       Some super content here!\n *     </ion-content>\n *   </ion-view>\n * </ion-nav-view>\n * ```\n *\n */\nIonicModule\n.directive('ionNavTitle', ['$document', function($document) {\n  return {\n    require: '^ionNavBar',\n    restrict: 'E',\n    compile: function(tElement, tAttrs) {\n      var navElementType = 'title';\n      var spanEle = $document[0].createElement('span');\n      for (var n in tAttrs.$attr) {\n        spanEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);\n      }\n      spanEle.classList.add('nav-bar-title');\n      spanEle.innerHTML = tElement.html();\n\n      tElement.attr('class', 'hide');\n      tElement.empty();\n\n      return {\n        pre: function($scope, $element, $attrs, navBarCtrl) {\n          // only register the plain HTML, the navBarCtrl takes care of scope/compile/link\n\n          var parentViewCtrl = $element.parent().data('$ionViewController');\n          if (parentViewCtrl) {\n            // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view\n            parentViewCtrl.navElement(navElementType, spanEle.outerHTML);\n\n          } else {\n            // these are buttons for all views that do not have their own ion-nav-buttons\n            navBarCtrl.navElement(navElementType, spanEle.outerHTML);\n          }\n\n          spanEle = null;\n        }\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name navTransition\n * @module ionic\n * @restrict A\n *\n * @description\n * The transition type which the nav view transition should use when it animates.\n * Current, options are `ios`, `android`, and `none`. More options coming soon.\n *\n * @usage\n *\n * ```html\n * <a nav-transition=\"none\" href=\"#/home\">Home</a>\n * ```\n */\nIonicModule\n.directive('navTransition', ['$ionicViewSwitcher', function($ionicViewSwitcher) {\n  return {\n    restrict: 'A',\n    priority: 1000,\n    link: function($scope, $element, $attr) {\n      $element.bind('click', function() {\n        $ionicViewSwitcher.nextTransition($attr.navTransition);\n      });\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionNavView\n * @module ionic\n * @restrict E\n * @codepen odqCz\n *\n * @description\n * As a user navigates throughout your app, Ionic is able to keep track of their\n * navigation history. By knowing their history, transitions between views\n * correctly enter and exit using the platform's transition style. An additional\n * benefit to Ionic's navigation system is its ability to manage multiple\n * histories. For example, each tab can have it's own navigation history stack.\n *\n * Ionic uses the AngularUI Router module so app interfaces can be organized\n * into various \"states\". Like Angular's core $route service, URLs can be used\n * to control the views. However, the AngularUI Router provides a more powerful\n * state manager in that states are bound to named, nested, and parallel views,\n * allowing more than one template to be rendered on the same page.\n * Additionally, each state is not required to be bound to a URL, and data can\n * be pushed to each state which allows much flexibility.\n *\n * The ionNavView directive is used to render templates in your application. Each template\n * is part of a state. States are usually mapped to a url, and are defined programatically\n * using angular-ui-router (see [their docs](https://github.com/angular-ui/ui-router/wiki),\n * and remember to replace ui-view with ion-nav-view in examples).\n *\n * @usage\n * In this example, we will create a navigation view that contains our different states for the app.\n *\n * To do this, in our markup we use ionNavView top level directive. To display a header bar we use\n * the {@link ionic.directive:ionNavBar} directive that updates as we navigate through the\n * navigation stack.\n *\n * Next, we need to setup our states that will be rendered.\n *\n * ```js\n * var app = angular.module('myApp', ['ionic']);\n * app.config(function($stateProvider) {\n *   $stateProvider\n *   .state('index', {\n *     url: '/',\n *     templateUrl: 'home.html'\n *   })\n *   .state('music', {\n *     url: '/music',\n *     templateUrl: 'music.html'\n *   });\n * });\n * ```\n * Then on app start, $stateProvider will look at the url, see it matches the index state,\n * and then try to load home.html into the `<ion-nav-view>`.\n *\n * Pages are loaded by the URLs given. One simple way to create templates in Angular is to put\n * them directly into your HTML file and use the `<script type=\"text/ng-template\">` syntax.\n * So here is one way to put home.html into our app:\n *\n * ```html\n * <script id=\"home\" type=\"text/ng-template\">\n *   <!-- The title of the ion-view will be shown on the navbar -->\n *   <ion-view view-title=\"Home\">\n *     <ion-content ng-controller=\"HomeCtrl\">\n *       <!-- The content of the page -->\n *       <a href=\"#/music\">Go to music page!</a>\n *     </ion-content>\n *   </ion-view>\n * </script>\n * ```\n *\n * This is good to do because the template will be cached for very fast loading, instead of\n * having to fetch them from the network.\n *\n * ## Caching\n *\n * By default, views are cached to improve performance. When a view is navigated away from, its\n * element is left in the DOM, and its scope is disconnected from the `$watch` cycle. When\n * navigating to a view that is already cached, its scope is then reconnected, and the existing\n * element that was left in the DOM becomes the active view. This also allows for the scroll\n * position of previous views to be maintained.\n *\n * Caching can be disabled and enabled in multiple ways. By default, Ionic will cache a maximum of\n * 10 views, and not only can this be configured, but apps can also explicitly state which views\n * should and should not be cached.\n *\n * Note that because we are caching these views, *we aren’t destroying scopes*. Instead, scopes\n * are being disconnected from the watch cycle. Because scopes are not being destroyed and\n * recreated, controllers are not loading again on a subsequent viewing. If the app/controller\n * needs to know when a view has entered or has left, then view events emitted from the\n * {@link ionic.directive:ionView} scope, such as `$ionicView.enter`, may be useful.\n *\n * By default, when navigating back in the history, the \"forward\" views are removed from the cache.\n * If you navigate forward to the same view again, it'll create a new DOM element and controller\n * instance. Basically, any forward views are reset each time. This can be configured using the\n * {@link ionic.provider:$ionicConfigProvider}:\n *\n * ```js\n * $ionicConfigProvider.views.forwardCache(true);\n * ```\n *\n * #### Disable cache globally\n *\n * The {@link ionic.provider:$ionicConfigProvider} can be used to set the maximum allowable views\n * which can be cached, but this can also be use to disable all caching by setting it to 0.\n *\n * ```js\n * $ionicConfigProvider.views.maxCache(0);\n * ```\n *\n * #### Disable cache within state provider\n *\n * ```js\n * $stateProvider.state('myState', {\n *    cache: false,\n *    url : '/myUrl',\n *    templateUrl : 'my-template.html'\n * })\n * ```\n *\n * #### Disable cache with an attribute\n *\n * ```html\n * <ion-view cache-view=\"false\" view-title=\"My Title!\">\n *   ...\n * </ion-view>\n * ```\n *\n *\n * ## AngularUI Router\n *\n * Please visit [AngularUI Router's docs](https://github.com/angular-ui/ui-router/wiki) for\n * more info. Below is a great video by the AngularUI Router team that may help to explain\n * how it all works:\n *\n * <iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/dqJRoh8MnBo\"\n * frameborder=\"0\" allowfullscreen></iframe>\n *\n * @param {string=} name A view name. The name should be unique amongst the other views in the\n * same state. You can have views of the same name that live in different states. For more\n * information, see ui-router's\n * [ui-view documentation](http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view).\n */\nIonicModule\n.directive('ionNavView', [\n  '$state',\n  '$ionicConfig',\nfunction($state, $ionicConfig) {\n  // IONIC's fork of Angular UI Router, v0.2.10\n  // the navView handles registering views in the history and how to transition between them\n  return {\n    restrict: 'E',\n    terminal: true,\n    priority: 2000,\n    transclude: true,\n    controller: '$ionicNavView',\n    compile: function(tElement, tAttrs, transclude) {\n\n      // a nav view element is a container for numerous views\n      tElement.addClass('view-container');\n      ionic.DomUtil.cachedAttr(tElement, 'nav-view-transition', $ionicConfig.views.transition());\n\n      return function($scope, $element, $attr, navViewCtrl) {\n        var latestLocals;\n\n        // Put in the compiled initial view\n        transclude($scope, function(clone) {\n          $element.append(clone);\n        });\n\n        var viewData = navViewCtrl.init();\n\n        // listen for $stateChangeSuccess\n        $scope.$on('$stateChangeSuccess', function() {\n          updateView(false);\n        });\n        $scope.$on('$viewContentLoading', function() {\n          updateView(false);\n        });\n\n        // initial load, ready go\n        updateView(true);\n\n\n        function updateView(firstTime) {\n          // get the current local according to the $state\n          var viewLocals = $state.$current && $state.$current.locals[viewData.name];\n\n          // do not update THIS nav-view if its is not the container for the given state\n          // if the viewLocals are the same as THIS latestLocals, then nothing to do\n          if (!viewLocals || (!firstTime && viewLocals === latestLocals)) return;\n\n          // update the latestLocals\n          latestLocals = viewLocals;\n          viewData.state = viewLocals.$$state;\n\n          // register, update and transition to the new view\n          navViewCtrl.register(viewLocals);\n        }\n\n      };\n    }\n  };\n}]);\n\nIonicModule\n\n.config(['$provide', function($provide) {\n  $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {\n    // drop the default ngClick directive\n    $delegate.shift();\n    return $delegate;\n  }]);\n}])\n\n/**\n * @private\n */\n.factory('$ionicNgClick', ['$parse', function($parse) {\n  return function(scope, element, clickExpr) {\n    var clickHandler = angular.isFunction(clickExpr) ?\n      clickExpr :\n      $parse(clickExpr);\n\n    element.on('click', function(event) {\n      scope.$apply(function() {\n        clickHandler(scope, {$event: (event)});\n      });\n    });\n\n    // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click\n    // something else nearby.\n    element.onclick = noop;\n  };\n}])\n\n.directive('ngClick', ['$ionicNgClick', function($ionicNgClick) {\n  return function(scope, element, attr) {\n    $ionicNgClick(scope, element, attr.ngClick);\n  };\n}])\n\n.directive('ionStopEvent', function() {\n  return {\n    restrict: 'A',\n    link: function(scope, element, attr) {\n      element.bind(attr.ionStopEvent, eventStopPropagation);\n    }\n  };\n});\nfunction eventStopPropagation(e) {\n  e.stopPropagation();\n}\n\n\n/**\n * @ngdoc directive\n * @name ionPane\n * @module ionic\n * @restrict E\n *\n * @description A simple container that fits content, with no side effects.  Adds the 'pane' class to the element.\n */\nIonicModule\n.directive('ionPane', function() {\n  return {\n    restrict: 'E',\n    link: function(scope, element) {\n      element.addClass('pane');\n    }\n  };\n});\n\n/*\n * We don't document the ionPopover directive, we instead document\n * the $ionicPopover service\n */\nIonicModule\n.directive('ionPopover', [function() {\n  return {\n    restrict: 'E',\n    transclude: true,\n    replace: true,\n    controller: [function() {}],\n    template: '<div class=\"popover-backdrop\">' +\n                '<div class=\"popover-wrapper\" ng-transclude></div>' +\n              '</div>'\n  };\n}]);\n\nIonicModule\n.directive('ionPopoverView', function() {\n  return {\n    restrict: 'E',\n    compile: function(element) {\n      element.append(jqLite('<div class=\"popover-arrow\">'));\n      element.addClass('popover');\n    }\n  };\n});\n\n/**\n * @ngdoc directive\n * @name ionRadio\n * @module ionic\n * @restrict E\n * @codepen saoBG\n * @description\n * The radio directive is no different than the HTML radio input, except it's styled differently.\n *\n * Radio behaves like any [AngularJS radio](http://docs.angularjs.org/api/ng/input/input[radio]).\n *\n * @usage\n * ```html\n * <ion-radio ng-model=\"choice\" ng-value=\"'A'\">Choose A</ion-radio>\n * <ion-radio ng-model=\"choice\" ng-value=\"'B'\">Choose B</ion-radio>\n * <ion-radio ng-model=\"choice\" ng-value=\"'C'\">Choose C</ion-radio>\n * ```\n *\n * @param {string=} name The name of the radio input.\n * @param {expression=} value The value of the radio input.\n * @param {boolean=} disabled The state of the radio input.\n * @param {string=} icon The icon to use when the radio input is selected.\n * @param {expression=} ng-value Angular equivalent of the value attribute.\n * @param {expression=} ng-model The angular model for the radio input.\n * @param {boolean=} ng-disabled Angular equivalent of the disabled attribute.\n * @param {expression=} ng-change Triggers given expression when radio input's model changes\n */\nIonicModule\n.directive('ionRadio', function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '?ngModel',\n    transclude: true,\n    template:\n      '<label class=\"item item-radio\">' +\n        '<input type=\"radio\" name=\"radio-group\">' +\n        '<div class=\"item-content disable-pointer-events\" ng-transclude></div>' +\n        '<i class=\"radio-icon disable-pointer-events icon ion-checkmark\"></i>' +\n      '</label>',\n\n    compile: function(element, attr) {\n      if (attr.icon) {\n        element.children().eq(2).removeClass('ion-checkmark').addClass(attr.icon);\n      }\n\n      var input = element.find('input');\n      forEach({\n          'name': attr.name,\n          'value': attr.value,\n          'disabled': attr.disabled,\n          'ng-value': attr.ngValue,\n          'ng-model': attr.ngModel,\n          'ng-disabled': attr.ngDisabled,\n          'ng-change': attr.ngChange,\n          'ng-required': attr.ngRequired,\n          'required': attr.required\n      }, function(value, name) {\n        if (isDefined(value)) {\n            input.attr(name, value);\n          }\n      });\n\n      return function(scope, element, attr) {\n        scope.getValue = function() {\n          return scope.ngValue || attr.value;\n        };\n      };\n    }\n  };\n});\n\n\n/**\n * @ngdoc directive\n * @name ionRefresher\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionContent, ionic.directive:ionScroll\n * @description\n * Allows you to add pull-to-refresh to a scrollView.\n *\n * Place it as the first child of your {@link ionic.directive:ionContent} or\n * {@link ionic.directive:ionScroll} element.\n *\n * When refreshing is complete, $broadcast the 'scroll.refreshComplete' event\n * from your controller.\n *\n * @usage\n *\n * ```html\n * <ion-content ng-controller=\"MyController\">\n *   <ion-refresher\n *     pulling-text=\"Pull to refresh...\"\n *     on-refresh=\"doRefresh()\">\n *   </ion-refresher>\n *   <ion-list>\n *     <ion-item ng-repeat=\"item in items\"></ion-item>\n *   </ion-list>\n * </ion-content>\n * ```\n * ```js\n * angular.module('testApp', ['ionic'])\n * .controller('MyController', function($scope, $http) {\n *   $scope.items = [1,2,3];\n *   $scope.doRefresh = function() {\n *     $http.get('/new-items')\n *      .success(function(newItems) {\n *        $scope.items = newItems;\n *      })\n *      .finally(function() {\n *        // Stop the ion-refresher from spinning\n *        $scope.$broadcast('scroll.refreshComplete');\n *      });\n *   };\n * });\n * ```\n *\n * @param {expression=} on-refresh Called when the user pulls down enough and lets go\n * of the refresher.\n * @param {expression=} on-pulling Called when the user starts to pull down\n * on the refresher.\n * @param {string=} pulling-text The text to display while the user is pulling down.\n * @param {string=} pulling-icon The icon to display while the user is pulling down.\n * Default: 'ion-android-arrow-down'.\n * @param {string=} spinner The {@link ionic.directive:ionSpinner} icon to display\n * after user lets go of the refresher. The SVG {@link ionic.directive:ionSpinner}\n * is now the default, replacing rotating font icons. Set to `none` to disable both the\n * spinner and the icon.\n * @param {string=} refreshing-icon The font icon to display after user lets go of the\n * refresher. This is depreicated in favor of the SVG {@link ionic.directive:ionSpinner}.\n * @param {boolean=} disable-pulling-rotation Disables the rotation animation of the pulling\n * icon when it reaches its activated threshold. To be used with a custom `pulling-icon`.\n *\n */\nIonicModule\n.directive('ionRefresher', [function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: ['?^$ionicScroll', 'ionRefresher'],\n    controller: '$ionicRefresher',\n    template:\n    '<div class=\"scroll-refresher invisible\" collection-repeat-ignore>' +\n      '<div class=\"ionic-refresher-content\" ' +\n      'ng-class=\"{\\'ionic-refresher-with-text\\': pullingText || refreshingText}\">' +\n        '<div class=\"icon-pulling\" ng-class=\"{\\'pulling-rotation-disabled\\':disablePullingRotation}\">' +\n          '<i class=\"icon {{pullingIcon}}\"></i>' +\n        '</div>' +\n        '<div class=\"text-pulling\" ng-bind-html=\"pullingText\"></div>' +\n        '<div class=\"icon-refreshing\">' +\n          '<ion-spinner ng-if=\"showSpinner\" icon=\"{{spinner}}\"></ion-spinner>' +\n          '<i ng-if=\"showIcon\" class=\"icon {{refreshingIcon}}\"></i>' +\n        '</div>' +\n        '<div class=\"text-refreshing\" ng-bind-html=\"refreshingText\"></div>' +\n      '</div>' +\n    '</div>',\n    link: function($scope, $element, $attrs, ctrls) {\n\n      // JS Scrolling uses the scroll controller\n      var scrollCtrl = ctrls[0],\n          refresherCtrl = ctrls[1];\n      if (!scrollCtrl || scrollCtrl.isNative()) {\n        // Kick off native scrolling\n        refresherCtrl.init();\n      } else {\n        $element[0].classList.add('js-scrolling');\n        scrollCtrl._setRefresher(\n          $scope,\n          $element[0],\n          refresherCtrl.getRefresherDomMethods()\n        );\n\n        $scope.$on('scroll.refreshComplete', function() {\n          $scope.$evalAsync(function() {\n            scrollCtrl.scrollView.finishPullToRefresh();\n          });\n        });\n      }\n\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionScroll\n * @module ionic\n * @delegate ionic.service:$ionicScrollDelegate\n * @codepen mwFuh\n * @restrict E\n *\n * @description\n * Creates a scrollable container for all content inside.\n *\n * @usage\n *\n * Basic usage:\n *\n * ```html\n * <ion-scroll zooming=\"true\" direction=\"xy\" style=\"width: 500px; height: 500px\">\n *   <div style=\"width: 5000px; height: 5000px; background: url('https://upload.wikimedia.org/wikipedia/commons/a/ad/Europe_geological_map-en.jpg') repeat\"></div>\n *  </ion-scroll>\n * ```\n *\n * Note that it's important to set the height of the scroll box as well as the height of the inner\n * content to enable scrolling. This makes it possible to have full control over scrollable areas.\n *\n * If you'd just like to have a center content scrolling area, use {@link ionic.directive:ionContent} instead.\n *\n * @param {string=} delegate-handle The handle used to identify this scrollView\n * with {@link ionic.service:$ionicScrollDelegate}.\n * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.\n * @param {boolean=} locking Whether to lock scrolling in one direction at a time. Useful to set to false when zoomed in or scrolling in two directions. Default true.\n * @param {boolean=} paging Whether to scroll with paging.\n * @param {expression=} on-refresh Called on pull-to-refresh, triggered by an {@link ionic.directive:ionRefresher}.\n * @param {expression=} on-scroll Called whenever the user scrolls.\n * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.\n * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.\n * @param {boolean=} zooming Whether to support pinch-to-zoom\n * @param {integer=} min-zoom The smallest zoom amount allowed (default is 0.5)\n * @param {integer=} max-zoom The largest zoom amount allowed (default is 3)\n * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges\n * of the content.  Defaults to true on iOS, false on Android.\n */\nIonicModule\n.directive('ionScroll', [\n  '$timeout',\n  '$controller',\n  '$ionicBind',\nfunction($timeout, $controller, $ionicBind) {\n  return {\n    restrict: 'E',\n    scope: true,\n    controller: function() {},\n    compile: function(element) {\n      element.addClass('scroll-view ionic-scroll');\n\n      //We cannot transclude here because it breaks element.data() inheritance on compile\n      var innerElement = jqLite('<div class=\"scroll\"></div>');\n      innerElement.append(element.contents());\n      element.append(innerElement);\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attr) {\n        $ionicBind($scope, $attr, {\n          direction: '@',\n          paging: '@',\n          $onScroll: '&onScroll',\n          scroll: '@',\n          scrollbarX: '@',\n          scrollbarY: '@',\n          zooming: '@',\n          minZoom: '@',\n          maxZoom: '@'\n        });\n        $scope.direction = $scope.direction || 'y';\n\n        if (isDefined($attr.padding)) {\n          $scope.$watch($attr.padding, function(newVal) {\n            innerElement.toggleClass('padding', !!newVal);\n          });\n        }\n        if ($scope.$eval($scope.paging) === true) {\n          innerElement.addClass('scroll-paging');\n        }\n\n        if (!$scope.direction) { $scope.direction = 'y'; }\n        var isPaging = $scope.$eval($scope.paging) === true;\n\n        var scrollViewOptions = {\n          el: $element[0],\n          delegateHandle: $attr.delegateHandle,\n          locking: ($attr.locking || 'true') === 'true',\n          bouncing: $scope.$eval($attr.hasBouncing),\n          paging: isPaging,\n          scrollbarX: $scope.$eval($scope.scrollbarX) !== false,\n          scrollbarY: $scope.$eval($scope.scrollbarY) !== false,\n          scrollingX: $scope.direction.indexOf('x') >= 0,\n          scrollingY: $scope.direction.indexOf('y') >= 0,\n          zooming: $scope.$eval($scope.zooming) === true,\n          maxZoom: $scope.$eval($scope.maxZoom) || 3,\n          minZoom: $scope.$eval($scope.minZoom) || 0.5,\n          preventDefault: true\n        };\n        if (isPaging) {\n          scrollViewOptions.speedMultiplier = 0.8;\n          scrollViewOptions.bouncing = false;\n        }\n\n        $controller('$ionicScroll', {\n          $scope: $scope,\n          scrollViewOptions: scrollViewOptions\n        });\n      }\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionSideMenu\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionSideMenus\n *\n * @description\n * A container for a side menu, sibling to an {@link ionic.directive:ionSideMenuContent} directive.\n *\n * @usage\n * ```html\n * <ion-side-menu\n *   side=\"left\"\n *   width=\"myWidthValue + 20\"\n *   is-enabled=\"shouldLeftSideMenuBeEnabled()\">\n * </ion-side-menu>\n * ```\n * For a complete side menu example, see the\n * {@link ionic.directive:ionSideMenus} documentation.\n *\n * @param {string} side Which side the side menu is currently on.  Allowed values: 'left' or 'right'.\n * @param {boolean=} is-enabled Whether this side menu is enabled.\n * @param {number=} width How many pixels wide the side menu should be.  Defaults to 275.\n */\nIonicModule\n.directive('ionSideMenu', function() {\n  return {\n    restrict: 'E',\n    require: '^ionSideMenus',\n    scope: true,\n    compile: function(element, attr) {\n      angular.isUndefined(attr.isEnabled) && attr.$set('isEnabled', 'true');\n      angular.isUndefined(attr.width) && attr.$set('width', '275');\n\n      element.addClass('menu menu-' + attr.side);\n\n      return function($scope, $element, $attr, sideMenuCtrl) {\n        $scope.side = $attr.side || 'left';\n\n        var sideMenu = sideMenuCtrl[$scope.side] = new ionic.views.SideMenu({\n          width: attr.width,\n          el: $element[0],\n          isEnabled: true\n        });\n\n        $scope.$watch($attr.width, function(val) {\n          var numberVal = +val;\n          if (numberVal && numberVal == val) {\n            sideMenu.setWidth(+val);\n          }\n        });\n        $scope.$watch($attr.isEnabled, function(val) {\n          sideMenu.setIsEnabled(!!val);\n        });\n      };\n    }\n  };\n});\n\n\n/**\n * @ngdoc directive\n * @name ionSideMenuContent\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionSideMenus\n *\n * @description\n * A container for the main visible content, sibling to one or more\n * {@link ionic.directive:ionSideMenu} directives.\n *\n * @usage\n * ```html\n * <ion-side-menu-content\n *   edge-drag-threshold=\"true\"\n *   drag-content=\"true\">\n * </ion-side-menu-content>\n * ```\n * For a complete side menu example, see the\n * {@link ionic.directive:ionSideMenus} documentation.\n *\n * @param {boolean=} drag-content Whether the content can be dragged. Default true.\n * @param {boolean|number=} edge-drag-threshold Whether the content drag can only start if it is below a certain threshold distance from the edge of the screen.  Default false. Accepts three types of values:\n   *  - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.\n   *  - If true is given, the default number of pixels (25) is used as the maximum allowed distance.\n   *  - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.\n *\n */\nIonicModule\n.directive('ionSideMenuContent', [\n  '$timeout',\n  '$ionicGesture',\n  '$window',\nfunction($timeout, $ionicGesture, $window) {\n\n  return {\n    restrict: 'EA', //DEPRECATED 'A'\n    require: '^ionSideMenus',\n    scope: true,\n    compile: function(element, attr) {\n      element.addClass('menu-content pane');\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attr, sideMenuCtrl) {\n        var startCoord = null;\n        var primaryScrollAxis = null;\n\n        if (isDefined(attr.dragContent)) {\n          $scope.$watch(attr.dragContent, function(value) {\n            sideMenuCtrl.canDragContent(value);\n          });\n        } else {\n          sideMenuCtrl.canDragContent(true);\n        }\n\n        if (isDefined(attr.edgeDragThreshold)) {\n          $scope.$watch(attr.edgeDragThreshold, function(value) {\n            sideMenuCtrl.edgeDragThreshold(value);\n          });\n        }\n\n        // Listen for taps on the content to close the menu\n        function onContentTap(gestureEvt) {\n          if (sideMenuCtrl.getOpenAmount() !== 0) {\n            sideMenuCtrl.close();\n            gestureEvt.gesture.srcEvent.preventDefault();\n            startCoord = null;\n            primaryScrollAxis = null;\n          } else if (!startCoord) {\n            startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);\n          }\n        }\n\n        function onDragX(e) {\n          if (!sideMenuCtrl.isDraggableTarget(e)) return;\n\n          if (getPrimaryScrollAxis(e) == 'x') {\n            sideMenuCtrl._handleDrag(e);\n            e.gesture.srcEvent.preventDefault();\n          }\n        }\n\n        function onDragY(e) {\n          if (getPrimaryScrollAxis(e) == 'x') {\n            e.gesture.srcEvent.preventDefault();\n          }\n        }\n\n        function onDragRelease(e) {\n          sideMenuCtrl._endDrag(e);\n          startCoord = null;\n          primaryScrollAxis = null;\n        }\n\n        function getPrimaryScrollAxis(gestureEvt) {\n          // gets whether the user is primarily scrolling on the X or Y\n          // If a majority of the drag has been on the Y since the start of\n          // the drag, but the X has moved a little bit, it's still a Y drag\n\n          if (primaryScrollAxis) {\n            // we already figured out which way they're scrolling\n            return primaryScrollAxis;\n          }\n\n          if (gestureEvt && gestureEvt.gesture) {\n\n            if (!startCoord) {\n              // get the starting point\n              startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);\n\n            } else {\n              // we already have a starting point, figure out which direction they're going\n              var endCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);\n\n              var xDistance = Math.abs(endCoord.x - startCoord.x);\n              var yDistance = Math.abs(endCoord.y - startCoord.y);\n\n              var scrollAxis = (xDistance < yDistance ? 'y' : 'x');\n\n              if (Math.max(xDistance, yDistance) > 30) {\n                // ok, we pretty much know which way they're going\n                // let's lock it in\n                primaryScrollAxis = scrollAxis;\n              }\n\n              return scrollAxis;\n            }\n          }\n          return 'y';\n        }\n\n        var content = {\n          element: element[0],\n          onDrag: function() {},\n          endDrag: function() {},\n          getTranslateX: function() {\n            return $scope.sideMenuContentTranslateX || 0;\n          },\n          setTranslateX: ionic.animationFrameThrottle(function(amount) {\n            var xTransform = content.offsetX + amount;\n            $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + xTransform + 'px,0,0)';\n            $timeout(function() {\n              $scope.sideMenuContentTranslateX = amount;\n            });\n          }),\n          setMarginLeft: ionic.animationFrameThrottle(function(amount) {\n            if (amount) {\n              amount = parseInt(amount, 10);\n              $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amount + 'px,0,0)';\n              $element[0].style.width = ($window.innerWidth - amount) + 'px';\n              content.offsetX = amount;\n            } else {\n              $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';\n              $element[0].style.width = '';\n              content.offsetX = 0;\n            }\n          }),\n          setMarginRight: ionic.animationFrameThrottle(function(amount) {\n            if (amount) {\n              amount = parseInt(amount, 10);\n              $element[0].style.width = ($window.innerWidth - amount) + 'px';\n              content.offsetX = amount;\n            } else {\n              $element[0].style.width = '';\n              content.offsetX = 0;\n            }\n            // reset incase left gets grabby\n            $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';\n          }),\n          enableAnimation: function() {\n            $scope.animationEnabled = true;\n            $element[0].classList.add('menu-animated');\n          },\n          disableAnimation: function() {\n            $scope.animationEnabled = false;\n            $element[0].classList.remove('menu-animated');\n          },\n          offsetX: 0\n        };\n\n        sideMenuCtrl.setContent(content);\n\n        // add gesture handlers\n        var gestureOpts = { stop_browser_behavior: false };\n        if (ionic.DomUtil.getParentOrSelfWithClass($element[0], 'overflow-scroll')) {\n          gestureOpts.prevent_default_directions = ['left', 'right'];\n        }\n        var contentTapGesture = $ionicGesture.on('tap', onContentTap, $element, gestureOpts);\n        var dragRightGesture = $ionicGesture.on('dragright', onDragX, $element, gestureOpts);\n        var dragLeftGesture = $ionicGesture.on('dragleft', onDragX, $element, gestureOpts);\n        var dragUpGesture = $ionicGesture.on('dragup', onDragY, $element, gestureOpts);\n        var dragDownGesture = $ionicGesture.on('dragdown', onDragY, $element, gestureOpts);\n        var releaseGesture = $ionicGesture.on('release', onDragRelease, $element, gestureOpts);\n\n        // Cleanup\n        $scope.$on('$destroy', function() {\n          if (content) {\n            content.element = null;\n            content = null;\n          }\n          $ionicGesture.off(dragLeftGesture, 'dragleft', onDragX);\n          $ionicGesture.off(dragRightGesture, 'dragright', onDragX);\n          $ionicGesture.off(dragUpGesture, 'dragup', onDragY);\n          $ionicGesture.off(dragDownGesture, 'dragdown', onDragY);\n          $ionicGesture.off(releaseGesture, 'release', onDragRelease);\n          $ionicGesture.off(contentTapGesture, 'tap', onContentTap);\n        });\n      }\n    }\n  };\n}]);\n\nIonicModule\n\n/**\n * @ngdoc directive\n * @name ionSideMenus\n * @module ionic\n * @delegate ionic.service:$ionicSideMenuDelegate\n * @restrict E\n *\n * @description\n * A container element for side menu(s) and the main content. Allows the left and/or right side menu\n * to be toggled by dragging the main content area side to side.\n *\n * To automatically close an opened menu, you can add the {@link ionic.directive:menuClose} attribute\n * directive. The `menu-close` attribute is usually added to links and buttons within\n * `ion-side-menu-content`, so that when the element is clicked, the opened side menu will\n * automatically close.\n *\n * \"Burger Icon\" toggles can be added to the header with the {@link ionic.directive:menuToggle}\n * attribute directive. Clicking the toggle will open and close the side menu like the `menu-close`\n * directive. The side menu will automatically hide on child pages, but can be overridden with the\n * enable-menu-with-back-views attribute mentioned below.\n *\n * By default, side menus are hidden underneath their side menu content and can be opened by swiping\n * the content left or right or by toggling a button to show the side menu. Additionally, by adding the\n * {@link ionic.directive:exposeAsideWhen} attribute directive to an\n * {@link ionic.directive:ionSideMenu} element directive, a side menu can be given instructions about\n * \"when\" the menu should be exposed (always viewable).\n *\n * ![Side Menu](http://ionicframework.com.s3.amazonaws.com/docs/controllers/sidemenu.gif)\n *\n * For more information on side menus, check out:\n *\n * - {@link ionic.directive:ionSideMenuContent}\n * - {@link ionic.directive:ionSideMenu}\n * - {@link ionic.directive:menuToggle}\n * - {@link ionic.directive:menuClose}\n * - {@link ionic.directive:exposeAsideWhen}\n *\n * @usage\n * To use side menus, add an `<ion-side-menus>` parent element. This will encompass all pages that have a\n * side menu, and have at least 2 child elements: 1 `<ion-side-menu-content>` for the center content,\n * and one or more `<ion-side-menu>` directives for each side menu(left/right) that you wish to place.\n *\n * ```html\n * <ion-side-menus>\n *   <!-- Center content -->\n *   <ion-side-menu-content ng-controller=\"ContentController\">\n *   </ion-side-menu-content>\n *\n *   <!-- Left menu -->\n *   <ion-side-menu side=\"left\">\n *   </ion-side-menu>\n *\n *   <!-- Right menu -->\n *   <ion-side-menu side=\"right\">\n *   </ion-side-menu>\n *\n *   <ion-side-menu-content>\n *   <!-- Main content, usually <ion-nav-view> -->\n *   </ion-side-menu-content>\n * </ion-side-menus>\n * ```\n * ```js\n * function ContentController($scope, $ionicSideMenuDelegate) {\n *   $scope.toggleLeft = function() {\n *     $ionicSideMenuDelegate.toggleLeft();\n *   };\n * }\n * ```\n *\n * @param {bool=} enable-menu-with-back-views Determines whether the side menu is enabled when the\n * back button is showing. When set to `false`, any {@link ionic.directive:menuToggle} will be hidden,\n * and the user cannot swipe to open the menu. When going back to the root page of the side menu (the\n * page without a back button visible), then any menuToggle buttons will show again, and menus will be\n * enabled again.\n * @param {string=} delegate-handle The handle used to identify this side menu\n * with {@link ionic.service:$ionicSideMenuDelegate}.\n *\n */\n.directive('ionSideMenus', ['$ionicBody', function($ionicBody) {\n  return {\n    restrict: 'ECA',\n    controller: '$ionicSideMenus',\n    compile: function(element, attr) {\n      attr.$set('class', (attr['class'] || '') + ' view');\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attrs, ctrl) {\n\n        ctrl.enableMenuWithBackViews($scope.$eval($attrs.enableMenuWithBackViews));\n\n        $scope.$on('$ionicExposeAside', function(evt, isAsideExposed) {\n          if (!$scope.$exposeAside) $scope.$exposeAside = {};\n          $scope.$exposeAside.active = isAsideExposed;\n          $ionicBody.enableClass(isAsideExposed, 'aside-open');\n        });\n\n        $scope.$on('$ionicView.beforeEnter', function(ev, d) {\n          if (d.historyId) {\n            $scope.$activeHistoryId = d.historyId;\n          }\n        });\n\n        $scope.$on('$destroy', function() {\n          $ionicBody.removeClass('menu-open', 'aside-open');\n        });\n\n      }\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @name ionSlideBox\n * @module ionic\n * @delegate ionic.service:$ionicSlideBoxDelegate\n * @restrict E\n * @description\n * The Slide Box is a multi-page container where each page can be swiped or dragged between:\n *\n * ![SlideBox](http://ionicframework.com.s3.amazonaws.com/docs/controllers/slideBox.gif)\n *\n * @usage\n * ```html\n * <ion-slide-box on-slide-changed=\"slideHasChanged($index)\">\n *   <ion-slide>\n *     <div class=\"box blue\"><h1>BLUE</h1></div>\n *   </ion-slide>\n *   <ion-slide>\n *     <div class=\"box yellow\"><h1>YELLOW</h1></div>\n *   </ion-slide>\n *   <ion-slide>\n *     <div class=\"box pink\"><h1>PINK</h1></div>\n *   </ion-slide>\n * </ion-slide-box>\n * ```\n *\n * @param {string=} delegate-handle The handle used to identify this slideBox\n * with {@link ionic.service:$ionicSlideBoxDelegate}.\n * @param {boolean=} does-continue Whether the slide box should loop.\n * @param {boolean=} auto-play Whether the slide box should automatically slide. Default true if does-continue is true.\n * @param {number=} slide-interval How many milliseconds to wait to change slides (if does-continue is true). Defaults to 4000.\n * @param {boolean=} show-pager Whether a pager should be shown for this slide box. Accepts expressions via `show-pager=\"{{shouldShow()}}\"`. Defaults to true.\n * @param {expression=} pager-click Expression to call when a pager is clicked (if show-pager is true). Is passed the 'index' variable.\n * @param {expression=} on-slide-changed Expression called whenever the slide is changed.  Is passed an '$index' variable.\n * @param {expression=} active-slide Model to bind the current slide to.\n */\nIonicModule\n.directive('ionSlideBox', [\n  '$timeout',\n  '$compile',\n  '$ionicSlideBoxDelegate',\n  '$ionicHistory',\n  '$ionicScrollDelegate',\nfunction($timeout, $compile, $ionicSlideBoxDelegate, $ionicHistory, $ionicScrollDelegate) {\n  return {\n    restrict: 'E',\n    replace: true,\n    transclude: true,\n    scope: {\n      autoPlay: '=',\n      doesContinue: '@',\n      slideInterval: '@',\n      showPager: '@',\n      pagerClick: '&',\n      disableScroll: '@',\n      onSlideChanged: '&',\n      activeSlide: '=?'\n    },\n    controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {\n      var _this = this;\n\n      var continuous = $scope.$eval($scope.doesContinue) === true;\n      var shouldAutoPlay = isDefined($attrs.autoPlay) ? !!$scope.autoPlay : false;\n      var slideInterval = shouldAutoPlay ? $scope.$eval($scope.slideInterval) || 4000 : 0;\n\n      var slider = new ionic.views.Slider({\n        el: $element[0],\n        auto: slideInterval,\n        continuous: continuous,\n        startSlide: $scope.activeSlide,\n        slidesChanged: function() {\n          $scope.currentSlide = slider.currentIndex();\n\n          // Try to trigger a digest\n          $timeout(function() {});\n        },\n        callback: function(slideIndex) {\n          $scope.currentSlide = slideIndex;\n          $scope.onSlideChanged({ index: $scope.currentSlide, $index: $scope.currentSlide});\n          $scope.$parent.$broadcast('slideBox.slideChanged', slideIndex);\n          $scope.activeSlide = slideIndex;\n          // Try to trigger a digest\n          $timeout(function() {});\n        },\n        onDrag: function() {\n          freezeAllScrolls(true);\n        },\n        onDragEnd: function() {\n          freezeAllScrolls(false);\n        }\n      });\n\n      function freezeAllScrolls(shouldFreeze) {\n        if (shouldFreeze && !_this.isScrollFreeze) {\n          $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);\n\n        } else if (!shouldFreeze && _this.isScrollFreeze) {\n          $ionicScrollDelegate.freezeAllScrolls(false);\n        }\n        _this.isScrollFreeze = shouldFreeze;\n      }\n\n      slider.enableSlide($scope.$eval($attrs.disableScroll) !== true);\n\n      $scope.$watch('activeSlide', function(nv) {\n        if (isDefined(nv)) {\n          slider.slide(nv);\n        }\n      });\n\n      $scope.$on('slideBox.nextSlide', function() {\n        slider.next();\n      });\n\n      $scope.$on('slideBox.prevSlide', function() {\n        slider.prev();\n      });\n\n      $scope.$on('slideBox.setSlide', function(e, index) {\n        slider.slide(index);\n      });\n\n      //Exposed for testing\n      this.__slider = slider;\n\n      var deregisterInstance = $ionicSlideBoxDelegate._registerInstance(\n        slider, $attrs.delegateHandle, function() {\n          return $ionicHistory.isActiveScope($scope);\n        }\n      );\n      $scope.$on('$destroy', function() {\n        deregisterInstance();\n        slider.kill();\n      });\n\n      this.slidesCount = function() {\n        return slider.slidesCount();\n      };\n\n      this.onPagerClick = function(index) {\n        void 0;\n        $scope.pagerClick({index: index});\n      };\n\n      $timeout(function() {\n        slider.load();\n      });\n    }],\n    template: '<div class=\"slider\">' +\n      '<div class=\"slider-slides\" ng-transclude>' +\n      '</div>' +\n    '</div>',\n\n    link: function($scope, $element, $attr) {\n      // if showPager is undefined, show the pager\n      if (!isDefined($attr.showPager)) {\n        $scope.showPager = true;\n        getPager().toggleClass('hide', !true);\n      }\n\n      $attr.$observe('showPager', function(show) {\n        show = $scope.$eval(show);\n        getPager().toggleClass('hide', !show);\n      });\n\n      var pager;\n      function getPager() {\n        if (!pager) {\n          var childScope = $scope.$new();\n          pager = jqLite('<ion-pager></ion-pager>');\n          $element.append(pager);\n          pager = $compile(pager)(childScope);\n        }\n        return pager;\n      }\n    }\n  };\n}])\n.directive('ionSlide', function() {\n  return {\n    restrict: 'E',\n    require: '^ionSlideBox',\n    compile: function(element) {\n      element.addClass('slider-slide');\n    }\n  };\n})\n\n.directive('ionPager', function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '^ionSlideBox',\n    template: '<div class=\"slider-pager\"><span class=\"slider-pager-page\" ng-repeat=\"slide in numSlides() track by $index\" ng-class=\"{active: $index == currentSlide}\" ng-click=\"pagerClick($index)\"><i class=\"icon ion-record\"></i></span></div>',\n    link: function($scope, $element, $attr, slideBox) {\n      var selectPage = function(index) {\n        var children = $element[0].children;\n        var length = children.length;\n        for (var i = 0; i < length; i++) {\n          if (i == index) {\n            children[i].classList.add('active');\n          } else {\n            children[i].classList.remove('active');\n          }\n        }\n      };\n\n      $scope.pagerClick = function(index) {\n        slideBox.onPagerClick(index);\n      };\n\n      $scope.numSlides = function() {\n        return new Array(slideBox.slidesCount());\n      };\n\n      $scope.$watch('currentSlide', function(v) {\n        selectPage(v);\n      });\n    }\n  };\n\n});\n\n/**\n* @ngdoc directive\n* @name ionSpinner\n* @module ionic\n* @restrict E\n *\n * @description\n * The `ionSpinner` directive provides a variety of animated spinners.\n * Spinners enables you to give your users feedback that the app is\n * processing/thinking/waiting/chillin' out, or whatever you'd like it to indicate.\n * By default, the {@link ionic.directive:ionRefresher} feature uses this spinner, rather\n * than rotating font icons (previously included in [ionicons](http://ionicons.com/)).\n * While font icons are great for simple or stationary graphics, they're not suited to\n * provide great animations, which is why Ionic uses SVG instead.\n *\n * Ionic offers ten spinners out of the box, and by default, it will use the appropriate spinner\n * for the platform on which it's running. Under the hood, the `ionSpinner` directive dynamically\n * builds the required SVG element, which allows Ionic to provide all ten of the animated SVGs\n * within 3KB.\n *\n * <style>\n * .spinner-table {\n *   max-width: 280px;\n * }\n * .spinner-table tbody > tr > th, .spinner-table tbody > tr > td {\n *   vertical-align: middle;\n *   width: 42px;\n *   height: 42px;\n * }\n * .spinner {\n *   stroke: #444;\n *   fill: #444; }\n *   .spinner svg {\n *     width: 28px;\n *     height: 28px; }\n *   .spinner.spinner-inverse {\n *     stroke: #fff;\n *     fill: #fff; }\n *\n * .spinner-android {\n *   stroke: #4b8bf4; }\n *\n * .spinner-ios, .spinner-ios-small {\n *   stroke: #69717d; }\n *\n * .spinner-spiral .stop1 {\n *   stop-color: #fff;\n *   stop-opacity: 0; }\n * .spinner-spiral.spinner-inverse .stop1 {\n *   stop-color: #000; }\n * .spinner-spiral.spinner-inverse .stop2 {\n *   stop-color: #fff; }\n * </style>\n *\n * <script src=\"http://code.ionicframework.com/nightly/js/ionic.bundle.min.js\"></script>\n * <table class=\"table spinner-table\" ng-app=\"ionic\">\n *  <tr>\n *    <th>\n *      <code>android</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"android\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>ios</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"ios\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>ios-small</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"ios-small\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>bubbles</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"bubbles\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>circles</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"circles\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>crescent</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"crescent\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>dots</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"dots\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>lines</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"lines\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>ripple</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"ripple\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>spiral</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"spiral\"></ion-spinner>\n *    </td>\n *  </tr>\n * </table>\n *\n * Each spinner uses SVG with SMIL animations, however, the Android spinner also uses JavaScript\n * so it also works on Android 4.0-4.3. Additionally, each spinner can be styled with CSS,\n * and scaled to any size.\n *\n *\n * @usage\n * The following code would use the default spinner for the platform it's running from. If it's neither\n * iOS or Android, it'll default to use `ios`.\n *\n * ```html\n * <ion-spinner></ion-spinner>\n * ```\n *\n * By setting the `icon` attribute, you can specify which spinner to use, no matter what\n * the platform is.\n *\n * ```html\n * <ion-spinner icon=\"spiral\"></ion-spinner>\n * ```\n *\n * ## Spinner Colors\n * Like with most of Ionic's other components, spinners can also be styled using\n * Ionic's standard color naming convention. For example:\n *\n * ```html\n * <ion-spinner class=\"spinner-energized\"></ion-spinner>\n * ```\n *\n *\n * ## Styling SVG with CSS\n * One cool thing about SVG is its ability to be styled with CSS! Some of the properties\n * have different names, for example, SVG uses the term `stroke` instead of `border`, and\n * `fill` instead of `background-color`.\n *\n * ```css\n * .spinner svg {\n *   width: 28px;\n *   height: 28px;\n *   stroke: #444;\n *   fill: #444;\n * }\n * ```\n *\n*/\nIonicModule\n.directive('ionSpinner', function() {\n  return {\n    restrict: 'E',\n    controller: '$ionicSpinner',\n    link: function($scope, $element, $attrs, ctrl) {\n      var spinnerName = ctrl.init();\n      $element.addClass('spinner spinner-' + spinnerName);\n    }\n  };\n});\n\n/**\n * @ngdoc directive\n * @name ionTab\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionTabs\n *\n * @description\n * Contains a tab's content.  The content only exists while the given tab is selected.\n *\n * Each ionTab has its own view history.\n *\n * @usage\n * ```html\n * <ion-tab\n *   title=\"Tab!\"\n *   icon=\"my-icon\"\n *   href=\"#/tab/tab-link\"\n *   on-select=\"onTabSelected()\"\n *   on-deselect=\"onTabDeselected()\">\n * </ion-tab>\n * ```\n * For a complete, working tab bar example, see the {@link ionic.directive:ionTabs} documentation.\n *\n * @param {string} title The title of the tab.\n * @param {string=} href The link that this tab will navigate to when tapped.\n * @param {string=} icon The icon of the tab. If given, this will become the default for icon-on and icon-off.\n * @param {string=} icon-on The icon of the tab while it is selected.\n * @param {string=} icon-off The icon of the tab while it is not selected.\n * @param {expression=} badge The badge to put on this tab (usually a number).\n * @param {expression=} badge-style The style of badge to put on this tab (eg: badge-positive).\n * @param {expression=} on-select Called when this tab is selected.\n * @param {expression=} on-deselect Called when this tab is deselected.\n * @param {expression=} ng-click By default, the tab will be selected on click. If ngClick is set, it will not.  You can explicitly switch tabs using {@link ionic.service:$ionicTabsDelegate#select $ionicTabsDelegate.select()}.\n * @param {expression=} hidden Whether the tab is to be hidden or not.\n * @param {expression=} disabled Whether the tab is to be disabled or not.\n */\nIonicModule\n.directive('ionTab', [\n  '$compile',\n  '$ionicConfig',\n  '$ionicBind',\n  '$ionicViewSwitcher',\nfunction($compile, $ionicConfig, $ionicBind, $ionicViewSwitcher) {\n\n  //Returns ' key=\"value\"' if value exists\n  function attrStr(k, v) {\n    return isDefined(v) ? ' ' + k + '=\"' + v + '\"' : '';\n  }\n  return {\n    restrict: 'E',\n    require: ['^ionTabs', 'ionTab'],\n    controller: '$ionicTab',\n    scope: true,\n    compile: function(element, attr) {\n\n      //We create the tabNavTemplate in the compile phase so that the\n      //attributes we pass down won't be interpolated yet - we want\n      //to pass down the 'raw' versions of the attributes\n      var tabNavTemplate = '<ion-tab-nav' +\n        attrStr('ng-click', attr.ngClick) +\n        attrStr('title', attr.title) +\n        attrStr('icon', attr.icon) +\n        attrStr('icon-on', attr.iconOn) +\n        attrStr('icon-off', attr.iconOff) +\n        attrStr('badge', attr.badge) +\n        attrStr('badge-style', attr.badgeStyle) +\n        attrStr('hidden', attr.hidden) +\n        attrStr('disabled', attr.disabled) +\n        attrStr('class', attr['class']) +\n        '></ion-tab-nav>';\n\n      //Remove the contents of the element so we can compile them later, if tab is selected\n      var tabContentEle = document.createElement('div');\n      for (var x = 0; x < element[0].children.length; x++) {\n        tabContentEle.appendChild(element[0].children[x].cloneNode(true));\n      }\n      var childElementCount = tabContentEle.childElementCount;\n      element.empty();\n\n      var navViewName, isNavView;\n      if (childElementCount) {\n        if (tabContentEle.children[0].tagName === 'ION-NAV-VIEW') {\n          // get the name if it's a nav-view\n          navViewName = tabContentEle.children[0].getAttribute('name');\n          tabContentEle.children[0].classList.add('view-container');\n          isNavView = true;\n        }\n        if (childElementCount === 1) {\n          // make the 1 child element the primary tab content container\n          tabContentEle = tabContentEle.children[0];\n        }\n        if (!isNavView) tabContentEle.classList.add('pane');\n        tabContentEle.classList.add('tab-content');\n      }\n\n      return function link($scope, $element, $attr, ctrls) {\n        var childScope;\n        var childElement;\n        var tabsCtrl = ctrls[0];\n        var tabCtrl = ctrls[1];\n        var isTabContentAttached = false;\n        $scope.$tabSelected = false;\n\n        $ionicBind($scope, $attr, {\n          onSelect: '&',\n          onDeselect: '&',\n          title: '@',\n          uiSref: '@',\n          href: '@'\n        });\n\n        tabsCtrl.add($scope);\n        $scope.$on('$destroy', function() {\n          if (!$scope.$tabsDestroy) {\n            // if the containing ionTabs directive is being destroyed\n            // then don't bother going through the controllers remove\n            // method, since remove will reset the active tab as each tab\n            // is being destroyed, causing unnecessary view loads and transitions\n            tabsCtrl.remove($scope);\n          }\n          tabNavElement.isolateScope().$destroy();\n          tabNavElement.remove();\n          tabNavElement = tabContentEle = childElement = null;\n        });\n\n        //Remove title attribute so browser-tooltip does not apear\n        $element[0].removeAttribute('title');\n\n        if (navViewName) {\n          tabCtrl.navViewName = $scope.navViewName = navViewName;\n        }\n        $scope.$on('$stateChangeSuccess', selectIfMatchesState);\n        selectIfMatchesState();\n        function selectIfMatchesState() {\n          if (tabCtrl.tabMatchesState()) {\n            tabsCtrl.select($scope, false);\n          }\n        }\n\n        var tabNavElement = jqLite(tabNavTemplate);\n        tabNavElement.data('$ionTabsController', tabsCtrl);\n        tabNavElement.data('$ionTabController', tabCtrl);\n        tabsCtrl.$tabsElement.append($compile(tabNavElement)($scope));\n\n\n        function tabSelected(isSelected) {\n          if (isSelected && childElementCount) {\n            // this tab is being selected\n\n            // check if the tab is already in the DOM\n            // only do this if the tab has child elements\n            if (!isTabContentAttached) {\n              // tab should be selected and is NOT in the DOM\n              // create a new scope and append it\n              childScope = $scope.$new();\n              childElement = jqLite(tabContentEle);\n              $ionicViewSwitcher.viewEleIsActive(childElement, true);\n              tabsCtrl.$element.append(childElement);\n              $compile(childElement)(childScope);\n              isTabContentAttached = true;\n            }\n\n            // remove the hide class so the tabs content shows up\n            $ionicViewSwitcher.viewEleIsActive(childElement, true);\n\n          } else if (isTabContentAttached && childElement) {\n            // this tab should NOT be selected, and it is already in the DOM\n\n            if ($ionicConfig.views.maxCache() > 0) {\n              // keep the tabs in the DOM, only css hide it\n              $ionicViewSwitcher.viewEleIsActive(childElement, false);\n\n            } else {\n              // do not keep tabs in the DOM\n              destroyTab();\n            }\n\n          }\n        }\n\n        function destroyTab() {\n          childScope && childScope.$destroy();\n          isTabContentAttached && childElement && childElement.remove();\n          tabContentEle.innerHTML = '';\n          isTabContentAttached = childScope = childElement = null;\n        }\n\n        $scope.$watch('$tabSelected', tabSelected);\n\n        $scope.$on('$ionicView.afterEnter', function() {\n          $ionicViewSwitcher.viewEleIsActive(childElement, $scope.$tabSelected);\n        });\n\n        $scope.$on('$ionicView.clearCache', function() {\n          if (!$scope.$tabSelected) {\n            destroyTab();\n          }\n        });\n\n      };\n    }\n  };\n}]);\n\nIonicModule\n.directive('ionTabNav', [function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: ['^ionTabs', '^ionTab'],\n    template:\n    '<a ng-class=\"{\\'tab-item-active\\': isTabActive(), \\'has-badge\\':badge, \\'tab-hidden\\':isHidden()}\" ' +\n      ' ng-disabled=\"disabled()\" class=\"tab-item\">' +\n      '<span class=\"badge {{badgeStyle}}\" ng-if=\"badge\">{{badge}}</span>' +\n      '<i class=\"icon {{getIconOn()}}\" ng-if=\"getIconOn() && isTabActive()\"></i>' +\n      '<i class=\"icon {{getIconOff()}}\" ng-if=\"getIconOff() && !isTabActive()\"></i>' +\n      '<span class=\"tab-title\" ng-bind-html=\"title\"></span>' +\n    '</a>',\n    scope: {\n      title: '@',\n      icon: '@',\n      iconOn: '@',\n      iconOff: '@',\n      badge: '=',\n      hidden: '@',\n      disabled: '&',\n      badgeStyle: '@',\n      'class': '@'\n    },\n    link: function($scope, $element, $attrs, ctrls) {\n      var tabsCtrl = ctrls[0],\n        tabCtrl = ctrls[1];\n\n      //Remove title attribute so browser-tooltip does not apear\n      $element[0].removeAttribute('title');\n\n      $scope.selectTab = function(e) {\n        e.preventDefault();\n        tabsCtrl.select(tabCtrl.$scope, true);\n      };\n      if (!$attrs.ngClick) {\n        $element.on('click', function(event) {\n          $scope.$apply(function() {\n            $scope.selectTab(event);\n          });\n        });\n      }\n\n      $scope.isHidden = function() {\n        if ($attrs.hidden === 'true' || $attrs.hidden === true) return true;\n        return false;\n      };\n\n      $scope.getIconOn = function() {\n        return $scope.iconOn || $scope.icon;\n      };\n      $scope.getIconOff = function() {\n        return $scope.iconOff || $scope.icon;\n      };\n\n      $scope.isTabActive = function() {\n        return tabsCtrl.selectedTab() === tabCtrl.$scope;\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionTabs\n * @module ionic\n * @delegate ionic.service:$ionicTabsDelegate\n * @restrict E\n * @codepen odqCz\n *\n * @description\n * Powers a multi-tabbed interface with a Tab Bar and a set of \"pages\" that can be tabbed\n * through.\n *\n * Assign any [tabs class](/docs/components#tabs) to the element to define\n * its look and feel.\n *\n * For iOS, tabs will appear at the bottom of the screen. For Android, tabs will be at the top\n * of the screen, below the nav-bar. This follows each OS's design specification, but can be\n * configured with the {@link ionic.provider:$ionicConfigProvider}.\n *\n * See the {@link ionic.directive:ionTab} directive's documentation for more details on\n * individual tabs.\n *\n * Note: do not place ion-tabs inside of an ion-content element; it has been known to cause a\n * certain CSS bug.\n *\n * @usage\n * ```html\n * <ion-tabs class=\"tabs-positive tabs-icon-only\">\n *\n *   <ion-tab title=\"Home\" icon-on=\"ion-ios-filing\" icon-off=\"ion-ios-filing-outline\">\n *     <!-- Tab 1 content -->\n *   </ion-tab>\n *\n *   <ion-tab title=\"About\" icon-on=\"ion-ios-clock\" icon-off=\"ion-ios-clock-outline\">\n *     <!-- Tab 2 content -->\n *   </ion-tab>\n *\n *   <ion-tab title=\"Settings\" icon-on=\"ion-ios-gear\" icon-off=\"ion-ios-gear-outline\">\n *     <!-- Tab 3 content -->\n *   </ion-tab>\n *\n * </ion-tabs>\n * ```\n *\n * @param {string=} delegate-handle The handle used to identify these tabs\n * with {@link ionic.service:$ionicTabsDelegate}.\n */\n\nIonicModule\n.directive('ionTabs', [\n  '$ionicTabsDelegate',\n  '$ionicConfig',\nfunction($ionicTabsDelegate, $ionicConfig) {\n  return {\n    restrict: 'E',\n    scope: true,\n    controller: '$ionicTabs',\n    compile: function(tElement) {\n      //We cannot use regular transclude here because it breaks element.data()\n      //inheritance on compile\n      var innerElement = jqLite('<div class=\"tab-nav tabs\">');\n      innerElement.append(tElement.contents());\n\n      tElement.append(innerElement)\n              .addClass('tabs-' + $ionicConfig.tabs.position() + ' tabs-' + $ionicConfig.tabs.style());\n\n      return { pre: prelink, post: postLink };\n      function prelink($scope, $element, $attr, tabsCtrl) {\n        var deregisterInstance = $ionicTabsDelegate._registerInstance(\n          tabsCtrl, $attr.delegateHandle, tabsCtrl.hasActiveScope\n        );\n\n        tabsCtrl.$scope = $scope;\n        tabsCtrl.$element = $element;\n        tabsCtrl.$tabsElement = jqLite($element[0].querySelector('.tabs'));\n\n        $scope.$watch(function() { return $element[0].className; }, function(value) {\n          var isTabsTop = value.indexOf('tabs-top') !== -1;\n          var isHidden = value.indexOf('tabs-item-hide') !== -1;\n          $scope.$hasTabs = !isTabsTop && !isHidden;\n          $scope.$hasTabsTop = isTabsTop && !isHidden;\n          $scope.$emit('$ionicTabs.top', $scope.$hasTabsTop);\n        });\n\n        function emitLifecycleEvent(ev, data) {\n          ev.stopPropagation();\n          var previousSelectedTab = tabsCtrl.previousSelectedTab();\n          if (previousSelectedTab) {\n            previousSelectedTab.$broadcast(ev.name.replace('NavView', 'Tabs'), data);\n          }\n        }\n\n        $scope.$on('$ionicNavView.beforeLeave', emitLifecycleEvent);\n        $scope.$on('$ionicNavView.afterLeave', emitLifecycleEvent);\n        $scope.$on('$ionicNavView.leave', emitLifecycleEvent);\n\n        $scope.$on('$destroy', function() {\n          // variable to inform child tabs that they're all being blown away\n          // used so that while destorying an individual tab, each one\n          // doesn't select the next tab as the active one, which causes unnecessary\n          // loading of tab views when each will eventually all go away anyway\n          $scope.$tabsDestroy = true;\n          deregisterInstance();\n          tabsCtrl.$tabsElement = tabsCtrl.$element = tabsCtrl.$scope = innerElement = null;\n          delete $scope.$hasTabs;\n          delete $scope.$hasTabsTop;\n        });\n      }\n\n      function postLink($scope, $element, $attr, tabsCtrl) {\n        if (!tabsCtrl.selectedTab()) {\n          // all the tabs have been added\n          // but one hasn't been selected yet\n          tabsCtrl.select(0);\n        }\n      }\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionToggle\n * @module ionic\n * @codepen tfAzj\n * @restrict E\n *\n * @description\n * A toggle is an animated switch which binds a given model to a boolean.\n *\n * Allows dragging of the switch's nub.\n *\n * The toggle behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]) otherwise.\n *\n * @param toggle-class {string=} Sets the CSS class on the inner `label.toggle` element created by the directive.\n *\n * @usage\n * Below is an example of a toggle directive which is wired up to the `airplaneMode` model\n * and has the `toggle-calm` CSS class assigned to the inner element.\n *\n * ```html\n * <ion-toggle ng-model=\"airplaneMode\" toggle-class=\"toggle-calm\">Airplane Mode</ion-toggle>\n * ```\n */\nIonicModule\n.directive('ionToggle', [\n  '$timeout',\n  '$ionicConfig',\nfunction($timeout, $ionicConfig) {\n\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '?ngModel',\n    transclude: true,\n    template:\n      '<div class=\"item item-toggle\">' +\n        '<div ng-transclude></div>' +\n        '<label class=\"toggle\">' +\n          '<input type=\"checkbox\">' +\n          '<div class=\"track\">' +\n            '<div class=\"handle\"></div>' +\n          '</div>' +\n        '</label>' +\n      '</div>',\n\n    compile: function(element, attr) {\n      var input = element.find('input');\n      forEach({\n        'name': attr.name,\n        'ng-value': attr.ngValue,\n        'ng-model': attr.ngModel,\n        'ng-checked': attr.ngChecked,\n        'ng-disabled': attr.ngDisabled,\n        'ng-true-value': attr.ngTrueValue,\n        'ng-false-value': attr.ngFalseValue,\n        'ng-change': attr.ngChange,\n        'ng-required': attr.ngRequired,\n        'required': attr.required\n      }, function(value, name) {\n        if (isDefined(value)) {\n          input.attr(name, value);\n        }\n      });\n\n      if (attr.toggleClass) {\n        element[0].getElementsByTagName('label')[0].classList.add(attr.toggleClass);\n      }\n\n      element.addClass('toggle-' + $ionicConfig.form.toggle());\n\n      return function($scope, $element) {\n        var el = $element[0].getElementsByTagName('label')[0];\n        var checkbox = el.children[0];\n        var track = el.children[1];\n        var handle = track.children[0];\n\n        var ngModelController = jqLite(checkbox).controller('ngModel');\n\n        $scope.toggle = new ionic.views.Toggle({\n          el: el,\n          track: track,\n          checkbox: checkbox,\n          handle: handle,\n          onChange: function() {\n            if (ngModelController) {\n              ngModelController.$setViewValue(checkbox.checked);\n              $scope.$apply();\n            }\n          }\n        });\n\n        $scope.$on('$destroy', function() {\n          $scope.toggle.destroy();\n        });\n      };\n    }\n\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionView\n * @module ionic\n * @restrict E\n * @parent ionNavView\n *\n * @description\n * A container for view content and any navigational and header bar information. When a view\n * enters and exits its parent {@link ionic.directive:ionNavView}, the view also emits view\n * information, such as its title, whether the back button should be displayed or not, whether the\n * corresponding {@link ionic.directive:ionNavBar} should be displayed or not, which transition the view\n * should use to animate, and which direction to animate.\n *\n * *Views are cached to improve performance.* When a view is navigated away from, its element is\n * left in the DOM, and its scope is disconnected from the `$watch` cycle. When navigating to a\n * view that is already cached, its scope is reconnected, and the existing element, which was\n * left in the DOM, becomes active again. This can be disabled, or the maximum number of cached\n * views changed in {@link ionic.provider:$ionicConfigProvider}, in the view's `$state` configuration, or\n * as an attribute on the view itself (see below).\n *\n * @usage\n * Below is an example where our page will load with a {@link ionic.directive:ionNavBar} containing\n * \"My Page\" as the title.\n *\n * ```html\n * <ion-nav-bar></ion-nav-bar>\n * <ion-nav-view>\n *   <ion-view view-title=\"My Page\">\n *     <ion-content>\n *       Hello!\n *     </ion-content>\n *   </ion-view>\n * </ion-nav-view>\n * ```\n *\n * ## View LifeCycle and Events\n *\n * Views can be cached, which means ***controllers normally only load once***, which may\n * affect your controller logic. To know when a view has entered or left, events\n * have been added that are emitted from the view's scope. These events also\n * contain data about the view, such as the title and whether the back button should\n * show. Also contained is transition data, such as the transition type and\n * direction that will be or was used.\n *\n * <table class=\"table\">\n *  <tr>\n *   <td><code>$ionicView.loaded</code></td>\n *   <td>The view has loaded. This event only happens once per\n * view being created and added to the DOM. If a view leaves but is cached,\n * then this event will not fire again on a subsequent viewing. The loaded event\n * is good place to put your setup code for the view; however, it is not the\n * recommended event to listen to when a view becomes active.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.enter</code></td>\n *   <td>The view has fully entered and is now the active view.\n * This event will fire, whether it was the first load or a cached view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.leave</code></td>\n *   <td>The view has finished leaving and is no longer the\n * active view. This event will fire, whether it is cached or destroyed.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.beforeEnter</code></td>\n *   <td>The view is about to enter and become the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.beforeLeave</code></td>\n *   <td>The view is about to leave and no longer be the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.afterEnter</code></td>\n *   <td>The view has fully entered and is now the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.afterLeave</code></td>\n *   <td>The view has finished leaving and is no longer the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.unloaded</code></td>\n *   <td>The view's controller has been destroyed and its element has been\n * removed from the DOM.</td>\n *  </tr>\n * </table>\n *\n * ## Caching\n *\n * Caching can be disabled and enabled in multiple ways. By default, Ionic will\n * cache a maximum of 10 views. You can optionally choose to disable caching at\n * either an individual view basis, or by global configuration. Please see the\n * _Caching_ section in {@link ionic.directive:ionNavView} for more info.\n *\n * @param {string=} view-title A text-only title to display on the parent {@link ionic.directive:ionNavBar}.\n * For an HTML title, such as an image, see {@link ionic.directive:ionNavTitle} instead.\n * @param {boolean=} cache-view If this view should be allowed to be cached or not.\n * Please see the _Caching_ section in {@link ionic.directive:ionNavView} for\n * more info. Default `true`\n * @param {boolean=} can-swipe-back If this view should be allowed to use the swipe to go back gesture or not.\n * This does not enable the swipe to go back feature if it is not available for the platform it's running\n * from, or there isn't a previous view. Default `true`\n * @param {boolean=} hide-back-button Whether to hide the back button on the parent\n * {@link ionic.directive:ionNavBar} by default.\n * @param {boolean=} hide-nav-bar Whether to hide the parent\n * {@link ionic.directive:ionNavBar} by default.\n */\nIonicModule\n.directive('ionView', function() {\n  return {\n    restrict: 'EA',\n    priority: 1000,\n    controller: '$ionicView',\n    compile: function(tElement) {\n      tElement.addClass('pane');\n      tElement[0].removeAttribute('title');\n      return function link($scope, $element, $attrs, viewCtrl) {\n        viewCtrl.init();\n      };\n    }\n  };\n});\n\n})();"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/ionic.bundle.js",
    "content": "/*!\n * ionic.bundle.js is a concatenation of:\n * ionic.js, angular.js, angular-animate.js,\n * angular-sanitize.js, angular-ui-router.js,\n * and ionic-angular.js\n */\n\n/*!\n * Copyright 2014 Drifty Co.\n * http://drifty.com/\n *\n * Ionic, v1.0.0\n * A powerful HTML5 mobile app framework.\n * http://ionicframework.com/\n *\n * By @maxlynch, @benjsperry, @adamdbradley <3\n *\n * Licensed under the MIT license. Please see LICENSE for more information.\n *\n */\n\n(function() {\n\n// Create global ionic obj and its namespaces\n// build processes may have already created an ionic obj\nwindow.ionic = window.ionic || {};\nwindow.ionic.views = {};\nwindow.ionic.version = '1.0.0';\n\n(function (ionic) {\n\n  ionic.DelegateService = function(methodNames) {\n\n    if (methodNames.indexOf('$getByHandle') > -1) {\n      throw new Error(\"Method '$getByHandle' is implicitly added to each delegate service. Do not list it as a method.\");\n    }\n\n    function trueFn() { return true; }\n\n    return ['$log', function($log) {\n\n      /*\n       * Creates a new object that will have all the methodNames given,\n       * and call them on the given the controller instance matching given\n       * handle.\n       * The reason we don't just let $getByHandle return the controller instance\n       * itself is that the controller instance might not exist yet.\n       *\n       * We want people to be able to do\n       * `var instance = $ionicScrollDelegate.$getByHandle('foo')` on controller\n       * instantiation, but on controller instantiation a child directive\n       * may not have been compiled yet!\n       *\n       * So this is our way of solving this problem: we create an object\n       * that will only try to fetch the controller with given handle\n       * once the methods are actually called.\n       */\n      function DelegateInstance(instances, handle) {\n        this._instances = instances;\n        this.handle = handle;\n      }\n      methodNames.forEach(function(methodName) {\n        DelegateInstance.prototype[methodName] = instanceMethodCaller(methodName);\n      });\n\n\n      /**\n       * The delegate service (eg $ionicNavBarDelegate) is just an instance\n       * with a non-defined handle, a couple extra methods for registering\n       * and narrowing down to a specific handle.\n       */\n      function DelegateService() {\n        this._instances = [];\n      }\n      DelegateService.prototype = DelegateInstance.prototype;\n      DelegateService.prototype._registerInstance = function(instance, handle, filterFn) {\n        var instances = this._instances;\n        instance.$$delegateHandle = handle;\n        instance.$$filterFn = filterFn || trueFn;\n        instances.push(instance);\n\n        return function deregister() {\n          var index = instances.indexOf(instance);\n          if (index !== -1) {\n            instances.splice(index, 1);\n          }\n        };\n      };\n      DelegateService.prototype.$getByHandle = function(handle) {\n        return new DelegateInstance(this._instances, handle);\n      };\n\n      return new DelegateService();\n\n      function instanceMethodCaller(methodName) {\n        return function caller() {\n          var handle = this.handle;\n          var args = arguments;\n          var foundInstancesCount = 0;\n          var returnValue;\n\n          this._instances.forEach(function(instance) {\n            if ((!handle || handle == instance.$$delegateHandle) && instance.$$filterFn(instance)) {\n              foundInstancesCount++;\n              var ret = instance[methodName].apply(instance, args);\n              //Only return the value from the first call\n              if (foundInstancesCount === 1) {\n                returnValue = ret;\n              }\n            }\n          });\n\n          if (!foundInstancesCount && handle) {\n            return $log.warn(\n              'Delegate for handle \"' + handle + '\" could not find a ' +\n              'corresponding element with delegate-handle=\"' + handle + '\"! ' +\n              methodName + '() was not called!\\n' +\n              'Possible cause: If you are calling ' + methodName + '() immediately, and ' +\n              'your element with delegate-handle=\"' + handle + '\" is a child of your ' +\n              'controller, then your element may not be compiled yet. Put a $timeout ' +\n              'around your call to ' + methodName + '() and try again.'\n            );\n          }\n          return returnValue;\n        };\n      }\n\n    }];\n  };\n\n})(window.ionic);\n\n(function(window, document, ionic) {\n\n  var readyCallbacks = [];\n  var isDomReady = document.readyState === 'complete' || document.readyState === 'interactive';\n\n  function domReady() {\n    isDomReady = true;\n    for (var x = 0; x < readyCallbacks.length; x++) {\n      ionic.requestAnimationFrame(readyCallbacks[x]);\n    }\n    readyCallbacks = [];\n    document.removeEventListener('DOMContentLoaded', domReady);\n  }\n  if (!isDomReady) {\n    document.addEventListener('DOMContentLoaded', domReady);\n  }\n\n\n  // From the man himself, Mr. Paul Irish.\n  // The requestAnimationFrame polyfill\n  // Put it on window just to preserve its context\n  // without having to use .call\n  window._rAF = (function() {\n    return window.requestAnimationFrame ||\n           window.webkitRequestAnimationFrame ||\n           window.mozRequestAnimationFrame ||\n           function(callback) {\n             window.setTimeout(callback, 16);\n           };\n  })();\n\n  var cancelAnimationFrame = window.cancelAnimationFrame ||\n    window.webkitCancelAnimationFrame ||\n    window.mozCancelAnimationFrame ||\n    window.webkitCancelRequestAnimationFrame;\n\n  /**\n  * @ngdoc utility\n  * @name ionic.DomUtil\n  * @module ionic\n  */\n  ionic.DomUtil = {\n    //Call with proper context\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#requestAnimationFrame\n     * @alias ionic.requestAnimationFrame\n     * @description Calls [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame), or a polyfill if not available.\n     * @param {function} callback The function to call when the next frame\n     * happens.\n     */\n    requestAnimationFrame: function(cb) {\n      return window._rAF(cb);\n    },\n\n    cancelAnimationFrame: function(requestId) {\n      cancelAnimationFrame(requestId);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#animationFrameThrottle\n     * @alias ionic.animationFrameThrottle\n     * @description\n     * When given a callback, if that callback is called 100 times between\n     * animation frames, adding Throttle will make it only run the last of\n     * the 100 calls.\n     *\n     * @param {function} callback a function which will be throttled to\n     * requestAnimationFrame\n     * @returns {function} A function which will then call the passed in callback.\n     * The passed in callback will receive the context the returned function is\n     * called with.\n     */\n    animationFrameThrottle: function(cb) {\n      var args, isQueued, context;\n      return function() {\n        args = arguments;\n        context = this;\n        if (!isQueued) {\n          isQueued = true;\n          ionic.requestAnimationFrame(function() {\n            cb.apply(context, args);\n            isQueued = false;\n          });\n        }\n      };\n    },\n\n    contains: function(parentNode, otherNode) {\n      var current = otherNode;\n      while (current) {\n        if (current === parentNode) return true;\n        current = current.parentNode;\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getPositionInParent\n     * @description\n     * Find an element's scroll offset within its container.\n     * @param {DOMElement} element The element to find the offset of.\n     * @returns {object} A position object with the following properties:\n     *   - `{number}` `left` The left offset of the element.\n     *   - `{number}` `top` The top offset of the element.\n     */\n    getPositionInParent: function(el) {\n      return {\n        left: el.offsetLeft,\n        top: el.offsetTop\n      };\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#ready\n     * @description\n     * Call a function when the DOM is ready, or if it is already ready\n     * call the function immediately.\n     * @param {function} callback The function to be called.\n     */\n    ready: function(cb) {\n      if (isDomReady) {\n        ionic.requestAnimationFrame(cb);\n      } else {\n        readyCallbacks.push(cb);\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getTextBounds\n     * @description\n     * Get a rect representing the bounds of the given textNode.\n     * @param {DOMElement} textNode The textNode to find the bounds of.\n     * @returns {object} An object representing the bounds of the node. Properties:\n     *   - `{number}` `left` The left position of the textNode.\n     *   - `{number}` `right` The right position of the textNode.\n     *   - `{number}` `top` The top position of the textNode.\n     *   - `{number}` `bottom` The bottom position of the textNode.\n     *   - `{number}` `width` The width of the textNode.\n     *   - `{number}` `height` The height of the textNode.\n     */\n    getTextBounds: function(textNode) {\n      if (document.createRange) {\n        var range = document.createRange();\n        range.selectNodeContents(textNode);\n        if (range.getBoundingClientRect) {\n          var rect = range.getBoundingClientRect();\n          if (rect) {\n            var sx = window.scrollX;\n            var sy = window.scrollY;\n\n            return {\n              top: rect.top + sy,\n              left: rect.left + sx,\n              right: rect.left + sx + rect.width,\n              bottom: rect.top + sy + rect.height,\n              width: rect.width,\n              height: rect.height\n            };\n          }\n        }\n      }\n      return null;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getChildIndex\n     * @description\n     * Get the first index of a child node within the given element of the\n     * specified type.\n     * @param {DOMElement} element The element to find the index of.\n     * @param {string} type The nodeName to match children of element against.\n     * @returns {number} The index, or -1, of a child with nodeName matching type.\n     */\n    getChildIndex: function(element, type) {\n      if (type) {\n        var ch = element.parentNode.children;\n        var c;\n        for (var i = 0, k = 0, j = ch.length; i < j; i++) {\n          c = ch[i];\n          if (c.nodeName && c.nodeName.toLowerCase() == type) {\n            if (c == element) {\n              return k;\n            }\n            k++;\n          }\n        }\n      }\n      return Array.prototype.slice.call(element.parentNode.children).indexOf(element);\n    },\n\n    /**\n     * @private\n     */\n    swapNodes: function(src, dest) {\n      dest.parentNode.insertBefore(src, dest);\n    },\n\n    elementIsDescendant: function(el, parent, stopAt) {\n      var current = el;\n      do {\n        if (current === parent) return true;\n        current = current.parentNode;\n      } while (current && current !== stopAt);\n      return false;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getParentWithClass\n     * @param {DOMElement} element\n     * @param {string} className\n     * @returns {DOMElement} The closest parent of element matching the\n     * className, or null.\n     */\n    getParentWithClass: function(e, className, depth) {\n      depth = depth || 10;\n      while (e.parentNode && depth--) {\n        if (e.parentNode.classList && e.parentNode.classList.contains(className)) {\n          return e.parentNode;\n        }\n        e = e.parentNode;\n      }\n      return null;\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getParentOrSelfWithClass\n     * @param {DOMElement} element\n     * @param {string} className\n     * @returns {DOMElement} The closest parent or self matching the\n     * className, or null.\n     */\n    getParentOrSelfWithClass: function(e, className, depth) {\n      depth = depth || 10;\n      while (e && depth--) {\n        if (e.classList && e.classList.contains(className)) {\n          return e;\n        }\n        e = e.parentNode;\n      }\n      return null;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#rectContains\n     * @param {number} x\n     * @param {number} y\n     * @param {number} x1\n     * @param {number} y1\n     * @param {number} x2\n     * @param {number} y2\n     * @returns {boolean} Whether {x,y} fits within the rectangle defined by\n     * {x1,y1,x2,y2}.\n     */\n    rectContains: function(x, y, x1, y1, x2, y2) {\n      if (x < x1 || x > x2) return false;\n      if (y < y1 || y > y2) return false;\n      return true;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#blurAll\n     * @description\n     * Blurs any currently focused input element\n     * @returns {DOMElement} The element blurred or null\n     */\n    blurAll: function() {\n      if (document.activeElement && document.activeElement != document.body) {\n        document.activeElement.blur();\n        return document.activeElement;\n      }\n      return null;\n    },\n\n    cachedAttr: function(ele, key, value) {\n      ele = ele && ele.length && ele[0] || ele;\n      if (ele && ele.setAttribute) {\n        var dataKey = '$attr-' + key;\n        if (arguments.length > 2) {\n          if (ele[dataKey] !== value) {\n            ele.setAttribute(key, value);\n            ele[dataKey] = value;\n          }\n        } else if (typeof ele[dataKey] == 'undefined') {\n          ele[dataKey] = ele.getAttribute(key);\n        }\n        return ele[dataKey];\n      }\n    },\n\n    cachedStyles: function(ele, styles) {\n      ele = ele && ele.length && ele[0] || ele;\n      if (ele && ele.style) {\n        for (var prop in styles) {\n          if (ele['$style-' + prop] !== styles[prop]) {\n            ele.style[prop] = ele['$style-' + prop] = styles[prop];\n          }\n        }\n      }\n    }\n\n  };\n\n  //Shortcuts\n  ionic.requestAnimationFrame = ionic.DomUtil.requestAnimationFrame;\n  ionic.cancelAnimationFrame = ionic.DomUtil.cancelAnimationFrame;\n  ionic.animationFrameThrottle = ionic.DomUtil.animationFrameThrottle;\n\n})(window, document, ionic);\n\n/**\n * ion-events.js\n *\n * Author: Max Lynch <max@drifty.com>\n *\n * Framework events handles various mobile browser events, and\n * detects special events like tap/swipe/etc. and emits them\n * as custom events that can be used in an app.\n *\n * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys!\n */\n\n(function(ionic) {\n\n  // Custom event polyfill\n  ionic.CustomEvent = (function() {\n    if( typeof window.CustomEvent === 'function' ) return CustomEvent;\n\n    var customEvent = function(event, params) {\n      var evt;\n      params = params || {\n        bubbles: false,\n        cancelable: false,\n        detail: undefined\n      };\n      try {\n        evt = document.createEvent(\"CustomEvent\");\n        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);\n      } catch (error) {\n        // fallback for browsers that don't support createEvent('CustomEvent')\n        evt = document.createEvent(\"Event\");\n        for (var param in params) {\n          evt[param] = params[param];\n        }\n        evt.initEvent(event, params.bubbles, params.cancelable);\n      }\n      return evt;\n    };\n    customEvent.prototype = window.Event.prototype;\n    return customEvent;\n  })();\n\n\n  /**\n   * @ngdoc utility\n   * @name ionic.EventController\n   * @module ionic\n   */\n  ionic.EventController = {\n    VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'],\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#trigger\n     * @alias ionic.trigger\n     * @param {string} eventType The event to trigger.\n     * @param {object} data The data for the event. Hint: pass in\n     * `{target: targetElement}`\n     * @param {boolean=} bubbles Whether the event should bubble up the DOM.\n     * @param {boolean=} cancelable Whether the event should be cancelable.\n     */\n    // Trigger a new event\n    trigger: function(eventType, data, bubbles, cancelable) {\n      var event = new ionic.CustomEvent(eventType, {\n        detail: data,\n        bubbles: !!bubbles,\n        cancelable: !!cancelable\n      });\n\n      // Make sure to trigger the event on the given target, or dispatch it from\n      // the window if we don't have an event target\n      data && data.target && data.target.dispatchEvent && data.target.dispatchEvent(event) || window.dispatchEvent(event);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#on\n     * @alias ionic.on\n     * @description Listen to an event on an element.\n     * @param {string} type The event to listen for.\n     * @param {function} callback The listener to be called.\n     * @param {DOMElement} element The element to listen for the event on.\n     */\n    on: function(type, callback, element) {\n      var e = element || window;\n\n      // Bind a gesture if it's a virtual event\n      for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) {\n        if(type == this.VIRTUALIZED_EVENTS[i]) {\n          var gesture = new ionic.Gesture(element);\n          gesture.on(type, callback);\n          return gesture;\n        }\n      }\n\n      // Otherwise bind a normal event\n      e.addEventListener(type, callback);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#off\n     * @alias ionic.off\n     * @description Remove an event listener.\n     * @param {string} type\n     * @param {function} callback\n     * @param {DOMElement} element\n     */\n    off: function(type, callback, element) {\n      element.removeEventListener(type, callback);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#onGesture\n     * @alias ionic.onGesture\n     * @description Add an event listener for a gesture on an element.\n     *\n     * Available eventTypes (from [hammer.js](http://eightmedia.github.io/hammer.js/)):\n     *\n     * `hold`, `tap`, `doubletap`, `drag`, `dragstart`, `dragend`, `dragup`, `dragdown`, <br/>\n     * `dragleft`, `dragright`, `swipe`, `swipeup`, `swipedown`, `swipeleft`, `swiperight`, <br/>\n     * `transform`, `transformstart`, `transformend`, `rotate`, `pinch`, `pinchin`, `pinchout`, </br>\n     * `touch`, `release`\n     *\n     * @param {string} eventType The gesture event to listen for.\n     * @param {function(e)} callback The function to call when the gesture\n     * happens.\n     * @param {DOMElement} element The angular element to listen for the event on.\n     * @param {object} options object.\n     * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).\n     */\n    onGesture: function(type, callback, element, options) {\n      var gesture = new ionic.Gesture(element, options);\n      gesture.on(type, callback);\n      return gesture;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#offGesture\n     * @alias ionic.offGesture\n     * @description Remove an event listener for a gesture created on an element.\n     * @param {ionic.Gesture} gesture The gesture that should be removed.\n     * @param {string} eventType The gesture event to remove the listener for.\n     * @param {function(e)} callback The listener to remove.\n\n     */\n    offGesture: function(gesture, type, callback) {\n      gesture && gesture.off(type, callback);\n    },\n\n    handlePopState: function() {}\n  };\n\n\n  // Map some convenient top-level functions for event handling\n  ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); };\n  ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); };\n  ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); };\n  ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); };\n  ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); };\n\n})(window.ionic);\n\n/* eslint camelcase:0 */\n/**\n  * Simple gesture controllers with some common gestures that emit\n  * gesture events.\n  *\n  * Ported from github.com/EightMedia/hammer.js Gestures - thanks!\n  */\n(function(ionic) {\n\n  /**\n   * ionic.Gestures\n   * use this to create instances\n   * @param   {HTMLElement}   element\n   * @param   {Object}        options\n   * @returns {ionic.Gestures.Instance}\n   * @constructor\n   */\n  ionic.Gesture = function(element, options) {\n    return new ionic.Gestures.Instance(element, options || {});\n  };\n\n  ionic.Gestures = {};\n\n  // default settings\n  ionic.Gestures.defaults = {\n    // add css to the element to prevent the browser from doing\n    // its native behavior. this doesnt prevent the scrolling,\n    // but cancels the contextmenu, tap highlighting etc\n    // set to false to disable this\n    stop_browser_behavior: 'disable-user-behavior'\n  };\n\n  // detect touchevents\n  ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled;\n  ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window);\n\n  // dont use mouseevents on mobile devices\n  ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i;\n  ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX);\n\n  // eventtypes per touchevent (start, move, end)\n  // are filled by ionic.Gestures.event.determineEventTypes on setup\n  ionic.Gestures.EVENT_TYPES = {};\n\n  // direction defines\n  ionic.Gestures.DIRECTION_DOWN = 'down';\n  ionic.Gestures.DIRECTION_LEFT = 'left';\n  ionic.Gestures.DIRECTION_UP = 'up';\n  ionic.Gestures.DIRECTION_RIGHT = 'right';\n\n  // pointer type\n  ionic.Gestures.POINTER_MOUSE = 'mouse';\n  ionic.Gestures.POINTER_TOUCH = 'touch';\n  ionic.Gestures.POINTER_PEN = 'pen';\n\n  // touch event defines\n  ionic.Gestures.EVENT_START = 'start';\n  ionic.Gestures.EVENT_MOVE = 'move';\n  ionic.Gestures.EVENT_END = 'end';\n\n  // hammer document where the base events are added at\n  ionic.Gestures.DOCUMENT = window.document;\n\n  // plugins namespace\n  ionic.Gestures.plugins = {};\n\n  // if the window events are set...\n  ionic.Gestures.READY = false;\n\n  /**\n   * setup events to detect gestures on the document\n   */\n  function setup() {\n    if(ionic.Gestures.READY) {\n      return;\n    }\n\n    // find what eventtypes we add listeners to\n    ionic.Gestures.event.determineEventTypes();\n\n    // Register all gestures inside ionic.Gestures.gestures\n    for(var name in ionic.Gestures.gestures) {\n      if(ionic.Gestures.gestures.hasOwnProperty(name)) {\n        ionic.Gestures.detection.register(ionic.Gestures.gestures[name]);\n      }\n    }\n\n    // Add touch events on the document\n    ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect);\n    ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect);\n\n    // ionic.Gestures is ready...!\n    ionic.Gestures.READY = true;\n  }\n\n  /**\n   * create new hammer instance\n   * all methods should return the instance itself, so it is chainable.\n   * @param   {HTMLElement}       element\n   * @param   {Object}            [options={}]\n   * @returns {ionic.Gestures.Instance}\n   * @name Gesture.Instance\n   * @constructor\n   */\n  ionic.Gestures.Instance = function(element, options) {\n    var self = this;\n\n    // A null element was passed into the instance, which means\n    // whatever lookup was done to find this element failed to find it\n    // so we can't listen for events on it.\n    if(element === null) {\n      void 0;\n      return this;\n    }\n\n    // setup ionic.GesturesJS window events and register all gestures\n    // this also sets up the default options\n    setup();\n\n    this.element = element;\n\n    // start/stop detection option\n    this.enabled = true;\n\n    // merge options\n    this.options = ionic.Gestures.utils.extend(\n        ionic.Gestures.utils.extend({}, ionic.Gestures.defaults),\n        options || {});\n\n    // add some css to the element to prevent the browser from doing its native behavoir\n    if(this.options.stop_browser_behavior) {\n      ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);\n    }\n\n    // start detection on touchstart\n    ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) {\n      if(self.enabled) {\n        ionic.Gestures.detection.startDetect(self, ev);\n      }\n    });\n\n    // return instance\n    return this;\n  };\n\n\n  ionic.Gestures.Instance.prototype = {\n    /**\n     * bind events to the instance\n     * @param   {String}      gesture\n     * @param   {Function}    handler\n     * @returns {ionic.Gestures.Instance}\n     */\n    on: function onEvent(gesture, handler){\n      var gestures = gesture.split(' ');\n      for(var t = 0; t < gestures.length; t++) {\n        this.element.addEventListener(gestures[t], handler, false);\n      }\n      return this;\n    },\n\n\n    /**\n     * unbind events to the instance\n     * @param   {String}      gesture\n     * @param   {Function}    handler\n     * @returns {ionic.Gestures.Instance}\n     */\n    off: function offEvent(gesture, handler){\n      var gestures = gesture.split(' ');\n      for(var t = 0; t < gestures.length; t++) {\n        this.element.removeEventListener(gestures[t], handler, false);\n      }\n      return this;\n    },\n\n\n    /**\n     * trigger gesture event\n     * @param   {String}      gesture\n     * @param   {Object}      eventData\n     * @returns {ionic.Gestures.Instance}\n     */\n    trigger: function triggerEvent(gesture, eventData){\n      // create DOM event\n      var event = ionic.Gestures.DOCUMENT.createEvent('Event');\n      event.initEvent(gesture, true, true);\n      event.gesture = eventData;\n\n      // trigger on the target if it is in the instance element,\n      // this is for event delegation tricks\n      var element = this.element;\n      if(ionic.Gestures.utils.hasParent(eventData.target, element)) {\n        element = eventData.target;\n      }\n\n      element.dispatchEvent(event);\n      return this;\n    },\n\n\n    /**\n     * enable of disable hammer.js detection\n     * @param   {Boolean}   state\n     * @returns {ionic.Gestures.Instance}\n     */\n    enable: function enable(state) {\n      this.enabled = state;\n      return this;\n    }\n  };\n\n  /**\n   * this holds the last move event,\n   * used to fix empty touchend issue\n   * see the onTouch event for an explanation\n   * type {Object}\n   */\n  var last_move_event = null;\n\n\n  /**\n   * when the mouse is hold down, this is true\n   * type {Boolean}\n   */\n  var enable_detect = false;\n\n\n  /**\n   * when touch events have been fired, this is true\n   * type {Boolean}\n   */\n  var touch_triggered = false;\n\n\n  ionic.Gestures.event = {\n    /**\n     * simple addEventListener\n     * @param   {HTMLElement}   element\n     * @param   {String}        type\n     * @param   {Function}      handler\n     */\n    bindDom: function(element, type, handler) {\n      var types = type.split(' ');\n      for(var t = 0; t < types.length; t++) {\n        element.addEventListener(types[t], handler, false);\n      }\n    },\n\n\n    /**\n     * touch events with mouse fallback\n     * @param   {HTMLElement}   element\n     * @param   {String}        eventType        like ionic.Gestures.EVENT_MOVE\n     * @param   {Function}      handler\n     */\n    onTouch: function onTouch(element, eventType, handler) {\n      var self = this;\n\n      this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {\n        var sourceEventType = ev.type.toLowerCase();\n\n        // onmouseup, but when touchend has been fired we do nothing.\n        // this is for touchdevices which also fire a mouseup on touchend\n        if(sourceEventType.match(/mouse/) && touch_triggered) {\n          return;\n        }\n\n        // mousebutton must be down or a touch event\n        else if( sourceEventType.match(/touch/) ||   // touch events are always on screen\n          sourceEventType.match(/pointerdown/) || // pointerevents touch\n          (sourceEventType.match(/mouse/) && ev.which === 1)   // mouse is pressed\n          ){\n            enable_detect = true;\n          }\n\n        // mouse isn't pressed\n        else if(sourceEventType.match(/mouse/) && ev.which !== 1) {\n          enable_detect = false;\n        }\n\n\n        // we are in a touch event, set the touch triggered bool to true,\n        // this for the conflicts that may occur on ios and android\n        if(sourceEventType.match(/touch|pointer/)) {\n          touch_triggered = true;\n        }\n\n        // count the total touches on the screen\n        var count_touches = 0;\n\n        // when touch has been triggered in this detection session\n        // and we are now handling a mouse event, we stop that to prevent conflicts\n        if(enable_detect) {\n          // update pointerevent\n          if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) {\n            count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);\n          }\n          // touch\n          else if(sourceEventType.match(/touch/)) {\n            count_touches = ev.touches.length;\n          }\n          // mouse\n          else if(!touch_triggered) {\n            count_touches = sourceEventType.match(/up/) ? 0 : 1;\n          }\n\n          // if we are in a end event, but when we remove one touch and\n          // we still have enough, set eventType to move\n          if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) {\n            eventType = ionic.Gestures.EVENT_MOVE;\n          }\n          // no touches, force the end event\n          else if(!count_touches) {\n            eventType = ionic.Gestures.EVENT_END;\n          }\n\n          // store the last move event\n          if(count_touches || last_move_event === null) {\n            last_move_event = ev;\n          }\n\n          // trigger the handler\n          handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev));\n\n          // remove pointerevent from list\n          if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) {\n            count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);\n          }\n        }\n\n        //debug(sourceEventType +\" \"+ eventType);\n\n        // on the end we reset everything\n        if(!count_touches) {\n          last_move_event = null;\n          enable_detect = false;\n          touch_triggered = false;\n          ionic.Gestures.PointerEvent.reset();\n        }\n      });\n    },\n\n\n    /**\n     * we have different events for each device/browser\n     * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant\n     */\n    determineEventTypes: function determineEventTypes() {\n      // determine the eventtype we want to set\n      var types;\n\n      // pointerEvents magic\n      if(ionic.Gestures.HAS_POINTEREVENTS) {\n        types = ionic.Gestures.PointerEvent.getEvents();\n      }\n      // on Android, iOS, blackberry, windows mobile we dont want any mouseevents\n      else if(ionic.Gestures.NO_MOUSEEVENTS) {\n        types = [\n          'touchstart',\n          'touchmove',\n          'touchend touchcancel'];\n      }\n      // for non pointer events browsers and mixed browsers,\n      // like chrome on windows8 touch laptop\n      else {\n        types = [\n          'touchstart mousedown',\n          'touchmove mousemove',\n          'touchend touchcancel mouseup'];\n      }\n\n      ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0];\n      ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1];\n      ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2];\n    },\n\n\n    /**\n     * create touchlist depending on the event\n     * @param   {Object}    ev\n     * @param   {String}    eventType   used by the fakemultitouch plugin\n     */\n    getTouchList: function getTouchList(ev/*, eventType*/) {\n      // get the fake pointerEvent touchlist\n      if(ionic.Gestures.HAS_POINTEREVENTS) {\n        return ionic.Gestures.PointerEvent.getTouchList();\n      }\n      // get the touchlist\n      else if(ev.touches) {\n        return ev.touches;\n      }\n      // make fake touchlist from mouse position\n      else {\n        ev.identifier = 1;\n        return [ev];\n      }\n    },\n\n\n    /**\n     * collect event data for ionic.Gestures js\n     * @param   {HTMLElement}   element\n     * @param   {String}        eventType        like ionic.Gestures.EVENT_MOVE\n     * @param   {Object}        eventData\n     */\n    collectEventData: function collectEventData(element, eventType, touches, ev) {\n\n      // find out pointerType\n      var pointerType = ionic.Gestures.POINTER_TOUCH;\n      if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) {\n        pointerType = ionic.Gestures.POINTER_MOUSE;\n      }\n\n      return {\n        center: ionic.Gestures.utils.getCenter(touches),\n        timeStamp: new Date().getTime(),\n        target: ev.target,\n        touches: touches,\n        eventType: eventType,\n        pointerType: pointerType,\n        srcEvent: ev,\n\n        /**\n         * prevent the browser default actions\n         * mostly used to disable scrolling of the browser\n         */\n        preventDefault: function() {\n          if(this.srcEvent.preventManipulation) {\n            this.srcEvent.preventManipulation();\n          }\n\n          if(this.srcEvent.preventDefault) {\n            // this.srcEvent.preventDefault();\n          }\n        },\n\n        /**\n         * stop bubbling the event up to its parents\n         */\n        stopPropagation: function() {\n          this.srcEvent.stopPropagation();\n        },\n\n        /**\n         * immediately stop gesture detection\n         * might be useful after a swipe was detected\n         * @return {*}\n         */\n        stopDetect: function() {\n          return ionic.Gestures.detection.stopDetect();\n        }\n      };\n    }\n  };\n\n  ionic.Gestures.PointerEvent = {\n    /**\n     * holds all pointers\n     * type {Object}\n     */\n    pointers: {},\n\n    /**\n     * get a list of pointers\n     * @returns {Array}     touchlist\n     */\n    getTouchList: function() {\n      var self = this;\n      var touchlist = [];\n\n      // we can use forEach since pointerEvents only is in IE10\n      Object.keys(self.pointers).sort().forEach(function(id) {\n        touchlist.push(self.pointers[id]);\n      });\n      return touchlist;\n    },\n\n    /**\n     * update the position of a pointer\n     * @param   {String}   type             ionic.Gestures.EVENT_END\n     * @param   {Object}   pointerEvent\n     */\n    updatePointer: function(type, pointerEvent) {\n      if(type == ionic.Gestures.EVENT_END) {\n        this.pointers = {};\n      }\n      else {\n        pointerEvent.identifier = pointerEvent.pointerId;\n        this.pointers[pointerEvent.pointerId] = pointerEvent;\n      }\n\n      return Object.keys(this.pointers).length;\n    },\n\n    /**\n     * check if ev matches pointertype\n     * @param   {String}        pointerType     ionic.Gestures.POINTER_MOUSE\n     * @param   {PointerEvent}  ev\n     */\n    matchType: function(pointerType, ev) {\n      if(!ev.pointerType) {\n        return false;\n      }\n\n      var types = {};\n      types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE);\n      types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH);\n      types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN);\n      return types[pointerType];\n    },\n\n\n    /**\n     * get events\n     */\n    getEvents: function() {\n      return [\n        'pointerdown MSPointerDown',\n      'pointermove MSPointerMove',\n      'pointerup pointercancel MSPointerUp MSPointerCancel'\n        ];\n    },\n\n    /**\n     * reset the list\n     */\n    reset: function() {\n      this.pointers = {};\n    }\n  };\n\n\n  ionic.Gestures.utils = {\n    /**\n     * extend method,\n     * also used for cloning when dest is an empty object\n     * @param   {Object}    dest\n     * @param   {Object}    src\n     * @param\t{Boolean}\tmerge\t\tdo a merge\n     * @returns {Object}    dest\n     */\n    extend: function extend(dest, src, merge) {\n      for (var key in src) {\n        if(dest[key] !== undefined && merge) {\n          continue;\n        }\n        dest[key] = src[key];\n      }\n      return dest;\n    },\n\n\n    /**\n     * find if a node is in the given parent\n     * used for event delegation tricks\n     * @param   {HTMLElement}   node\n     * @param   {HTMLElement}   parent\n     * @returns {boolean}       has_parent\n     */\n    hasParent: function(node, parent) {\n      while(node){\n        if(node == parent) {\n          return true;\n        }\n        node = node.parentNode;\n      }\n      return false;\n    },\n\n\n    /**\n     * get the center of all the touches\n     * @param   {Array}     touches\n     * @returns {Object}    center\n     */\n    getCenter: function getCenter(touches) {\n      var valuesX = [], valuesY = [];\n\n      for(var t = 0, len = touches.length; t < len; t++) {\n        valuesX.push(touches[t].pageX);\n        valuesY.push(touches[t].pageY);\n      }\n\n      return {\n        pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),\n          pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)\n      };\n    },\n\n\n    /**\n     * calculate the velocity between two points\n     * @param   {Number}    delta_time\n     * @param   {Number}    delta_x\n     * @param   {Number}    delta_y\n     * @returns {Object}    velocity\n     */\n    getVelocity: function getVelocity(delta_time, delta_x, delta_y) {\n      return {\n        x: Math.abs(delta_x / delta_time) || 0,\n        y: Math.abs(delta_y / delta_time) || 0\n      };\n    },\n\n\n    /**\n     * calculate the angle between two coordinates\n     * @param   {Touch}     touch1\n     * @param   {Touch}     touch2\n     * @returns {Number}    angle\n     */\n    getAngle: function getAngle(touch1, touch2) {\n      var y = touch2.pageY - touch1.pageY,\n      x = touch2.pageX - touch1.pageX;\n      return Math.atan2(y, x) * 180 / Math.PI;\n    },\n\n\n    /**\n     * angle to direction define\n     * @param   {Touch}     touch1\n     * @param   {Touch}     touch2\n     * @returns {String}    direction constant, like ionic.Gestures.DIRECTION_LEFT\n     */\n    getDirection: function getDirection(touch1, touch2) {\n      var x = Math.abs(touch1.pageX - touch2.pageX),\n      y = Math.abs(touch1.pageY - touch2.pageY);\n\n      if(x >= y) {\n        return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;\n      }\n      else {\n        return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;\n      }\n    },\n\n\n    /**\n     * calculate the distance between two touches\n     * @param   {Touch}     touch1\n     * @param   {Touch}     touch2\n     * @returns {Number}    distance\n     */\n    getDistance: function getDistance(touch1, touch2) {\n      var x = touch2.pageX - touch1.pageX,\n      y = touch2.pageY - touch1.pageY;\n      return Math.sqrt((x * x) + (y * y));\n    },\n\n\n    /**\n     * calculate the scale factor between two touchLists (fingers)\n     * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n     * @param   {Array}     start\n     * @param   {Array}     end\n     * @returns {Number}    scale\n     */\n    getScale: function getScale(start, end) {\n      // need two fingers...\n      if(start.length >= 2 && end.length >= 2) {\n        return this.getDistance(end[0], end[1]) /\n          this.getDistance(start[0], start[1]);\n      }\n      return 1;\n    },\n\n\n    /**\n     * calculate the rotation degrees between two touchLists (fingers)\n     * @param   {Array}     start\n     * @param   {Array}     end\n     * @returns {Number}    rotation\n     */\n    getRotation: function getRotation(start, end) {\n      // need two fingers\n      if(start.length >= 2 && end.length >= 2) {\n        return this.getAngle(end[1], end[0]) -\n          this.getAngle(start[1], start[0]);\n      }\n      return 0;\n    },\n\n\n    /**\n     * boolean if the direction is vertical\n     * @param    {String}    direction\n     * @returns  {Boolean}   is_vertical\n     */\n    isVertical: function isVertical(direction) {\n      return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN);\n    },\n\n\n    /**\n     * stop browser default behavior with css class\n     * @param   {HtmlElement}   element\n     * @param   {Object}        css_class\n     */\n    stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_class) {\n      // changed from making many style changes to just adding a preset classname\n      // less DOM manipulations, less code, and easier to control in the CSS side of things\n      // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method\n      if(element && element.classList) {\n        element.classList.add(css_class);\n        element.onselectstart = function() {\n          return false;\n        };\n      }\n    }\n  };\n\n\n  ionic.Gestures.detection = {\n    // contains all registred ionic.Gestures.gestures in the correct order\n    gestures: [],\n\n    // data of the current ionic.Gestures.gesture detection session\n    current: null,\n\n    // the previous ionic.Gestures.gesture session data\n    // is a full clone of the previous gesture.current object\n    previous: null,\n\n    // when this becomes true, no gestures are fired\n    stopped: false,\n\n\n    /**\n     * start ionic.Gestures.gesture detection\n     * @param   {ionic.Gestures.Instance}   inst\n     * @param   {Object}            eventData\n     */\n    startDetect: function startDetect(inst, eventData) {\n      // already busy with a ionic.Gestures.gesture detection on an element\n      if(this.current) {\n        return;\n      }\n\n      this.stopped = false;\n\n      this.current = {\n        inst: inst, // reference to ionic.GesturesInstance we're working for\n        startEvent: ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc\n        lastEvent: false, // last eventData\n        name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc\n      };\n\n      this.detect(eventData);\n    },\n\n\n    /**\n     * ionic.Gestures.gesture detection\n     * @param   {Object}    eventData\n     */\n    detect: function detect(eventData) {\n      if(!this.current || this.stopped) {\n        return null;\n      }\n\n      // extend event data with calculations about scale, distance etc\n      eventData = this.extendEventData(eventData);\n\n      // instance options\n      var inst_options = this.current.inst.options;\n\n      // call ionic.Gestures.gesture handlers\n      for(var g = 0, len = this.gestures.length; g < len; g++) {\n        var gesture = this.gestures[g];\n\n        // only when the instance options have enabled this gesture\n        if(!this.stopped && inst_options[gesture.name] !== false) {\n          // if a handler returns false, we stop with the detection\n          if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {\n            this.stopDetect();\n            break;\n          }\n        }\n      }\n\n      // store as previous event event\n      if(this.current) {\n        this.current.lastEvent = eventData;\n      }\n\n      // endevent, but not the last touch, so dont stop\n      if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length - 1) {\n        this.stopDetect();\n      }\n\n      return eventData;\n    },\n\n\n    /**\n     * clear the ionic.Gestures.gesture vars\n     * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected\n     * to stop other ionic.Gestures.gestures from being fired\n     */\n    stopDetect: function stopDetect() {\n      // clone current data to the store as the previous gesture\n      // used for the double tap gesture, since this is an other gesture detect session\n      this.previous = ionic.Gestures.utils.extend({}, this.current);\n\n      // reset the current\n      this.current = null;\n\n      // stopped!\n      this.stopped = true;\n    },\n\n\n    /**\n     * extend eventData for ionic.Gestures.gestures\n     * @param   {Object}   ev\n     * @returns {Object}   ev\n     */\n    extendEventData: function extendEventData(ev) {\n      var startEv = this.current.startEvent;\n\n      // if the touches change, set the new touches over the startEvent touches\n      // this because touchevents don't have all the touches on touchstart, or the\n      // user must place his fingers at the EXACT same time on the screen, which is not realistic\n      // but, sometimes it happens that both fingers are touching at the EXACT same time\n      if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {\n        // extend 1 level deep to get the touchlist with the touch objects\n        startEv.touches = [];\n        for(var i = 0, len = ev.touches.length; i < len; i++) {\n          startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i]));\n        }\n      }\n\n      var delta_time = ev.timeStamp - startEv.timeStamp,\n          delta_x = ev.center.pageX - startEv.center.pageX,\n          delta_y = ev.center.pageY - startEv.center.pageY,\n          velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y);\n\n      ionic.Gestures.utils.extend(ev, {\n        deltaTime: delta_time,\n        deltaX: delta_x,\n        deltaY: delta_y,\n\n        velocityX: velocity.x,\n        velocityY: velocity.y,\n\n        distance: ionic.Gestures.utils.getDistance(startEv.center, ev.center),\n        angle: ionic.Gestures.utils.getAngle(startEv.center, ev.center),\n        direction: ionic.Gestures.utils.getDirection(startEv.center, ev.center),\n\n        scale: ionic.Gestures.utils.getScale(startEv.touches, ev.touches),\n        rotation: ionic.Gestures.utils.getRotation(startEv.touches, ev.touches),\n\n        startEvent: startEv\n      });\n\n      return ev;\n    },\n\n\n    /**\n     * register new gesture\n     * @param   {Object}    gesture object, see gestures.js for documentation\n     * @returns {Array}     gestures\n     */\n    register: function register(gesture) {\n      // add an enable gesture options if there is no given\n      var options = gesture.defaults || {};\n      if(options[gesture.name] === undefined) {\n        options[gesture.name] = true;\n      }\n\n      // extend ionic.Gestures default options with the ionic.Gestures.gesture options\n      ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true);\n\n      // set its index\n      gesture.index = gesture.index || 1000;\n\n      // add ionic.Gestures.gesture to the list\n      this.gestures.push(gesture);\n\n      // sort the list by index\n      this.gestures.sort(function(a, b) {\n        if (a.index < b.index) {\n          return -1;\n        }\n        if (a.index > b.index) {\n          return 1;\n        }\n        return 0;\n      });\n\n      return this.gestures;\n    }\n  };\n\n\n  ionic.Gestures.gestures = ionic.Gestures.gestures || {};\n\n  /**\n   * Custom gestures\n   * ==============================\n   *\n   * Gesture object\n   * --------------------\n   * The object structure of a gesture:\n   *\n   * { name: 'mygesture',\n   *   index: 1337,\n   *   defaults: {\n   *     mygesture_option: true\n   *   }\n   *   handler: function(type, ev, inst) {\n   *     // trigger gesture event\n   *     inst.trigger(this.name, ev);\n   *   }\n   * }\n\n   * @param   {String}    name\n   * this should be the name of the gesture, lowercase\n   * it is also being used to disable/enable the gesture per instance config.\n   *\n   * @param   {Number}    [index=1000]\n   * the index of the gesture, where it is going to be in the stack of gestures detection\n   * like when you build an gesture that depends on the drag gesture, it is a good\n   * idea to place it after the index of the drag gesture.\n   *\n   * @param   {Object}    [defaults={}]\n   * the default settings of the gesture. these are added to the instance settings,\n   * and can be overruled per instance. you can also add the name of the gesture,\n   * but this is also added by default (and set to true).\n   *\n   * @param   {Function}  handler\n   * this handles the gesture detection of your custom gesture and receives the\n   * following arguments:\n   *\n   *      @param  {Object}    eventData\n   *      event data containing the following properties:\n   *          timeStamp   {Number}        time the event occurred\n   *          target      {HTMLElement}   target element\n   *          touches     {Array}         touches (fingers, pointers, mouse) on the screen\n   *          pointerType {String}        kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH\n   *          center      {Object}        center position of the touches. contains pageX and pageY\n   *          deltaTime   {Number}        the total time of the touches in the screen\n   *          deltaX      {Number}        the delta on x axis we haved moved\n   *          deltaY      {Number}        the delta on y axis we haved moved\n   *          velocityX   {Number}        the velocity on the x\n   *          velocityY   {Number}        the velocity on y\n   *          angle       {Number}        the angle we are moving\n   *          direction   {String}        the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT\n   *          distance    {Number}        the distance we haved moved\n   *          scale       {Number}        scaling of the touches, needs 2 touches\n   *          rotation    {Number}        rotation of the touches, needs 2 touches *\n   *          eventType   {String}        matches ionic.Gestures.EVENT_START|MOVE|END\n   *          srcEvent    {Object}        the source event, like TouchStart or MouseDown *\n   *          startEvent  {Object}        contains the same properties as above,\n   *                                      but from the first touch. this is used to calculate\n   *                                      distances, deltaTime, scaling etc\n   *\n   *      @param  {ionic.Gestures.Instance}    inst\n   *      the instance we are doing the detection for. you can get the options from\n   *      the inst.options object and trigger the gesture event by calling inst.trigger\n   *\n   *\n   * Handle gestures\n   * --------------------\n   * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current\n   * detection sessionic. It has the following properties\n   *      @param  {String}    name\n   *      contains the name of the gesture we have detected. it has not a real function,\n   *      only to check in other gestures if something is detected.\n   *      like in the drag gesture we set it to 'drag' and in the swipe gesture we can\n   *      check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name\n   *\n   *      readonly\n   *      @param  {ionic.Gestures.Instance}    inst\n   *      the instance we do the detection for\n   *\n   *      readonly\n   *      @param  {Object}    startEvent\n   *      contains the properties of the first gesture detection in this sessionic.\n   *      Used for calculations about timing, distance, etc.\n   *\n   *      readonly\n   *      @param  {Object}    lastEvent\n   *      contains all the properties of the last gesture detect in this sessionic.\n   *\n   * after the gesture detection session has been completed (user has released the screen)\n   * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous,\n   * this is usefull for gestures like doubletap, where you need to know if the\n   * previous gesture was a tap\n   *\n   * options that have been set by the instance can be received by calling inst.options\n   *\n   * You can trigger a gesture event by calling inst.trigger(\"mygesture\", event).\n   * The first param is the name of your gesture, the second the event argument\n   *\n   *\n   * Register gestures\n   * --------------------\n   * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered\n   * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register\n   * manually and pass your gesture object as a param\n   *\n   */\n\n  /**\n   * Hold\n   * Touch stays at the same place for x time\n   * events  hold\n   */\n  ionic.Gestures.gestures.Hold = {\n    name: 'hold',\n    index: 10,\n    defaults: {\n      hold_timeout: 500,\n      hold_threshold: 1\n    },\n    timer: null,\n    handler: function holdGesture(ev, inst) {\n      switch(ev.eventType) {\n        case ionic.Gestures.EVENT_START:\n          // clear any running timers\n          clearTimeout(this.timer);\n\n          // set the gesture so we can check in the timeout if it still is\n          ionic.Gestures.detection.current.name = this.name;\n\n          // set timer and if after the timeout it still is hold,\n          // we trigger the hold event\n          this.timer = setTimeout(function() {\n            if(ionic.Gestures.detection.current.name == 'hold') {\n              ionic.tap.cancelClick();\n              inst.trigger('hold', ev);\n            }\n          }, inst.options.hold_timeout);\n          break;\n\n          // when you move or end we clear the timer\n        case ionic.Gestures.EVENT_MOVE:\n          if(ev.distance > inst.options.hold_threshold) {\n            clearTimeout(this.timer);\n          }\n          break;\n\n        case ionic.Gestures.EVENT_END:\n          clearTimeout(this.timer);\n          break;\n      }\n    }\n  };\n\n\n  /**\n   * Tap/DoubleTap\n   * Quick touch at a place or double at the same place\n   * events  tap, doubletap\n   */\n  ionic.Gestures.gestures.Tap = {\n    name: 'tap',\n    index: 100,\n    defaults: {\n      tap_max_touchtime: 250,\n      tap_max_distance: 10,\n      tap_always: true,\n      doubletap_distance: 20,\n      doubletap_interval: 300\n    },\n    handler: function tapGesture(ev, inst) {\n      if(ev.eventType == ionic.Gestures.EVENT_END && ev.srcEvent.type != 'touchcancel') {\n        // previous gesture, for the double tap since these are two different gesture detections\n        var prev = ionic.Gestures.detection.previous,\n        did_doubletap = false;\n\n        // when the touchtime is higher then the max touch time\n        // or when the moving distance is too much\n        if(ev.deltaTime > inst.options.tap_max_touchtime ||\n            ev.distance > inst.options.tap_max_distance) {\n              return;\n            }\n\n        // check if double tap\n        if(prev && prev.name == 'tap' &&\n            (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&\n            ev.distance < inst.options.doubletap_distance) {\n              inst.trigger('doubletap', ev);\n              did_doubletap = true;\n            }\n\n        // do a single tap\n        if(!did_doubletap || inst.options.tap_always) {\n          ionic.Gestures.detection.current.name = 'tap';\n          inst.trigger('tap', ev);\n        }\n      }\n    }\n  };\n\n\n  /**\n   * Swipe\n   * triggers swipe events when the end velocity is above the threshold\n   * events  swipe, swipeleft, swiperight, swipeup, swipedown\n   */\n  ionic.Gestures.gestures.Swipe = {\n    name: 'swipe',\n    index: 40,\n    defaults: {\n      // set 0 for unlimited, but this can conflict with transform\n      swipe_max_touches: 1,\n      swipe_velocity: 0.4\n    },\n    handler: function swipeGesture(ev, inst) {\n      if(ev.eventType == ionic.Gestures.EVENT_END) {\n        // max touches\n        if(inst.options.swipe_max_touches > 0 &&\n            ev.touches.length > inst.options.swipe_max_touches) {\n              return;\n            }\n\n        // when the distance we moved is too small we skip this gesture\n        // or we can be already in dragging\n        if(ev.velocityX > inst.options.swipe_velocity ||\n            ev.velocityY > inst.options.swipe_velocity) {\n              // trigger swipe events\n              inst.trigger(this.name, ev);\n              inst.trigger(this.name + ev.direction, ev);\n            }\n      }\n    }\n  };\n\n\n  /**\n   * Drag\n   * Move with x fingers (default 1) around on the page. Blocking the scrolling when\n   * moving left and right is a good practice. When all the drag events are blocking\n   * you disable scrolling on that area.\n   * events  drag, drapleft, dragright, dragup, dragdown\n   */\n  ionic.Gestures.gestures.Drag = {\n    name: 'drag',\n    index: 50,\n    defaults: {\n      drag_min_distance: 10,\n      // Set correct_for_drag_min_distance to true to make the starting point of the drag\n      // be calculated from where the drag was triggered, not from where the touch started.\n      // Useful to avoid a jerk-starting drag, which can make fine-adjustments\n      // through dragging difficult, and be visually unappealing.\n      correct_for_drag_min_distance: true,\n      // set 0 for unlimited, but this can conflict with transform\n      drag_max_touches: 1,\n      // prevent default browser behavior when dragging occurs\n      // be careful with it, it makes the element a blocking element\n      // when you are using the drag gesture, it is a good practice to set this true\n      drag_block_horizontal: true,\n      drag_block_vertical: true,\n      // drag_lock_to_axis keeps the drag gesture on the axis that it started on,\n      // It disallows vertical directions if the initial direction was horizontal, and vice versa.\n      drag_lock_to_axis: false,\n      // drag lock only kicks in when distance > drag_lock_min_distance\n      // This way, locking occurs only when the distance has become large enough to reliably determine the direction\n      drag_lock_min_distance: 25,\n      // prevent default if the gesture is going the given direction\n      prevent_default_directions: []\n    },\n    triggered: false,\n    handler: function dragGesture(ev, inst) {\n      if (ev.srcEvent.type == 'touchstart' || ev.srcEvent.type == 'touchend') {\n        this.preventedFirstMove = false;\n\n      } else if (!this.preventedFirstMove && ev.srcEvent.type == 'touchmove') {\n        if (inst.options.prevent_default_directions.indexOf(ev.direction) != -1) {\n          ev.srcEvent.preventDefault();\n        }\n        this.preventedFirstMove = true;\n      }\n\n      // current gesture isnt drag, but dragged is true\n      // this means an other gesture is busy. now call dragend\n      if(ionic.Gestures.detection.current.name != this.name && this.triggered) {\n        inst.trigger(this.name + 'end', ev);\n        this.triggered = false;\n        return;\n      }\n\n      // max touches\n      if(inst.options.drag_max_touches > 0 &&\n          ev.touches.length > inst.options.drag_max_touches) {\n            return;\n          }\n\n      switch(ev.eventType) {\n        case ionic.Gestures.EVENT_START:\n          this.triggered = false;\n          break;\n\n        case ionic.Gestures.EVENT_MOVE:\n          // when the distance we moved is too small we skip this gesture\n          // or we can be already in dragging\n          if(ev.distance < inst.options.drag_min_distance &&\n              ionic.Gestures.detection.current.name != this.name) {\n                return;\n              }\n\n          // we are dragging!\n          if(ionic.Gestures.detection.current.name != this.name) {\n            ionic.Gestures.detection.current.name = this.name;\n            if (inst.options.correct_for_drag_min_distance) {\n              // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center.\n              // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0.\n              // It might be useful to save the original start point somewhere\n              var factor = Math.abs(inst.options.drag_min_distance / ev.distance);\n              ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor;\n              ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor;\n\n              // recalculate event data using new start point\n              ev = ionic.Gestures.detection.extendEventData(ev);\n            }\n          }\n\n          // lock drag to axis?\n          if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance <= ev.distance)) {\n            ev.drag_locked_to_axis = true;\n          }\n          var last_direction = ionic.Gestures.detection.current.lastEvent.direction;\n          if(ev.drag_locked_to_axis && last_direction !== ev.direction) {\n            // keep direction on the axis that the drag gesture started on\n            if(ionic.Gestures.utils.isVertical(last_direction)) {\n              ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;\n            }\n            else {\n              ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;\n            }\n          }\n\n          // first time, trigger dragstart event\n          if(!this.triggered) {\n            inst.trigger(this.name + 'start', ev);\n            this.triggered = true;\n          }\n\n          // trigger normal event\n          inst.trigger(this.name, ev);\n\n          // direction event, like dragdown\n          inst.trigger(this.name + ev.direction, ev);\n\n          // block the browser events\n          if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) ||\n              (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) {\n                ev.preventDefault();\n              }\n          break;\n\n        case ionic.Gestures.EVENT_END:\n          // trigger dragend\n          if(this.triggered) {\n            inst.trigger(this.name + 'end', ev);\n          }\n\n          this.triggered = false;\n          break;\n      }\n    }\n  };\n\n\n  /**\n   * Transform\n   * User want to scale or rotate with 2 fingers\n   * events  transform, pinch, pinchin, pinchout, rotate\n   */\n  ionic.Gestures.gestures.Transform = {\n    name: 'transform',\n    index: 45,\n    defaults: {\n      // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1\n      transform_min_scale: 0.01,\n      // rotation in degrees\n      transform_min_rotation: 1,\n      // prevent default browser behavior when two touches are on the screen\n      // but it makes the element a blocking element\n      // when you are using the transform gesture, it is a good practice to set this true\n      transform_always_block: false\n    },\n    triggered: false,\n    handler: function transformGesture(ev, inst) {\n      // current gesture isnt drag, but dragged is true\n      // this means an other gesture is busy. now call dragend\n      if(ionic.Gestures.detection.current.name != this.name && this.triggered) {\n        inst.trigger(this.name + 'end', ev);\n        this.triggered = false;\n        return;\n      }\n\n      // atleast multitouch\n      if(ev.touches.length < 2) {\n        return;\n      }\n\n      // prevent default when two fingers are on the screen\n      if(inst.options.transform_always_block) {\n        ev.preventDefault();\n      }\n\n      switch(ev.eventType) {\n        case ionic.Gestures.EVENT_START:\n          this.triggered = false;\n          break;\n\n        case ionic.Gestures.EVENT_MOVE:\n          var scale_threshold = Math.abs(1 - ev.scale);\n          var rotation_threshold = Math.abs(ev.rotation);\n\n          // when the distance we moved is too small we skip this gesture\n          // or we can be already in dragging\n          if(scale_threshold < inst.options.transform_min_scale &&\n              rotation_threshold < inst.options.transform_min_rotation) {\n                return;\n              }\n\n          // we are transforming!\n          ionic.Gestures.detection.current.name = this.name;\n\n          // first time, trigger dragstart event\n          if(!this.triggered) {\n            inst.trigger(this.name + 'start', ev);\n            this.triggered = true;\n          }\n\n          inst.trigger(this.name, ev); // basic transform event\n\n          // trigger rotate event\n          if(rotation_threshold > inst.options.transform_min_rotation) {\n            inst.trigger('rotate', ev);\n          }\n\n          // trigger pinch event\n          if(scale_threshold > inst.options.transform_min_scale) {\n            inst.trigger('pinch', ev);\n            inst.trigger('pinch' + ((ev.scale < 1) ? 'in' : 'out'), ev);\n          }\n          break;\n\n        case ionic.Gestures.EVENT_END:\n          // trigger dragend\n          if(this.triggered) {\n            inst.trigger(this.name + 'end', ev);\n          }\n\n          this.triggered = false;\n          break;\n      }\n    }\n  };\n\n\n  /**\n   * Touch\n   * Called as first, tells the user has touched the screen\n   * events  touch\n   */\n  ionic.Gestures.gestures.Touch = {\n    name: 'touch',\n    index: -Infinity,\n    defaults: {\n      // call preventDefault at touchstart, and makes the element blocking by\n      // disabling the scrolling of the page, but it improves gestures like\n      // transforming and dragging.\n      // be careful with using this, it can be very annoying for users to be stuck\n      // on the page\n      prevent_default: false,\n\n      // disable mouse events, so only touch (or pen!) input triggers events\n      prevent_mouseevents: false\n    },\n    handler: function touchGesture(ev, inst) {\n      if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) {\n        ev.stopDetect();\n        return;\n      }\n\n      if(inst.options.prevent_default) {\n        ev.preventDefault();\n      }\n\n      if(ev.eventType == ionic.Gestures.EVENT_START) {\n        inst.trigger(this.name, ev);\n      }\n    }\n  };\n\n\n  /**\n   * Release\n   * Called as last, tells the user has released the screen\n   * events  release\n   */\n  ionic.Gestures.gestures.Release = {\n    name: 'release',\n    index: Infinity,\n    handler: function releaseGesture(ev, inst) {\n      if(ev.eventType == ionic.Gestures.EVENT_END) {\n        inst.trigger(this.name, ev);\n      }\n    }\n  };\n})(window.ionic);\n\n(function(window, document, ionic) {\n\n  function getParameterByName(name) {\n    name = name.replace(/[\\[]/, \"\\\\[\").replace(/[\\]]/, \"\\\\]\");\n    var regex = new RegExp(\"[\\\\?&]\" + name + \"=([^&#]*)\"),\n    results = regex.exec(location.search);\n    return results === null ? \"\" : decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n  }\n\n  var IOS = 'ios';\n  var ANDROID = 'android';\n  var WINDOWS_PHONE = 'windowsphone';\n  var requestAnimationFrame = ionic.requestAnimationFrame;\n\n  /**\n   * @ngdoc utility\n   * @name ionic.Platform\n   * @module ionic\n   * @description\n   * A set of utility methods that can be used to retrieve the device ready state and\n   * various other information such as what kind of platform the app is currently installed on.\n   *\n   * @usage\n   * ```js\n   * angular.module('PlatformApp', ['ionic'])\n   * .controller('PlatformCtrl', function($scope) {\n   *\n   *   ionic.Platform.ready(function(){\n   *     // will execute when device is ready, or immediately if the device is already ready.\n   *   });\n   *\n   *   var deviceInformation = ionic.Platform.device();\n   *\n   *   var isWebView = ionic.Platform.isWebView();\n   *   var isIPad = ionic.Platform.isIPad();\n   *   var isIOS = ionic.Platform.isIOS();\n   *   var isAndroid = ionic.Platform.isAndroid();\n   *   var isWindowsPhone = ionic.Platform.isWindowsPhone();\n   *\n   *   var currentPlatform = ionic.Platform.platform();\n   *   var currentPlatformVersion = ionic.Platform.version();\n   *\n   *   ionic.Platform.exitApp(); // stops the app\n   * });\n   * ```\n   */\n  var self = ionic.Platform = {\n\n    // Put navigator on platform so it can be mocked and set\n    // the browser does not allow window.navigator to be set\n    navigator: window.navigator,\n\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#isReady\n     * @returns {boolean} Whether the device is ready.\n     */\n    isReady: false,\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#isFullScreen\n     * @returns {boolean} Whether the device is fullscreen.\n     */\n    isFullScreen: false,\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#platforms\n     * @returns {Array(string)} An array of all platforms found.\n     */\n    platforms: null,\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#grade\n     * @returns {string} What grade the current platform is.\n     */\n    grade: null,\n    ua: navigator.userAgent,\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#ready\n     * @description\n     * Trigger a callback once the device is ready, or immediately\n     * if the device is already ready. This method can be run from\n     * anywhere and does not need to be wrapped by any additonal methods.\n     * When the app is within a WebView (Cordova), it'll fire\n     * the callback once the device is ready. If the app is within\n     * a web browser, it'll fire the callback after `window.load`.\n     * Please remember that Cordova features (Camera, FileSystem, etc) still\n     * will not work in a web browser.\n     * @param {function} callback The function to call.\n     */\n    ready: function(cb) {\n      // run through tasks to complete now that the device is ready\n      if (self.isReady) {\n        cb();\n      } else {\n        // the platform isn't ready yet, add it to this array\n        // which will be called once the platform is ready\n        readyCallbacks.push(cb);\n      }\n    },\n\n    /**\n     * @private\n     */\n    detect: function() {\n      self._checkPlatforms();\n\n      requestAnimationFrame(function() {\n        // only add to the body class if we got platform info\n        for (var i = 0; i < self.platforms.length; i++) {\n          document.body.classList.add('platform-' + self.platforms[i]);\n        }\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#setGrade\n     * @description Set the grade of the device: 'a', 'b', or 'c'. 'a' is the best\n     * (most css features enabled), 'c' is the worst.  By default, sets the grade\n     * depending on the current device.\n     * @param {string} grade The new grade to set.\n     */\n    setGrade: function(grade) {\n      var oldGrade = self.grade;\n      self.grade = grade;\n      requestAnimationFrame(function() {\n        if (oldGrade) {\n          document.body.classList.remove('grade-' + oldGrade);\n        }\n        document.body.classList.add('grade-' + grade);\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#device\n     * @description Return the current device (given by cordova).\n     * @returns {object} The device object.\n     */\n    device: function() {\n      return window.device || {};\n    },\n\n    _checkPlatforms: function() {\n      self.platforms = [];\n      var grade = 'a';\n\n      if (self.isWebView()) {\n        self.platforms.push('webview');\n        if (!(!window.cordova && !window.PhoneGap && !window.phonegap)) {\n          self.platforms.push('cordova');\n        } else if (window.forge) {\n          self.platforms.push('trigger');\n        }\n      } else {\n        self.platforms.push('browser');\n      }\n      if (self.isIPad()) self.platforms.push('ipad');\n\n      var platform = self.platform();\n      if (platform) {\n        self.platforms.push(platform);\n\n        var version = self.version();\n        if (version) {\n          var v = version.toString();\n          if (v.indexOf('.') > 0) {\n            v = v.replace('.', '_');\n          } else {\n            v += '_0';\n          }\n          self.platforms.push(platform + v.split('_')[0]);\n          self.platforms.push(platform + v);\n\n          if (self.isAndroid() && version < 4.4) {\n            grade = (version < 4 ? 'c' : 'b');\n          } else if (self.isWindowsPhone()) {\n            grade = 'b';\n          }\n        }\n      }\n\n      self.setGrade(grade);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isWebView\n     * @returns {boolean} Check if we are running within a WebView (such as Cordova).\n     */\n    isWebView: function() {\n      return !(!window.cordova && !window.PhoneGap && !window.phonegap && !window.forge);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isIPad\n     * @returns {boolean} Whether we are running on iPad.\n     */\n    isIPad: function() {\n      if (/iPad/i.test(self.navigator.platform)) {\n        return true;\n      }\n      return /iPad/i.test(self.ua);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isIOS\n     * @returns {boolean} Whether we are running on iOS.\n     */\n    isIOS: function() {\n      return self.is(IOS);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isAndroid\n     * @returns {boolean} Whether we are running on Android.\n     */\n    isAndroid: function() {\n      return self.is(ANDROID);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isWindowsPhone\n     * @returns {boolean} Whether we are running on Windows Phone.\n     */\n    isWindowsPhone: function() {\n      return self.is(WINDOWS_PHONE);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#platform\n     * @returns {string} The name of the current platform.\n     */\n    platform: function() {\n      // singleton to get the platform name\n      if (platformName === null) self.setPlatform(self.device().platform);\n      return platformName;\n    },\n\n    /**\n     * @private\n     */\n    setPlatform: function(n) {\n      if (typeof n != 'undefined' && n !== null && n.length) {\n        platformName = n.toLowerCase();\n      } else if (getParameterByName('ionicplatform')) {\n        platformName = getParameterByName('ionicplatform');\n      } else if (self.ua.indexOf('Android') > 0) {\n        platformName = ANDROID;\n      } else if (/iPhone|iPad|iPod/.test(self.ua)) {\n        platformName = IOS;\n      } else if (self.ua.indexOf('Windows Phone') > -1) {\n        platformName = WINDOWS_PHONE;\n      } else {\n        platformName = self.navigator.platform && navigator.platform.toLowerCase().split(' ')[0] || '';\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#version\n     * @returns {number} The version of the current device platform.\n     */\n    version: function() {\n      // singleton to get the platform version\n      if (platformVersion === null) self.setVersion(self.device().version);\n      return platformVersion;\n    },\n\n    /**\n     * @private\n     */\n    setVersion: function(v) {\n      if (typeof v != 'undefined' && v !== null) {\n        v = v.split('.');\n        v = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0));\n        if (!isNaN(v)) {\n          platformVersion = v;\n          return;\n        }\n      }\n\n      platformVersion = 0;\n\n      // fallback to user-agent checking\n      var pName = self.platform();\n      var versionMatch = {\n        'android': /Android (\\d+).(\\d+)?/,\n        'ios': /OS (\\d+)_(\\d+)?/,\n        'windowsphone': /Windows Phone (\\d+).(\\d+)?/\n      };\n      if (versionMatch[pName]) {\n        v = self.ua.match(versionMatch[pName]);\n        if (v && v.length > 2) {\n          platformVersion = parseFloat(v[1] + '.' + v[2]);\n        }\n      }\n    },\n\n    // Check if the platform is the one detected by cordova\n    is: function(type) {\n      type = type.toLowerCase();\n      // check if it has an array of platforms\n      if (self.platforms) {\n        for (var x = 0; x < self.platforms.length; x++) {\n          if (self.platforms[x] === type) return true;\n        }\n      }\n      // exact match\n      var pName = self.platform();\n      if (pName) {\n        return pName === type.toLowerCase();\n      }\n\n      // A quick hack for to check userAgent\n      return self.ua.toLowerCase().indexOf(type) >= 0;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#exitApp\n     * @description Exit the app.\n     */\n    exitApp: function() {\n      self.ready(function() {\n        navigator.app && navigator.app.exitApp && navigator.app.exitApp();\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#showStatusBar\n     * @description Shows or hides the device status bar (in Cordova). Requires `cordova plugin add org.apache.cordova.statusbar`\n     * @param {boolean} shouldShow Whether or not to show the status bar.\n     */\n    showStatusBar: function(val) {\n      // Only useful when run within cordova\n      self._showStatusBar = val;\n      self.ready(function() {\n        // run this only when or if the platform (cordova) is ready\n        requestAnimationFrame(function() {\n          if (self._showStatusBar) {\n            // they do not want it to be full screen\n            window.StatusBar && window.StatusBar.show();\n            document.body.classList.remove('status-bar-hide');\n          } else {\n            // it should be full screen\n            window.StatusBar && window.StatusBar.hide();\n            document.body.classList.add('status-bar-hide');\n          }\n        });\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#fullScreen\n     * @description\n     * Sets whether the app is fullscreen or not (in Cordova).\n     * @param {boolean=} showFullScreen Whether or not to set the app to fullscreen. Defaults to true. Requires `cordova plugin add org.apache.cordova.statusbar`\n     * @param {boolean=} showStatusBar Whether or not to show the device's status bar. Defaults to false.\n     */\n    fullScreen: function(showFullScreen, showStatusBar) {\n      // showFullScreen: default is true if no param provided\n      self.isFullScreen = (showFullScreen !== false);\n\n      // add/remove the fullscreen classname to the body\n      ionic.DomUtil.ready(function() {\n        // run this only when or if the DOM is ready\n        requestAnimationFrame(function() {\n          if (self.isFullScreen) {\n            document.body.classList.add('fullscreen');\n          } else {\n            document.body.classList.remove('fullscreen');\n          }\n        });\n        // showStatusBar: default is false if no param provided\n        self.showStatusBar((showStatusBar === true));\n      });\n    }\n\n  };\n\n  var platformName = null, // just the name, like iOS or Android\n  platformVersion = null, // a float of the major and minor, like 7.1\n  readyCallbacks = [],\n  windowLoadListenderAttached;\n\n  // setup listeners to know when the device is ready to go\n  function onWindowLoad() {\n    if (self.isWebView()) {\n      // the window and scripts are fully loaded, and a cordova/phonegap\n      // object exists then let's listen for the deviceready\n      document.addEventListener(\"deviceready\", onPlatformReady, false);\n    } else {\n      // the window and scripts are fully loaded, but the window object doesn't have the\n      // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova\n      onPlatformReady();\n    }\n    if (windowLoadListenderAttached) {\n      window.removeEventListener(\"load\", onWindowLoad, false);\n    }\n  }\n  if (document.readyState === 'complete') {\n    onWindowLoad();\n  } else {\n    windowLoadListenderAttached = true;\n    window.addEventListener(\"load\", onWindowLoad, false);\n  }\n\n  function onPlatformReady() {\n    // the device is all set to go, init our own stuff then fire off our event\n    self.isReady = true;\n    self.detect();\n    for (var x = 0; x < readyCallbacks.length; x++) {\n      // fire off all the callbacks that were added before the platform was ready\n      readyCallbacks[x]();\n    }\n    readyCallbacks = [];\n    ionic.trigger('platformready', { target: document });\n\n    requestAnimationFrame(function() {\n      document.body.classList.add('platform-ready');\n    });\n  }\n\n})(this, document, ionic);\n\n(function(document, ionic) {\n  'use strict';\n\n  // Ionic CSS polyfills\n  ionic.CSS = {};\n\n  (function() {\n\n    // transform\n    var i, keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform',\n                   '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform', 'msTransform'];\n\n    for (i = 0; i < keys.length; i++) {\n      if (document.documentElement.style[keys[i]] !== undefined) {\n        ionic.CSS.TRANSFORM = keys[i];\n        break;\n      }\n    }\n\n    // transition\n    keys = ['webkitTransition', 'mozTransition', 'msTransition', 'transition'];\n    for (i = 0; i < keys.length; i++) {\n      if (document.documentElement.style[keys[i]] !== undefined) {\n        ionic.CSS.TRANSITION = keys[i];\n        break;\n      }\n    }\n\n    // The only prefix we care about is webkit for transitions.\n    var isWebkit = ionic.CSS.TRANSITION.indexOf('webkit') > -1;\n\n    // transition duration\n    ionic.CSS.TRANSITION_DURATION = (isWebkit ? '-webkit-' : '') + 'transition-duration';\n\n    // To be sure transitionend works everywhere, include *both* the webkit and non-webkit events\n    ionic.CSS.TRANSITIONEND = (isWebkit ? 'webkitTransitionEnd ' : '') + 'transitionend';\n  })();\n\n  // classList polyfill for them older Androids\n  // https://gist.github.com/devongovett/1381839\n  if (!(\"classList\" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {\n    Object.defineProperty(HTMLElement.prototype, 'classList', {\n      get: function() {\n        var self = this;\n        function update(fn) {\n          return function() {\n            var x, classes = self.className.split(/\\s+/);\n\n            for (x = 0; x < arguments.length; x++) {\n              fn(classes, classes.indexOf(arguments[x]), arguments[x]);\n            }\n\n            self.className = classes.join(\" \");\n          };\n        }\n\n        return {\n          add: update(function(classes, index, value) {\n            ~index || classes.push(value);\n          }),\n\n          remove: update(function(classes, index) {\n            ~index && classes.splice(index, 1);\n          }),\n\n          toggle: update(function(classes, index, value) {\n            ~index ? classes.splice(index, 1) : classes.push(value);\n          }),\n\n          contains: function(value) {\n            return !!~self.className.split(/\\s+/).indexOf(value);\n          },\n\n          item: function(i) {\n            return self.className.split(/\\s+/)[i] || null;\n          }\n        };\n\n      }\n    });\n  }\n\n})(document, ionic);\n\n\n/**\n * @ngdoc page\n * @name tap\n * @module ionic\n * @description\n * On touch devices such as a phone or tablet, some browsers implement a 300ms delay between\n * the time the user stops touching the display and the moment the browser executes the\n * click. This delay was initially introduced so the browser can know whether the user wants to\n * double-tap to zoom in on the webpage.  Basically, the browser waits roughly 300ms to see if\n * the user is double-tapping, or just tapping on the display once.\n *\n * Out of the box, Ionic automatically removes the 300ms delay in order to make Ionic apps\n * feel more \"native\" like. Resultingly, other solutions such as\n * [fastclick](https://github.com/ftlabs/fastclick) and Angular's\n * [ngTouch](https://docs.angularjs.org/api/ngTouch) should not be included, to avoid conflicts.\n *\n * Some browsers already remove the delay with certain settings, such as the CSS property\n * `touch-events: none` or with specific meta tag viewport values. However, each of these\n * browsers still handle clicks differently, such as when to fire off or cancel the event\n * (like scrolling when the target is a button, or holding a button down).\n * For browsers that already remove the 300ms delay, consider Ionic's tap system as a way to\n * normalize how clicks are handled across the various devices so there's an expected response\n * no matter what the device, platform or version. Additionally, Ionic will prevent\n * ghostclicks which even browsers that remove the delay still experience.\n *\n * In some cases, third-party libraries may also be working with touch events which can interfere\n * with the tap system. For example, mapping libraries like Google or Leaflet Maps often implement\n * a touch detection system which conflicts with Ionic's tap system.\n *\n * ### Disabling the tap system\n *\n * To disable the tap for an element and all of its children elements,\n * add the attribute `data-tap-disabled=\"true\"`.\n *\n * ```html\n * <div data-tap-disabled=\"true\">\n *     <div id=\"google-map\"></div>\n * </div>\n * ```\n *\n * ### Additional Notes:\n *\n * - Ionic tap  works with Ionic's JavaScript scrolling\n * - Elements can come and go from the DOM and Ionic tap doesn't keep adding and removing\n *   listeners\n * - No \"tap delay\" after the first \"tap\" (you can tap as fast as you want, they all click)\n * - Minimal events listeners, only being added to document\n * - Correct focus in/out on each input type (select, textearea, range) on each platform/device\n * - Shows and hides virtual keyboard correctly for each platform/device\n * - Works with labels surrounding inputs\n * - Does not fire off a click if the user moves the pointer too far\n * - Adds and removes an 'activated' css class\n * - Multiple [unit tests](https://github.com/driftyco/ionic/blob/master/test/unit/utils/tap.unit.js) for each scenario\n *\n */\n/*\n\n IONIC TAP\n ---------------\n - Both touch and mouse events are added to the document.body on DOM ready\n - If a touch event happens, it does not use mouse event listeners\n - On touchend, if the distance between start and end was small, trigger a click\n - In the triggered click event, add a 'isIonicTap' property\n - The triggered click receives the same x,y coordinates as as the end event\n - On document.body click listener (with useCapture=true), only allow clicks with 'isIonicTap'\n - Triggering clicks with mouse events work the same as touch, except with mousedown/mouseup\n - Tapping inputs is disabled during scrolling\n*/\n\nvar tapDoc; // the element which the listeners are on (document.body)\nvar tapActiveEle; // the element which is active (probably has focus)\nvar tapEnabledTouchEvents;\nvar tapMouseResetTimer;\nvar tapPointerMoved;\nvar tapPointerStart;\nvar tapTouchFocusedInput;\nvar tapLastTouchTarget;\nvar tapTouchMoveListener = 'touchmove';\n\n// how much the coordinates can be off between start/end, but still a click\nvar TAP_RELEASE_TOLERANCE = 12; // default tolerance\nvar TAP_RELEASE_BUTTON_TOLERANCE = 50; // button elements should have a larger tolerance\n\nvar tapEventListeners = {\n  'click': tapClickGateKeeper,\n\n  'mousedown': tapMouseDown,\n  'mouseup': tapMouseUp,\n  'mousemove': tapMouseMove,\n\n  'touchstart': tapTouchStart,\n  'touchend': tapTouchEnd,\n  'touchcancel': tapTouchCancel,\n  'touchmove': tapTouchMove,\n\n  'pointerdown': tapTouchStart,\n  'pointerup': tapTouchEnd,\n  'pointercancel': tapTouchCancel,\n  'pointermove': tapTouchMove,\n\n  'MSPointerDown': tapTouchStart,\n  'MSPointerUp': tapTouchEnd,\n  'MSPointerCancel': tapTouchCancel,\n  'MSPointerMove': tapTouchMove,\n\n  'focusin': tapFocusIn,\n  'focusout': tapFocusOut\n};\n\nionic.tap = {\n\n  register: function(ele) {\n    tapDoc = ele;\n\n    tapEventListener('click', true, true);\n    tapEventListener('mouseup');\n    tapEventListener('mousedown');\n\n    if (window.navigator.pointerEnabled) {\n      tapEventListener('pointerdown');\n      tapEventListener('pointerup');\n      tapEventListener('pointcancel');\n      tapTouchMoveListener = 'pointermove';\n\n    } else if (window.navigator.msPointerEnabled) {\n      tapEventListener('MSPointerDown');\n      tapEventListener('MSPointerUp');\n      tapEventListener('MSPointerCancel');\n      tapTouchMoveListener = 'MSPointerMove';\n\n    } else {\n      tapEventListener('touchstart');\n      tapEventListener('touchend');\n      tapEventListener('touchcancel');\n    }\n\n    tapEventListener('focusin');\n    tapEventListener('focusout');\n\n    return function() {\n      for (var type in tapEventListeners) {\n        tapEventListener(type, false);\n      }\n      tapDoc = null;\n      tapActiveEle = null;\n      tapEnabledTouchEvents = false;\n      tapPointerMoved = false;\n      tapPointerStart = null;\n    };\n  },\n\n  ignoreScrollStart: function(e) {\n    return (e.defaultPrevented) ||  // defaultPrevented has been assigned by another component handling the event\n           (/^(file|range)$/i).test(e.target.type) ||\n           (e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll')) == 'true' || // manually set within an elements attributes\n           (!!(/^(object|embed)$/i).test(e.target.tagName)) ||  // flash/movie/object touches should not try to scroll\n           ionic.tap.isElementTapDisabled(e.target); // check if this element, or an ancestor, has `data-tap-disabled` attribute\n  },\n\n  isTextInput: function(ele) {\n    return !!ele &&\n           (ele.tagName == 'TEXTAREA' ||\n            ele.contentEditable === 'true' ||\n            (ele.tagName == 'INPUT' && !(/^(radio|checkbox|range|file|submit|reset|color|image|button)$/i).test(ele.type)));\n  },\n\n  isDateInput: function(ele) {\n    return !!ele &&\n            (ele.tagName == 'INPUT' && (/^(date|time|datetime-local|month|week)$/i).test(ele.type));\n  },\n\n  isKeyboardElement: function(ele) {\n    if ( !ionic.Platform.isIOS() || ionic.Platform.isIPad() ) {\n      return ionic.tap.isTextInput(ele) && !ionic.tap.isDateInput(ele);\n    } else {\n      return ionic.tap.isTextInput(ele) || ( !!ele && ele.tagName == \"SELECT\");\n    }\n  },\n\n  isLabelWithTextInput: function(ele) {\n    var container = tapContainingElement(ele, false);\n\n    return !!container &&\n           ionic.tap.isTextInput(tapTargetElement(container));\n  },\n\n  containsOrIsTextInput: function(ele) {\n    return ionic.tap.isTextInput(ele) || ionic.tap.isLabelWithTextInput(ele);\n  },\n\n  cloneFocusedInput: function(container) {\n    if (ionic.tap.hasCheckedClone) return;\n    ionic.tap.hasCheckedClone = true;\n\n    ionic.requestAnimationFrame(function() {\n      var focusInput = container.querySelector(':focus');\n      if (ionic.tap.isTextInput(focusInput)) {\n        var clonedInput = focusInput.cloneNode(true);\n\n        clonedInput.value = focusInput.value;\n        clonedInput.classList.add('cloned-text-input');\n        clonedInput.readOnly = true;\n        if (focusInput.isContentEditable) {\n          clonedInput.contentEditable = focusInput.contentEditable;\n          clonedInput.innerHTML = focusInput.innerHTML;\n        }\n        focusInput.parentElement.insertBefore(clonedInput, focusInput);\n        focusInput.classList.add('previous-input-focus');\n\n        clonedInput.scrollTop = focusInput.scrollTop;\n      }\n    });\n  },\n\n  hasCheckedClone: false,\n\n  removeClonedInputs: function(container) {\n    ionic.tap.hasCheckedClone = false;\n\n    ionic.requestAnimationFrame(function() {\n      var clonedInputs = container.querySelectorAll('.cloned-text-input');\n      var previousInputFocus = container.querySelectorAll('.previous-input-focus');\n      var x;\n\n      for (x = 0; x < clonedInputs.length; x++) {\n        clonedInputs[x].parentElement.removeChild(clonedInputs[x]);\n      }\n\n      for (x = 0; x < previousInputFocus.length; x++) {\n        previousInputFocus[x].classList.remove('previous-input-focus');\n        previousInputFocus[x].style.top = '';\n        if ( ionic.keyboard.isOpen && !ionic.keyboard.isClosing ) previousInputFocus[x].focus();\n      }\n    });\n  },\n\n  requiresNativeClick: function(ele) {\n    if (!ele || ele.disabled || (/^(file|range)$/i).test(ele.type) || (/^(object|video)$/i).test(ele.tagName) || ionic.tap.isLabelContainingFileInput(ele)) {\n      return true;\n    }\n    return ionic.tap.isElementTapDisabled(ele);\n  },\n\n  isLabelContainingFileInput: function(ele) {\n    var lbl = tapContainingElement(ele);\n    if (lbl.tagName !== 'LABEL') return false;\n    var fileInput = lbl.querySelector('input[type=file]');\n    if (fileInput && fileInput.disabled === false) return true;\n    return false;\n  },\n\n  isElementTapDisabled: function(ele) {\n    if (ele && ele.nodeType === 1) {\n      var element = ele;\n      while (element) {\n        if ((element.dataset ? element.dataset.tapDisabled : element.getAttribute('data-tap-disabled')) == 'true') {\n          return true;\n        }\n        element = element.parentElement;\n      }\n    }\n    return false;\n  },\n\n  setTolerance: function(releaseTolerance, releaseButtonTolerance) {\n    TAP_RELEASE_TOLERANCE = releaseTolerance;\n    TAP_RELEASE_BUTTON_TOLERANCE = releaseButtonTolerance;\n  },\n\n  cancelClick: function() {\n    // used to cancel any simulated clicks which may happen on a touchend/mouseup\n    // gestures uses this method within its tap and hold events\n    tapPointerMoved = true;\n  },\n\n  pointerCoord: function(event) {\n    // This method can get coordinates for both a mouse click\n    // or a touch depending on the given event\n    var c = { x: 0, y: 0 };\n    if (event) {\n      var touches = event.touches && event.touches.length ? event.touches : [event];\n      var e = (event.changedTouches && event.changedTouches[0]) || touches[0];\n      if (e) {\n        c.x = e.clientX || e.pageX || 0;\n        c.y = e.clientY || e.pageY || 0;\n      }\n    }\n    return c;\n  }\n\n};\n\nfunction tapEventListener(type, enable, useCapture) {\n  if (enable !== false) {\n    tapDoc.addEventListener(type, tapEventListeners[type], useCapture);\n  } else {\n    tapDoc.removeEventListener(type, tapEventListeners[type]);\n  }\n}\n\nfunction tapClick(e) {\n  // simulate a normal click by running the element's click method then focus on it\n  var container = tapContainingElement(e.target);\n  var ele = tapTargetElement(container);\n\n  if (ionic.tap.requiresNativeClick(ele) || tapPointerMoved) return false;\n\n  var c = ionic.tap.pointerCoord(e);\n\n  //console.log('tapClick', e.type, ele.tagName, '('+c.x+','+c.y+')');\n  triggerMouseEvent('click', ele, c.x, c.y);\n\n  // if it's an input, focus in on the target, otherwise blur\n  tapHandleFocus(ele);\n}\n\nfunction triggerMouseEvent(type, ele, x, y) {\n  // using initMouseEvent instead of MouseEvent for our Android friends\n  var clickEvent = document.createEvent(\"MouseEvents\");\n  clickEvent.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, false, false, false, false, 0, null);\n  clickEvent.isIonicTap = true;\n  ele.dispatchEvent(clickEvent);\n}\n\nfunction tapClickGateKeeper(e) {\n  //console.log('click ' + Date.now() + ' isIonicTap: ' + (e.isIonicTap ? true : false));\n  if (e.target.type == 'submit' && e.detail === 0) {\n    // do not prevent click if it came from an \"Enter\" or \"Go\" keypress submit\n    return null;\n  }\n\n  // do not allow through any click events that were not created by ionic.tap\n  if ((ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) ||\n      (!e.isIonicTap && !ionic.tap.requiresNativeClick(e.target))) {\n    //console.log('clickPrevent', e.target.tagName);\n    e.stopPropagation();\n\n    if (!ionic.tap.isLabelWithTextInput(e.target)) {\n      // labels clicks from native should not preventDefault othersize keyboard will not show on input focus\n      e.preventDefault();\n    }\n    return false;\n  }\n}\n\n// MOUSE\nfunction tapMouseDown(e) {\n  //console.log('mousedown ' + Date.now());\n  if (e.isIonicTap || tapIgnoreEvent(e)) return null;\n\n  if (tapEnabledTouchEvents) {\n    void 0;\n    e.stopPropagation();\n\n    if ((!ionic.tap.isTextInput(e.target) || tapLastTouchTarget !== e.target) && !(/^(select|option)$/i).test(e.target.tagName)) {\n      // If you preventDefault on a text input then you cannot move its text caret/cursor.\n      // Allow through only the text input default. However, without preventDefault on an\n      // input the 300ms delay can change focus on inputs after the keyboard shows up.\n      // The focusin event handles the chance of focus changing after the keyboard shows.\n      e.preventDefault();\n    }\n\n    return false;\n  }\n\n  tapPointerMoved = false;\n  tapPointerStart = ionic.tap.pointerCoord(e);\n\n  tapEventListener('mousemove');\n  ionic.activator.start(e);\n}\n\nfunction tapMouseUp(e) {\n  //console.log(\"mouseup \" + Date.now());\n  if (tapEnabledTouchEvents) {\n    e.stopPropagation();\n    e.preventDefault();\n    return false;\n  }\n\n  if (tapIgnoreEvent(e) || (/^(select|option)$/i).test(e.target.tagName)) return false;\n\n  if (!tapHasPointerMoved(e)) {\n    tapClick(e);\n  }\n  tapEventListener('mousemove', false);\n  ionic.activator.end();\n  tapPointerMoved = false;\n}\n\nfunction tapMouseMove(e) {\n  if (tapHasPointerMoved(e)) {\n    tapEventListener('mousemove', false);\n    ionic.activator.end();\n    tapPointerMoved = true;\n    return false;\n  }\n}\n\n\n// TOUCH\nfunction tapTouchStart(e) {\n  //console.log(\"touchstart \" + Date.now());\n  if (tapIgnoreEvent(e)) return;\n\n  tapPointerMoved = false;\n\n  tapEnableTouchEvents();\n  tapPointerStart = ionic.tap.pointerCoord(e);\n\n  tapEventListener(tapTouchMoveListener);\n  ionic.activator.start(e);\n\n  if (ionic.Platform.isIOS() && ionic.tap.isLabelWithTextInput(e.target)) {\n    // if the tapped element is a label, which has a child input\n    // then preventDefault so iOS doesn't ugly auto scroll to the input\n    // but do not prevent default on Android or else you cannot move the text caret\n    // and do not prevent default on Android or else no virtual keyboard shows up\n\n    var textInput = tapTargetElement(tapContainingElement(e.target));\n    if (textInput !== tapActiveEle) {\n      // don't preventDefault on an already focused input or else iOS's text caret isn't usable\n      e.preventDefault();\n    }\n  }\n}\n\nfunction tapTouchEnd(e) {\n  //console.log('touchend ' + Date.now());\n  if (tapIgnoreEvent(e)) return;\n\n  tapEnableTouchEvents();\n  if (!tapHasPointerMoved(e)) {\n    tapClick(e);\n\n    if ((/^(select|option)$/i).test(e.target.tagName)) {\n      e.preventDefault();\n    }\n  }\n\n  tapLastTouchTarget = e.target;\n  tapTouchCancel();\n}\n\nfunction tapTouchMove(e) {\n  if (tapHasPointerMoved(e)) {\n    tapPointerMoved = true;\n    tapEventListener(tapTouchMoveListener, false);\n    ionic.activator.end();\n    return false;\n  }\n}\n\nfunction tapTouchCancel() {\n  tapEventListener(tapTouchMoveListener, false);\n  ionic.activator.end();\n  tapPointerMoved = false;\n}\n\nfunction tapEnableTouchEvents() {\n  tapEnabledTouchEvents = true;\n  clearTimeout(tapMouseResetTimer);\n  tapMouseResetTimer = setTimeout(function() {\n    tapEnabledTouchEvents = false;\n  }, 600);\n}\n\nfunction tapIgnoreEvent(e) {\n  if (e.isTapHandled) return true;\n  e.isTapHandled = true;\n\n  if (ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) {\n    e.preventDefault();\n    return true;\n  }\n}\n\nfunction tapHandleFocus(ele) {\n  tapTouchFocusedInput = null;\n\n  var triggerFocusIn = false;\n\n  if (ele.tagName == 'SELECT') {\n    // trick to force Android options to show up\n    triggerMouseEvent('mousedown', ele, 0, 0);\n    ele.focus && ele.focus();\n    triggerFocusIn = true;\n\n  } else if (tapActiveElement() === ele) {\n    // already is the active element and has focus\n    triggerFocusIn = true;\n\n  } else if ((/^(input|textarea)$/i).test(ele.tagName) || ele.isContentEditable) {\n    triggerFocusIn = true;\n    ele.focus && ele.focus();\n    ele.value = ele.value;\n    if (tapEnabledTouchEvents) {\n      tapTouchFocusedInput = ele;\n    }\n\n  } else {\n    tapFocusOutActive();\n  }\n\n  if (triggerFocusIn) {\n    tapActiveElement(ele);\n    ionic.trigger('ionic.focusin', {\n      target: ele\n    }, true);\n  }\n}\n\nfunction tapFocusOutActive() {\n  var ele = tapActiveElement();\n  if (ele && ((/^(input|textarea|select)$/i).test(ele.tagName) || ele.isContentEditable)) {\n    void 0;\n    ele.blur();\n  }\n  tapActiveElement(null);\n}\n\nfunction tapFocusIn(e) {\n  //console.log('focusin ' + Date.now());\n  // Because a text input doesn't preventDefault (so the caret still works) there's a chance\n  // that its mousedown event 300ms later will change the focus to another element after\n  // the keyboard shows up.\n\n  if (tapEnabledTouchEvents &&\n      ionic.tap.isTextInput(tapActiveElement()) &&\n      ionic.tap.isTextInput(tapTouchFocusedInput) &&\n      tapTouchFocusedInput !== e.target) {\n\n    // 1) The pointer is from touch events\n    // 2) There is an active element which is a text input\n    // 3) A text input was just set to be focused on by a touch event\n    // 4) A new focus has been set, however the target isn't the one the touch event wanted\n    void 0;\n    tapTouchFocusedInput.focus();\n    tapTouchFocusedInput = null;\n  }\n  ionic.scroll.isScrolling = false;\n}\n\nfunction tapFocusOut() {\n  //console.log(\"focusout\");\n  tapActiveElement(null);\n}\n\nfunction tapActiveElement(ele) {\n  if (arguments.length) {\n    tapActiveEle = ele;\n  }\n  return tapActiveEle || document.activeElement;\n}\n\nfunction tapHasPointerMoved(endEvent) {\n  if (!endEvent || endEvent.target.nodeType !== 1 || !tapPointerStart || (tapPointerStart.x === 0 && tapPointerStart.y === 0)) {\n    return false;\n  }\n  var endCoordinates = ionic.tap.pointerCoord(endEvent);\n\n  var hasClassList = !!(endEvent.target.classList && endEvent.target.classList.contains &&\n    typeof endEvent.target.classList.contains === 'function');\n  var releaseTolerance = hasClassList && endEvent.target.classList.contains('button') ?\n    TAP_RELEASE_BUTTON_TOLERANCE :\n    TAP_RELEASE_TOLERANCE;\n\n  return Math.abs(tapPointerStart.x - endCoordinates.x) > releaseTolerance ||\n         Math.abs(tapPointerStart.y - endCoordinates.y) > releaseTolerance;\n}\n\nfunction tapContainingElement(ele, allowSelf) {\n  var climbEle = ele;\n  for (var x = 0; x < 6; x++) {\n    if (!climbEle) break;\n    if (climbEle.tagName === 'LABEL') return climbEle;\n    climbEle = climbEle.parentElement;\n  }\n  if (allowSelf !== false) return ele;\n}\n\nfunction tapTargetElement(ele) {\n  if (ele && ele.tagName === 'LABEL') {\n    if (ele.control) return ele.control;\n\n    // older devices do not support the \"control\" property\n    if (ele.querySelector) {\n      var control = ele.querySelector('input,textarea,select');\n      if (control) return control;\n    }\n  }\n  return ele;\n}\n\nionic.DomUtil.ready(function() {\n  var ng = typeof angular !== 'undefined' ? angular : null;\n  //do nothing for e2e tests\n  if (!ng || (ng && !ng.scenario)) {\n    ionic.tap.register(document);\n  }\n});\n\n(function(document, ionic) {\n  'use strict';\n\n  var queueElements = {};   // elements that should get an active state in XX milliseconds\n  var activeElements = {};  // elements that are currently active\n  var keyId = 0;            // a counter for unique keys for the above ojects\n  var ACTIVATED_CLASS = 'activated';\n\n  ionic.activator = {\n\n    start: function(e) {\n      var hitX = ionic.tap.pointerCoord(e).x;\n      if (hitX > 0 && hitX < 30) {\n        return;\n      }\n\n      // when an element is touched/clicked, it climbs up a few\n      // parents to see if it is an .item or .button element\n      ionic.requestAnimationFrame(function() {\n        if ((ionic.scroll && ionic.scroll.isScrolling) || ionic.tap.requiresNativeClick(e.target)) return;\n        var ele = e.target;\n        var eleToActivate;\n\n        for (var x = 0; x < 6; x++) {\n          if (!ele || ele.nodeType !== 1) break;\n          if (eleToActivate && ele.classList && ele.classList.contains('item')) {\n            eleToActivate = ele;\n            break;\n          }\n          if (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click')) {\n            eleToActivate = ele;\n            break;\n          }\n          if (ele.classList.contains('button')) {\n            eleToActivate = ele;\n            break;\n          }\n          // no sense climbing past these\n          if (ele.tagName == 'ION-CONTENT' || (ele.classList && ele.classList.contains('pane')) || ele.tagName == 'BODY') {\n            break;\n          }\n          ele = ele.parentElement;\n        }\n\n        if (eleToActivate) {\n          // queue that this element should be set to active\n          queueElements[keyId] = eleToActivate;\n\n          // on the next frame, set the queued elements to active\n          ionic.requestAnimationFrame(activateElements);\n\n          keyId = (keyId > 29 ? 0 : keyId + 1);\n        }\n\n      });\n    },\n\n    end: function() {\n      // clear out any active/queued elements after XX milliseconds\n      setTimeout(clear, 200);\n    }\n\n  };\n\n  function clear() {\n    // clear out any elements that are queued to be set to active\n    queueElements = {};\n\n    // in the next frame, remove the active class from all active elements\n    ionic.requestAnimationFrame(deactivateElements);\n  }\n\n  function activateElements() {\n    // activate all elements in the queue\n    for (var key in queueElements) {\n      if (queueElements[key]) {\n        queueElements[key].classList.add(ACTIVATED_CLASS);\n        activeElements[key] = queueElements[key];\n      }\n    }\n    queueElements = {};\n  }\n\n  function deactivateElements() {\n    if (ionic.transition && ionic.transition.isActive) {\n      setTimeout(deactivateElements, 400);\n      return;\n    }\n\n    for (var key in activeElements) {\n      if (activeElements[key]) {\n        activeElements[key].classList.remove(ACTIVATED_CLASS);\n        delete activeElements[key];\n      }\n    }\n  }\n\n})(document, ionic);\n\n(function(ionic) {\n  /* for nextUid function below */\n  var nextId = 0;\n\n  /**\n   * Various utilities used throughout Ionic\n   *\n   * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed.\n   */\n  ionic.Utils = {\n\n    arrayMove: function(arr, oldIndex, newIndex) {\n      if (newIndex >= arr.length) {\n        var k = newIndex - arr.length;\n        while ((k--) + 1) {\n          arr.push(undefined);\n        }\n      }\n      arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);\n      return arr;\n    },\n\n    /**\n     * Return a function that will be called with the given context\n     */\n    proxy: function(func, context) {\n      var args = Array.prototype.slice.call(arguments, 2);\n      return function() {\n        return func.apply(context, args.concat(Array.prototype.slice.call(arguments)));\n      };\n    },\n\n    /**\n     * Only call a function once in the given interval.\n     *\n     * @param func {Function} the function to call\n     * @param wait {int} how long to wait before/after to allow function calls\n     * @param immediate {boolean} whether to call immediately or after the wait interval\n     */\n     debounce: function(func, wait, immediate) {\n      var timeout, args, context, timestamp, result;\n      return function() {\n        context = this;\n        args = arguments;\n        timestamp = new Date();\n        var later = function() {\n          var last = (new Date()) - timestamp;\n          if (last < wait) {\n            timeout = setTimeout(later, wait - last);\n          } else {\n            timeout = null;\n            if (!immediate) result = func.apply(context, args);\n          }\n        };\n        var callNow = immediate && !timeout;\n        if (!timeout) {\n          timeout = setTimeout(later, wait);\n        }\n        if (callNow) result = func.apply(context, args);\n        return result;\n      };\n    },\n\n    /**\n     * Throttle the given fun, only allowing it to be\n     * called at most every `wait` ms.\n     */\n    throttle: function(func, wait, options) {\n      var context, args, result;\n      var timeout = null;\n      var previous = 0;\n      options || (options = {});\n      var later = function() {\n        previous = options.leading === false ? 0 : Date.now();\n        timeout = null;\n        result = func.apply(context, args);\n      };\n      return function() {\n        var now = Date.now();\n        if (!previous && options.leading === false) previous = now;\n        var remaining = wait - (now - previous);\n        context = this;\n        args = arguments;\n        if (remaining <= 0) {\n          clearTimeout(timeout);\n          timeout = null;\n          previous = now;\n          result = func.apply(context, args);\n        } else if (!timeout && options.trailing !== false) {\n          timeout = setTimeout(later, remaining);\n        }\n        return result;\n      };\n    },\n     // Borrowed from Backbone.js's extend\n     // Helper function to correctly set up the prototype chain, for subclasses.\n     // Similar to `goog.inherits`, but uses a hash of prototype properties and\n     // class properties to be extended.\n    inherit: function(protoProps, staticProps) {\n      var parent = this;\n      var child;\n\n      // The constructor function for the new subclass is either defined by you\n      // (the \"constructor\" property in your `extend` definition), or defaulted\n      // by us to simply call the parent's constructor.\n      if (protoProps && protoProps.hasOwnProperty('constructor')) {\n        child = protoProps.constructor;\n      } else {\n        child = function() { return parent.apply(this, arguments); };\n      }\n\n      // Add static properties to the constructor function, if supplied.\n      ionic.extend(child, parent, staticProps);\n\n      // Set the prototype chain to inherit from `parent`, without calling\n      // `parent`'s constructor function.\n      var Surrogate = function() { this.constructor = child; };\n      Surrogate.prototype = parent.prototype;\n      child.prototype = new Surrogate();\n\n      // Add prototype properties (instance properties) to the subclass,\n      // if supplied.\n      if (protoProps) ionic.extend(child.prototype, protoProps);\n\n      // Set a convenience property in case the parent's prototype is needed\n      // later.\n      child.__super__ = parent.prototype;\n\n      return child;\n    },\n\n    // Extend adapted from Underscore.js\n    extend: function(obj) {\n       var args = Array.prototype.slice.call(arguments, 1);\n       for (var i = 0; i < args.length; i++) {\n         var source = args[i];\n         if (source) {\n           for (var prop in source) {\n             obj[prop] = source[prop];\n           }\n         }\n       }\n       return obj;\n    },\n\n    nextUid: function() {\n      return 'ion' + (nextId++);\n    },\n\n    disconnectScope: function disconnectScope(scope) {\n      if (!scope) return;\n\n      if (scope.$root === scope) {\n        return; // we can't disconnect the root node;\n      }\n      var parent = scope.$parent;\n      scope.$$disconnected = true;\n      scope.$broadcast('$ionic.disconnectScope', scope);\n\n      // See Scope.$destroy\n      if (parent.$$childHead === scope) {\n        parent.$$childHead = scope.$$nextSibling;\n      }\n      if (parent.$$childTail === scope) {\n        parent.$$childTail = scope.$$prevSibling;\n      }\n      if (scope.$$prevSibling) {\n        scope.$$prevSibling.$$nextSibling = scope.$$nextSibling;\n      }\n      if (scope.$$nextSibling) {\n        scope.$$nextSibling.$$prevSibling = scope.$$prevSibling;\n      }\n      scope.$$nextSibling = scope.$$prevSibling = null;\n    },\n\n    reconnectScope: function reconnectScope(scope) {\n      if (!scope) return;\n\n      if (scope.$root === scope) {\n        return; // we can't disconnect the root node;\n      }\n      if (!scope.$$disconnected) {\n        return;\n      }\n      var parent = scope.$parent;\n      scope.$$disconnected = false;\n      scope.$broadcast('$ionic.reconnectScope', scope);\n      // See Scope.$new for this logic...\n      scope.$$prevSibling = parent.$$childTail;\n      if (parent.$$childHead) {\n        parent.$$childTail.$$nextSibling = scope;\n        parent.$$childTail = scope;\n      } else {\n        parent.$$childHead = parent.$$childTail = scope;\n      }\n    },\n\n    isScopeDisconnected: function(scope) {\n      var climbScope = scope;\n      while (climbScope) {\n        if (climbScope.$$disconnected) return true;\n        climbScope = climbScope.$parent;\n      }\n      return false;\n    }\n  };\n\n  // Bind a few of the most useful functions to the ionic scope\n  ionic.inherit = ionic.Utils.inherit;\n  ionic.extend = ionic.Utils.extend;\n  ionic.throttle = ionic.Utils.throttle;\n  ionic.proxy = ionic.Utils.proxy;\n  ionic.debounce = ionic.Utils.debounce;\n\n})(window.ionic);\n\n/**\n * @ngdoc page\n * @name keyboard\n * @module ionic\n * @description\n * On both Android and iOS, Ionic will attempt to prevent the keyboard from\n * obscuring inputs and focusable elements when it appears by scrolling them\n * into view.  In order for this to work, any focusable elements must be within\n * a [Scroll View](http://ionicframework.com/docs/api/directive/ionScroll/)\n * or a directive such as [Content](http://ionicframework.com/docs/api/directive/ionContent/)\n * that has a Scroll View.\n *\n * It will also attempt to prevent the native overflow scrolling on focus,\n * which can cause layout issues such as pushing headers up and out of view.\n *\n * The keyboard fixes work best in conjunction with the\n * [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard),\n * although it will perform reasonably well without.  However, if you are using\n * Cordova there is no reason not to use the plugin.\n *\n * ### Hide when keyboard shows\n *\n * To hide an element when the keyboard is open, add the class `hide-on-keyboard-open`.\n *\n * ```html\n * <div class=\"hide-on-keyboard-open\">\n *   <div id=\"google-map\"></div>\n * </div>\n * ```\n * ----------\n *\n * ### Plugin Usage\n * Information on using the plugin can be found at\n * [https://github.com/driftyco/ionic-plugins-keyboard](https://github.com/driftyco/ionic-plugins-keyboard).\n *\n * ----------\n *\n * ### Android Notes\n * - If your app is running in fullscreen, i.e. you have\n *   `<preference name=\"Fullscreen\" value=\"true\" />` in your `config.xml` file\n *   you will need to set `ionic.Platform.isFullScreen = true` manually.\n *\n * - You can configure the behavior of the web view when the keyboard shows by setting\n *   [android:windowSoftInputMode](http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode)\n *   to either `adjustPan`, `adjustResize` or `adjustNothing` in your app's\n *   activity in `AndroidManifest.xml`. `adjustResize` is the recommended setting\n *   for Ionic, but if for some reason you do use `adjustPan` you will need to\n *   set `ionic.Platform.isFullScreen = true`.\n *\n *   ```xml\n *   <activity android:windowSoftInputMode=\"adjustResize\">\n *\n *   ```\n *\n * ### iOS Notes\n * - If the content of your app (including the header) is being pushed up and\n *   out of view on input focus, try setting `cordova.plugins.Keyboard.disableScroll(true)`.\n *   This does **not** disable scrolling in the Ionic scroll view, rather it\n *   disables the native overflow scrolling that happens automatically as a\n *   result of focusing on inputs below the keyboard.\n *\n */\n\n/**\n * The current viewport height.\n */\nvar keyboardCurrentViewportHeight = 0;\n\n/**\n * The viewport height when in portrait orientation.\n */\nvar keyboardPortraitViewportHeight = 0;\n\n/**\n * The viewport height when in landscape orientation.\n */\nvar keyboardLandscapeViewportHeight = 0;\n\n/**\n * The currently focused input.\n */\nvar keyboardActiveElement;\n\n/**\n * The scroll view containing the currently focused input.\n */\nvar scrollView;\n\n/**\n * Timer for the setInterval that polls window.innerHeight to determine whether\n * the layout has updated for the keyboard showing/hiding.\n */\nvar waitForResizeTimer;\n\n/**\n * Sometimes when switching inputs or orientations, focusout will fire before\n * focusin, so this timer is for the small setTimeout to determine if we should\n * really focusout/hide the keyboard.\n */\nvar keyboardFocusOutTimer;\n\n/**\n * on Android, orientationchange will fire before the keyboard plugin notifies\n * the browser that the keyboard will show/is showing, so this flag indicates\n * to nativeShow that there was an orientationChange and we should update\n * the viewport height with an accurate keyboard height value\n */\nvar wasOrientationChange = false;\n\n/**\n * CSS class added to the body indicating the keyboard is open.\n */\nvar KEYBOARD_OPEN_CSS = 'keyboard-open';\n\n/**\n * CSS class that indicates a scroll container.\n */\nvar SCROLL_CONTAINER_CSS = 'scroll-content';\n\n/**\n * Debounced keyboardFocusIn function\n */\nvar debouncedKeyboardFocusIn = ionic.debounce(keyboardFocusIn, 200, true);\n\n/**\n * Debounced keyboardNativeShow function\n */\nvar debouncedKeyboardNativeShow = ionic.debounce(keyboardNativeShow, 100, true);\n\n/**\n * Ionic keyboard namespace.\n * @namespace keyboard\n */\nionic.keyboard = {\n\n  /**\n   * Whether the keyboard is open or not.\n   */\n  isOpen: false,\n\n  /**\n   * Whether the keyboard is closing or not.\n   */\n  isClosing: false,\n\n  /**\n   * Whether the keyboard is opening or not.\n   */\n  isOpening: false,\n\n  /**\n   * The height of the keyboard in pixels, as reported by the keyboard plugin.\n   * If the plugin is not available, calculated as the difference in\n   * window.innerHeight after the keyboard has shown.\n   */\n  height: 0,\n\n  /**\n   * Whether the device is in landscape orientation or not.\n   */\n  isLandscape: false,\n\n  /**\n   * Whether the keyboard event listeners have been added or not\n   */\n  isInitialized: false,\n\n  /**\n   * Hide the keyboard, if it is open.\n   */\n  hide: function() {\n    if (keyboardHasPlugin()) {\n      cordova.plugins.Keyboard.close();\n    }\n    keyboardActiveElement && keyboardActiveElement.blur();\n  },\n\n  /**\n   * An alias for cordova.plugins.Keyboard.show(). If the keyboard plugin\n   * is installed, show the keyboard.\n   */\n  show: function() {\n    if (keyboardHasPlugin()) {\n      cordova.plugins.Keyboard.show();\n    }\n  },\n\n  /**\n   * Remove all keyboard related event listeners, effectively disabling Ionic's\n   * keyboard adjustments.\n   */\n  disable: function() {\n    if (keyboardHasPlugin()) {\n      window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow );\n      window.removeEventListener('native.keyboardhide', keyboardFocusOut);\n    } else {\n      document.body.removeEventListener('focusout', keyboardFocusOut);\n    }\n\n    document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn);\n    document.body.removeEventListener('focusin', debouncedKeyboardFocusIn);\n\n    window.removeEventListener('orientationchange', keyboardOrientationChange);\n\n    if ( window.navigator.msPointerEnabled ) {\n      document.removeEventListener(\"MSPointerDown\", keyboardInit);\n    } else {\n      document.removeEventListener('touchstart', keyboardInit);\n    }\n    ionic.keyboard.isInitialized = false;\n  },\n\n  /**\n   * Alias for keyboardInit, initialize all keyboard related event listeners.\n   */\n  enable: function() {\n    keyboardInit();\n  }\n};\n\n// Initialize the viewport height (after ionic.keyboard.height has been\n// defined).\nkeyboardCurrentViewportHeight = getViewportHeight();\n\n\n                             /* Event handlers */\n/* ------------------------------------------------------------------------- */\n\n/**\n * Event handler for first touch event, initializes all event listeners\n * for keyboard related events. Also aliased by ionic.keyboard.enable.\n */\nfunction keyboardInit() {\n\n  if (ionic.keyboard.isInitialized) return;\n\n  if (keyboardHasPlugin()) {\n    window.addEventListener('native.keyboardshow', debouncedKeyboardNativeShow);\n    window.addEventListener('native.keyboardhide', keyboardFocusOut);\n  } else {\n    document.body.addEventListener('focusout', keyboardFocusOut);\n  }\n\n  document.body.addEventListener('ionic.focusin', debouncedKeyboardFocusIn);\n  document.body.addEventListener('focusin', debouncedKeyboardFocusIn);\n\n  if (window.navigator.msPointerEnabled) {\n    document.removeEventListener(\"MSPointerDown\", keyboardInit);\n  } else {\n    document.removeEventListener('touchstart', keyboardInit);\n  }\n\n  ionic.keyboard.isInitialized = true;\n}\n\n/**\n * Event handler for 'native.keyboardshow' event, sets keyboard.height to the\n * reported height and keyboard.isOpening to true. Then calls\n * keyboardWaitForResize with keyboardShow or keyboardUpdateViewportHeight as\n * the callback depending on whether the event was triggered by a focusin or\n * an orientationchange.\n */\nfunction keyboardNativeShow(e) {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardNativeShow fired at: \" + Date.now());\n  //console.log(\"keyboardNativeshow window.innerHeight: \" + window.innerHeight);\n\n  if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {\n    ionic.keyboard.isOpening = true;\n    ionic.keyboard.isClosing = false;\n  }\n\n  ionic.keyboard.height = e.keyboardHeight;\n  //console.log('nativeshow keyboard height:' + e.keyboardHeight);\n\n  if (wasOrientationChange) {\n    keyboardWaitForResize(keyboardUpdateViewportHeight, true);\n  } else {\n    keyboardWaitForResize(keyboardShow, true);\n  }\n}\n\n/**\n * Event handler for 'focusin' and 'ionic.focusin' events. Initializes\n * keyboard state (keyboardActiveElement and keyboard.isOpening) for the\n * appropriate adjustments once the window has resized.  If not using the\n * keyboard plugin, calls keyboardWaitForResize with keyboardShow as the\n * callback or keyboardShow right away if the keyboard is already open.  If\n * using the keyboard plugin does nothing and lets keyboardNativeShow handle\n * adjustments with a more accurate keyboard height.\n */\nfunction keyboardFocusIn(e) {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardFocusIn from: \" + e.type + \" at: \" + Date.now());\n\n  if (!e.target ||\n      e.target.readOnly ||\n      !ionic.tap.isKeyboardElement(e.target) ||\n      !(scrollView = inputScrollView(e.target))) {\n    keyboardActiveElement = null;\n    return;\n  }\n\n  keyboardActiveElement = e.target;\n\n  // if using JS scrolling, undo the effects of native overflow scroll so the\n  // scroll view is positioned correctly\n  document.body.scrollTop = 0;\n  scrollView.scrollTop = 0;\n  ionic.requestAnimationFrame(function(){\n    document.body.scrollTop = 0;\n    scrollView.scrollTop = 0;\n  });\n\n  if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {\n    ionic.keyboard.isOpening = true;\n    ionic.keyboard.isClosing = false;\n  }\n\n  // attempt to prevent browser from natively scrolling input into view while\n  // we are trying to do the same (while we are scrolling) if the user taps the\n  // keyboard\n  document.addEventListener('keydown', keyboardOnKeyDown, false);\n\n  // any showing part of the document that isn't within the scroll the user\n  // could touchmove and cause some ugly changes to the app, so disable\n  // any touchmove events while the keyboard is open using e.preventDefault()\n  if (window.navigator.msPointerEnabled) {\n    document.addEventListener(\"MSPointerMove\", keyboardPreventDefault, false);\n  } else {\n    document.addEventListener('touchmove', keyboardPreventDefault, false);\n  }\n\n  // if we aren't using the plugin and the keyboard isn't open yet, wait for the\n  // window to resize so we can get an accurate estimate of the keyboard size,\n  // otherwise we do nothing and let nativeShow call keyboardShow once we have\n  // an exact keyboard height\n  // if the keyboard is already open, go ahead and scroll the input into view\n  // if necessary\n  if (!ionic.keyboard.isOpen && !keyboardHasPlugin()) {\n    keyboardWaitForResize(keyboardShow, true);\n\n  } else if (ionic.keyboard.isOpen) {\n    keyboardShow();\n  }\n}\n\n/**\n * Event handler for 'focusout' events. Sets keyboard.isClosing to true and\n * calls keyboardWaitForResize with keyboardHide as the callback after a small\n * timeout.\n */\nfunction keyboardFocusOut() {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardFocusOut fired at: \" + Date.now());\n  //console.log(\"keyboardFocusOut event type: \" + e.type);\n\n  if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) {\n    ionic.keyboard.isClosing = true;\n    ionic.keyboard.isOpening = false;\n  }\n\n  // Call keyboardHide with a slight delay because sometimes on focus or\n  // orientation change focusin is called immediately after, so we give it time\n  // to cancel keyboardHide\n  keyboardFocusOutTimer = setTimeout(function() {\n    ionic.requestAnimationFrame(function() {\n      // focusOut during or right after an orientationchange, so we didn't get\n      // a chance to update the viewport height yet, do it and keyboardHide\n      //console.log(\"focusOut, wasOrientationChange: \" + wasOrientationChange);\n      if (wasOrientationChange) {\n        keyboardWaitForResize(function(){\n          keyboardUpdateViewportHeight();\n          keyboardHide();\n        }, false);\n      } else {\n        keyboardWaitForResize(keyboardHide, false);\n      }\n    });\n  }, 50);\n}\n\n/**\n * Event handler for 'orientationchange' events. If using the keyboard plugin\n * and the keyboard is open on Android, sets wasOrientationChange to true so\n * nativeShow can update the viewport height with an accurate keyboard height.\n * If the keyboard isn't open or keyboard plugin isn't being used,\n * waits for the window to resize before updating the viewport height.\n *\n * On iOS, where orientationchange fires after the keyboard has already shown,\n * updates the viewport immediately, regardless of if the keyboard is already\n * open.\n */\nfunction keyboardOrientationChange() {\n  //console.log(\"orientationchange fired at: \" + Date.now());\n  //console.log(\"orientation was: \" + (ionic.keyboard.isLandscape ? \"landscape\" : \"portrait\"));\n\n  // toggle orientation\n  ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape;\n  // //console.log(\"now orientation is: \" + (ionic.keyboard.isLandscape ? \"landscape\" : \"portrait\"));\n\n  // no need to wait for resizing on iOS, and orientationchange always fires\n  // after the keyboard has opened, so it doesn't matter if it's open or not\n  if (ionic.Platform.isIOS()) {\n    keyboardUpdateViewportHeight();\n  }\n\n  // On Android, if the keyboard isn't open or we aren't using the keyboard\n  // plugin, update the viewport height once everything has resized. If the\n  // keyboard is open and we are using the keyboard plugin do nothing and let\n  // nativeShow handle it using an accurate keyboard height.\n  if ( ionic.Platform.isAndroid()) {\n    if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) {\n      keyboardWaitForResize(keyboardUpdateViewportHeight, false);\n    } else {\n      wasOrientationChange = true;\n    }\n  }\n}\n\n/**\n * Event handler for 'keydown' event. Tries to prevent browser from natively\n * scrolling an input into view when a user taps the keyboard while we are\n * scrolling the input into view ourselves with JS.\n */\nfunction keyboardOnKeyDown(e) {\n  if (ionic.scroll.isScrolling) {\n    keyboardPreventDefault(e);\n  }\n}\n\n/**\n * Event for 'touchmove' or 'MSPointerMove'. Prevents native scrolling on\n * elements outside the scroll view while the keyboard is open.\n */\nfunction keyboardPreventDefault(e) {\n  if (e.target.tagName !== 'TEXTAREA') {\n    e.preventDefault();\n  }\n}\n\n                              /* Private API */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Polls window.innerHeight until it has updated to an expected value (or\n * sufficient time has passed) before calling the specified callback function.\n * Only necessary for non-fullscreen Android which sometimes reports multiple\n * window.innerHeight values during interim layouts while it is resizing.\n *\n * On iOS, the window.innerHeight will already be updated, but we use the 50ms\n * delay as essentially a timeout so that scroll view adjustments happen after\n * the keyboard has shown so there isn't a white flash from us resizing too\n * quickly.\n *\n * @param {Function} callback the function to call once the window has resized\n * @param {boolean} isOpening whether the resize is from the keyboard opening\n * or not\n */\nfunction keyboardWaitForResize(callback, isOpening) {\n  clearInterval(waitForResizeTimer);\n  var count = 0;\n  var maxCount;\n  var initialHeight = getViewportHeight();\n  var viewportHeight = initialHeight;\n\n  //console.log(\"waitForResize initial viewport height: \" + viewportHeight);\n  //var start = Date.now();\n  //console.log(\"start: \" + start);\n\n  // want to fail relatively quickly on modern android devices, since it's much\n  // more likely we just have a bad keyboard height\n  if (ionic.Platform.isAndroid() && ionic.Platform.version() < 4.4) {\n    maxCount = 30;\n  } else if (ionic.Platform.isAndroid()) {\n    maxCount = 10;\n  } else {\n    maxCount = 1;\n  }\n\n  // poll timer\n  waitForResizeTimer = setInterval(function(){\n    viewportHeight = getViewportHeight();\n\n    // height hasn't updated yet, try again in 50ms\n    // if not using plugin, wait for maxCount to ensure we have waited long enough\n    // to get an accurate keyboard height\n    if (++count < maxCount &&\n        ((!isPortraitViewportHeight(viewportHeight) &&\n         !isLandscapeViewportHeight(viewportHeight)) ||\n         !ionic.keyboard.height)) {\n      return;\n    }\n\n    // infer the keyboard height from the resize if not using the keyboard plugin\n    if (!keyboardHasPlugin()) {\n      ionic.keyboard.height = Math.abs(initialHeight - window.innerHeight);\n    }\n\n    // set to true if we were waiting for the keyboard to open\n    ionic.keyboard.isOpen = isOpening;\n\n    clearInterval(waitForResizeTimer);\n    //var end = Date.now();\n    //console.log(\"waitForResize count: \" + count);\n    //console.log(\"end: \" + end);\n    //console.log(\"difference: \" + ( end - start ) + \"ms\");\n\n    //console.log(\"callback: \" + callback.name);\n    callback();\n\n  }, 50);\n\n  return maxCount; //for tests\n}\n\n/**\n * On keyboard close sets keyboard state to closed, resets the scroll view,\n * removes CSS from body indicating keyboard was open, removes any event\n * listeners for when the keyboard is open and on Android blurs the active\n * element (which in some cases will still have focus even if the keyboard\n * is closed and can cause it to reappear on subsequent taps).\n */\nfunction keyboardHide() {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardHide\");\n\n  ionic.keyboard.isOpen = false;\n  ionic.keyboard.isClosing = false;\n\n  if (keyboardActiveElement) {\n    ionic.trigger('resetScrollView', {\n      target: keyboardActiveElement\n    }, true);\n  }\n\n  ionic.requestAnimationFrame(function(){\n    document.body.classList.remove(KEYBOARD_OPEN_CSS);\n  });\n\n  // the keyboard is gone now, remove the touchmove that disables native scroll\n  if (window.navigator.msPointerEnabled) {\n    document.removeEventListener(\"MSPointerMove\", keyboardPreventDefault);\n  } else {\n    document.removeEventListener('touchmove', keyboardPreventDefault);\n  }\n  document.removeEventListener('keydown', keyboardOnKeyDown);\n\n  if (ionic.Platform.isAndroid()) {\n    // on android closing the keyboard with the back/dismiss button won't remove\n    // focus and keyboard can re-appear on subsequent taps (like scrolling)\n    if (keyboardHasPlugin()) cordova.plugins.Keyboard.close();\n    keyboardActiveElement && keyboardActiveElement.blur();\n  }\n\n  keyboardActiveElement = null;\n}\n\n/**\n * On keyboard open sets keyboard state to open, adds CSS to the body\n * indicating the keyboard is open and tells the scroll view to resize and\n * the currently focused input into view if necessary.\n */\nfunction keyboardShow() {\n\n  ionic.keyboard.isOpen = true;\n  ionic.keyboard.isOpening = false;\n\n  var details = {\n    keyboardHeight: keyboardGetHeight(),\n    viewportHeight: keyboardCurrentViewportHeight\n  };\n\n  if (keyboardActiveElement) {\n    details.target = keyboardActiveElement;\n\n    var elementBounds = keyboardActiveElement.getBoundingClientRect();\n\n    details.elementTop = Math.round(elementBounds.top);\n    details.elementBottom = Math.round(elementBounds.bottom);\n\n    details.windowHeight = details.viewportHeight - details.keyboardHeight;\n    //console.log(\"keyboardShow viewportHeight: \" + details.viewportHeight +\n    //\", windowHeight: \" + details.windowHeight +\n    //\", keyboardHeight: \" + details.keyboardHeight);\n\n    // figure out if the element is under the keyboard\n    details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight);\n    //console.log(\"isUnderKeyboard: \" + details.isElementUnderKeyboard);\n    //console.log(\"elementBottom: \" + details.elementBottom);\n\n    // send event so the scroll view adjusts\n    ionic.trigger('scrollChildIntoView', details, true);\n  }\n\n  setTimeout(function(){\n    document.body.classList.add(KEYBOARD_OPEN_CSS);\n  }, 400);\n\n  return details; //for testing\n}\n\n/* eslint no-unused-vars:0 */\nfunction keyboardGetHeight() {\n  // check if we already have a keyboard height from the plugin or resize calculations\n  if (ionic.keyboard.height) {\n    return ionic.keyboard.height;\n  }\n\n  if (ionic.Platform.isAndroid()) {\n    // should be using the plugin, no way to know how big the keyboard is, so guess\n    if ( ionic.Platform.isFullScreen ) {\n      return 275;\n    }\n    // otherwise just calculate it\n    var contentHeight = window.innerHeight;\n    if (contentHeight < keyboardCurrentViewportHeight) {\n      return keyboardCurrentViewportHeight - contentHeight;\n    } else {\n      return 0;\n    }\n  }\n\n  // fallback for when it's the webview without the plugin\n  // or for just the standard web browser\n  // TODO: have these be based on device\n  if (ionic.Platform.isIOS()) {\n    if (ionic.keyboard.isLandscape) {\n      return 206;\n    }\n\n    if (!ionic.Platform.isWebView()) {\n      return 216;\n    }\n\n    return 260;\n  }\n\n  // safe guess\n  return 275;\n}\n\nfunction isPortraitViewportHeight(viewportHeight) {\n  return !!(!ionic.keyboard.isLandscape &&\n         keyboardPortraitViewportHeight &&\n         (Math.abs(keyboardPortraitViewportHeight - viewportHeight) < 2));\n}\n\nfunction isLandscapeViewportHeight(viewportHeight) {\n  return !!(ionic.keyboard.isLandscape &&\n         keyboardLandscapeViewportHeight &&\n         (Math.abs(keyboardLandscapeViewportHeight - viewportHeight) < 2));\n}\n\nfunction keyboardUpdateViewportHeight() {\n  wasOrientationChange = false;\n  keyboardCurrentViewportHeight = getViewportHeight();\n\n  if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {\n    //console.log(\"saved landscape: \" + keyboardCurrentViewportHeight);\n    keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;\n\n  } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {\n    //console.log(\"saved portrait: \" + keyboardCurrentViewportHeight);\n    keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;\n  }\n\n  if (keyboardActiveElement) {\n    ionic.trigger('resetScrollView', {\n      target: keyboardActiveElement\n    }, true);\n  }\n\n  if (ionic.keyboard.isOpen && ionic.tap.isTextInput(keyboardActiveElement)) {\n    keyboardShow();\n  }\n}\n\nfunction keyboardInitViewportHeight() {\n  var viewportHeight = getViewportHeight();\n  //console.log(\"Keyboard init VP: \" + viewportHeight + \" \" + window.innerWidth);\n  // can't just use window.innerHeight in case the keyboard is opened immediately\n  if ((viewportHeight / window.innerWidth) < 1) {\n    ionic.keyboard.isLandscape = true;\n  }\n  //console.log(\"ionic.keyboard.isLandscape is: \" + ionic.keyboard.isLandscape);\n\n  // initialize or update the current viewport height values\n  keyboardCurrentViewportHeight = viewportHeight;\n  if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {\n    keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;\n  } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {\n    keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;\n  }\n}\n\nfunction getViewportHeight() {\n  var windowHeight = window.innerHeight;\n  //console.log('window.innerHeight is: ' + windowHeight);\n  //console.log('kb height is: ' + ionic.keyboard.height);\n  //console.log('kb isOpen: ' + ionic.keyboard.isOpen);\n\n  //TODO: add iPad undocked/split kb once kb plugin supports it\n  // the keyboard overlays the window on Android fullscreen\n  if (!(ionic.Platform.isAndroid() && ionic.Platform.isFullScreen) &&\n      (ionic.keyboard.isOpen || ionic.keyboard.isOpening) &&\n      !ionic.keyboard.isClosing) {\n\n     return windowHeight + keyboardGetHeight();\n  }\n  return windowHeight;\n}\n\nfunction inputScrollView(ele) {\n  while(ele) {\n    if (ele.classList.contains(SCROLL_CONTAINER_CSS)) {\n      return ele;\n    }\n    ele = ele.parentElement;\n  }\n  return null;\n}\n\nfunction keyboardHasPlugin() {\n  return !!(window.cordova && cordova.plugins && cordova.plugins.Keyboard);\n}\n\nionic.Platform.ready(function() {\n  keyboardInitViewportHeight();\n\n  window.addEventListener('orientationchange', keyboardOrientationChange);\n\n  // if orientation changes while app is in background, update on resuming\n  /*\n  if ( ionic.Platform.isWebView() ) {\n    document.addEventListener('resume', keyboardInitViewportHeight);\n\n    if (ionic.Platform.isAndroid()) {\n      //TODO: onbackpressed to detect keyboard close without focusout or plugin\n    }\n  }\n  */\n\n  // if orientation changes while app is in background, update on resuming\n/*  if ( ionic.Platform.isWebView() ) {\n    document.addEventListener('pause', function() {\n      window.removeEventListener('orientationchange', keyboardOrientationChange);\n    })\n    document.addEventListener('resume', function() {\n      keyboardInitViewportHeight();\n      window.addEventListener('orientationchange', keyboardOrientationChange)\n    });\n  }*/\n\n  // Android sometimes reports bad innerHeight on window.load\n  // try it again in a lil bit to play it safe\n  setTimeout(keyboardInitViewportHeight, 999);\n\n  // only initialize the adjustments for the virtual keyboard\n  // if a touchstart event happens\n  if (window.navigator.msPointerEnabled) {\n    document.addEventListener(\"MSPointerDown\", keyboardInit, false);\n  } else {\n    document.addEventListener('touchstart', keyboardInit, false);\n  }\n});\n\n\n\nvar viewportTag;\nvar viewportProperties = {};\n\nionic.viewport = {\n  orientation: function() {\n    // 0 = Portrait\n    // 90 = Landscape\n    // not using window.orientation because each device has a different implementation\n    return (window.innerWidth > window.innerHeight ? 90 : 0);\n  }\n};\n\nfunction viewportLoadTag() {\n  var x;\n\n  for (x = 0; x < document.head.children.length; x++) {\n    if (document.head.children[x].name == 'viewport') {\n      viewportTag = document.head.children[x];\n      break;\n    }\n  }\n\n  if (viewportTag) {\n    var props = viewportTag.content.toLowerCase().replace(/\\s+/g, '').split(',');\n    var keyValue;\n    for (x = 0; x < props.length; x++) {\n      if (props[x]) {\n        keyValue = props[x].split('=');\n        viewportProperties[ keyValue[0] ] = (keyValue.length > 1 ? keyValue[1] : '_');\n      }\n    }\n    viewportUpdate();\n  }\n}\n\nfunction viewportUpdate() {\n  // unit tests in viewport.unit.js\n\n  var initWidth = viewportProperties.width;\n  var initHeight = viewportProperties.height;\n  var p = ionic.Platform;\n  var version = p.version();\n  var DEVICE_WIDTH = 'device-width';\n  var DEVICE_HEIGHT = 'device-height';\n  var orientation = ionic.viewport.orientation();\n\n  // Most times we're removing the height and adding the width\n  // So this is the default to start with, then modify per platform/version/oreintation\n  delete viewportProperties.height;\n  viewportProperties.width = DEVICE_WIDTH;\n\n  if (p.isIPad()) {\n    // iPad\n\n    if (version > 7) {\n      // iPad >= 7.1\n      // https://issues.apache.org/jira/browse/CB-4323\n      delete viewportProperties.width;\n\n    } else {\n      // iPad <= 7.0\n\n      if (p.isWebView()) {\n        // iPad <= 7.0 WebView\n\n        if (orientation == 90) {\n          // iPad <= 7.0 WebView Landscape\n          viewportProperties.height = '0';\n\n        } else if (version == 7) {\n          // iPad <= 7.0 WebView Portait\n          viewportProperties.height = DEVICE_HEIGHT;\n        }\n      } else {\n        // iPad <= 6.1 Browser\n        if (version < 7) {\n          viewportProperties.height = '0';\n        }\n      }\n    }\n\n  } else if (p.isIOS()) {\n    // iPhone\n\n    if (p.isWebView()) {\n      // iPhone WebView\n\n      if (version > 7) {\n        // iPhone >= 7.1 WebView\n        delete viewportProperties.width;\n\n      } else if (version < 7) {\n        // iPhone <= 6.1 WebView\n        // if height was set it needs to get removed with this hack for <= 6.1\n        if (initHeight) viewportProperties.height = '0';\n\n      } else if (version == 7) {\n        //iPhone == 7.0 WebView\n        viewportProperties.height = DEVICE_HEIGHT;\n      }\n\n    } else {\n      // iPhone Browser\n\n      if (version < 7) {\n        // iPhone <= 6.1 Browser\n        // if height was set it needs to get removed with this hack for <= 6.1\n        if (initHeight) viewportProperties.height = '0';\n      }\n    }\n\n  }\n\n  // only update the viewport tag if there was a change\n  if (initWidth !== viewportProperties.width || initHeight !== viewportProperties.height) {\n    viewportTagUpdate();\n  }\n}\n\nfunction viewportTagUpdate() {\n  var key, props = [];\n  for (key in viewportProperties) {\n    if (viewportProperties[key]) {\n      props.push(key + (viewportProperties[key] == '_' ? '' : '=' + viewportProperties[key]));\n    }\n  }\n\n  viewportTag.content = props.join(', ');\n}\n\nionic.Platform.ready(function() {\n  viewportLoadTag();\n\n  window.addEventListener(\"orientationchange\", function() {\n    setTimeout(viewportUpdate, 1000);\n  }, false);\n});\n\n(function(ionic) {\n'use strict';\n  ionic.views.View = function() {\n    this.initialize.apply(this, arguments);\n  };\n\n  ionic.views.View.inherit = ionic.inherit;\n\n  ionic.extend(ionic.views.View.prototype, {\n    initialize: function() {}\n  });\n\n})(window.ionic);\n\n/*\n * Scroller\n * http://github.com/zynga/scroller\n *\n * Copyright 2011, Zynga Inc.\n * Licensed under the MIT License.\n * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt\n *\n * Based on the work of: Unify Project (unify-project.org)\n * http://unify-project.org\n * Copyright 2011, Deutsche Telekom AG\n * License: MIT + Apache (V2)\n */\n\n/* jshint eqnull: true */\n\n/**\n * Generic animation class with support for dropped frames both optional easing and duration.\n *\n * Optional duration is useful when the lifetime is defined by another condition than time\n * e.g. speed of an animating object, etc.\n *\n * Dropped frame logic allows to keep using the same updater logic independent from the actual\n * rendering. This eases a lot of cases where it might be pretty complex to break down a state\n * based on the pure time difference.\n */\nvar zyngaCore = { effect: {} };\n(function(global) {\n  var time = Date.now || function() {\n    return +new Date();\n  };\n  var desiredFrames = 60;\n  var millisecondsPerSecond = 1000;\n  var running = {};\n  var counter = 1;\n\n  zyngaCore.effect.Animate = {\n\n    /**\n     * A requestAnimationFrame wrapper / polyfill.\n     *\n     * @param callback {Function} The callback to be invoked before the next repaint.\n     * @param root {HTMLElement} The root element for the repaint\n     */\n    requestAnimationFrame: (function() {\n\n      // Check for request animation Frame support\n      var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame;\n      var isNative = !!requestFrame;\n\n      if (requestFrame && !/requestAnimationFrame\\(\\)\\s*\\{\\s*\\[native code\\]\\s*\\}/i.test(requestFrame.toString())) {\n        isNative = false;\n      }\n\n      if (isNative) {\n        return function(callback, root) {\n          requestFrame(callback, root);\n        };\n      }\n\n      var TARGET_FPS = 60;\n      var requests = {};\n      var requestCount = 0;\n      var rafHandle = 1;\n      var intervalHandle = null;\n      var lastActive = +new Date();\n\n      return function(callback) {\n        var callbackHandle = rafHandle++;\n\n        // Store callback\n        requests[callbackHandle] = callback;\n        requestCount++;\n\n        // Create timeout at first request\n        if (intervalHandle === null) {\n\n          intervalHandle = setInterval(function() {\n\n            var time = +new Date();\n            var currentRequests = requests;\n\n            // Reset data structure before executing callbacks\n            requests = {};\n            requestCount = 0;\n\n            for(var key in currentRequests) {\n              if (currentRequests.hasOwnProperty(key)) {\n                currentRequests[key](time);\n                lastActive = time;\n              }\n            }\n\n            // Disable the timeout when nothing happens for a certain\n            // period of time\n            if (time - lastActive > 2500) {\n              clearInterval(intervalHandle);\n              intervalHandle = null;\n            }\n\n          }, 1000 / TARGET_FPS);\n        }\n\n        return callbackHandle;\n      };\n\n    })(),\n\n\n    /**\n     * Stops the given animation.\n     *\n     * @param id {Integer} Unique animation ID\n     * @return {Boolean} Whether the animation was stopped (aka, was running before)\n     */\n    stop: function(id) {\n      var cleared = running[id] != null;\n      if (cleared) {\n        running[id] = null;\n      }\n\n      return cleared;\n    },\n\n\n    /**\n     * Whether the given animation is still running.\n     *\n     * @param id {Integer} Unique animation ID\n     * @return {Boolean} Whether the animation is still running\n     */\n    isRunning: function(id) {\n      return running[id] != null;\n    },\n\n\n    /**\n     * Start the animation.\n     *\n     * @param stepCallback {Function} Pointer to function which is executed on every step.\n     *   Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }`\n     * @param verifyCallback {Function} Executed before every animation step.\n     *   Signature of the method should be `function() { return continueWithAnimation; }`\n     * @param completedCallback {Function}\n     *   Signature of the method should be `function(droppedFrames, finishedAnimation) {}`\n     * @param duration {Integer} Milliseconds to run the animation\n     * @param easingMethod {Function} Pointer to easing function\n     *   Signature of the method should be `function(percent) { return modifiedValue; }`\n     * @param root {Element} Render root, when available. Used for internal\n     *   usage of requestAnimationFrame.\n     * @return {Integer} Identifier of animation. Can be used to stop it any time.\n     */\n    start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) {\n\n      var start = time();\n      var lastFrame = start;\n      var percent = 0;\n      var dropCounter = 0;\n      var id = counter++;\n\n      if (!root) {\n        root = document.body;\n      }\n\n      // Compacting running db automatically every few new animations\n      if (id % 20 === 0) {\n        var newRunning = {};\n        for (var usedId in running) {\n          newRunning[usedId] = true;\n        }\n        running = newRunning;\n      }\n\n      // This is the internal step method which is called every few milliseconds\n      var step = function(virtual) {\n\n        // Normalize virtual value\n        var render = virtual !== true;\n\n        // Get current time\n        var now = time();\n\n        // Verification is executed before next animation step\n        if (!running[id] || (verifyCallback && !verifyCallback(id))) {\n\n          running[id] = null;\n          completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false);\n          return;\n\n        }\n\n        // For the current rendering to apply let's update omitted steps in memory.\n        // This is important to bring internal state variables up-to-date with progress in time.\n        if (render) {\n\n          var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1;\n          for (var j = 0; j < Math.min(droppedFrames, 4); j++) {\n            step(true);\n            dropCounter++;\n          }\n\n        }\n\n        // Compute percent value\n        if (duration) {\n          percent = (now - start) / duration;\n          if (percent > 1) {\n            percent = 1;\n          }\n        }\n\n        // Execute step callback, then...\n        var value = easingMethod ? easingMethod(percent) : percent;\n        if ((stepCallback(value, now, render) === false || percent === 1) && render) {\n          running[id] = null;\n          completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null);\n        } else if (render) {\n          lastFrame = now;\n          zyngaCore.effect.Animate.requestAnimationFrame(step, root);\n        }\n      };\n\n      // Mark as running\n      running[id] = true;\n\n      // Init first step\n      zyngaCore.effect.Animate.requestAnimationFrame(step, root);\n\n      // Return unique animation ID\n      return id;\n    }\n  };\n})(this);\n\n/*\n * Scroller\n * http://github.com/zynga/scroller\n *\n * Copyright 2011, Zynga Inc.\n * Licensed under the MIT License.\n * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt\n *\n * Based on the work of: Unify Project (unify-project.org)\n * http://unify-project.org\n * Copyright 2011, Deutsche Telekom AG\n * License: MIT + Apache (V2)\n */\n\n(function(ionic) {\n  var NOOP = function(){};\n\n  // Easing Equations (c) 2003 Robert Penner, all rights reserved.\n  // Open source under the BSD License.\n\n  /**\n   * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)\n  **/\n  var easeOutCubic = function(pos) {\n    return (Math.pow((pos - 1), 3) + 1);\n  };\n\n  /**\n   * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)\n  **/\n  var easeInOutCubic = function(pos) {\n    if ((pos /= 0.5) < 1) {\n      return 0.5 * Math.pow(pos, 3);\n    }\n\n    return 0.5 * (Math.pow((pos - 2), 3) + 2);\n  };\n\n\n/**\n * ionic.views.Scroll\n * A powerful scroll view with support for bouncing, pull to refresh, and paging.\n * @param   {Object}        options options for the scroll view\n * @class A scroll view system\n * @memberof ionic.views\n */\nionic.views.Scroll = ionic.views.View.inherit({\n  initialize: function(options) {\n    var self = this;\n\n    self.__container = options.el;\n    self.__content = options.el.firstElementChild;\n\n    //Remove any scrollTop attached to these elements; they are virtual scroll now\n    //This also stops on-load-scroll-to-window.location.hash that the browser does\n    setTimeout(function() {\n      if (self.__container && self.__content) {\n        self.__container.scrollTop = 0;\n        self.__content.scrollTop = 0;\n      }\n    });\n\n    self.options = {\n\n      /** Disable scrolling on x-axis by default */\n      scrollingX: false,\n      scrollbarX: true,\n\n      /** Enable scrolling on y-axis */\n      scrollingY: true,\n      scrollbarY: true,\n\n      startX: 0,\n      startY: 0,\n\n      /** The amount to dampen mousewheel events */\n      wheelDampen: 6,\n\n      /** The minimum size the scrollbars scale to while scrolling */\n      minScrollbarSizeX: 5,\n      minScrollbarSizeY: 5,\n\n      /** Scrollbar fading after scrolling */\n      scrollbarsFade: true,\n      scrollbarFadeDelay: 300,\n      /** The initial fade delay when the pane is resized or initialized */\n      scrollbarResizeFadeDelay: 1000,\n\n      /** Enable animations for deceleration, snap back, zooming and scrolling */\n      animating: true,\n\n      /** duration for animations triggered by scrollTo/zoomTo */\n      animationDuration: 250,\n\n      /** The velocity required to make the scroll view \"slide\" after touchend */\n      decelVelocityThreshold: 4,\n\n      /** The velocity required to make the scroll view \"slide\" after touchend when using paging */\n      decelVelocityThresholdPaging: 4,\n\n      /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */\n      bouncing: true,\n\n      /** Enable locking to the main axis if user moves only slightly on one of them at start */\n      locking: true,\n\n      /** Enable pagination mode (switching between full page content panes) */\n      paging: false,\n\n      /** Enable snapping of content to a configured pixel grid */\n      snapping: false,\n\n      /** Enable zooming of content via API, fingers and mouse wheel */\n      zooming: false,\n\n      /** Minimum zoom level */\n      minZoom: 0.5,\n\n      /** Maximum zoom level */\n      maxZoom: 3,\n\n      /** Multiply or decrease scrolling speed **/\n      speedMultiplier: 1,\n\n      deceleration: 0.97,\n\n      /** Whether to prevent default on a scroll operation to capture drag events **/\n      preventDefault: false,\n\n      /** Callback that is fired on the later of touch end or deceleration end,\n        provided that another scrolling action has not begun. Used to know\n        when to fade out a scrollbar. */\n      scrollingComplete: NOOP,\n\n      /** This configures the amount of change applied to deceleration when reaching boundaries  **/\n      penetrationDeceleration: 0.03,\n\n      /** This configures the amount of change applied to acceleration when reaching boundaries  **/\n      penetrationAcceleration: 0.08,\n\n      // The ms interval for triggering scroll events\n      scrollEventInterval: 10,\n\n      freeze: false,\n\n      getContentWidth: function() {\n        return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);\n      },\n      getContentHeight: function() {\n        return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));\n      }\n    };\n\n    for (var key in options) {\n      self.options[key] = options[key];\n    }\n\n    self.hintResize = ionic.debounce(function() {\n      self.resize();\n    }, 1000, true);\n\n    self.onScroll = function() {\n\n      if (!ionic.scroll.isScrolling) {\n        setTimeout(self.setScrollStart, 50);\n      } else {\n        clearTimeout(self.scrollTimer);\n        self.scrollTimer = setTimeout(self.setScrollStop, 80);\n      }\n\n    };\n\n    self.freeze = function(shouldFreeze) {\n      if (arguments.length) {\n        self.options.freeze = shouldFreeze;\n      }\n      return self.options.freeze;\n    };\n\n    self.setScrollStart = function() {\n      ionic.scroll.isScrolling = Math.abs(ionic.scroll.lastTop - self.__scrollTop) > 1;\n      clearTimeout(self.scrollTimer);\n      self.scrollTimer = setTimeout(self.setScrollStop, 80);\n    };\n\n    self.setScrollStop = function() {\n      ionic.scroll.isScrolling = false;\n      ionic.scroll.lastTop = self.__scrollTop;\n    };\n\n    self.triggerScrollEvent = ionic.throttle(function() {\n      self.onScroll();\n      ionic.trigger('scroll', {\n        scrollTop: self.__scrollTop,\n        scrollLeft: self.__scrollLeft,\n        target: self.__container\n      });\n    }, self.options.scrollEventInterval);\n\n    self.triggerScrollEndEvent = function() {\n      ionic.trigger('scrollend', {\n        scrollTop: self.__scrollTop,\n        scrollLeft: self.__scrollLeft,\n        target: self.__container\n      });\n    };\n\n    self.__scrollLeft = self.options.startX;\n    self.__scrollTop = self.options.startY;\n\n    // Get the render update function, initialize event handlers,\n    // and calculate the size of the scroll container\n    self.__callback = self.getRenderFn();\n    self.__initEventHandlers();\n    self.__createScrollbars();\n\n  },\n\n  run: function() {\n    this.resize();\n\n    // Fade them out\n    this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay);\n  },\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: STATUS\n  ---------------------------------------------------------------------------\n  */\n\n  /** Whether only a single finger is used in touch handling */\n  __isSingleTouch: false,\n\n  /** Whether a touch event sequence is in progress */\n  __isTracking: false,\n\n  /** Whether a deceleration animation went to completion. */\n  __didDecelerationComplete: false,\n\n  /**\n   * Whether a gesture zoom/rotate event is in progress. Activates when\n   * a gesturestart event happens. This has higher priority than dragging.\n   */\n  __isGesturing: false,\n\n  /**\n   * Whether the user has moved by such a distance that we have enabled\n   * dragging mode. Hint: It's only enabled after some pixels of movement to\n   * not interrupt with clicks etc.\n   */\n  __isDragging: false,\n\n  /**\n   * Not touching and dragging anymore, and smoothly animating the\n   * touch sequence using deceleration.\n   */\n  __isDecelerating: false,\n\n  /**\n   * Smoothly animating the currently configured change\n   */\n  __isAnimating: false,\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: DIMENSIONS\n  ---------------------------------------------------------------------------\n  */\n\n  /** Available outer left position (from document perspective) */\n  __clientLeft: 0,\n\n  /** Available outer top position (from document perspective) */\n  __clientTop: 0,\n\n  /** Available outer width */\n  __clientWidth: 0,\n\n  /** Available outer height */\n  __clientHeight: 0,\n\n  /** Outer width of content */\n  __contentWidth: 0,\n\n  /** Outer height of content */\n  __contentHeight: 0,\n\n  /** Snapping width for content */\n  __snapWidth: 100,\n\n  /** Snapping height for content */\n  __snapHeight: 100,\n\n  /** Height to assign to refresh area */\n  __refreshHeight: null,\n\n  /** Whether the refresh process is enabled when the event is released now */\n  __refreshActive: false,\n\n  /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */\n  __refreshActivate: null,\n\n  /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */\n  __refreshDeactivate: null,\n\n  /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */\n  __refreshStart: null,\n\n  /** Zoom level */\n  __zoomLevel: 1,\n\n  /** Scroll position on x-axis */\n  __scrollLeft: 0,\n\n  /** Scroll position on y-axis */\n  __scrollTop: 0,\n\n  /** Maximum allowed scroll position on x-axis */\n  __maxScrollLeft: 0,\n\n  /** Maximum allowed scroll position on y-axis */\n  __maxScrollTop: 0,\n\n  /* Scheduled left position (final position when animating) */\n  __scheduledLeft: 0,\n\n  /* Scheduled top position (final position when animating) */\n  __scheduledTop: 0,\n\n  /* Scheduled zoom level (final scale when animating) */\n  __scheduledZoom: 0,\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: LAST POSITIONS\n  ---------------------------------------------------------------------------\n  */\n\n  /** Left position of finger at start */\n  __lastTouchLeft: null,\n\n  /** Top position of finger at start */\n  __lastTouchTop: null,\n\n  /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */\n  __lastTouchMove: null,\n\n  /** List of positions, uses three indexes for each state: left, top, timestamp */\n  __positions: null,\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: DECELERATION SUPPORT\n  ---------------------------------------------------------------------------\n  */\n\n  /** Minimum left scroll position during deceleration */\n  __minDecelerationScrollLeft: null,\n\n  /** Minimum top scroll position during deceleration */\n  __minDecelerationScrollTop: null,\n\n  /** Maximum left scroll position during deceleration */\n  __maxDecelerationScrollLeft: null,\n\n  /** Maximum top scroll position during deceleration */\n  __maxDecelerationScrollTop: null,\n\n  /** Current factor to modify horizontal scroll position with on every step */\n  __decelerationVelocityX: null,\n\n  /** Current factor to modify vertical scroll position with on every step */\n  __decelerationVelocityY: null,\n\n\n  /** the browser-specific property to use for transforms */\n  __transformProperty: null,\n  __perspectiveProperty: null,\n\n  /** scrollbar indicators */\n  __indicatorX: null,\n  __indicatorY: null,\n\n  /** Timeout for scrollbar fading */\n  __scrollbarFadeTimeout: null,\n\n  /** whether we've tried to wait for size already */\n  __didWaitForSize: null,\n  __sizerTimeout: null,\n\n  __initEventHandlers: function() {\n    var self = this;\n\n    // Event Handler\n    var container = self.__container;\n\n    // save height when scroll view is shrunk so we don't need to reflow\n    var scrollViewOffsetHeight;\n\n    /**\n     * Shrink the scroll view when the keyboard is up if necessary and if the\n     * focused input is below the bottom of the shrunk scroll view, scroll it\n     * into view.\n     */\n    self.scrollChildIntoView = function(e) {\n      //console.log(\"scrollChildIntoView at: \" + Date.now());\n\n      // D\n      var scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;\n      // D - A\n      scrollViewOffsetHeight = container.offsetHeight;\n      var alreadyShrunk = self.isShrunkForKeyboard;\n\n      var isModal = container.parentNode.classList.contains('modal');\n      // 680px is when the media query for 60% modal width kicks in\n      var isInsetModal = isModal && window.innerWidth >= 680;\n\n     /*\n      *  _______\n      * |---A---| <- top of scroll view\n      * |       |\n      * |---B---| <- keyboard\n      * |   C   | <- input\n      * |---D---| <- initial bottom of scroll view\n      * |___E___| <- bottom of viewport\n      *\n      *  All commented calculations relative to the top of the viewport (ie E\n      *  is the viewport height, not 0)\n      */\n      if (!alreadyShrunk) {\n        // shrink scrollview so we can actually scroll if the input is hidden\n        // if it isn't shrink so we can scroll to inputs under the keyboard\n        // inset modals won't shrink on Android on their own when the keyboard appears\n        if ( ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal ) {\n          // if there are things below the scroll view account for them and\n          // subtract them from the keyboard height when resizing\n          // E - D                         E                         D\n          var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop;\n\n          // 0 or D - B if D > B           E - B                     E - D\n          var keyboardOffset = Math.max(0, e.detail.keyboardHeight - scrollBottomOffsetToBottom);\n\n          ionic.requestAnimationFrame(function(){\n            // D - A or B - A if D > B       D - A             max(0, D - B)\n            scrollViewOffsetHeight = scrollViewOffsetHeight - keyboardOffset;\n            container.style.height = scrollViewOffsetHeight + \"px\";\n            container.style.overflow = \"visible\";\n\n            //update scroll view\n            self.resize();\n          });\n        }\n\n        self.isShrunkForKeyboard = true;\n      }\n\n      /*\n       *  _______\n       * |---A---| <- top of scroll view\n       * |   *   | <- where we want to scroll to\n       * |--B-D--| <- keyboard, bottom of scroll view\n       * |   C   | <- input\n       * |       |\n       * |___E___| <- bottom of viewport\n       *\n       *  All commented calculations relative to the top of the viewport (ie E\n       *  is the viewport height, not 0)\n       */\n      // if the element is positioned under the keyboard scroll it into view\n      if (e.detail.isElementUnderKeyboard) {\n\n        ionic.requestAnimationFrame(function(){\n          container.scrollTop = 0;\n          // update D if we shrunk\n          if (self.isShrunkForKeyboard && !alreadyShrunk) {\n            scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;\n          }\n\n          // middle of the scrollview, this is where we want to scroll to\n          // (D - A) / 2\n          var scrollMidpointOffset = scrollViewOffsetHeight * 0.5;\n          //console.log(\"container.offsetHeight: \" + scrollViewOffsetHeight);\n\n          // middle of the input we want to scroll into view\n          // C\n          var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2);\n\n          // distance from middle of input to the bottom of the scroll view\n          // C - D                                C               D\n          var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop;\n\n          //C - D + (D - A)/2          C - D                     (D - A)/ 2\n          var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset;\n\n          if ( scrollTop > 0) {\n            if (ionic.Platform.isIOS()) ionic.tap.cloneFocusedInput(container, self);\n            self.scrollBy(0, scrollTop, true);\n            self.onScroll();\n          }\n        });\n      }\n\n      // Only the first scrollView parent of the element that broadcasted this event\n      // (the active element that needs to be shown) should receive this event\n      e.stopPropagation();\n    };\n\n    self.resetScrollView = function() {\n      //return scrollview to original height once keyboard has hidden\n      if ( self.isShrunkForKeyboard ) {\n        self.isShrunkForKeyboard = false;\n        container.style.height = \"\";\n        container.style.overflow = \"\";\n      }\n      self.resize();\n    };\n\n    //Broadcasted when keyboard is shown on some platforms.\n    //See js/utils/keyboard.js\n    container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);\n\n    // Listen on document because container may not have had the last\n    // keyboardActiveElement, for example after closing a modal with a focused\n    // input and returning to a previously resized scroll view in an ion-content.\n    // Since we can only resize scroll views that are currently visible, just resize\n    // the current scroll view when the keyboard is closed.\n    document.addEventListener('resetScrollView', self.resetScrollView);\n\n    function getEventTouches(e) {\n      return e.touches && e.touches.length ? e.touches : [{\n        pageX: e.pageX,\n        pageY: e.pageY\n      }];\n    }\n\n    self.touchStart = function(e) {\n      self.startCoordinates = ionic.tap.pointerCoord(e);\n\n      if ( ionic.tap.ignoreScrollStart(e) ) {\n        return;\n      }\n\n      self.__isDown = true;\n\n      if ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) {\n        // do not start if the target is a text input\n        // if there is a touchmove on this input, then we can start the scroll\n        self.__hasStarted = false;\n        return;\n      }\n\n      self.__isSelectable = true;\n      self.__enableScrollY = true;\n      self.__hasStarted = true;\n      self.doTouchStart(getEventTouches(e), e.timeStamp);\n      e.preventDefault();\n    };\n\n    self.touchMove = function(e) {\n      if (self.options.freeze || !self.__isDown ||\n        (!self.__isDown && e.defaultPrevented) ||\n        (e.target.tagName === 'TEXTAREA' && e.target.parentElement.querySelector(':focus')) ) {\n        return;\n      }\n\n      if ( !self.__hasStarted && ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) ) {\n        // the target is a text input and scroll has started\n        // since the text input doesn't start on touchStart, do it here\n        self.__hasStarted = true;\n        self.doTouchStart(getEventTouches(e), e.timeStamp);\n        e.preventDefault();\n        return;\n      }\n\n      if (self.startCoordinates) {\n        // we have start coordinates, so get this touch move's current coordinates\n        var currentCoordinates = ionic.tap.pointerCoord(e);\n\n        if ( self.__isSelectable &&\n            ionic.tap.isTextInput(e.target) &&\n            Math.abs(self.startCoordinates.x - currentCoordinates.x) > 20 ) {\n          // user slid the text input's caret on its x axis, disable any future y scrolling\n          self.__enableScrollY = false;\n          self.__isSelectable = true;\n        }\n\n        if ( self.__enableScrollY && Math.abs(self.startCoordinates.y - currentCoordinates.y) > 10 ) {\n          // user scrolled the entire view on the y axis\n          // disabled being able to select text on an input\n          // hide the input which has focus, and show a cloned one that doesn't have focus\n          self.__isSelectable = false;\n          ionic.tap.cloneFocusedInput(container, self);\n        }\n      }\n\n      self.doTouchMove(getEventTouches(e), e.timeStamp, e.scale);\n      self.__isDown = true;\n    };\n\n    self.touchMoveBubble = function(e) {\n      if(self.__isDown && self.options.preventDefault) {\n        e.preventDefault();\n      }\n    };\n\n    self.touchEnd = function(e) {\n      if (!self.__isDown) return;\n\n      self.doTouchEnd(e, e.timeStamp);\n      self.__isDown = false;\n      self.__hasStarted = false;\n      self.__isSelectable = true;\n      self.__enableScrollY = true;\n\n      if ( !self.__isDragging && !self.__isDecelerating && !self.__isAnimating ) {\n        ionic.tap.removeClonedInputs(container, self);\n      }\n    };\n\n    self.mouseWheel = ionic.animationFrameThrottle(function(e) {\n      var scrollParent = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'ionic-scroll');\n      if (!self.options.freeze && scrollParent === self.__container) {\n\n        self.hintResize();\n        self.scrollBy(\n          (e.wheelDeltaX || e.deltaX || 0) / self.options.wheelDampen,\n          (-e.wheelDeltaY || e.deltaY || 0) / self.options.wheelDampen\n        );\n\n        self.__fadeScrollbars('in');\n        clearTimeout(self.__wheelHideBarTimeout);\n        self.__wheelHideBarTimeout = setTimeout(function() {\n          self.__fadeScrollbars('out');\n        }, 100);\n      }\n    });\n\n    if ('ontouchstart' in window) {\n      // Touch Events\n      container.addEventListener(\"touchstart\", self.touchStart, false);\n      if(self.options.preventDefault) container.addEventListener(\"touchmove\", self.touchMoveBubble, false);\n      document.addEventListener(\"touchmove\", self.touchMove, false);\n      document.addEventListener(\"touchend\", self.touchEnd, false);\n      document.addEventListener(\"touchcancel\", self.touchEnd, false);\n\n    } else if (window.navigator.pointerEnabled) {\n      // Pointer Events\n      container.addEventListener(\"pointerdown\", self.touchStart, false);\n      if(self.options.preventDefault) container.addEventListener(\"pointermove\", self.touchMoveBubble, false);\n      document.addEventListener(\"pointermove\", self.touchMove, false);\n      document.addEventListener(\"pointerup\", self.touchEnd, false);\n      document.addEventListener(\"pointercancel\", self.touchEnd, false);\n      document.addEventListener(\"wheel\", self.mouseWheel, false);\n\n    } else if (window.navigator.msPointerEnabled) {\n      // IE10, WP8 (Pointer Events)\n      container.addEventListener(\"MSPointerDown\", self.touchStart, false);\n      if(self.options.preventDefault) container.addEventListener(\"MSPointerMove\", self.touchMoveBubble, false);\n      document.addEventListener(\"MSPointerMove\", self.touchMove, false);\n      document.addEventListener(\"MSPointerUp\", self.touchEnd, false);\n      document.addEventListener(\"MSPointerCancel\", self.touchEnd, false);\n      document.addEventListener(\"wheel\", self.mouseWheel, false);\n\n    } else {\n      // Mouse Events\n      var mousedown = false;\n\n      self.mouseDown = function(e) {\n        if ( ionic.tap.ignoreScrollStart(e) || e.target.tagName === 'SELECT' ) {\n          return;\n        }\n        self.doTouchStart(getEventTouches(e), e.timeStamp);\n\n        if ( !ionic.tap.isTextInput(e.target) ) {\n          e.preventDefault();\n        }\n        mousedown = true;\n      };\n\n      self.mouseMove = function(e) {\n        if (self.options.freeze || !mousedown || (!mousedown && e.defaultPrevented)) {\n          return;\n        }\n\n        self.doTouchMove(getEventTouches(e), e.timeStamp);\n\n        mousedown = true;\n      };\n\n      self.mouseMoveBubble = function(e) {\n        if (mousedown && self.options.preventDefault) {\n          e.preventDefault();\n        }\n      };\n\n      self.mouseUp = function(e) {\n        if (!mousedown) {\n          return;\n        }\n\n        self.doTouchEnd(e, e.timeStamp);\n\n        mousedown = false;\n      };\n\n      container.addEventListener(\"mousedown\", self.mouseDown, false);\n      if(self.options.preventDefault) container.addEventListener(\"mousemove\", self.mouseMoveBubble, false);\n      document.addEventListener(\"mousemove\", self.mouseMove, false);\n      document.addEventListener(\"mouseup\", self.mouseUp, false);\n      document.addEventListener('mousewheel', self.mouseWheel, false);\n      document.addEventListener('wheel', self.mouseWheel, false);\n    }\n  },\n\n  __cleanup: function() {\n    var self = this;\n    var container = self.__container;\n\n    container.removeEventListener('touchstart', self.touchStart);\n    container.removeEventListener('touchmove', self.touchMoveBubble);\n    document.removeEventListener('touchmove', self.touchMove);\n    document.removeEventListener('touchend', self.touchEnd);\n    document.removeEventListener('touchcancel', self.touchCancel);\n\n    container.removeEventListener(\"pointerdown\", self.touchStart);\n    container.removeEventListener(\"pointermove\", self.touchMoveBubble);\n    document.removeEventListener(\"pointermove\", self.touchMove);\n    document.removeEventListener(\"pointerup\", self.touchEnd);\n    document.removeEventListener(\"pointercancel\", self.touchEnd);\n\n    container.removeEventListener(\"MSPointerDown\", self.touchStart);\n    container.removeEventListener(\"MSPointerMove\", self.touchMoveBubble);\n    document.removeEventListener(\"MSPointerMove\", self.touchMove);\n    document.removeEventListener(\"MSPointerUp\", self.touchEnd);\n    document.removeEventListener(\"MSPointerCancel\", self.touchEnd);\n\n    container.removeEventListener(\"mousedown\", self.mouseDown);\n    container.removeEventListener(\"mousemove\", self.mouseMoveBubble);\n    document.removeEventListener(\"mousemove\", self.mouseMove);\n    document.removeEventListener(\"mouseup\", self.mouseUp);\n    document.removeEventListener('mousewheel', self.mouseWheel);\n    document.removeEventListener('wheel', self.mouseWheel);\n\n    container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);\n    document.removeEventListener('resetScrollView', self.resetScrollView);\n\n    ionic.tap.removeClonedInputs(container, self);\n\n    delete self.__container;\n    delete self.__content;\n    delete self.__indicatorX;\n    delete self.__indicatorY;\n    delete self.options.el;\n\n    self.__callback = self.scrollChildIntoView = self.resetScrollView = NOOP;\n\n    self.mouseMove = self.mouseDown = self.mouseUp = self.mouseWheel =\n      self.touchStart = self.touchMove = self.touchEnd = self.touchCancel = NOOP;\n\n    self.resize = self.scrollTo = self.zoomTo =\n      self.__scrollingComplete = NOOP;\n    container = null;\n  },\n\n  /** Create a scroll bar div with the given direction **/\n  __createScrollbar: function(direction) {\n    var bar = document.createElement('div'),\n      indicator = document.createElement('div');\n\n    indicator.className = 'scroll-bar-indicator scroll-bar-fade-out';\n\n    if (direction == 'h') {\n      bar.className = 'scroll-bar scroll-bar-h';\n    } else {\n      bar.className = 'scroll-bar scroll-bar-v';\n    }\n\n    bar.appendChild(indicator);\n    return bar;\n  },\n\n  __createScrollbars: function() {\n    var self = this;\n    var indicatorX, indicatorY;\n\n    if (self.options.scrollingX) {\n      indicatorX = {\n        el: self.__createScrollbar('h'),\n        sizeRatio: 1\n      };\n      indicatorX.indicator = indicatorX.el.children[0];\n\n      if (self.options.scrollbarX) {\n        self.__container.appendChild(indicatorX.el);\n      }\n      self.__indicatorX = indicatorX;\n    }\n\n    if (self.options.scrollingY) {\n      indicatorY = {\n        el: self.__createScrollbar('v'),\n        sizeRatio: 1\n      };\n      indicatorY.indicator = indicatorY.el.children[0];\n\n      if (self.options.scrollbarY) {\n        self.__container.appendChild(indicatorY.el);\n      }\n      self.__indicatorY = indicatorY;\n    }\n  },\n\n  __resizeScrollbars: function() {\n    var self = this;\n\n    // Update horiz bar\n    if (self.__indicatorX) {\n      var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20);\n      if (width > self.__contentWidth) {\n        width = 0;\n      }\n      if (width !== self.__indicatorX.size) {\n        ionic.requestAnimationFrame(function(){\n          self.__indicatorX.indicator.style.width = width + 'px';\n        });\n      }\n      self.__indicatorX.size = width;\n      self.__indicatorX.minScale = self.options.minScrollbarSizeX / width;\n      self.__indicatorX.maxPos = self.__clientWidth - width;\n      self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1;\n    }\n\n    // Update vert bar\n    if (self.__indicatorY) {\n      var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20);\n      if (height > self.__contentHeight) {\n        height = 0;\n      }\n      if (height !== self.__indicatorY.size) {\n        ionic.requestAnimationFrame(function(){\n          self.__indicatorY && (self.__indicatorY.indicator.style.height = height + 'px');\n        });\n      }\n      self.__indicatorY.size = height;\n      self.__indicatorY.minScale = self.options.minScrollbarSizeY / height;\n      self.__indicatorY.maxPos = self.__clientHeight - height;\n      self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1;\n    }\n  },\n\n  /**\n   * Move and scale the scrollbars as the page scrolls.\n   */\n  __repositionScrollbars: function() {\n    var self = this,\n        heightScale, widthScale,\n        widthDiff, heightDiff,\n        x, y,\n        xstop = 0, ystop = 0;\n\n    if (self.__indicatorX) {\n      // Handle the X scrollbar\n\n      // Don't go all the way to the right if we have a vertical scrollbar as well\n      if (self.__indicatorY) xstop = 10;\n\n      x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0;\n\n      // The the difference between the last content X position, and our overscrolled one\n      widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop);\n\n      if (self.__scrollLeft < 0) {\n\n        widthScale = Math.max(self.__indicatorX.minScale,\n            (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size);\n\n        // Stay at left\n        x = 0;\n\n        // Make sure scale is transformed from the left/center origin point\n        self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center';\n      } else if (widthDiff > 0) {\n\n        widthScale = Math.max(self.__indicatorX.minScale,\n            (self.__indicatorX.size - widthDiff) / self.__indicatorX.size);\n\n        // Stay at the furthest x for the scrollable viewport\n        x = self.__indicatorX.maxPos - xstop;\n\n        // Make sure scale is transformed from the right/center origin point\n        self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center';\n\n      } else {\n\n        // Normal motion\n        x = Math.min(self.__maxScrollLeft, Math.max(0, x));\n        widthScale = 1;\n\n      }\n\n      var translate3dX = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')';\n      if (self.__indicatorX.transformProp !== translate3dX) {\n        self.__indicatorX.indicator.style[self.__transformProperty] = translate3dX;\n        self.__indicatorX.transformProp = translate3dX;\n      }\n    }\n\n    if (self.__indicatorY) {\n\n      y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0;\n\n      // Don't go all the way to the right if we have a vertical scrollbar as well\n      if (self.__indicatorX) ystop = 10;\n\n      heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop);\n\n      if (self.__scrollTop < 0) {\n\n        heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size);\n\n        // Stay at top\n        y = 0;\n\n        // Make sure scale is transformed from the center/top origin point\n        if (self.__indicatorY.originProp !== 'center top') {\n          self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top';\n          self.__indicatorY.originProp = 'center top';\n        }\n\n      } else if (heightDiff > 0) {\n\n        heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size);\n\n        // Stay at bottom of scrollable viewport\n        y = self.__indicatorY.maxPos - ystop;\n\n        // Make sure scale is transformed from the center/bottom origin point\n        if (self.__indicatorY.originProp !== 'center bottom') {\n          self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom';\n          self.__indicatorY.originProp = 'center bottom';\n        }\n\n      } else {\n\n        // Normal motion\n        y = Math.min(self.__maxScrollTop, Math.max(0, y));\n        heightScale = 1;\n\n      }\n\n      var translate3dY = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')';\n      if (self.__indicatorY.transformProp !== translate3dY) {\n        self.__indicatorY.indicator.style[self.__transformProperty] = translate3dY;\n        self.__indicatorY.transformProp = translate3dY;\n      }\n    }\n  },\n\n  __fadeScrollbars: function(direction, delay) {\n    var self = this;\n\n    if (!self.options.scrollbarsFade) {\n      return;\n    }\n\n    var className = 'scroll-bar-fade-out';\n\n    if (self.options.scrollbarsFade === true) {\n      clearTimeout(self.__scrollbarFadeTimeout);\n\n      if (direction == 'in') {\n        if (self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); }\n        if (self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); }\n      } else {\n        self.__scrollbarFadeTimeout = setTimeout(function() {\n          if (self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); }\n          if (self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); }\n        }, delay || self.options.scrollbarFadeDelay);\n      }\n    }\n  },\n\n  __scrollingComplete: function() {\n    this.options.scrollingComplete();\n    ionic.tap.removeClonedInputs(this.__container, this);\n    this.__fadeScrollbars('out');\n  },\n\n  resize: function(continueScrolling) {\n    var self = this;\n    if (!self.__container || !self.options) return;\n\n    // Update Scroller dimensions for changed content\n    // Add padding to bottom of content\n    self.setDimensions(\n      self.__container.clientWidth,\n      self.__container.clientHeight,\n      self.options.getContentWidth(),\n      self.options.getContentHeight(),\n      continueScrolling\n    );\n  },\n  /*\n  ---------------------------------------------------------------------------\n    PUBLIC API\n  ---------------------------------------------------------------------------\n  */\n\n  getRenderFn: function() {\n    var self = this;\n\n    var content = self.__content;\n\n    var docStyle = document.documentElement.style;\n\n    var engine;\n    if ('MozAppearance' in docStyle) {\n      engine = 'gecko';\n    } else if ('WebkitAppearance' in docStyle) {\n      engine = 'webkit';\n    } else if (typeof navigator.cpuClass === 'string') {\n      engine = 'trident';\n    }\n\n    var vendorPrefix = {\n      trident: 'ms',\n      gecko: 'Moz',\n      webkit: 'Webkit',\n      presto: 'O'\n    }[engine];\n\n    var helperElem = document.createElement(\"div\");\n    var undef;\n\n    var perspectiveProperty = vendorPrefix + \"Perspective\";\n    var transformProperty = vendorPrefix + \"Transform\";\n    var transformOriginProperty = vendorPrefix + 'TransformOrigin';\n\n    self.__perspectiveProperty = transformProperty;\n    self.__transformProperty = transformProperty;\n    self.__transformOriginProperty = transformOriginProperty;\n\n    if (helperElem.style[perspectiveProperty] !== undef) {\n\n      return function(left, top, zoom, wasResize) {\n        var translate3d = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')';\n        if (translate3d !== self.contentTransform) {\n          content.style[transformProperty] = translate3d;\n          self.contentTransform = translate3d;\n        }\n        self.__repositionScrollbars();\n        if (!wasResize) {\n          self.triggerScrollEvent();\n        }\n      };\n\n    } else if (helperElem.style[transformProperty] !== undef) {\n\n      return function(left, top, zoom, wasResize) {\n        content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')';\n        self.__repositionScrollbars();\n        if (!wasResize) {\n          self.triggerScrollEvent();\n        }\n      };\n\n    } else {\n\n      return function(left, top, zoom, wasResize) {\n        content.style.marginLeft = left ? (-left / zoom) + 'px' : '';\n        content.style.marginTop = top ? (-top / zoom) + 'px' : '';\n        content.style.zoom = zoom || '';\n        self.__repositionScrollbars();\n        if (!wasResize) {\n          self.triggerScrollEvent();\n        }\n      };\n\n    }\n  },\n\n\n  /**\n   * Configures the dimensions of the client (outer) and content (inner) elements.\n   * Requires the available space for the outer element and the outer size of the inner element.\n   * All values which are falsy (null or zero etc.) are ignored and the old value is kept.\n   *\n   * @param clientWidth {Integer} Inner width of outer element\n   * @param clientHeight {Integer} Inner height of outer element\n   * @param contentWidth {Integer} Outer width of inner element\n   * @param contentHeight {Integer} Outer height of inner element\n   */\n  setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight, continueScrolling) {\n    var self = this;\n\n    if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {\n      // this scrollview isn't rendered, don't bother\n      return;\n    }\n\n    // Only update values which are defined\n    if (clientWidth === +clientWidth) {\n      self.__clientWidth = clientWidth;\n    }\n\n    if (clientHeight === +clientHeight) {\n      self.__clientHeight = clientHeight;\n    }\n\n    if (contentWidth === +contentWidth) {\n      self.__contentWidth = contentWidth;\n    }\n\n    if (contentHeight === +contentHeight) {\n      self.__contentHeight = contentHeight;\n    }\n\n    // Refresh maximums\n    self.__computeScrollMax();\n    self.__resizeScrollbars();\n\n    // Refresh scroll position\n    if (!continueScrolling) {\n      self.scrollTo(self.__scrollLeft, self.__scrollTop, true, null, true);\n    }\n\n  },\n\n\n  /**\n   * Sets the client coordinates in relation to the document.\n   *\n   * @param left {Integer} Left position of outer element\n   * @param top {Integer} Top position of outer element\n   */\n  setPosition: function(left, top) {\n    this.__clientLeft = left || 0;\n    this.__clientTop = top || 0;\n  },\n\n\n  /**\n   * Configures the snapping (when snapping is active)\n   *\n   * @param width {Integer} Snapping width\n   * @param height {Integer} Snapping height\n   */\n  setSnapSize: function(width, height) {\n    this.__snapWidth = width;\n    this.__snapHeight = height;\n  },\n\n\n  /**\n   * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever\n   * the user event is released during visibility of this zone. This was introduced by some apps on iOS like\n   * the official Twitter client.\n   *\n   * @param height {Integer} Height of pull-to-refresh zone on top of rendered list\n   * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release.\n   * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled.\n   * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh.\n   * @param showCallback {Function} Callback to execute when the refresher should be shown. This is for showing the refresher during a negative scrollTop.\n   * @param hideCallback {Function} Callback to execute when the refresher should be hidden. This is for hiding the refresher when it's behind the nav bar.\n   * @param tailCallback {Function} Callback to execute just before the refresher returns to it's original state. This is for zooming out the refresher.\n   * @param pullProgressCallback Callback to state the progress while pulling to refresh\n   */\n  activatePullToRefresh: function(height, refresherMethods) {\n    var self = this;\n\n    self.__refreshHeight = height;\n    self.__refreshActivate = function() { ionic.requestAnimationFrame(refresherMethods.activate); };\n    self.__refreshDeactivate = function() { ionic.requestAnimationFrame(refresherMethods.deactivate); };\n    self.__refreshStart = function() { ionic.requestAnimationFrame(refresherMethods.start); };\n    self.__refreshShow = function() { ionic.requestAnimationFrame(refresherMethods.show); };\n    self.__refreshHide = function() { ionic.requestAnimationFrame(refresherMethods.hide); };\n    self.__refreshTail = function() { ionic.requestAnimationFrame(refresherMethods.tail); };\n    self.__refreshTailTime = 100;\n    self.__minSpinTime = 600;\n  },\n\n\n  /**\n   * Starts pull-to-refresh manually.\n   */\n  triggerPullToRefresh: function() {\n    // Use publish instead of scrollTo to allow scrolling to out of boundary position\n    // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled\n    this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true);\n\n    var d = new Date();\n    this.refreshStartTime = d.getTime();\n\n    if (this.__refreshStart) {\n      this.__refreshStart();\n    }\n  },\n\n\n  /**\n   * Signalizes that pull-to-refresh is finished.\n   */\n  finishPullToRefresh: function() {\n    var self = this;\n    // delay to make sure the spinner has a chance to spin for a split second before it's dismissed\n    var d = new Date();\n    var delay = 0;\n    if (self.refreshStartTime + self.__minSpinTime > d.getTime()) {\n      delay = self.refreshStartTime + self.__minSpinTime - d.getTime();\n    }\n    setTimeout(function() {\n      if (self.__refreshTail) {\n        self.__refreshTail();\n      }\n      setTimeout(function() {\n        self.__refreshActive = false;\n        if (self.__refreshDeactivate) {\n          self.__refreshDeactivate();\n        }\n        if (self.__refreshHide) {\n          self.__refreshHide();\n        }\n\n        self.scrollTo(self.__scrollLeft, self.__scrollTop, true);\n      }, self.__refreshTailTime);\n    }, delay);\n  },\n\n\n  /**\n   * Returns the scroll position and zooming values\n   *\n   * @return {Map} `left` and `top` scroll position and `zoom` level\n   */\n  getValues: function() {\n    return {\n      left: this.__scrollLeft,\n      top: this.__scrollTop,\n      zoom: this.__zoomLevel\n    };\n  },\n\n\n  /**\n   * Returns the maximum scroll values\n   *\n   * @return {Map} `left` and `top` maximum scroll values\n   */\n  getScrollMax: function() {\n    return {\n      left: this.__maxScrollLeft,\n      top: this.__maxScrollTop\n    };\n  },\n\n\n  /**\n   * Zooms to the given level. Supports optional animation. Zooms\n   * the center when no coordinates are given.\n   *\n   * @param level {Number} Level to zoom to\n   * @param animate {Boolean} Whether to use animation\n   * @param originLeft {Number} Zoom in at given left coordinate\n   * @param originTop {Number} Zoom in at given top coordinate\n   */\n  zoomTo: function(level, animate, originLeft, originTop) {\n    var self = this;\n\n    if (!self.options.zooming) {\n      throw new Error(\"Zooming is not enabled!\");\n    }\n\n    // Stop deceleration\n    if (self.__isDecelerating) {\n      zyngaCore.effect.Animate.stop(self.__isDecelerating);\n      self.__isDecelerating = false;\n    }\n\n    var oldLevel = self.__zoomLevel;\n\n    // Normalize input origin to center of viewport if not defined\n    if (originLeft == null) {\n      originLeft = self.__clientWidth / 2;\n    }\n\n    if (originTop == null) {\n      originTop = self.__clientHeight / 2;\n    }\n\n    // Limit level according to configuration\n    level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);\n\n    // Recompute maximum values while temporary tweaking maximum scroll ranges\n    self.__computeScrollMax(level);\n\n    // Recompute left and top coordinates based on new zoom level\n    var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft;\n    var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop;\n\n    // Limit x-axis\n    if (left > self.__maxScrollLeft) {\n      left = self.__maxScrollLeft;\n    } else if (left < 0) {\n      left = 0;\n    }\n\n    // Limit y-axis\n    if (top > self.__maxScrollTop) {\n      top = self.__maxScrollTop;\n    } else if (top < 0) {\n      top = 0;\n    }\n\n    // Push values out\n    self.__publish(left, top, level, animate);\n\n  },\n\n\n  /**\n   * Zooms the content by the given factor.\n   *\n   * @param factor {Number} Zoom by given factor\n   * @param animate {Boolean} Whether to use animation\n   * @param originLeft {Number} Zoom in at given left coordinate\n   * @param originTop {Number} Zoom in at given top coordinate\n   */\n  zoomBy: function(factor, animate, originLeft, originTop) {\n    this.zoomTo(this.__zoomLevel * factor, animate, originLeft, originTop);\n  },\n\n\n  /**\n   * Scrolls to the given position. Respect limitations and snapping automatically.\n   *\n   * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>\n   * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>\n   * @param animate {Boolean} Whether the scrolling should happen using an animation\n   * @param zoom {Number} Zoom level to go to\n   */\n  scrollTo: function(left, top, animate, zoom, wasResize) {\n    var self = this;\n\n    // Stop deceleration\n    if (self.__isDecelerating) {\n      zyngaCore.effect.Animate.stop(self.__isDecelerating);\n      self.__isDecelerating = false;\n    }\n\n    // Correct coordinates based on new zoom level\n    if (zoom != null && zoom !== self.__zoomLevel) {\n\n      if (!self.options.zooming) {\n        throw new Error(\"Zooming is not enabled!\");\n      }\n\n      left *= zoom;\n      top *= zoom;\n\n      // Recompute maximum values while temporary tweaking maximum scroll ranges\n      self.__computeScrollMax(zoom);\n\n    } else {\n\n      // Keep zoom when not defined\n      zoom = self.__zoomLevel;\n\n    }\n\n    if (!self.options.scrollingX) {\n\n      left = self.__scrollLeft;\n\n    } else {\n\n      if (self.options.paging) {\n        left = Math.round(left / self.__clientWidth) * self.__clientWidth;\n      } else if (self.options.snapping) {\n        left = Math.round(left / self.__snapWidth) * self.__snapWidth;\n      }\n\n    }\n\n    if (!self.options.scrollingY) {\n\n      top = self.__scrollTop;\n\n    } else {\n\n      if (self.options.paging) {\n        top = Math.round(top / self.__clientHeight) * self.__clientHeight;\n      } else if (self.options.snapping) {\n        top = Math.round(top / self.__snapHeight) * self.__snapHeight;\n      }\n\n    }\n\n    // Limit for allowed ranges\n    left = Math.max(Math.min(self.__maxScrollLeft, left), 0);\n    top = Math.max(Math.min(self.__maxScrollTop, top), 0);\n\n    // Don't animate when no change detected, still call publish to make sure\n    // that rendered position is really in-sync with internal data\n    if (left === self.__scrollLeft && top === self.__scrollTop) {\n      animate = false;\n    }\n\n    // Publish new values\n    self.__publish(left, top, zoom, animate, wasResize);\n\n  },\n\n\n  /**\n   * Scroll by the given offset\n   *\n   * @param left {Number} Scroll x-axis by given offset\n   * @param top {Number} Scroll y-axis by given offset\n   * @param animate {Boolean} Whether to animate the given change\n   */\n  scrollBy: function(left, top, animate) {\n    var self = this;\n\n    var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;\n    var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;\n\n    self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);\n  },\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    EVENT CALLBACKS\n  ---------------------------------------------------------------------------\n  */\n\n  /**\n   * Mouse wheel handler for zooming support\n   */\n  doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) {\n    var change = wheelDelta > 0 ? 0.97 : 1.03;\n    return this.zoomTo(this.__zoomLevel * change, false, pageX - this.__clientLeft, pageY - this.__clientTop);\n  },\n\n  /**\n   * Touch start handler for scrolling support\n   */\n  doTouchStart: function(touches, timeStamp) {\n    var self = this;\n\n    // remember if the deceleration was just stopped\n    self.__decStopped = !!(self.__isDecelerating || self.__isAnimating);\n\n    self.hintResize();\n\n    if (timeStamp instanceof Date) {\n      timeStamp = timeStamp.valueOf();\n    }\n    if (typeof timeStamp !== \"number\") {\n      timeStamp = Date.now();\n    }\n\n    // Reset interruptedAnimation flag\n    self.__interruptedAnimation = true;\n\n    // Stop deceleration\n    if (self.__isDecelerating) {\n      zyngaCore.effect.Animate.stop(self.__isDecelerating);\n      self.__isDecelerating = false;\n      self.__interruptedAnimation = true;\n    }\n\n    // Stop animation\n    if (self.__isAnimating) {\n      zyngaCore.effect.Animate.stop(self.__isAnimating);\n      self.__isAnimating = false;\n      self.__interruptedAnimation = true;\n    }\n\n    // Use center point when dealing with two fingers\n    var currentTouchLeft, currentTouchTop;\n    var isSingleTouch = touches.length === 1;\n    if (isSingleTouch) {\n      currentTouchLeft = touches[0].pageX;\n      currentTouchTop = touches[0].pageY;\n    } else {\n      currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;\n      currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;\n    }\n\n    // Store initial positions\n    self.__initialTouchLeft = currentTouchLeft;\n    self.__initialTouchTop = currentTouchTop;\n\n    // Store initial touchList for scale calculation\n    self.__initialTouches = touches;\n\n    // Store current zoom level\n    self.__zoomLevelStart = self.__zoomLevel;\n\n    // Store initial touch positions\n    self.__lastTouchLeft = currentTouchLeft;\n    self.__lastTouchTop = currentTouchTop;\n\n    // Store initial move time stamp\n    self.__lastTouchMove = timeStamp;\n\n    // Reset initial scale\n    self.__lastScale = 1;\n\n    // Reset locking flags\n    self.__enableScrollX = !isSingleTouch && self.options.scrollingX;\n    self.__enableScrollY = !isSingleTouch && self.options.scrollingY;\n\n    // Reset tracking flag\n    self.__isTracking = true;\n\n    // Reset deceleration complete flag\n    self.__didDecelerationComplete = false;\n\n    // Dragging starts directly with two fingers, otherwise lazy with an offset\n    self.__isDragging = !isSingleTouch;\n\n    // Some features are disabled in multi touch scenarios\n    self.__isSingleTouch = isSingleTouch;\n\n    // Clearing data structure\n    self.__positions = [];\n\n  },\n\n\n  /**\n   * Touch move handler for scrolling support\n   */\n  doTouchMove: function(touches, timeStamp, scale) {\n    if (timeStamp instanceof Date) {\n      timeStamp = timeStamp.valueOf();\n    }\n    if (typeof timeStamp !== \"number\") {\n      timeStamp = Date.now();\n    }\n\n    var self = this;\n\n    // Ignore event when tracking is not enabled (event might be outside of element)\n    if (!self.__isTracking) {\n      return;\n    }\n\n    var currentTouchLeft, currentTouchTop;\n\n    // Compute move based around of center of fingers\n    if (touches.length === 2) {\n      currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;\n      currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;\n\n      // Calculate scale when not present and only when touches are used\n      if (!scale && self.options.zooming) {\n        scale = self.__getScale(self.__initialTouches, touches);\n      }\n    } else {\n      currentTouchLeft = touches[0].pageX;\n      currentTouchTop = touches[0].pageY;\n    }\n\n    var positions = self.__positions;\n\n    // Are we already is dragging mode?\n    if (self.__isDragging) {\n        self.__decStopped = false;\n\n      // Compute move distance\n      var moveX = currentTouchLeft - self.__lastTouchLeft;\n      var moveY = currentTouchTop - self.__lastTouchTop;\n\n      // Read previous scroll position and zooming\n      var scrollLeft = self.__scrollLeft;\n      var scrollTop = self.__scrollTop;\n      var level = self.__zoomLevel;\n\n      // Work with scaling\n      if (scale != null && self.options.zooming) {\n\n        var oldLevel = level;\n\n        // Recompute level based on previous scale and new scale\n        level = level / self.__lastScale * scale;\n\n        // Limit level according to configuration\n        level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);\n\n        // Only do further compution when change happened\n        if (oldLevel !== level) {\n\n          // Compute relative event position to container\n          var currentTouchLeftRel = currentTouchLeft - self.__clientLeft;\n          var currentTouchTopRel = currentTouchTop - self.__clientTop;\n\n          // Recompute left and top coordinates based on new zoom level\n          scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel;\n          scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel;\n\n          // Recompute max scroll values\n          self.__computeScrollMax(level);\n\n        }\n      }\n\n      if (self.__enableScrollX) {\n\n        scrollLeft -= moveX * self.options.speedMultiplier;\n        var maxScrollLeft = self.__maxScrollLeft;\n\n        if (scrollLeft > maxScrollLeft || scrollLeft < 0) {\n\n          // Slow down on the edges\n          if (self.options.bouncing) {\n\n            scrollLeft += (moveX / 2 * self.options.speedMultiplier);\n\n          } else if (scrollLeft > maxScrollLeft) {\n\n            scrollLeft = maxScrollLeft;\n\n          } else {\n\n            scrollLeft = 0;\n\n          }\n        }\n      }\n\n      // Compute new vertical scroll position\n      if (self.__enableScrollY) {\n\n        scrollTop -= moveY * self.options.speedMultiplier;\n        var maxScrollTop = self.__maxScrollTop;\n\n        if (scrollTop > maxScrollTop || scrollTop < 0) {\n\n          // Slow down on the edges\n          if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) {\n\n            scrollTop += (moveY / 2 * self.options.speedMultiplier);\n\n            // Support pull-to-refresh (only when only y is scrollable)\n            if (!self.__enableScrollX && self.__refreshHeight != null) {\n\n              // hide the refresher when it's behind the header bar in case of header transparency\n              if (scrollTop < 0) {\n                self.__refreshHidden = false;\n                self.__refreshShow();\n              } else {\n                self.__refreshHide();\n                self.__refreshHidden = true;\n              }\n\n              if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) {\n\n                self.__refreshActive = true;\n                if (self.__refreshActivate) {\n                  self.__refreshActivate();\n                }\n\n              } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) {\n\n                self.__refreshActive = false;\n                if (self.__refreshDeactivate) {\n                  self.__refreshDeactivate();\n                }\n\n              }\n            }\n\n          } else if (scrollTop > maxScrollTop) {\n\n            scrollTop = maxScrollTop;\n\n          } else {\n\n            scrollTop = 0;\n\n          }\n        } else if (self.__refreshHeight && !self.__refreshHidden) {\n          // if a positive scroll value and the refresher is still not hidden, hide it\n          self.__refreshHide();\n          self.__refreshHidden = true;\n        }\n      }\n\n      // Keep list from growing infinitely (holding min 10, max 20 measure points)\n      if (positions.length > 60) {\n        positions.splice(0, 30);\n      }\n\n      // Track scroll movement for decleration\n      positions.push(scrollLeft, scrollTop, timeStamp);\n\n      // Sync scroll position\n      self.__publish(scrollLeft, scrollTop, level);\n\n    // Otherwise figure out whether we are switching into dragging mode now.\n    } else {\n\n      var minimumTrackingForScroll = self.options.locking ? 3 : 0;\n      var minimumTrackingForDrag = 5;\n\n      var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft);\n      var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop);\n\n      self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll;\n      self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll;\n\n      positions.push(self.__scrollLeft, self.__scrollTop, timeStamp);\n\n      self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag);\n      if (self.__isDragging) {\n        self.__interruptedAnimation = false;\n        self.__fadeScrollbars('in');\n      }\n\n    }\n\n    // Update last touch positions and time stamp for next event\n    self.__lastTouchLeft = currentTouchLeft;\n    self.__lastTouchTop = currentTouchTop;\n    self.__lastTouchMove = timeStamp;\n    self.__lastScale = scale;\n\n  },\n\n\n  /**\n   * Touch end handler for scrolling support\n   */\n  doTouchEnd: function(e, timeStamp) {\n    if (timeStamp instanceof Date) {\n      timeStamp = timeStamp.valueOf();\n    }\n    if (typeof timeStamp !== \"number\") {\n      timeStamp = Date.now();\n    }\n\n    var self = this;\n\n    // Ignore event when tracking is not enabled (no touchstart event on element)\n    // This is required as this listener ('touchmove') sits on the document and not on the element itself.\n    if (!self.__isTracking) {\n      return;\n    }\n\n    // Not touching anymore (when two finger hit the screen there are two touch end events)\n    self.__isTracking = false;\n\n    // Be sure to reset the dragging flag now. Here we also detect whether\n    // the finger has moved fast enough to switch into a deceleration animation.\n    if (self.__isDragging) {\n\n      // Reset dragging flag\n      self.__isDragging = false;\n\n      // Start deceleration\n      // Verify that the last move detected was in some relevant time frame\n      if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) {\n\n        // Then figure out what the scroll position was about 100ms ago\n        var positions = self.__positions;\n        var endPos = positions.length - 1;\n        var startPos = endPos;\n\n        // Move pointer to position measured 100ms ago\n        for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) {\n          startPos = i;\n        }\n\n        // If start and stop position is identical in a 100ms timeframe,\n        // we cannot compute any useful deceleration.\n        if (startPos !== endPos) {\n\n          // Compute relative movement between these two points\n          var timeOffset = positions[endPos] - positions[startPos];\n          var movedLeft = self.__scrollLeft - positions[startPos - 2];\n          var movedTop = self.__scrollTop - positions[startPos - 1];\n\n          // Based on 50ms compute the movement to apply for each render step\n          self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60);\n          self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60);\n\n          // How much velocity is required to start the deceleration\n          var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? self.options.decelVelocityThresholdPaging : self.options.decelVelocityThreshold;\n\n          // Verify that we have enough velocity to start deceleration\n          if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) {\n\n            // Deactivate pull-to-refresh when decelerating\n            if (!self.__refreshActive) {\n              self.__startDeceleration(timeStamp);\n            }\n          }\n        } else {\n          self.__scrollingComplete();\n        }\n      } else if ((timeStamp - self.__lastTouchMove) > 100) {\n        self.__scrollingComplete();\n      }\n\n    } else if (self.__decStopped) {\n      // the deceleration was stopped\n      // user flicked the scroll fast, and stop dragging, then did a touchstart to stop the srolling\n      // tell the touchend event code to do nothing, we don't want to actually send a click\n      e.isTapHandled = true;\n      self.__decStopped = false;\n    }\n\n    // If this was a slower move it is per default non decelerated, but this\n    // still means that we want snap back to the bounds which is done here.\n    // This is placed outside the condition above to improve edge case stability\n    // e.g. touchend fired without enabled dragging. This should normally do not\n    // have modified the scroll positions or even showed the scrollbars though.\n    if (!self.__isDecelerating) {\n\n      if (self.__refreshActive && self.__refreshStart) {\n\n        // Use publish instead of scrollTo to allow scrolling to out of boundary position\n        // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled\n        self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true);\n\n        var d = new Date();\n        self.refreshStartTime = d.getTime();\n\n        if (self.__refreshStart) {\n          self.__refreshStart();\n        }\n        // for iOS-ey style scrolling\n        if (!ionic.Platform.isAndroid())self.__startDeceleration();\n      } else {\n\n        if (self.__interruptedAnimation || self.__isDragging) {\n          self.__scrollingComplete();\n        }\n        self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel);\n\n        // Directly signalize deactivation (nothing todo on refresh?)\n        if (self.__refreshActive) {\n\n          self.__refreshActive = false;\n          if (self.__refreshDeactivate) {\n            self.__refreshDeactivate();\n          }\n\n        }\n      }\n    }\n\n    // Fully cleanup list\n    self.__positions.length = 0;\n\n  },\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    PRIVATE API\n  ---------------------------------------------------------------------------\n  */\n\n  /**\n   * Applies the scroll position to the content element\n   *\n   * @param left {Number} Left scroll position\n   * @param top {Number} Top scroll position\n   * @param animate {Boolean} Whether animation should be used to move to the new coordinates\n   */\n  __publish: function(left, top, zoom, animate, wasResize) {\n\n    var self = this;\n\n    // Remember whether we had an animation, then we try to continue based on the current \"drive\" of the animation\n    var wasAnimating = self.__isAnimating;\n    if (wasAnimating) {\n      zyngaCore.effect.Animate.stop(wasAnimating);\n      self.__isAnimating = false;\n    }\n\n    if (animate && self.options.animating) {\n\n      // Keep scheduled positions for scrollBy/zoomBy functionality\n      self.__scheduledLeft = left;\n      self.__scheduledTop = top;\n      self.__scheduledZoom = zoom;\n\n      var oldLeft = self.__scrollLeft;\n      var oldTop = self.__scrollTop;\n      var oldZoom = self.__zoomLevel;\n\n      var diffLeft = left - oldLeft;\n      var diffTop = top - oldTop;\n      var diffZoom = zoom - oldZoom;\n\n      var step = function(percent, now, render) {\n\n        if (render) {\n\n          self.__scrollLeft = oldLeft + (diffLeft * percent);\n          self.__scrollTop = oldTop + (diffTop * percent);\n          self.__zoomLevel = oldZoom + (diffZoom * percent);\n\n          // Push values out\n          if (self.__callback) {\n            self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel, wasResize);\n          }\n\n        }\n      };\n\n      var verify = function(id) {\n        return self.__isAnimating === id;\n      };\n\n      var completed = function(renderedFramesPerSecond, animationId, wasFinished) {\n        if (animationId === self.__isAnimating) {\n          self.__isAnimating = false;\n        }\n        if (self.__didDecelerationComplete || wasFinished) {\n          self.__scrollingComplete();\n        }\n\n        if (self.options.zooming) {\n          self.__computeScrollMax();\n        }\n      };\n\n      // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out\n      self.__isAnimating = zyngaCore.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic);\n\n    } else {\n\n      self.__scheduledLeft = self.__scrollLeft = left;\n      self.__scheduledTop = self.__scrollTop = top;\n      self.__scheduledZoom = self.__zoomLevel = zoom;\n\n      // Push values out\n      if (self.__callback) {\n        self.__callback(left, top, zoom, wasResize);\n      }\n\n      // Fix max scroll ranges\n      if (self.options.zooming) {\n        self.__computeScrollMax();\n      }\n    }\n  },\n\n\n  /**\n   * Recomputes scroll minimum values based on client dimensions and content dimensions.\n   */\n  __computeScrollMax: function(zoomLevel) {\n    var self = this;\n\n    if (zoomLevel == null) {\n      zoomLevel = self.__zoomLevel;\n    }\n\n    self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0);\n    self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0);\n\n    if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {\n      self.__didWaitForSize = true;\n      self.__waitForSize();\n    }\n  },\n\n\n  /**\n   * If the scroll view isn't sized correctly on start, wait until we have at least some size\n   */\n  __waitForSize: function() {\n    var self = this;\n\n    clearTimeout(self.__sizerTimeout);\n\n    var sizer = function() {\n      self.resize(true);\n    };\n\n    sizer();\n    self.__sizerTimeout = setTimeout(sizer, 500);\n  },\n\n  /*\n  ---------------------------------------------------------------------------\n    ANIMATION (DECELERATION) SUPPORT\n  ---------------------------------------------------------------------------\n  */\n\n  /**\n   * Called when a touch sequence end and the speed of the finger was high enough\n   * to switch into deceleration mode.\n   */\n  __startDeceleration: function() {\n    var self = this;\n\n    if (self.options.paging) {\n\n      var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0);\n      var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0);\n      var clientWidth = self.__clientWidth;\n      var clientHeight = self.__clientHeight;\n\n      // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area.\n      // Each page should have exactly the size of the client area.\n      self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth;\n      self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight;\n      self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth;\n      self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight;\n\n    } else {\n\n      self.__minDecelerationScrollLeft = 0;\n      self.__minDecelerationScrollTop = 0;\n      self.__maxDecelerationScrollLeft = self.__maxScrollLeft;\n      self.__maxDecelerationScrollTop = self.__maxScrollTop;\n      if (self.__refreshActive) self.__minDecelerationScrollTop = self.__refreshHeight * -1;\n    }\n\n    // Wrap class method\n    var step = function(percent, now, render) {\n      self.__stepThroughDeceleration(render);\n    };\n\n    // How much velocity is required to keep the deceleration running\n    self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1;\n\n    // Detect whether it's still worth to continue animating steps\n    // If we are already slow enough to not being user perceivable anymore, we stop the whole process here.\n    var verify = function() {\n      var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating ||\n        Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating;\n      if (!shouldContinue) {\n        self.__didDecelerationComplete = true;\n\n        //Make sure the scroll values are within the boundaries after a bounce,\n        //not below 0 or above maximum\n        if (self.options.bouncing && !self.__refreshActive) {\n          self.scrollTo(\n            Math.min( Math.max(self.__scrollLeft, 0), self.__maxScrollLeft ),\n            Math.min( Math.max(self.__scrollTop, 0), self.__maxScrollTop ),\n            self.__refreshActive\n          );\n        }\n      }\n      return shouldContinue;\n    };\n\n    var completed = function() {\n      self.__isDecelerating = false;\n      if (self.__didDecelerationComplete) {\n        self.__scrollingComplete();\n      }\n\n      // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions\n      if (self.options.paging) {\n        self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping);\n      }\n    };\n\n    // Start animation and switch on flag\n    self.__isDecelerating = zyngaCore.effect.Animate.start(step, verify, completed);\n\n  },\n\n\n  /**\n   * Called on every step of the animation\n   *\n   * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only!\n   */\n  __stepThroughDeceleration: function(render) {\n    var self = this;\n\n\n    //\n    // COMPUTE NEXT SCROLL POSITION\n    //\n\n    // Add deceleration to scroll position\n    var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX;// * self.options.deceleration);\n    var scrollTop = self.__scrollTop + self.__decelerationVelocityY;// * self.options.deceleration);\n\n\n    //\n    // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE\n    //\n\n    if (!self.options.bouncing) {\n\n      var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft);\n      if (scrollLeftFixed !== scrollLeft) {\n        scrollLeft = scrollLeftFixed;\n        self.__decelerationVelocityX = 0;\n      }\n\n      var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop);\n      if (scrollTopFixed !== scrollTop) {\n        scrollTop = scrollTopFixed;\n        self.__decelerationVelocityY = 0;\n      }\n\n    }\n\n\n    //\n    // UPDATE SCROLL POSITION\n    //\n\n    if (render) {\n\n      self.__publish(scrollLeft, scrollTop, self.__zoomLevel);\n\n    } else {\n\n      self.__scrollLeft = scrollLeft;\n      self.__scrollTop = scrollTop;\n\n    }\n\n\n    //\n    // SLOW DOWN\n    //\n\n    // Slow down velocity on every iteration\n    if (!self.options.paging) {\n\n      // This is the factor applied to every iteration of the animation\n      // to slow down the process. This should emulate natural behavior where\n      // objects slow down when the initiator of the movement is removed\n      var frictionFactor = self.options.deceleration;\n\n      self.__decelerationVelocityX *= frictionFactor;\n      self.__decelerationVelocityY *= frictionFactor;\n\n    }\n\n\n    //\n    // BOUNCING SUPPORT\n    //\n\n    if (self.options.bouncing) {\n\n      var scrollOutsideX = 0;\n      var scrollOutsideY = 0;\n\n      // This configures the amount of change applied to deceleration/acceleration when reaching boundaries\n      var penetrationDeceleration = self.options.penetrationDeceleration;\n      var penetrationAcceleration = self.options.penetrationAcceleration;\n\n      // Check limits\n      if (scrollLeft < self.__minDecelerationScrollLeft) {\n        scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft;\n      } else if (scrollLeft > self.__maxDecelerationScrollLeft) {\n        scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft;\n      }\n\n      if (scrollTop < self.__minDecelerationScrollTop) {\n        scrollOutsideY = self.__minDecelerationScrollTop - scrollTop;\n      } else if (scrollTop > self.__maxDecelerationScrollTop) {\n        scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop;\n      }\n\n      // Slow down until slow enough, then flip back to snap position\n      if (scrollOutsideX !== 0) {\n        var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft;\n        if (isHeadingOutwardsX) {\n          self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration;\n        }\n        var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating;\n        //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds\n        if (!isHeadingOutwardsX || isStoppedX) {\n          self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration;\n        }\n      }\n\n      if (scrollOutsideY !== 0) {\n        var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop;\n        if (isHeadingOutwardsY) {\n          self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration;\n        }\n        var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating;\n        //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds\n        if (!isHeadingOutwardsY || isStoppedY) {\n          self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration;\n        }\n      }\n    }\n  },\n\n\n  /**\n   * calculate the distance between two touches\n   * @param   {Touch}     touch1\n   * @param   {Touch}     touch2\n   * @returns {Number}    distance\n   */\n  __getDistance: function getDistance(touch1, touch2) {\n    var x = touch2.pageX - touch1.pageX,\n    y = touch2.pageY - touch1.pageY;\n    return Math.sqrt((x * x) + (y * y));\n  },\n\n\n  /**\n   * calculate the scale factor between two touchLists (fingers)\n   * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n   * @param   {Array}     start\n   * @param   {Array}     end\n   * @returns {Number}    scale\n   */\n  __getScale: function getScale(start, end) {\n    // need two fingers...\n    if (start.length >= 2 && end.length >= 2) {\n      return this.__getDistance(end[0], end[1]) /\n        this.__getDistance(start[0], start[1]);\n    }\n    return 1;\n  }\n});\n\nionic.scroll = {\n  isScrolling: false,\n  lastTop: 0\n};\n\n})(ionic);\n\n(function(ionic) {\n  var NOOP = function() {};\n  var depreciated = function(name) {\n    void 0;\n  };\n  ionic.views.ScrollNative = ionic.views.View.inherit({\n\n    initialize: function(options) {\n      var self = this;\n      self.__container = self.el = options.el;\n      self.__content = options.el.firstElementChild;\n      self.isNative = true;\n\n      self.__scrollTop = self.el.scrollTop;\n      self.__scrollLeft = self.el.scrollLeft;\n      self.__clientHeight = self.__content.clientHeight;\n      self.__clientWidth = self.__content.clientWidth;\n      self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);\n      self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);\n\n      self.options = {\n\n        freeze: false,\n\n        getContentWidth: function() {\n          return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);\n        },\n\n        getContentHeight: function() {\n          return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));\n        }\n\n      };\n\n      for (var key in options) {\n        self.options[key] = options[key];\n      }\n\n      /**\n       * Sets isScrolling to true, and automatically deactivates if not called again in 80ms.\n       */\n      self.onScroll = function() {\n        if (!ionic.scroll.isScrolling) {\n          ionic.scroll.isScrolling = true;\n        }\n\n        clearTimeout(self.scrollTimer);\n        self.scrollTimer = setTimeout(function() {\n          ionic.scroll.isScrolling = false;\n        }, 80);\n      };\n\n      self.freeze = NOOP;\n\n      self.__initEventHandlers();\n    },\n\n    /**  Methods not used in native scrolling */\n    __callback: function() { depreciated('__callback'); },\n    zoomTo: function() { depreciated('zoomTo'); },\n    zoomBy: function() { depreciated('zoomBy'); },\n    activatePullToRefresh: function() { depreciated('activatePullToRefresh'); },\n\n    /**\n     * Returns the scroll position and zooming values\n     *\n     * @return {Map} `left` and `top` scroll position and `zoom` level\n     */\n    resize: function(continueScrolling) {\n      var self = this;\n      if (!self.__container || !self.options) return;\n\n      // Update Scroller dimensions for changed content\n      // Add padding to bottom of content\n      self.setDimensions(\n        self.__container.clientWidth,\n        self.__container.clientHeight,\n        self.options.getContentWidth(),\n        self.options.getContentHeight(),\n        continueScrolling\n      );\n    },\n\n    /**\n     * Initialize the scrollview\n     * In native scrolling, this only means we need to gather size information\n     */\n    run: function() {\n      this.resize();\n    },\n\n    /**\n     * Returns the scroll position and zooming values\n     *\n     * @return {Map} `left` and `top` scroll position and `zoom` level\n     */\n    getValues: function() {\n      var self = this;\n      self.update();\n      return {\n        left: self.__scrollLeft,\n        top: self.__scrollTop,\n        zoom: 1\n      };\n    },\n\n    /**\n     * Updates the __scrollLeft and __scrollTop values to el's current value\n     */\n    update: function() {\n      var self = this;\n      self.__scrollLeft = self.el.scrollLeft;\n      self.__scrollTop = self.el.scrollTop;\n    },\n\n    /**\n     * Configures the dimensions of the client (outer) and content (inner) elements.\n     * Requires the available space for the outer element and the outer size of the inner element.\n     * All values which are falsy (null or zero etc.) are ignored and the old value is kept.\n     *\n     * @param clientWidth {Integer} Inner width of outer element\n     * @param clientHeight {Integer} Inner height of outer element\n     * @param contentWidth {Integer} Outer width of inner element\n     * @param contentHeight {Integer} Outer height of inner element\n     */\n    setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) {\n      var self = this;\n\n      if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {\n        // this scrollview isn't rendered, don't bother\n        return;\n      }\n\n      // Only update values which are defined\n      if (clientWidth === +clientWidth) {\n        self.__clientWidth = clientWidth;\n      }\n\n      if (clientHeight === +clientHeight) {\n        self.__clientHeight = clientHeight;\n      }\n\n      if (contentWidth === +contentWidth) {\n        self.__contentWidth = contentWidth;\n      }\n\n      if (contentHeight === +contentHeight) {\n        self.__contentHeight = contentHeight;\n      }\n\n      // Refresh maximums\n      self.__computeScrollMax();\n    },\n\n    /**\n     * Returns the maximum scroll values\n     *\n     * @return {Map} `left` and `top` maximum scroll values\n     */\n    getScrollMax: function() {\n      return {\n        left: this.__maxScrollLeft,\n        top: this.__maxScrollTop\n      };\n    },\n\n    /**\n     * Scrolls by the given amount in px.\n     *\n     * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>\n     * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>\n     * @param animate {Boolean} Whether the scrolling should happen using an animation\n     */\n\n    scrollBy: function(left, top, animate) {\n      var self = this;\n\n      // update scroll vars before refferencing them\n      self.update();\n\n      var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;\n      var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;\n\n      self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);\n    },\n\n    /**\n     * Scrolls to the given position in px.\n     *\n     * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>\n     * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>\n     * @param animate {Boolean} Whether the scrolling should happen using an animation\n     */\n    scrollTo: function(left, top, animate) {\n      var self = this;\n      if (!animate) {\n        self.el.scrollTop = top;\n        self.el.scrollLeft = left;\n        self.resize();\n        return;\n      }\n      animateScroll(top, left);\n\n      function animateScroll(Y, X) {\n        // scroll animation loop w/ easing\n        // credit https://gist.github.com/dezinezync/5487119\n        var start = Date.now(),\n          duration = 1000, //milliseconds\n          fromY = self.el.scrollTop,\n          fromX = self.el.scrollLeft;\n\n        if (fromY === Y && fromX === X) {\n          self.resize();\n          return; /* Prevent scrolling to the Y point if already there */\n        }\n\n        // decelerating to zero velocity\n        function easeOutCubic(t) {\n          return (--t) * t * t + 1;\n        }\n\n        // scroll loop\n        function animateScrollStep() {\n          var currentTime = Date.now(),\n            time = Math.min(1, ((currentTime - start) / duration)),\n          // where .5 would be 50% of time on a linear scale easedT gives a\n          // fraction based on the easing method\n            easedT = easeOutCubic(time);\n\n          if (fromY != Y) {\n            self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10);\n          }\n          if (fromX != X) {\n            self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10);\n          }\n\n          if (time < 1) {\n            ionic.requestAnimationFrame(animateScrollStep);\n\n          } else {\n            // done\n            self.resize();\n          }\n        }\n\n        // start scroll loop\n        ionic.requestAnimationFrame(animateScrollStep);\n      }\n    },\n\n\n\n    /*\n     ---------------------------------------------------------------------------\n     PRIVATE API\n     ---------------------------------------------------------------------------\n     */\n\n    /**\n     * If the scroll view isn't sized correctly on start, wait until we have at least some size\n     */\n    __waitForSize: function() {\n      var self = this;\n\n      clearTimeout(self.__sizerTimeout);\n\n      var sizer = function() {\n        self.resize(true);\n      };\n\n      sizer();\n      self.__sizerTimeout = setTimeout(sizer, 500);\n    },\n\n\n    /**\n     * Recomputes scroll minimum values based on client dimensions and content dimensions.\n     */\n    __computeScrollMax: function() {\n      var self = this;\n\n      self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);\n      self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);\n\n      if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {\n        self.__didWaitForSize = true;\n        self.__waitForSize();\n      }\n    },\n\n    __initEventHandlers: function() {\n      var self = this;\n\n      // Event Handler\n      var container = self.__container;\n\n      // should be unnecessary in native scrolling, but keep in case bugs show up\n      self.scrollChildIntoView = NOOP;\n\n      self.resetScrollView = function() {\n        //return scrollview to original height once keyboard has hidden\n        if (self.isScrolledIntoView) {\n          self.isScrolledIntoView = false;\n          container.style.height = \"\";\n          container.style.overflow = \"\";\n          self.resize();\n          ionic.scroll.isScrolling = false;\n        }\n      };\n\n      container.addEventListener('resetScrollView', self.resetScrollView);\n      container.addEventListener('scroll', self.onScroll);\n\n      //Broadcasted when keyboard is shown on some platforms.\n      //See js/utils/keyboard.js\n      container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);\n      container.addEventListener('resetScrollView', self.resetScrollView);\n    },\n\n    __cleanup: function() {\n      var self = this;\n      var container = self.__container;\n\n      container.removeEventListener('resetScrollView', self.resetScrollView);\n      container.removeEventListener('scroll', self.onScroll);\n\n      container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);\n      container.removeEventListener('resetScrollView', self.resetScrollView);\n\n      ionic.tap.removeClonedInputs(container, self);\n\n      delete self.__container;\n      delete self.__content;\n      delete self.__indicatorX;\n      delete self.__indicatorY;\n      delete self.options.el;\n\n      self.resize = self.scrollTo = self.onScroll = self.resetScrollView = NOOP;\n      container = null;\n    }\n  });\n\n})(ionic);\n\n\n(function(ionic) {\n'use strict';\n\n  var ITEM_CLASS = 'item';\n  var ITEM_CONTENT_CLASS = 'item-content';\n  var ITEM_SLIDING_CLASS = 'item-sliding';\n  var ITEM_OPTIONS_CLASS = 'item-options';\n  var ITEM_PLACEHOLDER_CLASS = 'item-placeholder';\n  var ITEM_REORDERING_CLASS = 'item-reordering';\n  var ITEM_REORDER_BTN_CLASS = 'item-reorder';\n\n  var DragOp = function() {};\n  DragOp.prototype = {\n    start: function(){},\n    drag: function(){},\n    end: function(){},\n    isSameItem: function() {\n      return false;\n    }\n  };\n\n  var SlideDrag = function(opts) {\n    this.dragThresholdX = opts.dragThresholdX || 10;\n    this.el = opts.el;\n    this.item = opts.item;\n    this.canSwipe = opts.canSwipe;\n  };\n\n  SlideDrag.prototype = new DragOp();\n\n  SlideDrag.prototype.start = function(e) {\n    var content, buttons, offsetX, buttonsWidth;\n\n    if (!this.canSwipe()) {\n      return;\n    }\n\n    if (e.target.classList.contains(ITEM_CONTENT_CLASS)) {\n      content = e.target;\n    } else if (e.target.classList.contains(ITEM_CLASS)) {\n      content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);\n    } else {\n      content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS);\n    }\n\n    // If we don't have a content area as one of our children (or ourselves), skip\n    if (!content) {\n      return;\n    }\n\n    // Make sure we aren't animating as we slide\n    content.classList.remove(ITEM_SLIDING_CLASS);\n\n    // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start)\n    offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0;\n\n    // Grab the buttons\n    buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);\n    if (!buttons) {\n      return;\n    }\n    buttons.classList.remove('invisible');\n\n    buttonsWidth = buttons.offsetWidth;\n\n    this._currentDrag = {\n      buttons: buttons,\n      buttonsWidth: buttonsWidth,\n      content: content,\n      startOffsetX: offsetX\n    };\n  };\n\n  /**\n   * Check if this is the same item that was previously dragged.\n   */\n  SlideDrag.prototype.isSameItem = function(op) {\n    if (op._lastDrag && this._currentDrag) {\n      return this._currentDrag.content == op._lastDrag.content;\n    }\n    return false;\n  };\n\n  SlideDrag.prototype.clean = function(isInstant) {\n    var lastDrag = this._lastDrag;\n\n    if (!lastDrag || !lastDrag.content) return;\n\n    lastDrag.content.style[ionic.CSS.TRANSITION] = '';\n    lastDrag.content.style[ionic.CSS.TRANSFORM] = '';\n    if (isInstant) {\n      lastDrag.content.style[ionic.CSS.TRANSITION] = 'none';\n      makeInvisible();\n      ionic.requestAnimationFrame(function() {\n        lastDrag.content.style[ionic.CSS.TRANSITION] = '';\n      });\n    } else {\n      ionic.requestAnimationFrame(function() {\n        setTimeout(makeInvisible, 250);\n      });\n    }\n    function makeInvisible() {\n      lastDrag.buttons && lastDrag.buttons.classList.add('invisible');\n    }\n  };\n\n  SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {\n    var buttonsWidth;\n\n    // We really aren't dragging\n    if (!this._currentDrag) {\n      return;\n    }\n\n    // Check if we should start dragging. Check if we've dragged past the threshold,\n    // or we are starting from the open state.\n    if (!this._isDragging &&\n        ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) ||\n        (Math.abs(this._currentDrag.startOffsetX) > 0))) {\n      this._isDragging = true;\n    }\n\n    if (this._isDragging) {\n      buttonsWidth = this._currentDrag.buttonsWidth;\n\n      // Grab the new X point, capping it at zero\n      var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX);\n\n      // If the new X position is past the buttons, we need to slow down the drag (rubber band style)\n      if (newX < -buttonsWidth) {\n        // Calculate the new X position, capped at the top of the buttons\n        newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));\n      }\n\n      this._currentDrag.content.$$ionicOptionsOpen = newX !== 0;\n\n      this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)';\n      this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none';\n    }\n  });\n\n  SlideDrag.prototype.end = function(e, doneCallback) {\n    var self = this;\n\n    // There is no drag, just end immediately\n    if (!self._currentDrag) {\n      doneCallback && doneCallback();\n      return;\n    }\n\n    // If we are currently dragging, we want to snap back into place\n    // The final resting point X will be the width of the exposed buttons\n    var restingPoint = -self._currentDrag.buttonsWidth;\n\n    // Check if the drag didn't clear the buttons mid-point\n    // and we aren't moving fast enough to swipe open\n    if (e.gesture.deltaX > -(self._currentDrag.buttonsWidth / 2)) {\n\n      // If we are going left but too slow, or going right, go back to resting\n      if (e.gesture.direction == \"left\" && Math.abs(e.gesture.velocityX) < 0.3) {\n        restingPoint = 0;\n\n      } else if (e.gesture.direction == \"right\") {\n        restingPoint = 0;\n      }\n\n    }\n\n    ionic.requestAnimationFrame(function() {\n      if (restingPoint === 0) {\n        self._currentDrag.content.style[ionic.CSS.TRANSFORM] = '';\n        var buttons = self._currentDrag.buttons;\n        setTimeout(function() {\n          buttons && buttons.classList.add('invisible');\n        }, 250);\n      } else {\n        self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)';\n      }\n      self._currentDrag.content.style[ionic.CSS.TRANSITION] = '';\n\n\n      // Kill the current drag\n      if (!self._lastDrag) {\n        self._lastDrag = {};\n      }\n      ionic.extend(self._lastDrag, self._currentDrag);\n      if (self._currentDrag) {\n        self._currentDrag.buttons = null;\n        self._currentDrag.content = null;\n      }\n      self._currentDrag = null;\n\n      // We are done, notify caller\n      doneCallback && doneCallback();\n    });\n  };\n\n  var ReorderDrag = function(opts) {\n    var self = this;\n\n    self.dragThresholdY = opts.dragThresholdY || 0;\n    self.onReorder = opts.onReorder;\n    self.listEl = opts.listEl;\n    self.el = self.item = opts.el;\n    self.scrollEl = opts.scrollEl;\n    self.scrollView = opts.scrollView;\n    // Get the True Top of the list el http://www.quirksmode.org/js/findpos.html\n    self.listElTrueTop = 0;\n    if (self.listEl.offsetParent) {\n      var obj = self.listEl;\n      do {\n        self.listElTrueTop += obj.offsetTop;\n        obj = obj.offsetParent;\n      } while (obj);\n    }\n  };\n\n  ReorderDrag.prototype = new DragOp();\n\n  ReorderDrag.prototype._moveElement = function(e) {\n    var y = e.gesture.center.pageY +\n      this.scrollView.getValues().top -\n      (this._currentDrag.elementHeight / 2) -\n      this.listElTrueTop;\n    this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, ' + y + 'px, 0)';\n  };\n\n  ReorderDrag.prototype.deregister = function() {\n    this.listEl = this.el = this.scrollEl = this.scrollView = null;\n  };\n\n  ReorderDrag.prototype.start = function(e) {\n\n    var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase());\n    var elementHeight = this.el.scrollHeight;\n    var placeholder = this.el.cloneNode(true);\n\n    placeholder.classList.add(ITEM_PLACEHOLDER_CLASS);\n\n    this.el.parentNode.insertBefore(placeholder, this.el);\n    this.el.classList.add(ITEM_REORDERING_CLASS);\n\n    this._currentDrag = {\n      elementHeight: elementHeight,\n      startIndex: startIndex,\n      placeholder: placeholder,\n      scrollHeight: scroll,\n      list: placeholder.parentNode\n    };\n\n    this._moveElement(e);\n  };\n\n  ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {\n    // We really aren't dragging\n    var self = this;\n    if (!this._currentDrag) {\n      return;\n    }\n\n    var scrollY = 0;\n    var pageY = e.gesture.center.pageY;\n    var offset = this.listElTrueTop;\n\n    //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary\n    if (this.scrollView) {\n\n      var container = this.scrollView.__container;\n      scrollY = this.scrollView.getValues().top;\n\n      var containerTop = container.offsetTop;\n      var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight / 2;\n      var pixelsPastBottom = pageY + this._currentDrag.elementHeight / 2 - containerTop - container.offsetHeight;\n\n      if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) {\n        this.scrollView.scrollBy(null, -pixelsPastTop);\n        //Trigger another drag so the scrolling keeps going\n        ionic.requestAnimationFrame(function() {\n          self.drag(e);\n        });\n      }\n      if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) {\n        if (scrollY < this.scrollView.getScrollMax().top) {\n          this.scrollView.scrollBy(null, pixelsPastBottom);\n          //Trigger another drag so the scrolling keeps going\n          ionic.requestAnimationFrame(function() {\n            self.drag(e);\n          });\n        }\n      }\n    }\n\n    // Check if we should start dragging. Check if we've dragged past the threshold,\n    // or we are starting from the open state.\n    if (!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) {\n      this._isDragging = true;\n    }\n\n    if (this._isDragging) {\n      this._moveElement(e);\n\n      this._currentDrag.currentY = scrollY + pageY - offset;\n\n      // this._reorderItems();\n    }\n  });\n\n  // When an item is dragged, we need to reorder any items for sorting purposes\n  ReorderDrag.prototype._getReorderIndex = function() {\n    var self = this;\n\n    var siblings = Array.prototype.slice.call(self._currentDrag.placeholder.parentNode.children)\n      .filter(function(el) {\n        return el.nodeName === self.el.nodeName && el !== self.el;\n      });\n\n    var dragOffsetTop = self._currentDrag.currentY;\n    var el;\n    for (var i = 0, len = siblings.length; i < len; i++) {\n      el = siblings[i];\n      if (i === len - 1) {\n        if (dragOffsetTop > el.offsetTop) {\n          return i;\n        }\n      } else if (i === 0) {\n        if (dragOffsetTop < el.offsetTop + el.offsetHeight) {\n          return i;\n        }\n      } else if (dragOffsetTop > el.offsetTop - el.offsetHeight / 2 &&\n                 dragOffsetTop < el.offsetTop + el.offsetHeight) {\n        return i;\n      }\n    }\n    return self._currentDrag.startIndex;\n  };\n\n  ReorderDrag.prototype.end = function(e, doneCallback) {\n    if (!this._currentDrag) {\n      doneCallback && doneCallback();\n      return;\n    }\n\n    var placeholder = this._currentDrag.placeholder;\n    var finalIndex = this._getReorderIndex();\n\n    // Reposition the element\n    this.el.classList.remove(ITEM_REORDERING_CLASS);\n    this.el.style[ionic.CSS.TRANSFORM] = '';\n\n    placeholder.parentNode.insertBefore(this.el, placeholder);\n    placeholder.parentNode.removeChild(placeholder);\n\n    this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalIndex);\n\n    this._currentDrag = {\n      placeholder: null,\n      content: null\n    };\n    this._currentDrag = null;\n    doneCallback && doneCallback();\n  };\n\n\n\n  /**\n   * The ListView handles a list of items. It will process drag animations, edit mode,\n   * and other operations that are common on mobile lists or table views.\n   */\n  ionic.views.ListView = ionic.views.View.inherit({\n    initialize: function(opts) {\n      var self = this;\n\n      opts = ionic.extend({\n        onReorder: function() {},\n        virtualRemoveThreshold: -200,\n        virtualAddThreshold: 200,\n        canSwipe: function() {\n          return true;\n        }\n      }, opts);\n\n      ionic.extend(self, opts);\n\n      if (!self.itemHeight && self.listEl) {\n        self.itemHeight = self.listEl.children[0] && parseInt(self.listEl.children[0].style.height, 10);\n      }\n\n      self.onRefresh = opts.onRefresh || function() {};\n      self.onRefreshOpening = opts.onRefreshOpening || function() {};\n      self.onRefreshHolding = opts.onRefreshHolding || function() {};\n\n      var gestureOpts = {};\n      // don't prevent native scrolling\n      if (ionic.DomUtil.getParentOrSelfWithClass(self.el, 'overflow-scroll')) {\n        gestureOpts.prevent_default_directions = ['left', 'right'];\n      }\n\n      window.ionic.onGesture('release', function(e) {\n        self._handleEndDrag(e);\n      }, self.el, gestureOpts);\n\n      window.ionic.onGesture('drag', function(e) {\n        self._handleDrag(e);\n      }, self.el, gestureOpts);\n      // Start the drag states\n      self._initDrag();\n    },\n\n    /**\n     * Be sure to cleanup references.\n     */\n    deregister: function() {\n      this.el = this.listEl = this.scrollEl = this.scrollView = null;\n\n      // ensure no scrolls have been left frozen\n      if (this.isScrollFreeze) {\n        self.scrollView.freeze(false);\n      }\n    },\n\n    /**\n     * Called to tell the list to stop refreshing. This is useful\n     * if you are refreshing the list and are done with refreshing.\n     */\n    stopRefreshing: function() {\n      var refresher = this.el.querySelector('.list-refresher');\n      refresher.style.height = '0';\n    },\n\n    /**\n     * If we scrolled and have virtual mode enabled, compute the window\n     * of active elements in order to figure out the viewport to render.\n     */\n    didScroll: function(e) {\n      var self = this;\n\n      if (self.isVirtual) {\n        var itemHeight = self.itemHeight;\n\n        // Grab the total height of the list\n        var scrollHeight = e.target.scrollHeight;\n\n        // Get the viewport height\n        var viewportHeight = self.el.parentNode.offsetHeight;\n\n        // High water is the pixel position of the first element to include (everything before\n        // that will be removed)\n        var highWater = Math.max(0, e.scrollTop + self.virtualRemoveThreshold);\n\n        // Low water is the pixel position of the last element to include (everything after\n        // that will be removed)\n        var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + self.virtualAddThreshold);\n\n        // Get the first and last elements in the list based on how many can fit\n        // between the pixel range of lowWater and highWater\n        var first = parseInt(Math.abs(highWater / itemHeight), 10);\n        var last = parseInt(Math.abs(lowWater / itemHeight), 10);\n\n        // Get the items we need to remove\n        self._virtualItemsToRemove = Array.prototype.slice.call(self.listEl.children, 0, first);\n\n        self.renderViewport && self.renderViewport(highWater, lowWater, first, last);\n      }\n    },\n\n    didStopScrolling: function() {\n      if (this.isVirtual) {\n        for (var i = 0; i < this._virtualItemsToRemove.length; i++) {\n          //el.parentNode.removeChild(el);\n          this.didHideItem && this.didHideItem(i);\n        }\n        // Once scrolling stops, check if we need to remove old items\n\n      }\n    },\n\n    /**\n     * Clear any active drag effects on the list.\n     */\n    clearDragEffects: function(isInstant) {\n      if (this._lastDragOp) {\n        this._lastDragOp.clean && this._lastDragOp.clean(isInstant);\n        this._lastDragOp.deregister && this._lastDragOp.deregister();\n        this._lastDragOp = null;\n      }\n    },\n\n    _initDrag: function() {\n      // Store the last one\n      if (this._lastDragOp) {\n        this._lastDragOp.deregister && this._lastDragOp.deregister();\n      }\n      this._lastDragOp = this._dragOp;\n\n      this._dragOp = null;\n    },\n\n    // Return the list item from the given target\n    _getItem: function(target) {\n      while (target) {\n        if (target.classList && target.classList.contains(ITEM_CLASS)) {\n          return target;\n        }\n        target = target.parentNode;\n      }\n      return null;\n    },\n\n\n    _startDrag: function(e) {\n      var self = this;\n\n      self._isDragging = false;\n\n      var lastDragOp = self._lastDragOp;\n      var item;\n\n      // If we have an open SlideDrag and we're scrolling the list. Clear it.\n      if (self._didDragUpOrDown && lastDragOp instanceof SlideDrag) {\n          lastDragOp.clean && lastDragOp.clean();\n      }\n\n      // Check if this is a reorder drag\n      if (ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_REORDER_BTN_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {\n        item = self._getItem(e.target);\n\n        if (item) {\n          self._dragOp = new ReorderDrag({\n            listEl: self.el,\n            el: item,\n            scrollEl: self.scrollEl,\n            scrollView: self.scrollView,\n            onReorder: function(el, start, end) {\n              self.onReorder && self.onReorder(el, start, end);\n            }\n          });\n          self._dragOp.start(e);\n          e.preventDefault();\n        }\n      }\n\n      // Or check if this is a swipe to the side drag\n      else if (!self._didDragUpOrDown && (e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) {\n\n        // Make sure this is an item with buttons\n        item = self._getItem(e.target);\n        if (item && item.querySelector('.item-options')) {\n          self._dragOp = new SlideDrag({\n            el: self.el,\n            item: item,\n            canSwipe: self.canSwipe\n          });\n          self._dragOp.start(e);\n          e.preventDefault();\n          self.isScrollFreeze = self.scrollView.freeze(true);\n        }\n      }\n\n      // If we had a last drag operation and this is a new one on a different item, clean that last one\n      if (lastDragOp && self._dragOp && !self._dragOp.isSameItem(lastDragOp) && e.defaultPrevented) {\n        lastDragOp.clean && lastDragOp.clean();\n      }\n    },\n\n\n    _handleEndDrag: function(e) {\n      var self = this;\n\n      if (self.scrollView) {\n        self.isScrollFreeze = self.scrollView.freeze(false);\n      }\n\n      self._didDragUpOrDown = false;\n\n      if (!self._dragOp) {\n        return;\n      }\n\n      self._dragOp.end(e, function() {\n        self._initDrag();\n      });\n    },\n\n    /**\n     * Process the drag event to move the item to the left or right.\n     */\n    _handleDrag: function(e) {\n      var self = this;\n\n      if (Math.abs(e.gesture.deltaY) > 5) {\n        self._didDragUpOrDown = true;\n      }\n\n      // If we get a drag event, make sure we aren't in another drag, then check if we should\n      // start one\n      if (!self.isDragging && !self._dragOp) {\n        self._startDrag(e);\n      }\n\n      // No drag still, pass it up\n      if (!self._dragOp) {\n        return;\n      }\n\n      e.gesture.srcEvent.preventDefault();\n      self._dragOp.drag(e);\n    }\n\n  });\n\n})(ionic);\n\n(function(ionic) {\n'use strict';\n\n  ionic.views.Modal = ionic.views.View.inherit({\n    initialize: function(opts) {\n      opts = ionic.extend({\n        focusFirstInput: false,\n        unfocusOnHide: true,\n        focusFirstDelay: 600,\n        backdropClickToClose: true,\n        hardwareBackButtonClose: true,\n      }, opts);\n\n      ionic.extend(this, opts);\n\n      this.el = opts.el;\n    },\n    show: function() {\n      var self = this;\n\n      if(self.focusFirstInput) {\n        // Let any animations run first\n        window.setTimeout(function() {\n          var input = self.el.querySelector('input, textarea');\n          input && input.focus && input.focus();\n        }, self.focusFirstDelay);\n      }\n    },\n    hide: function() {\n      // Unfocus all elements\n      if(this.unfocusOnHide) {\n        var inputs = this.el.querySelectorAll('input, textarea');\n        // Let any animations run first\n        window.setTimeout(function() {\n          for(var i = 0; i < inputs.length; i++) {\n            inputs[i].blur && inputs[i].blur();\n          }\n        });\n      }\n    }\n  });\n\n})(ionic);\n\n(function(ionic) {\n'use strict';\n\n  /**\n   * The side menu view handles one of the side menu's in a Side Menu Controller\n   * configuration.\n   * It takes a DOM reference to that side menu element.\n   */\n  ionic.views.SideMenu = ionic.views.View.inherit({\n    initialize: function(opts) {\n      this.el = opts.el;\n      this.isEnabled = (typeof opts.isEnabled === 'undefined') ? true : opts.isEnabled;\n      this.setWidth(opts.width);\n    },\n    getFullWidth: function() {\n      return this.width;\n    },\n    setWidth: function(width) {\n      this.width = width;\n      this.el.style.width = width + 'px';\n    },\n    setIsEnabled: function(isEnabled) {\n      this.isEnabled = isEnabled;\n    },\n    bringUp: function() {\n      if(this.el.style.zIndex !== '0') {\n        this.el.style.zIndex = '0';\n      }\n    },\n    pushDown: function() {\n      if(this.el.style.zIndex !== '-1') {\n        this.el.style.zIndex = '-1';\n      }\n    }\n  });\n\n  ionic.views.SideMenuContent = ionic.views.View.inherit({\n    initialize: function(opts) {\n      ionic.extend(this, {\n        animationClass: 'menu-animated',\n        onDrag: function() {},\n        onEndDrag: function() {}\n      }, opts);\n\n      ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el);\n      ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el);\n    },\n    _onDrag: function(e) {\n      this.onDrag && this.onDrag(e);\n    },\n    _onEndDrag: function(e) {\n      this.onEndDrag && this.onEndDrag(e);\n    },\n    disableAnimation: function() {\n      this.el.classList.remove(this.animationClass);\n    },\n    enableAnimation: function() {\n      this.el.classList.add(this.animationClass);\n    },\n    getTranslateX: function() {\n      return parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]);\n    },\n    setTranslateX: ionic.animationFrameThrottle(function(x) {\n      this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)';\n    })\n  });\n\n})(ionic);\n\n/*\n * Adapted from Swipe.js 2.0\n *\n * Brad Birdsall\n * Copyright 2013, MIT License\n *\n*/\n\n(function(ionic) {\n'use strict';\n\nionic.views.Slider = ionic.views.View.inherit({\n  initialize: function (options) {\n    var slider = this;\n\n    // utilities\n    var noop = function() {}; // simple no operation function\n    var offloadFn = function(fn) { setTimeout(fn || noop, 0); }; // offload a functions execution\n\n    // check browser capabilities\n    var browser = {\n      addEventListener: !!window.addEventListener,\n      touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,\n      transitions: (function(temp) {\n        var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];\n        for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;\n        return false;\n      })(document.createElement('swipe'))\n    };\n\n\n    var container = options.el;\n\n    // quit if no root element\n    if (!container) return;\n    var element = container.children[0];\n    var slides, slidePos, width, length;\n    options = options || {};\n    var index = parseInt(options.startSlide, 10) || 0;\n    var speed = options.speed || 300;\n    options.continuous = options.continuous !== undefined ? options.continuous : true;\n\n    function setup() {\n\n      // do not setup if the container has no width\n      if (!container.offsetWidth) {\n        return;\n      }\n\n      // cache slides\n      slides = element.children;\n      length = slides.length;\n\n      // set continuous to false if only one slide\n      if (slides.length < 2) options.continuous = false;\n\n      //special case if two slides\n      if (browser.transitions && options.continuous && slides.length < 3) {\n        element.appendChild(slides[0].cloneNode(true));\n        element.appendChild(element.children[1].cloneNode(true));\n        slides = element.children;\n      }\n\n      // create an array to store current positions of each slide\n      slidePos = new Array(slides.length);\n\n      // determine width of each slide\n      width = container.offsetWidth || container.getBoundingClientRect().width;\n\n      element.style.width = (slides.length * width) + 'px';\n\n      // stack elements\n      var pos = slides.length;\n      while(pos--) {\n\n        var slide = slides[pos];\n\n        slide.style.width = width + 'px';\n        slide.setAttribute('data-index', pos);\n\n        if (browser.transitions) {\n          slide.style.left = (pos * -width) + 'px';\n          move(pos, index > pos ? -width : (index < pos ? width : 0), 0);\n        }\n\n      }\n\n      // reposition elements before and after index\n      if (options.continuous && browser.transitions) {\n        move(circle(index - 1), -width, 0);\n        move(circle(index + 1), width, 0);\n      }\n\n      if (!browser.transitions) element.style.left = (index * -width) + 'px';\n\n      container.style.visibility = 'visible';\n\n      options.slidesChanged && options.slidesChanged();\n    }\n\n    function prev(slideSpeed) {\n\n      if (options.continuous) slide(index - 1, slideSpeed);\n      else if (index) slide(index - 1, slideSpeed);\n\n    }\n\n    function next(slideSpeed) {\n\n      if (options.continuous) slide(index + 1, slideSpeed);\n      else if (index < slides.length - 1) slide(index + 1, slideSpeed);\n\n    }\n\n    function circle(index) {\n\n      // a simple positive modulo using slides.length\n      return (slides.length + (index % slides.length)) % slides.length;\n\n    }\n\n    function slide(to, slideSpeed) {\n\n      // do nothing if already on requested slide\n      if (index == to) return;\n\n      if (browser.transitions) {\n\n        var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward\n\n        // get the actual position of the slide\n        if (options.continuous) {\n          var naturalDirection = direction;\n          direction = -slidePos[circle(to)] / width;\n\n          // if going forward but to < index, use to = slides.length + to\n          // if going backward but to > index, use to = -slides.length + to\n          if (direction !== naturalDirection) to = -direction * slides.length + to;\n\n        }\n\n        var diff = Math.abs(index - to) - 1;\n\n        // move all the slides between index and to in the right direction\n        while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);\n\n        to = circle(to);\n\n        move(index, width * direction, slideSpeed || speed);\n        move(to, 0, slideSpeed || speed);\n\n        if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place\n\n      } else {\n\n        to = circle(to);\n        animate(index * -width, to * -width, slideSpeed || speed);\n        //no fallback for a circular continuous if the browser does not accept transitions\n      }\n\n      index = to;\n      offloadFn(options.callback && options.callback(index, slides[index]));\n    }\n\n    function move(index, dist, speed) {\n\n      translate(index, dist, speed);\n      slidePos[index] = dist;\n\n    }\n\n    function translate(index, dist, speed) {\n\n      var slide = slides[index];\n      var style = slide && slide.style;\n\n      if (!style) return;\n\n      style.webkitTransitionDuration =\n      style.MozTransitionDuration =\n      style.msTransitionDuration =\n      style.OTransitionDuration =\n      style.transitionDuration = speed + 'ms';\n\n      style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';\n      style.msTransform =\n      style.MozTransform =\n      style.OTransform = 'translateX(' + dist + 'px)';\n\n    }\n\n    function animate(from, to, speed) {\n\n      // if not an animation, just reposition\n      if (!speed) {\n\n        element.style.left = to + 'px';\n        return;\n\n      }\n\n      var start = +new Date();\n\n      var timer = setInterval(function() {\n\n        var timeElap = +new Date() - start;\n\n        if (timeElap > speed) {\n\n          element.style.left = to + 'px';\n\n          if (delay) begin();\n\n          options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);\n\n          clearInterval(timer);\n          return;\n\n        }\n\n        element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';\n\n      }, 4);\n\n    }\n\n    // setup auto slideshow\n    var delay = options.auto || 0;\n    var interval;\n\n    function begin() {\n\n      interval = setTimeout(next, delay);\n\n    }\n\n    function stop() {\n\n      delay = options.auto || 0;\n      clearTimeout(interval);\n\n    }\n\n\n    // setup initial vars\n    var start = {};\n    var delta = {};\n    var isScrolling;\n\n    // setup event capturing\n    var events = {\n\n      handleEvent: function(event) {\n        if(event.type == 'mousedown' || event.type == 'mouseup' || event.type == 'mousemove') {\n          event.touches = [{\n            pageX: event.pageX,\n            pageY: event.pageY\n          }];\n        }\n\n        switch (event.type) {\n          case 'mousedown': this.start(event); break;\n          case 'touchstart': this.start(event); break;\n          case 'touchmove': this.touchmove(event); break;\n          case 'mousemove': this.touchmove(event); break;\n          case 'touchend': offloadFn(this.end(event)); break;\n          case 'mouseup': offloadFn(this.end(event)); break;\n          case 'webkitTransitionEnd':\n          case 'msTransitionEnd':\n          case 'oTransitionEnd':\n          case 'otransitionend':\n          case 'transitionend': offloadFn(this.transitionEnd(event)); break;\n          case 'resize': offloadFn(setup); break;\n        }\n\n        if (options.stopPropagation) event.stopPropagation();\n\n      },\n      start: function(event) {\n\n        var touches = event.touches[0];\n\n        // measure start values\n        start = {\n\n          // get initial touch coords\n          x: touches.pageX,\n          y: touches.pageY,\n\n          // store time to determine touch duration\n          time: +new Date()\n\n        };\n\n        // used for testing first move event\n        isScrolling = undefined;\n\n        // reset delta and end measurements\n        delta = {};\n\n        // attach touchmove and touchend listeners\n        if(browser.touch) {\n          element.addEventListener('touchmove', this, false);\n          element.addEventListener('touchend', this, false);\n        } else {\n          element.addEventListener('mousemove', this, false);\n          element.addEventListener('mouseup', this, false);\n          document.addEventListener('mouseup', this, false);\n        }\n      },\n      touchmove: function(event) {\n\n        // ensure swiping with one touch and not pinching\n        // ensure sliding is enabled\n        if (event.touches.length > 1 ||\n            event.scale && event.scale !== 1 ||\n            slider.slideIsDisabled) {\n          return;\n        }\n\n        if (options.disableScroll) event.preventDefault();\n\n        var touches = event.touches[0];\n\n        // measure change in x and y\n        delta = {\n          x: touches.pageX - start.x,\n          y: touches.pageY - start.y\n        };\n\n        // determine if scrolling test has run - one time test\n        if ( typeof isScrolling == 'undefined') {\n          isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );\n        }\n\n        // if user is not trying to scroll vertically\n        if (!isScrolling) {\n\n          // prevent native scrolling\n          event.preventDefault();\n\n          // stop slideshow\n          stop();\n\n          // increase resistance if first or last slide\n          if (options.continuous) { // we don't add resistance at the end\n\n            translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);\n            translate(index, delta.x + slidePos[index], 0);\n            translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);\n\n          } else {\n\n            delta.x =\n              delta.x /\n                ( (!index && delta.x > 0 ||         // if first slide and sliding left\n                  index == slides.length - 1 &&     // or if last slide and sliding right\n                  delta.x < 0                       // and if sliding at all\n                ) ?\n                ( Math.abs(delta.x) / width + 1 )      // determine resistance level\n                : 1 );                                 // no resistance if false\n\n            // translate 1:1\n            translate(index - 1, delta.x + slidePos[index - 1], 0);\n            translate(index, delta.x + slidePos[index], 0);\n            translate(index + 1, delta.x + slidePos[index + 1], 0);\n          }\n\n          options.onDrag && options.onDrag();\n        }\n\n      },\n      end: function() {\n\n        // measure duration\n        var duration = +new Date() - start.time;\n\n        // determine if slide attempt triggers next/prev slide\n        var isValidSlide =\n              Number(duration) < 250 &&         // if slide duration is less than 250ms\n              Math.abs(delta.x) > 20 ||         // and if slide amt is greater than 20px\n              Math.abs(delta.x) > width / 2;      // or if slide amt is greater than half the width\n\n        // determine if slide attempt is past start and end\n        var isPastBounds = (!index && delta.x > 0) ||      // if first slide and slide amt is greater than 0\n              (index == slides.length - 1 && delta.x < 0); // or if last slide and slide amt is less than 0\n\n        if (options.continuous) isPastBounds = false;\n\n        // determine direction of swipe (true:right, false:left)\n        var direction = delta.x < 0;\n\n        // if not scrolling vertically\n        if (!isScrolling) {\n\n          if (isValidSlide && !isPastBounds) {\n\n            if (direction) {\n\n              if (options.continuous) { // we need to get the next in this direction in place\n\n                move(circle(index - 1), -width, 0);\n                move(circle(index + 2), width, 0);\n\n              } else {\n                move(index - 1, -width, 0);\n              }\n\n              move(index, slidePos[index] - width, speed);\n              move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);\n              index = circle(index + 1);\n\n            } else {\n              if (options.continuous) { // we need to get the next in this direction in place\n\n                move(circle(index + 1), width, 0);\n                move(circle(index - 2), -width, 0);\n\n              } else {\n                move(index + 1, width, 0);\n              }\n\n              move(index, slidePos[index] + width, speed);\n              move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);\n              index = circle(index - 1);\n\n            }\n\n            options.callback && options.callback(index, slides[index]);\n\n          } else {\n\n            if (options.continuous) {\n\n              move(circle(index - 1), -width, speed);\n              move(index, 0, speed);\n              move(circle(index + 1), width, speed);\n\n            } else {\n\n              move(index - 1, -width, speed);\n              move(index, 0, speed);\n              move(index + 1, width, speed);\n            }\n\n          }\n\n        }\n\n        // kill touchmove and touchend event listeners until touchstart called again\n        if(browser.touch) {\n          element.removeEventListener('touchmove', events, false);\n          element.removeEventListener('touchend', events, false);\n        } else {\n          element.removeEventListener('mousemove', events, false);\n          element.removeEventListener('mouseup', events, false);\n          document.removeEventListener('mouseup', events, false);\n        }\n\n        options.onDragEnd && options.onDragEnd();\n      },\n      transitionEnd: function(event) {\n\n        if (parseInt(event.target.getAttribute('data-index'), 10) == index) {\n\n          if (delay) begin();\n\n          options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);\n\n        }\n\n      }\n\n    };\n\n    // Public API\n    this.update = function() {\n      setTimeout(setup);\n    };\n    this.setup = function() {\n      setup();\n    };\n\n    this.loop = function(value) {\n      if (arguments.length) options.continuous = !!value;\n      return options.continuous;\n    };\n\n    this.enableSlide = function(shouldEnable) {\n      if (arguments.length) {\n        this.slideIsDisabled = !shouldEnable;\n      }\n      return !this.slideIsDisabled;\n    };\n\n    this.slide = this.select = function(to, speed) {\n      // cancel slideshow\n      stop();\n\n      slide(to, speed);\n    };\n\n    this.prev = this.previous = function() {\n      // cancel slideshow\n      stop();\n\n      prev();\n    };\n\n    this.next = function() {\n      // cancel slideshow\n      stop();\n\n      next();\n    };\n\n    this.stop = function() {\n      // cancel slideshow\n      stop();\n    };\n\n    this.start = function() {\n      begin();\n    };\n\n    this.autoPlay = function(newDelay) {\n      if (!delay || delay < 0) {\n        stop();\n      } else {\n        delay = newDelay;\n        begin();\n      }\n    };\n\n    this.currentIndex = this.selected = function() {\n      // return current index position\n      return index;\n    };\n\n    this.slidesCount = this.count = function() {\n      // return total number of slides\n      return length;\n    };\n\n    this.kill = function() {\n      // cancel slideshow\n      stop();\n\n      // reset element\n      element.style.width = '';\n      element.style.left = '';\n\n      // reset slides so no refs are held on to\n      slides && (slides = []);\n\n      // removed event listeners\n      if (browser.addEventListener) {\n\n        // remove current event listeners\n        element.removeEventListener('touchstart', events, false);\n        element.removeEventListener('webkitTransitionEnd', events, false);\n        element.removeEventListener('msTransitionEnd', events, false);\n        element.removeEventListener('oTransitionEnd', events, false);\n        element.removeEventListener('otransitionend', events, false);\n        element.removeEventListener('transitionend', events, false);\n        window.removeEventListener('resize', events, false);\n\n      }\n      else {\n\n        window.onresize = null;\n\n      }\n    };\n\n    this.load = function() {\n      // trigger setup\n      setup();\n\n      // start auto slideshow if applicable\n      if (delay) begin();\n\n\n      // add event listeners\n      if (browser.addEventListener) {\n\n        // set touchstart event on element\n        if (browser.touch) {\n          element.addEventListener('touchstart', events, false);\n        } else {\n          element.addEventListener('mousedown', events, false);\n        }\n\n        if (browser.transitions) {\n          element.addEventListener('webkitTransitionEnd', events, false);\n          element.addEventListener('msTransitionEnd', events, false);\n          element.addEventListener('oTransitionEnd', events, false);\n          element.addEventListener('otransitionend', events, false);\n          element.addEventListener('transitionend', events, false);\n        }\n\n        // set resize event on window\n        window.addEventListener('resize', events, false);\n\n      } else {\n\n        window.onresize = function () { setup(); }; // to play nice with old IE\n\n      }\n    };\n\n  }\n});\n\n})(ionic);\n\n(function(ionic) {\n'use strict';\n\n  ionic.views.Toggle = ionic.views.View.inherit({\n    initialize: function(opts) {\n      var self = this;\n\n      this.el = opts.el;\n      this.checkbox = opts.checkbox;\n      this.track = opts.track;\n      this.handle = opts.handle;\n      this.openPercent = -1;\n      this.onChange = opts.onChange || function() {};\n\n      this.triggerThreshold = opts.triggerThreshold || 20;\n\n      this.dragStartHandler = function(e) {\n        self.dragStart(e);\n      };\n      this.dragHandler = function(e) {\n        self.drag(e);\n      };\n      this.holdHandler = function(e) {\n        self.hold(e);\n      };\n      this.releaseHandler = function(e) {\n        self.release(e);\n      };\n\n      this.dragStartGesture = ionic.onGesture('dragstart', this.dragStartHandler, this.el);\n      this.dragGesture = ionic.onGesture('drag', this.dragHandler, this.el);\n      this.dragHoldGesture = ionic.onGesture('hold', this.holdHandler, this.el);\n      this.dragReleaseGesture = ionic.onGesture('release', this.releaseHandler, this.el);\n    },\n\n    destroy: function() {\n      ionic.offGesture(this.dragStartGesture, 'dragstart', this.dragStartGesture);\n      ionic.offGesture(this.dragGesture, 'drag', this.dragGesture);\n      ionic.offGesture(this.dragHoldGesture, 'hold', this.holdHandler);\n      ionic.offGesture(this.dragReleaseGesture, 'release', this.releaseHandler);\n    },\n\n    tap: function() {\n      if(this.el.getAttribute('disabled') !== 'disabled') {\n        this.val( !this.checkbox.checked );\n      }\n    },\n\n    dragStart: function(e) {\n      if(this.checkbox.disabled) return;\n\n      this._dragInfo = {\n        width: this.el.offsetWidth,\n        left: this.el.offsetLeft,\n        right: this.el.offsetLeft + this.el.offsetWidth,\n        triggerX: this.el.offsetWidth / 2,\n        initialState: this.checkbox.checked\n      };\n\n      // Stop any parent dragging\n      e.gesture.srcEvent.preventDefault();\n\n      // Trigger hold styles\n      this.hold(e);\n    },\n\n    drag: function(e) {\n      var self = this;\n      if(!this._dragInfo) { return; }\n\n      // Stop any parent dragging\n      e.gesture.srcEvent.preventDefault();\n\n      ionic.requestAnimationFrame(function () {\n        if (!self._dragInfo) { return; }\n\n        var px = e.gesture.touches[0].pageX - self._dragInfo.left;\n        var mx = self._dragInfo.width - self.triggerThreshold;\n\n        // The initial state was on, so \"tend towards\" on\n        if(self._dragInfo.initialState) {\n          if(px < self.triggerThreshold) {\n            self.setOpenPercent(0);\n          } else if(px > self._dragInfo.triggerX) {\n            self.setOpenPercent(100);\n          }\n        } else {\n          // The initial state was off, so \"tend towards\" off\n          if(px < self._dragInfo.triggerX) {\n            self.setOpenPercent(0);\n          } else if(px > mx) {\n            self.setOpenPercent(100);\n          }\n        }\n      });\n    },\n\n    endDrag: function() {\n      this._dragInfo = null;\n    },\n\n    hold: function() {\n      this.el.classList.add('dragging');\n    },\n    release: function(e) {\n      this.el.classList.remove('dragging');\n      this.endDrag(e);\n    },\n\n\n    setOpenPercent: function(openPercent) {\n      // only make a change if the new open percent has changed\n      if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) {\n        this.openPercent = openPercent;\n\n        if(openPercent === 0) {\n          this.val(false);\n        } else if(openPercent === 100) {\n          this.val(true);\n        } else {\n          var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) );\n          openPixel = (openPixel < 1 ? 0 : openPixel);\n          this.handle.style[ionic.CSS.TRANSFORM] = 'translate3d(' + openPixel + 'px,0,0)';\n        }\n      }\n    },\n\n    val: function(value) {\n      if(value === true || value === false) {\n        if(this.handle.style[ionic.CSS.TRANSFORM] !== \"\") {\n          this.handle.style[ionic.CSS.TRANSFORM] = \"\";\n        }\n        this.checkbox.checked = value;\n        this.openPercent = (value ? 100 : 0);\n        this.onChange && this.onChange();\n      }\n      return this.checkbox.checked;\n    }\n\n  });\n\n})(ionic);\n\n})();\n/*!\n * ionic.bundle.js is a concatenation of:\n * ionic.js, angular.js, angular-animate.js,\n * angular-sanitize.js, angular-ui-router.js,\n * and ionic-angular.js\n */\n\n/**\n * @license AngularJS v1.3.13\n * (c) 2010-2014 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, document, undefined) {'use strict';\n\n/**\n * @description\n *\n * This object provides a utility for producing rich Error messages within\n * Angular. It can be called as follows:\n *\n * var exampleMinErr = minErr('example');\n * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);\n *\n * The above creates an instance of minErr in the example namespace. The\n * resulting error will have a namespaced error code of example.one.  The\n * resulting error will replace {0} with the value of foo, and {1} with the\n * value of bar. The object is not restricted in the number of arguments it can\n * take.\n *\n * If fewer arguments are specified than necessary for interpolation, the extra\n * interpolation markers will be preserved in the final string.\n *\n * Since data will be parsed statically during a build step, some restrictions\n * are applied with respect to how minErr instances are created and called.\n * Instances should have names of the form namespaceMinErr for a minErr created\n * using minErr('namespace') . Error codes, namespaces and template strings\n * should all be static strings, not variables or general expressions.\n *\n * @param {string} module The namespace to use for the new minErr instance.\n * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning\n *   error from returned function, for cases when a particular type of error is useful.\n * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance\n */\n\nfunction minErr(module, ErrorConstructor) {\n  ErrorConstructor = ErrorConstructor || Error;\n  return function() {\n    var code = arguments[0],\n      prefix = '[' + (module ? module + ':' : '') + code + '] ',\n      template = arguments[1],\n      templateArgs = arguments,\n\n      message, i;\n\n    message = prefix + template.replace(/\\{\\d+\\}/g, function(match) {\n      var index = +match.slice(1, -1), arg;\n\n      if (index + 2 < templateArgs.length) {\n        return toDebugString(templateArgs[index + 2]);\n      }\n      return match;\n    });\n\n    message = message + '\\nhttp://errors.angularjs.org/1.3.13/' +\n      (module ? module + '/' : '') + code;\n    for (i = 2; i < arguments.length; i++) {\n      message = message + (i == 2 ? '?' : '&') + 'p' + (i - 2) + '=' +\n        encodeURIComponent(toDebugString(arguments[i]));\n    }\n    return new ErrorConstructor(message);\n  };\n}\n\n/* We need to tell jshint what variables are being exported */\n/* global angular: true,\n  msie: true,\n  jqLite: true,\n  jQuery: true,\n  slice: true,\n  splice: true,\n  push: true,\n  toString: true,\n  ngMinErr: true,\n  angularModule: true,\n  uid: true,\n  REGEX_STRING_REGEXP: true,\n  VALIDITY_STATE_PROPERTY: true,\n\n  lowercase: true,\n  uppercase: true,\n  manualLowercase: true,\n  manualUppercase: true,\n  nodeName_: true,\n  isArrayLike: true,\n  forEach: true,\n  sortedKeys: true,\n  forEachSorted: true,\n  reverseParams: true,\n  nextUid: true,\n  setHashKey: true,\n  extend: true,\n  int: true,\n  inherit: true,\n  noop: true,\n  identity: true,\n  valueFn: true,\n  isUndefined: true,\n  isDefined: true,\n  isObject: true,\n  isString: true,\n  isNumber: true,\n  isDate: true,\n  isArray: true,\n  isFunction: true,\n  isRegExp: true,\n  isWindow: true,\n  isScope: true,\n  isFile: true,\n  isFormData: true,\n  isBlob: true,\n  isBoolean: true,\n  isPromiseLike: true,\n  trim: true,\n  escapeForRegexp: true,\n  isElement: true,\n  makeMap: true,\n  includes: true,\n  arrayRemove: true,\n  copy: true,\n  shallowCopy: true,\n  equals: true,\n  csp: true,\n  concat: true,\n  sliceArgs: true,\n  bind: true,\n  toJsonReplacer: true,\n  toJson: true,\n  fromJson: true,\n  startingTag: true,\n  tryDecodeURIComponent: true,\n  parseKeyValue: true,\n  toKeyValue: true,\n  encodeUriSegment: true,\n  encodeUriQuery: true,\n  angularInit: true,\n  bootstrap: true,\n  getTestability: true,\n  snake_case: true,\n  bindJQuery: true,\n  assertArg: true,\n  assertArgFn: true,\n  assertNotHasOwnProperty: true,\n  getter: true,\n  getBlockNodes: true,\n  hasOwnProperty: true,\n  createMap: true,\n\n  NODE_TYPE_ELEMENT: true,\n  NODE_TYPE_TEXT: true,\n  NODE_TYPE_COMMENT: true,\n  NODE_TYPE_DOCUMENT: true,\n  NODE_TYPE_DOCUMENT_FRAGMENT: true,\n*/\n\n////////////////////////////////////\n\n/**\n * @ngdoc module\n * @name ng\n * @module ng\n * @description\n *\n * # ng (core module)\n * The ng module is loaded by default when an AngularJS application is started. The module itself\n * contains the essential components for an AngularJS application to function. The table below\n * lists a high level breakdown of each of the services/factories, filters, directives and testing\n * components available within this core module.\n *\n * <div doc-module-components=\"ng\"></div>\n */\n\nvar REGEX_STRING_REGEXP = /^\\/(.+)\\/([a-z]*)$/;\n\n// The name of a form control's ValidityState property.\n// This is used so that it's possible for internal tests to create mock ValidityStates.\nvar VALIDITY_STATE_PROPERTY = 'validity';\n\n/**\n * @ngdoc function\n * @name angular.lowercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to lowercase.\n * @param {string} string String to be converted to lowercase.\n * @returns {string} Lowercased string.\n */\nvar lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * @ngdoc function\n * @name angular.uppercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to uppercase.\n * @param {string} string String to be converted to uppercase.\n * @returns {string} Uppercased string.\n */\nvar uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};\n\n\nvar manualLowercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})\n      : s;\n};\nvar manualUppercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})\n      : s;\n};\n\n\n// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish\n// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods\n// with correct but slower alternatives.\nif ('i' !== 'I'.toLowerCase()) {\n  lowercase = manualLowercase;\n  uppercase = manualUppercase;\n}\n\n\nvar\n    msie,             // holds major version number for IE, or NaN if UA is not IE.\n    jqLite,           // delay binding since jQuery could be loaded after us.\n    jQuery,           // delay binding\n    slice             = [].slice,\n    splice            = [].splice,\n    push              = [].push,\n    toString          = Object.prototype.toString,\n    ngMinErr          = minErr('ng'),\n\n    /** @name angular */\n    angular           = window.angular || (window.angular = {}),\n    angularModule,\n    uid               = 0;\n\n/**\n * documentMode is an IE-only property\n * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx\n */\nmsie = document.documentMode;\n\n\n/**\n * @private\n * @param {*} obj\n * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,\n *                   String ...)\n */\nfunction isArrayLike(obj) {\n  if (obj == null || isWindow(obj)) {\n    return false;\n  }\n\n  var length = obj.length;\n\n  if (obj.nodeType === NODE_TYPE_ELEMENT && length) {\n    return true;\n  }\n\n  return isString(obj) || isArray(obj) || length === 0 ||\n         typeof length === 'number' && length > 0 && (length - 1) in obj;\n}\n\n/**\n * @ngdoc function\n * @name angular.forEach\n * @module ng\n * @kind function\n *\n * @description\n * Invokes the `iterator` function once for each item in `obj` collection, which can be either an\n * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`\n * is the value of an object property or an array element, `key` is the object property key or\n * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.\n *\n * It is worth noting that `.forEach` does not iterate over inherited properties because it filters\n * using the `hasOwnProperty` method.\n *\n * Unlike ES262's\n * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),\n * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just\n * return the value provided.\n *\n   ```js\n     var values = {name: 'misko', gender: 'male'};\n     var log = [];\n     angular.forEach(values, function(value, key) {\n       this.push(key + ': ' + value);\n     }, log);\n     expect(log).toEqual(['name: misko', 'gender: male']);\n   ```\n *\n * @param {Object|Array} obj Object to iterate over.\n * @param {Function} iterator Iterator function.\n * @param {Object=} context Object to become context (`this`) for the iterator function.\n * @returns {Object|Array} Reference to `obj`.\n */\n\nfunction forEach(obj, iterator, context) {\n  var key, length;\n  if (obj) {\n    if (isFunction(obj)) {\n      for (key in obj) {\n        // Need to check if hasOwnProperty exists,\n        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function\n        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (isArray(obj) || isArrayLike(obj)) {\n      var isPrimitive = typeof obj !== 'object';\n      for (key = 0, length = obj.length; key < length; key++) {\n        if (isPrimitive || key in obj) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (obj.forEach && obj.forEach !== forEach) {\n        obj.forEach(iterator, context, obj);\n    } else {\n      for (key in obj) {\n        if (obj.hasOwnProperty(key)) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nfunction sortedKeys(obj) {\n  return Object.keys(obj).sort();\n}\n\nfunction forEachSorted(obj, iterator, context) {\n  var keys = sortedKeys(obj);\n  for (var i = 0; i < keys.length; i++) {\n    iterator.call(context, obj[keys[i]], keys[i]);\n  }\n  return keys;\n}\n\n\n/**\n * when using forEach the params are value, key, but it is often useful to have key, value.\n * @param {function(string, *)} iteratorFn\n * @returns {function(*, string)}\n */\nfunction reverseParams(iteratorFn) {\n  return function(value, key) { iteratorFn(key, value); };\n}\n\n/**\n * A consistent way of creating unique IDs in angular.\n *\n * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before\n * we hit number precision issues in JavaScript.\n *\n * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M\n *\n * @returns {number} an unique alpha-numeric string\n */\nfunction nextUid() {\n  return ++uid;\n}\n\n\n/**\n * Set or clear the hashkey for an object.\n * @param obj object\n * @param h the hashkey (!truthy to delete the hashkey)\n */\nfunction setHashKey(obj, h) {\n  if (h) {\n    obj.$$hashKey = h;\n  } else {\n    delete obj.$$hashKey;\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.extend\n * @module ng\n * @kind function\n *\n * @description\n * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.\n * Note: Keep in mind that `angular.extend` does not support recursive merge (deep copy).\n *\n * @param {Object} dst Destination object.\n * @param {...Object} src Source object(s).\n * @returns {Object} Reference to `dst`.\n */\nfunction extend(dst) {\n  var h = dst.$$hashKey;\n\n  for (var i = 1, ii = arguments.length; i < ii; i++) {\n    var obj = arguments[i];\n    if (obj) {\n      var keys = Object.keys(obj);\n      for (var j = 0, jj = keys.length; j < jj; j++) {\n        var key = keys[j];\n        dst[key] = obj[key];\n      }\n    }\n  }\n\n  setHashKey(dst, h);\n  return dst;\n}\n\nfunction int(str) {\n  return parseInt(str, 10);\n}\n\n\nfunction inherit(parent, extra) {\n  return extend(Object.create(parent), extra);\n}\n\n/**\n * @ngdoc function\n * @name angular.noop\n * @module ng\n * @kind function\n *\n * @description\n * A function that performs no operations. This function can be useful when writing code in the\n * functional style.\n   ```js\n     function foo(callback) {\n       var result = calculateResult();\n       (callback || angular.noop)(result);\n     }\n   ```\n */\nfunction noop() {}\nnoop.$inject = [];\n\n\n/**\n * @ngdoc function\n * @name angular.identity\n * @module ng\n * @kind function\n *\n * @description\n * A function that returns its first argument. This function is useful when writing code in the\n * functional style.\n *\n   ```js\n     function transformer(transformationFn, value) {\n       return (transformationFn || angular.identity)(value);\n     };\n   ```\n  * @param {*} value to be returned.\n  * @returns {*} the value passed in.\n */\nfunction identity($) {return $;}\nidentity.$inject = [];\n\n\nfunction valueFn(value) {return function() {return value;};}\n\n/**\n * @ngdoc function\n * @name angular.isUndefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is undefined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is undefined.\n */\nfunction isUndefined(value) {return typeof value === 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is defined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is defined.\n */\nfunction isDefined(value) {return typeof value !== 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isObject\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not\n * considered to be objects. Note that JavaScript arrays are objects.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Object` but not `null`.\n */\nfunction isObject(value) {\n  // http://jsperf.com/isobject4\n  return value !== null && typeof value === 'object';\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isString\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `String`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `String`.\n */\nfunction isString(value) {return typeof value === 'string';}\n\n\n/**\n * @ngdoc function\n * @name angular.isNumber\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Number`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Number`.\n */\nfunction isNumber(value) {return typeof value === 'number';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDate\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a value is a date.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Date`.\n */\nfunction isDate(value) {\n  return toString.call(value) === '[object Date]';\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isArray\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Array`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Array`.\n */\nvar isArray = Array.isArray;\n\n/**\n * @ngdoc function\n * @name angular.isFunction\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Function`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Function`.\n */\nfunction isFunction(value) {return typeof value === 'function';}\n\n\n/**\n * Determines if a value is a regular expression object.\n *\n * @private\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `RegExp`.\n */\nfunction isRegExp(value) {\n  return toString.call(value) === '[object RegExp]';\n}\n\n\n/**\n * Checks if `obj` is a window object.\n *\n * @private\n * @param {*} obj Object to check\n * @returns {boolean} True if `obj` is a window obj.\n */\nfunction isWindow(obj) {\n  return obj && obj.window === obj;\n}\n\n\nfunction isScope(obj) {\n  return obj && obj.$evalAsync && obj.$watch;\n}\n\n\nfunction isFile(obj) {\n  return toString.call(obj) === '[object File]';\n}\n\n\nfunction isFormData(obj) {\n  return toString.call(obj) === '[object FormData]';\n}\n\n\nfunction isBlob(obj) {\n  return toString.call(obj) === '[object Blob]';\n}\n\n\nfunction isBoolean(value) {\n  return typeof value === 'boolean';\n}\n\n\nfunction isPromiseLike(obj) {\n  return obj && isFunction(obj.then);\n}\n\n\nvar trim = function(value) {\n  return isString(value) ? value.trim() : value;\n};\n\n// Copied from:\n// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021\n// Prereq: s is a string.\nvar escapeForRegexp = function(s) {\n  return s.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1').\n           replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * @ngdoc function\n * @name angular.isElement\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a DOM element (or wrapped jQuery element).\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).\n */\nfunction isElement(node) {\n  return !!(node &&\n    (node.nodeName  // we are a direct element\n    || (node.prop && node.attr && node.find)));  // we have an on and find method part of jQuery API\n}\n\n/**\n * @param str 'key1,key2,...'\n * @returns {object} in the form of {key1:true, key2:true, ...}\n */\nfunction makeMap(str) {\n  var obj = {}, items = str.split(\",\"), i;\n  for (i = 0; i < items.length; i++)\n    obj[items[i]] = true;\n  return obj;\n}\n\n\nfunction nodeName_(element) {\n  return lowercase(element.nodeName || (element[0] && element[0].nodeName));\n}\n\nfunction includes(array, obj) {\n  return Array.prototype.indexOf.call(array, obj) != -1;\n}\n\nfunction arrayRemove(array, value) {\n  var index = array.indexOf(value);\n  if (index >= 0)\n    array.splice(index, 1);\n  return value;\n}\n\n/**\n * @ngdoc function\n * @name angular.copy\n * @module ng\n * @kind function\n *\n * @description\n * Creates a deep copy of `source`, which should be an object or an array.\n *\n * * If no destination is supplied, a copy of the object or array is created.\n * * If a destination is provided, all of its elements (for arrays) or properties (for objects)\n *   are deleted and then all elements/properties from the source are copied to it.\n * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.\n * * If `source` is identical to 'destination' an exception will be thrown.\n *\n * @param {*} source The source that will be used to make a copy.\n *                   Can be any type, including primitives, `null`, and `undefined`.\n * @param {(Object|Array)=} destination Destination into which the source is copied. If\n *     provided, must be of the same type as `source`.\n * @returns {*} The copy or updated `destination`, if `destination` was specified.\n *\n * @example\n <example module=\"copyExample\">\n <file name=\"index.html\">\n <div ng-controller=\"ExampleController\">\n <form novalidate class=\"simple-form\">\n Name: <input type=\"text\" ng-model=\"user.name\" /><br />\n E-mail: <input type=\"email\" ng-model=\"user.email\" /><br />\n Gender: <input type=\"radio\" ng-model=\"user.gender\" value=\"male\" />male\n <input type=\"radio\" ng-model=\"user.gender\" value=\"female\" />female<br />\n <button ng-click=\"reset()\">RESET</button>\n <button ng-click=\"update(user)\">SAVE</button>\n </form>\n <pre>form = {{user | json}}</pre>\n <pre>master = {{master | json}}</pre>\n </div>\n\n <script>\n  angular.module('copyExample', [])\n    .controller('ExampleController', ['$scope', function($scope) {\n      $scope.master= {};\n\n      $scope.update = function(user) {\n        // Example with 1 argument\n        $scope.master= angular.copy(user);\n      };\n\n      $scope.reset = function() {\n        // Example with 2 arguments\n        angular.copy($scope.master, $scope.user);\n      };\n\n      $scope.reset();\n    }]);\n </script>\n </file>\n </example>\n */\nfunction copy(source, destination, stackSource, stackDest) {\n  if (isWindow(source) || isScope(source)) {\n    throw ngMinErr('cpws',\n      \"Can't copy! Making copies of Window or Scope instances is not supported.\");\n  }\n\n  if (!destination) {\n    destination = source;\n    if (source) {\n      if (isArray(source)) {\n        destination = copy(source, [], stackSource, stackDest);\n      } else if (isDate(source)) {\n        destination = new Date(source.getTime());\n      } else if (isRegExp(source)) {\n        destination = new RegExp(source.source, source.toString().match(/[^\\/]*$/)[0]);\n        destination.lastIndex = source.lastIndex;\n      } else if (isObject(source)) {\n        var emptyObject = Object.create(Object.getPrototypeOf(source));\n        destination = copy(source, emptyObject, stackSource, stackDest);\n      }\n    }\n  } else {\n    if (source === destination) throw ngMinErr('cpi',\n      \"Can't copy! Source and destination are identical.\");\n\n    stackSource = stackSource || [];\n    stackDest = stackDest || [];\n\n    if (isObject(source)) {\n      var index = stackSource.indexOf(source);\n      if (index !== -1) return stackDest[index];\n\n      stackSource.push(source);\n      stackDest.push(destination);\n    }\n\n    var result;\n    if (isArray(source)) {\n      destination.length = 0;\n      for (var i = 0; i < source.length; i++) {\n        result = copy(source[i], null, stackSource, stackDest);\n        if (isObject(source[i])) {\n          stackSource.push(source[i]);\n          stackDest.push(result);\n        }\n        destination.push(result);\n      }\n    } else {\n      var h = destination.$$hashKey;\n      if (isArray(destination)) {\n        destination.length = 0;\n      } else {\n        forEach(destination, function(value, key) {\n          delete destination[key];\n        });\n      }\n      for (var key in source) {\n        if (source.hasOwnProperty(key)) {\n          result = copy(source[key], null, stackSource, stackDest);\n          if (isObject(source[key])) {\n            stackSource.push(source[key]);\n            stackDest.push(result);\n          }\n          destination[key] = result;\n        }\n      }\n      setHashKey(destination,h);\n    }\n\n  }\n  return destination;\n}\n\n/**\n * Creates a shallow copy of an object, an array or a primitive.\n *\n * Assumes that there are no proto properties for objects.\n */\nfunction shallowCopy(src, dst) {\n  if (isArray(src)) {\n    dst = dst || [];\n\n    for (var i = 0, ii = src.length; i < ii; i++) {\n      dst[i] = src[i];\n    }\n  } else if (isObject(src)) {\n    dst = dst || {};\n\n    for (var key in src) {\n      if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n        dst[key] = src[key];\n      }\n    }\n  }\n\n  return dst || src;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.equals\n * @module ng\n * @kind function\n *\n * @description\n * Determines if two objects or two values are equivalent. Supports value types, regular\n * expressions, arrays and objects.\n *\n * Two objects or values are considered equivalent if at least one of the following is true:\n *\n * * Both objects or values pass `===` comparison.\n * * Both objects or values are of the same type and all of their properties are equal by\n *   comparing them with `angular.equals`.\n * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)\n * * Both values represent the same regular expression (In JavaScript,\n *   /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual\n *   representation matches).\n *\n * During a property comparison, properties of `function` type and properties with names\n * that begin with `$` are ignored.\n *\n * Scope and DOMWindow objects are being compared only by identify (`===`).\n *\n * @param {*} o1 Object or value to compare.\n * @param {*} o2 Object or value to compare.\n * @returns {boolean} True if arguments are equal.\n */\nfunction equals(o1, o2) {\n  if (o1 === o2) return true;\n  if (o1 === null || o2 === null) return false;\n  if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n  var t1 = typeof o1, t2 = typeof o2, length, key, keySet;\n  if (t1 == t2) {\n    if (t1 == 'object') {\n      if (isArray(o1)) {\n        if (!isArray(o2)) return false;\n        if ((length = o1.length) == o2.length) {\n          for (key = 0; key < length; key++) {\n            if (!equals(o1[key], o2[key])) return false;\n          }\n          return true;\n        }\n      } else if (isDate(o1)) {\n        if (!isDate(o2)) return false;\n        return equals(o1.getTime(), o2.getTime());\n      } else if (isRegExp(o1) && isRegExp(o2)) {\n        return o1.toString() == o2.toString();\n      } else {\n        if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;\n        keySet = {};\n        for (key in o1) {\n          if (key.charAt(0) === '$' || isFunction(o1[key])) continue;\n          if (!equals(o1[key], o2[key])) return false;\n          keySet[key] = true;\n        }\n        for (key in o2) {\n          if (!keySet.hasOwnProperty(key) &&\n              key.charAt(0) !== '$' &&\n              o2[key] !== undefined &&\n              !isFunction(o2[key])) return false;\n        }\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nvar csp = function() {\n  if (isDefined(csp.isActive_)) return csp.isActive_;\n\n  var active = !!(document.querySelector('[ng-csp]') ||\n                  document.querySelector('[data-ng-csp]'));\n\n  if (!active) {\n    try {\n      /* jshint -W031, -W054 */\n      new Function('');\n      /* jshint +W031, +W054 */\n    } catch (e) {\n      active = true;\n    }\n  }\n\n  return (csp.isActive_ = active);\n};\n\n\n\nfunction concat(array1, array2, index) {\n  return array1.concat(slice.call(array2, index));\n}\n\nfunction sliceArgs(args, startIndex) {\n  return slice.call(args, startIndex || 0);\n}\n\n\n/* jshint -W101 */\n/**\n * @ngdoc function\n * @name angular.bind\n * @module ng\n * @kind function\n *\n * @description\n * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for\n * `fn`). You can supply optional `args` that are prebound to the function. This feature is also\n * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as\n * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).\n *\n * @param {Object} self Context which `fn` should be evaluated in.\n * @param {function()} fn Function to be bound.\n * @param {...*} args Optional arguments to be prebound to the `fn` function call.\n * @returns {function()} Function that wraps the `fn` with all the specified bindings.\n */\n/* jshint +W101 */\nfunction bind(self, fn) {\n  var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\n  if (isFunction(fn) && !(fn instanceof RegExp)) {\n    return curryArgs.length\n      ? function() {\n          return arguments.length\n            ? fn.apply(self, concat(curryArgs, arguments, 0))\n            : fn.apply(self, curryArgs);\n        }\n      : function() {\n          return arguments.length\n            ? fn.apply(self, arguments)\n            : fn.call(self);\n        };\n  } else {\n    // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)\n    return fn;\n  }\n}\n\n\nfunction toJsonReplacer(key, value) {\n  var val = value;\n\n  if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {\n    val = undefined;\n  } else if (isWindow(value)) {\n    val = '$WINDOW';\n  } else if (value &&  document === value) {\n    val = '$DOCUMENT';\n  } else if (isScope(value)) {\n    val = '$SCOPE';\n  }\n\n  return val;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.toJson\n * @module ng\n * @kind function\n *\n * @description\n * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be\n * stripped since angular uses this notation internally.\n *\n * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.\n * @param {boolean|number=} pretty If set to true, the JSON output will contain newlines and whitespace.\n *    If set to an integer, the JSON output will contain that many spaces per indentation (the default is 2).\n * @returns {string|undefined} JSON-ified string representing `obj`.\n */\nfunction toJson(obj, pretty) {\n  if (typeof obj === 'undefined') return undefined;\n  if (!isNumber(pretty)) {\n    pretty = pretty ? 2 : null;\n  }\n  return JSON.stringify(obj, toJsonReplacer, pretty);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.fromJson\n * @module ng\n * @kind function\n *\n * @description\n * Deserializes a JSON string.\n *\n * @param {string} json JSON string to deserialize.\n * @returns {Object|Array|string|number} Deserialized JSON string.\n */\nfunction fromJson(json) {\n  return isString(json)\n      ? JSON.parse(json)\n      : json;\n}\n\n\n/**\n * @returns {string} Returns the string representation of the element.\n */\nfunction startingTag(element) {\n  element = jqLite(element).clone();\n  try {\n    // turns out IE does not let you set .html() on elements which\n    // are not allowed to have children. So we just ignore it.\n    element.empty();\n  } catch (e) {}\n  var elemHtml = jqLite('<div>').append(element).html();\n  try {\n    return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :\n        elemHtml.\n          match(/^(<[^>]+>)/)[1].\n          replace(/^<([\\w\\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });\n  } catch (e) {\n    return lowercase(elemHtml);\n  }\n\n}\n\n\n/////////////////////////////////////////////////\n\n/**\n * Tries to decode the URI component without throwing an exception.\n *\n * @private\n * @param str value potential URI component to check.\n * @returns {boolean} True if `value` can be decoded\n * with the decodeURIComponent function.\n */\nfunction tryDecodeURIComponent(value) {\n  try {\n    return decodeURIComponent(value);\n  } catch (e) {\n    // Ignore any invalid uri component\n  }\n}\n\n\n/**\n * Parses an escaped url query string into key-value pairs.\n * @returns {Object.<string,boolean|Array>}\n */\nfunction parseKeyValue(/**string*/keyValue) {\n  var obj = {}, key_value, key;\n  forEach((keyValue || \"\").split('&'), function(keyValue) {\n    if (keyValue) {\n      key_value = keyValue.replace(/\\+/g,'%20').split('=');\n      key = tryDecodeURIComponent(key_value[0]);\n      if (isDefined(key)) {\n        var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;\n        if (!hasOwnProperty.call(obj, key)) {\n          obj[key] = val;\n        } else if (isArray(obj[key])) {\n          obj[key].push(val);\n        } else {\n          obj[key] = [obj[key],val];\n        }\n      }\n    }\n  });\n  return obj;\n}\n\nfunction toKeyValue(obj) {\n  var parts = [];\n  forEach(obj, function(value, key) {\n    if (isArray(value)) {\n      forEach(value, function(arrayValue) {\n        parts.push(encodeUriQuery(key, true) +\n                   (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));\n      });\n    } else {\n    parts.push(encodeUriQuery(key, true) +\n               (value === true ? '' : '=' + encodeUriQuery(value, true)));\n    }\n  });\n  return parts.length ? parts.join('&') : '';\n}\n\n\n/**\n * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path\n * segments:\n *    segment       = *pchar\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriSegment(val) {\n  return encodeUriQuery(val, true).\n             replace(/%26/gi, '&').\n             replace(/%3D/gi, '=').\n             replace(/%2B/gi, '+');\n}\n\n\n/**\n * This method is intended for encoding *key* or *value* parts of query component. We need a custom\n * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be\n * encoded per http://tools.ietf.org/html/rfc3986:\n *    query       = *( pchar / \"/\" / \"?\" )\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriQuery(val, pctEncodeSpaces) {\n  return encodeURIComponent(val).\n             replace(/%40/gi, '@').\n             replace(/%3A/gi, ':').\n             replace(/%24/g, '$').\n             replace(/%2C/gi, ',').\n             replace(/%3B/gi, ';').\n             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n}\n\nvar ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];\n\nfunction getNgAttribute(element, ngAttr) {\n  var attr, i, ii = ngAttrPrefixes.length;\n  element = jqLite(element);\n  for (i = 0; i < ii; ++i) {\n    attr = ngAttrPrefixes[i] + ngAttr;\n    if (isString(attr = element.attr(attr))) {\n      return attr;\n    }\n  }\n  return null;\n}\n\n/**\n * @ngdoc directive\n * @name ngApp\n * @module ng\n *\n * @element ANY\n * @param {angular.Module} ngApp an optional application\n *   {@link angular.module module} name to load.\n * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be\n *   created in \"strict-di\" mode. This means that the application will fail to invoke functions which\n *   do not use explicit function annotation (and are thus unsuitable for minification), as described\n *   in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in\n *   tracking down the root of these bugs.\n *\n * @description\n *\n * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive\n * designates the **root element** of the application and is typically placed near the root element\n * of the page - e.g. on the `<body>` or `<html>` tags.\n *\n * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`\n * found in the document will be used to define the root element to auto-bootstrap as an\n * application. To run multiple applications in an HTML document you must manually bootstrap them using\n * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.\n *\n * You can specify an **AngularJS module** to be used as the root module for the application.  This\n * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It\n * should contain the application code needed or have dependencies on other modules that will\n * contain the code. See {@link angular.module} for more information.\n *\n * In the example below if the `ngApp` directive were not placed on the `html` element then the\n * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`\n * would not be resolved to `3`.\n *\n * `ngApp` is the easiest, and most common way to bootstrap an application.\n *\n <example module=\"ngAppDemo\">\n   <file name=\"index.html\">\n   <div ng-controller=\"ngAppDemoController\">\n     I can add: {{a}} + {{b}} =  {{ a+b }}\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {\n     $scope.a = 1;\n     $scope.b = 2;\n   });\n   </file>\n </example>\n *\n * Using `ngStrictDi`, you would see something like this:\n *\n <example ng-app-included=\"true\">\n   <file name=\"index.html\">\n   <div ng-app=\"ngAppStrictDemo\" ng-strict-di>\n       <div ng-controller=\"GoodController1\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style (see\n              script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"GoodController2\">\n           Name: <input ng-model=\"name\"><br />\n           Hello, {{name}}!\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style\n              (see script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"BadController\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>The controller could not be instantiated, due to relying\n              on automatic function annotations (which are disabled in\n              strict mode). As such, the content of this section is not\n              interpolated, and there should be an error in your web console.\n           </p>\n       </div>\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppStrictDemo', [])\n     // BadController will fail to instantiate, due to relying on automatic function annotation,\n     // rather than an explicit annotation\n     .controller('BadController', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     })\n     // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,\n     // due to using explicit annotations using the array style and $inject property, respectively.\n     .controller('GoodController1', ['$scope', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     }])\n     .controller('GoodController2', GoodController2);\n     function GoodController2($scope) {\n       $scope.name = \"World\";\n     }\n     GoodController2.$inject = ['$scope'];\n   </file>\n   <file name=\"style.css\">\n   div[ng-controller] {\n       margin-bottom: 1em;\n       -webkit-border-radius: 4px;\n       border-radius: 4px;\n       border: 1px solid;\n       padding: .5em;\n   }\n   div[ng-controller^=Good] {\n       border-color: #d6e9c6;\n       background-color: #dff0d8;\n       color: #3c763d;\n   }\n   div[ng-controller^=Bad] {\n       border-color: #ebccd1;\n       background-color: #f2dede;\n       color: #a94442;\n       margin-bottom: 0;\n   }\n   </file>\n </example>\n */\nfunction angularInit(element, bootstrap) {\n  var appElement,\n      module,\n      config = {};\n\n  // The element `element` has priority over any other element\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n\n    if (!appElement && element.hasAttribute && element.hasAttribute(name)) {\n      appElement = element;\n      module = element.getAttribute(name);\n    }\n  });\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n    var candidate;\n\n    if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\\\:') + ']'))) {\n      appElement = candidate;\n      module = candidate.getAttribute(name);\n    }\n  });\n  if (appElement) {\n    config.strictDi = getNgAttribute(appElement, \"strict-di\") !== null;\n    bootstrap(appElement, module ? [module] : [], config);\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.bootstrap\n * @module ng\n * @description\n * Use this function to manually start up angular application.\n *\n * See: {@link guide/bootstrap Bootstrap}\n *\n * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.\n * They must use {@link ng.directive:ngApp ngApp}.\n *\n * Angular will detect if it has been loaded into the browser more than once and only allow the\n * first loaded script to be bootstrapped and will report a warning to the browser console for\n * each of the subsequent scripts. This prevents strange results in applications, where otherwise\n * multiple instances of Angular try to work on the DOM.\n *\n * ```html\n * <!doctype html>\n * <html>\n * <body>\n * <div ng-controller=\"WelcomeController\">\n *   {{greeting}}\n * </div>\n *\n * <script src=\"angular.js\"></script>\n * <script>\n *   var app = angular.module('demo', [])\n *   .controller('WelcomeController', function($scope) {\n *       $scope.greeting = 'Welcome!';\n *   });\n *   angular.bootstrap(document, ['demo']);\n * </script>\n * </body>\n * </html>\n * ```\n *\n * @param {DOMElement} element DOM element which is the root of angular application.\n * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.\n *     Each item in the array should be the name of a predefined module or a (DI annotated)\n *     function that will be invoked by the injector as a `config` block.\n *     See: {@link angular.module modules}\n * @param {Object=} config an object for defining configuration options for the application. The\n *     following keys are supported:\n *\n * * `strictDi` - disable automatic function annotation for the application. This is meant to\n *   assist in finding bugs which break minified code. Defaults to `false`.\n *\n * @returns {auto.$injector} Returns the newly created injector for this app.\n */\nfunction bootstrap(element, modules, config) {\n  if (!isObject(config)) config = {};\n  var defaultConfig = {\n    strictDi: false\n  };\n  config = extend(defaultConfig, config);\n  var doBootstrap = function() {\n    element = jqLite(element);\n\n    if (element.injector()) {\n      var tag = (element[0] === document) ? 'document' : startingTag(element);\n      //Encode angle brackets to prevent input from being sanitized to empty string #8683\n      throw ngMinErr(\n          'btstrpd',\n          \"App Already Bootstrapped with this Element '{0}'\",\n          tag.replace(/</,'&lt;').replace(/>/,'&gt;'));\n    }\n\n    modules = modules || [];\n    modules.unshift(['$provide', function($provide) {\n      $provide.value('$rootElement', element);\n    }]);\n\n    if (config.debugInfoEnabled) {\n      // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.\n      modules.push(['$compileProvider', function($compileProvider) {\n        $compileProvider.debugInfoEnabled(true);\n      }]);\n    }\n\n    modules.unshift('ng');\n    var injector = createInjector(modules, config.strictDi);\n    injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',\n       function bootstrapApply(scope, element, compile, injector) {\n        scope.$apply(function() {\n          element.data('$injector', injector);\n          compile(element)(scope);\n        });\n      }]\n    );\n    return injector;\n  };\n\n  var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;\n  var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;\n\n  if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {\n    config.debugInfoEnabled = true;\n    window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');\n  }\n\n  if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {\n    return doBootstrap();\n  }\n\n  window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');\n  angular.resumeBootstrap = function(extraModules) {\n    forEach(extraModules, function(module) {\n      modules.push(module);\n    });\n    return doBootstrap();\n  };\n\n  if (isFunction(angular.resumeDeferredBootstrap)) {\n    angular.resumeDeferredBootstrap();\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.reloadWithDebugInfo\n * @module ng\n * @description\n * Use this function to reload the current application with debug information turned on.\n * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.\n *\n * See {@link ng.$compileProvider#debugInfoEnabled} for more.\n */\nfunction reloadWithDebugInfo() {\n  window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\n  window.location.reload();\n}\n\n/**\n * @name angular.getTestability\n * @module ng\n * @description\n * Get the testability service for the instance of Angular on the given\n * element.\n * @param {DOMElement} element DOM element which is the root of angular application.\n */\nfunction getTestability(rootElement) {\n  var injector = angular.element(rootElement).injector();\n  if (!injector) {\n    throw ngMinErr('test',\n      'no injector found for element argument to getTestability');\n  }\n  return injector.get('$$testability');\n}\n\nvar SNAKE_CASE_REGEXP = /[A-Z]/g;\nfunction snake_case(name, separator) {\n  separator = separator || '_';\n  return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n    return (pos ? separator : '') + letter.toLowerCase();\n  });\n}\n\nvar bindJQueryFired = false;\nvar skipDestroyOnNextJQueryCleanData;\nfunction bindJQuery() {\n  var originalCleanData;\n\n  if (bindJQueryFired) {\n    return;\n  }\n\n  // bind to jQuery if present;\n  jQuery = window.jQuery;\n  // Use jQuery if it exists with proper functionality, otherwise default to us.\n  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.\n  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older\n  // versions. It will not work for sure with jQuery <1.7, though.\n  if (jQuery && jQuery.fn.on) {\n    jqLite = jQuery;\n    extend(jQuery.fn, {\n      scope: JQLitePrototype.scope,\n      isolateScope: JQLitePrototype.isolateScope,\n      controller: JQLitePrototype.controller,\n      injector: JQLitePrototype.injector,\n      inheritedData: JQLitePrototype.inheritedData\n    });\n\n    // All nodes removed from the DOM via various jQuery APIs like .remove()\n    // are passed through jQuery.cleanData. Monkey-patch this method to fire\n    // the $destroy event on all removed nodes.\n    originalCleanData = jQuery.cleanData;\n    jQuery.cleanData = function(elems) {\n      var events;\n      if (!skipDestroyOnNextJQueryCleanData) {\n        for (var i = 0, elem; (elem = elems[i]) != null; i++) {\n          events = jQuery._data(elem, \"events\");\n          if (events && events.$destroy) {\n            jQuery(elem).triggerHandler('$destroy');\n          }\n        }\n      } else {\n        skipDestroyOnNextJQueryCleanData = false;\n      }\n      originalCleanData(elems);\n    };\n  } else {\n    jqLite = JQLite;\n  }\n\n  angular.element = jqLite;\n\n  // Prevent double-proxying.\n  bindJQueryFired = true;\n}\n\n/**\n * throw error if the argument is falsy.\n */\nfunction assertArg(arg, name, reason) {\n  if (!arg) {\n    throw ngMinErr('areq', \"Argument '{0}' is {1}\", (name || '?'), (reason || \"required\"));\n  }\n  return arg;\n}\n\nfunction assertArgFn(arg, name, acceptArrayAnnotation) {\n  if (acceptArrayAnnotation && isArray(arg)) {\n      arg = arg[arg.length - 1];\n  }\n\n  assertArg(isFunction(arg), name, 'not a function, got ' +\n      (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));\n  return arg;\n}\n\n/**\n * throw error if the name given is hasOwnProperty\n * @param  {String} name    the name to test\n * @param  {String} context the context in which the name is used, such as module or directive\n */\nfunction assertNotHasOwnProperty(name, context) {\n  if (name === 'hasOwnProperty') {\n    throw ngMinErr('badname', \"hasOwnProperty is not a valid {0} name\", context);\n  }\n}\n\n/**\n * Return the value accessible from the object by path. Any undefined traversals are ignored\n * @param {Object} obj starting object\n * @param {String} path path to traverse\n * @param {boolean} [bindFnToScope=true]\n * @returns {Object} value as accessible by path\n */\n//TODO(misko): this function needs to be removed\nfunction getter(obj, path, bindFnToScope) {\n  if (!path) return obj;\n  var keys = path.split('.');\n  var key;\n  var lastInstance = obj;\n  var len = keys.length;\n\n  for (var i = 0; i < len; i++) {\n    key = keys[i];\n    if (obj) {\n      obj = (lastInstance = obj)[key];\n    }\n  }\n  if (!bindFnToScope && isFunction(obj)) {\n    return bind(lastInstance, obj);\n  }\n  return obj;\n}\n\n/**\n * Return the DOM siblings between the first and last node in the given array.\n * @param {Array} array like object\n * @returns {jqLite} jqLite collection containing the nodes\n */\nfunction getBlockNodes(nodes) {\n  // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original\n  //             collection, otherwise update the original collection.\n  var node = nodes[0];\n  var endNode = nodes[nodes.length - 1];\n  var blockNodes = [node];\n\n  do {\n    node = node.nextSibling;\n    if (!node) break;\n    blockNodes.push(node);\n  } while (node !== endNode);\n\n  return jqLite(blockNodes);\n}\n\n\n/**\n * Creates a new object without a prototype. This object is useful for lookup without having to\n * guard against prototypically inherited properties via hasOwnProperty.\n *\n * Related micro-benchmarks:\n * - http://jsperf.com/object-create2\n * - http://jsperf.com/proto-map-lookup/2\n * - http://jsperf.com/for-in-vs-object-keys2\n *\n * @returns {Object}\n */\nfunction createMap() {\n  return Object.create(null);\n}\n\nvar NODE_TYPE_ELEMENT = 1;\nvar NODE_TYPE_TEXT = 3;\nvar NODE_TYPE_COMMENT = 8;\nvar NODE_TYPE_DOCUMENT = 9;\nvar NODE_TYPE_DOCUMENT_FRAGMENT = 11;\n\n/**\n * @ngdoc type\n * @name angular.Module\n * @module ng\n * @description\n *\n * Interface for configuring angular {@link angular.module modules}.\n */\n\nfunction setupModuleLoader(window) {\n\n  var $injectorMinErr = minErr('$injector');\n  var ngMinErr = minErr('ng');\n\n  function ensure(obj, name, factory) {\n    return obj[name] || (obj[name] = factory());\n  }\n\n  var angular = ensure(window, 'angular', Object);\n\n  // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap\n  angular.$$minErr = angular.$$minErr || minErr;\n\n  return ensure(angular, 'module', function() {\n    /** @type {Object.<string, angular.Module>} */\n    var modules = {};\n\n    /**\n     * @ngdoc function\n     * @name angular.module\n     * @module ng\n     * @description\n     *\n     * The `angular.module` is a global place for creating, registering and retrieving Angular\n     * modules.\n     * All modules (angular core or 3rd party) that should be available to an application must be\n     * registered using this mechanism.\n     *\n     * When passed two or more arguments, a new module is created.  If passed only one argument, an\n     * existing module (the name passed as the first argument to `module`) is retrieved.\n     *\n     *\n     * # Module\n     *\n     * A module is a collection of services, directives, controllers, filters, and configuration information.\n     * `angular.module` is used to configure the {@link auto.$injector $injector}.\n     *\n     * ```js\n     * // Create a new module\n     * var myModule = angular.module('myModule', []);\n     *\n     * // register a new service\n     * myModule.value('appName', 'MyCoolApp');\n     *\n     * // configure existing services inside initialization blocks.\n     * myModule.config(['$locationProvider', function($locationProvider) {\n     *   // Configure existing providers\n     *   $locationProvider.hashPrefix('!');\n     * }]);\n     * ```\n     *\n     * Then you can create an injector and load your modules like this:\n     *\n     * ```js\n     * var injector = angular.injector(['ng', 'myModule'])\n     * ```\n     *\n     * However it's more likely that you'll just use\n     * {@link ng.directive:ngApp ngApp} or\n     * {@link angular.bootstrap} to simplify this process for you.\n     *\n     * @param {!string} name The name of the module to create or retrieve.\n     * @param {!Array.<string>=} requires If specified then new module is being created. If\n     *        unspecified then the module is being retrieved for further configuration.\n     * @param {Function=} configFn Optional configuration function for the module. Same as\n     *        {@link angular.Module#config Module#config()}.\n     * @returns {module} new module with the {@link angular.Module} api.\n     */\n    return function module(name, requires, configFn) {\n      var assertNotHasOwnProperty = function(name, context) {\n        if (name === 'hasOwnProperty') {\n          throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n        }\n      };\n\n      assertNotHasOwnProperty(name, 'module');\n      if (requires && modules.hasOwnProperty(name)) {\n        modules[name] = null;\n      }\n      return ensure(modules, name, function() {\n        if (!requires) {\n          throw $injectorMinErr('nomod', \"Module '{0}' is not available! You either misspelled \" +\n             \"the module name or forgot to load it. If registering a module ensure that you \" +\n             \"specify the dependencies as the second argument.\", name);\n        }\n\n        /** @type {!Array.<Array.<*>>} */\n        var invokeQueue = [];\n\n        /** @type {!Array.<Function>} */\n        var configBlocks = [];\n\n        /** @type {!Array.<Function>} */\n        var runBlocks = [];\n\n        var config = invokeLater('$injector', 'invoke', 'push', configBlocks);\n\n        /** @type {angular.Module} */\n        var moduleInstance = {\n          // Private state\n          _invokeQueue: invokeQueue,\n          _configBlocks: configBlocks,\n          _runBlocks: runBlocks,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#requires\n           * @module ng\n           *\n           * @description\n           * Holds the list of modules which the injector will load before the current module is\n           * loaded.\n           */\n          requires: requires,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#name\n           * @module ng\n           *\n           * @description\n           * Name of the module.\n           */\n          name: name,\n\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#provider\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerType Construction function for creating new instance of the\n           *                                service.\n           * @description\n           * See {@link auto.$provide#provider $provide.provider()}.\n           */\n          provider: invokeLater('$provide', 'provider'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#factory\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerFunction Function for creating new instance of the service.\n           * @description\n           * See {@link auto.$provide#factory $provide.factory()}.\n           */\n          factory: invokeLater('$provide', 'factory'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#service\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} constructor A constructor function that will be instantiated.\n           * @description\n           * See {@link auto.$provide#service $provide.service()}.\n           */\n          service: invokeLater('$provide', 'service'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#value\n           * @module ng\n           * @param {string} name service name\n           * @param {*} object Service instance object.\n           * @description\n           * See {@link auto.$provide#value $provide.value()}.\n           */\n          value: invokeLater('$provide', 'value'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#constant\n           * @module ng\n           * @param {string} name constant name\n           * @param {*} object Constant value.\n           * @description\n           * Because the constant are fixed, they get applied before other provide methods.\n           * See {@link auto.$provide#constant $provide.constant()}.\n           */\n          constant: invokeLater('$provide', 'constant', 'unshift'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#animation\n           * @module ng\n           * @param {string} name animation name\n           * @param {Function} animationFactory Factory function for creating new instance of an\n           *                                    animation.\n           * @description\n           *\n           * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.\n           *\n           *\n           * Defines an animation hook that can be later used with\n           * {@link ngAnimate.$animate $animate} service and directives that use this service.\n           *\n           * ```js\n           * module.animation('.animation-name', function($inject1, $inject2) {\n           *   return {\n           *     eventName : function(element, done) {\n           *       //code to run the animation\n           *       //once complete, then run done()\n           *       return function cancellationFunction(element) {\n           *         //code to cancel the animation\n           *       }\n           *     }\n           *   }\n           * })\n           * ```\n           *\n           * See {@link ng.$animateProvider#register $animateProvider.register()} and\n           * {@link ngAnimate ngAnimate module} for more information.\n           */\n          animation: invokeLater('$animateProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#filter\n           * @module ng\n           * @param {string} name Filter name.\n           * @param {Function} filterFactory Factory function for creating new instance of filter.\n           * @description\n           * See {@link ng.$filterProvider#register $filterProvider.register()}.\n           */\n          filter: invokeLater('$filterProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#controller\n           * @module ng\n           * @param {string|Object} name Controller name, or an object map of controllers where the\n           *    keys are the names and the values are the constructors.\n           * @param {Function} constructor Controller constructor function.\n           * @description\n           * See {@link ng.$controllerProvider#register $controllerProvider.register()}.\n           */\n          controller: invokeLater('$controllerProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#directive\n           * @module ng\n           * @param {string|Object} name Directive name, or an object map of directives where the\n           *    keys are the names and the values are the factories.\n           * @param {Function} directiveFactory Factory function for creating new instance of\n           * directives.\n           * @description\n           * See {@link ng.$compileProvider#directive $compileProvider.directive()}.\n           */\n          directive: invokeLater('$compileProvider', 'directive'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#config\n           * @module ng\n           * @param {Function} configFn Execute this function on module load. Useful for service\n           *    configuration.\n           * @description\n           * Use this method to register work which needs to be performed on module loading.\n           * For more about how to configure services, see\n           * {@link providers#provider-recipe Provider Recipe}.\n           */\n          config: config,\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#run\n           * @module ng\n           * @param {Function} initializationFn Execute this function after injector creation.\n           *    Useful for application initialization.\n           * @description\n           * Use this method to register work which should be performed when the injector is done\n           * loading all modules.\n           */\n          run: function(block) {\n            runBlocks.push(block);\n            return this;\n          }\n        };\n\n        if (configFn) {\n          config(configFn);\n        }\n\n        return moduleInstance;\n\n        /**\n         * @param {string} provider\n         * @param {string} method\n         * @param {String=} insertMethod\n         * @returns {angular.Module}\n         */\n        function invokeLater(provider, method, insertMethod, queue) {\n          if (!queue) queue = invokeQueue;\n          return function() {\n            queue[insertMethod || 'push']([provider, method, arguments]);\n            return moduleInstance;\n          };\n        }\n      });\n    };\n  });\n\n}\n\n/* global: toDebugString: true */\n\nfunction serializeObject(obj) {\n  var seen = [];\n\n  return JSON.stringify(obj, function(key, val) {\n    val = toJsonReplacer(key, val);\n    if (isObject(val)) {\n\n      if (seen.indexOf(val) >= 0) return '<<already seen>>';\n\n      seen.push(val);\n    }\n    return val;\n  });\n}\n\nfunction toDebugString(obj) {\n  if (typeof obj === 'function') {\n    return obj.toString().replace(/ \\{[\\s\\S]*$/, '');\n  } else if (typeof obj === 'undefined') {\n    return 'undefined';\n  } else if (typeof obj !== 'string') {\n    return serializeObject(obj);\n  }\n  return obj;\n}\n\n/* global angularModule: true,\n  version: true,\n\n  $LocaleProvider,\n  $CompileProvider,\n\n  htmlAnchorDirective,\n  inputDirective,\n  inputDirective,\n  formDirective,\n  scriptDirective,\n  selectDirective,\n  styleDirective,\n  optionDirective,\n  ngBindDirective,\n  ngBindHtmlDirective,\n  ngBindTemplateDirective,\n  ngClassDirective,\n  ngClassEvenDirective,\n  ngClassOddDirective,\n  ngCspDirective,\n  ngCloakDirective,\n  ngControllerDirective,\n  ngFormDirective,\n  ngHideDirective,\n  ngIfDirective,\n  ngIncludeDirective,\n  ngIncludeFillContentDirective,\n  ngInitDirective,\n  ngNonBindableDirective,\n  ngPluralizeDirective,\n  ngRepeatDirective,\n  ngShowDirective,\n  ngStyleDirective,\n  ngSwitchDirective,\n  ngSwitchWhenDirective,\n  ngSwitchDefaultDirective,\n  ngOptionsDirective,\n  ngTranscludeDirective,\n  ngModelDirective,\n  ngListDirective,\n  ngChangeDirective,\n  patternDirective,\n  patternDirective,\n  requiredDirective,\n  requiredDirective,\n  minlengthDirective,\n  minlengthDirective,\n  maxlengthDirective,\n  maxlengthDirective,\n  ngValueDirective,\n  ngModelOptionsDirective,\n  ngAttributeAliasDirectives,\n  ngEventDirectives,\n\n  $AnchorScrollProvider,\n  $AnimateProvider,\n  $BrowserProvider,\n  $CacheFactoryProvider,\n  $ControllerProvider,\n  $DocumentProvider,\n  $ExceptionHandlerProvider,\n  $FilterProvider,\n  $InterpolateProvider,\n  $IntervalProvider,\n  $HttpProvider,\n  $HttpBackendProvider,\n  $LocationProvider,\n  $LogProvider,\n  $ParseProvider,\n  $RootScopeProvider,\n  $QProvider,\n  $$QProvider,\n  $$SanitizeUriProvider,\n  $SceProvider,\n  $SceDelegateProvider,\n  $SnifferProvider,\n  $TemplateCacheProvider,\n  $TemplateRequestProvider,\n  $$TestabilityProvider,\n  $TimeoutProvider,\n  $$RAFProvider,\n  $$AsyncCallbackProvider,\n  $WindowProvider,\n  $$jqLiteProvider\n*/\n\n\n/**\n * @ngdoc object\n * @name angular.version\n * @module ng\n * @description\n * An object that contains information about the current AngularJS version. This object has the\n * following properties:\n *\n * - `full` – `{string}` – Full version string, such as \"0.9.18\".\n * - `major` – `{number}` – Major version number, such as \"0\".\n * - `minor` – `{number}` – Minor version number, such as \"9\".\n * - `dot` – `{number}` – Dot version number, such as \"18\".\n * - `codeName` – `{string}` – Code name of the release, such as \"jiggling-armfat\".\n */\nvar version = {\n  full: '1.3.13',    // all of these placeholder strings will be replaced by grunt's\n  major: 1,    // package task\n  minor: 3,\n  dot: 13,\n  codeName: 'meticulous-riffleshuffle'\n};\n\n\nfunction publishExternalAPI(angular) {\n  extend(angular, {\n    'bootstrap': bootstrap,\n    'copy': copy,\n    'extend': extend,\n    'equals': equals,\n    'element': jqLite,\n    'forEach': forEach,\n    'injector': createInjector,\n    'noop': noop,\n    'bind': bind,\n    'toJson': toJson,\n    'fromJson': fromJson,\n    'identity': identity,\n    'isUndefined': isUndefined,\n    'isDefined': isDefined,\n    'isString': isString,\n    'isFunction': isFunction,\n    'isObject': isObject,\n    'isNumber': isNumber,\n    'isElement': isElement,\n    'isArray': isArray,\n    'version': version,\n    'isDate': isDate,\n    'lowercase': lowercase,\n    'uppercase': uppercase,\n    'callbacks': {counter: 0},\n    'getTestability': getTestability,\n    '$$minErr': minErr,\n    '$$csp': csp,\n    'reloadWithDebugInfo': reloadWithDebugInfo\n  });\n\n  angularModule = setupModuleLoader(window);\n  try {\n    angularModule('ngLocale');\n  } catch (e) {\n    angularModule('ngLocale', []).provider('$locale', $LocaleProvider);\n  }\n\n  angularModule('ng', ['ngLocale'], ['$provide',\n    function ngModule($provide) {\n      // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.\n      $provide.provider({\n        $$sanitizeUri: $$SanitizeUriProvider\n      });\n      $provide.provider('$compile', $CompileProvider).\n        directive({\n            a: htmlAnchorDirective,\n            input: inputDirective,\n            textarea: inputDirective,\n            form: formDirective,\n            script: scriptDirective,\n            select: selectDirective,\n            style: styleDirective,\n            option: optionDirective,\n            ngBind: ngBindDirective,\n            ngBindHtml: ngBindHtmlDirective,\n            ngBindTemplate: ngBindTemplateDirective,\n            ngClass: ngClassDirective,\n            ngClassEven: ngClassEvenDirective,\n            ngClassOdd: ngClassOddDirective,\n            ngCloak: ngCloakDirective,\n            ngController: ngControllerDirective,\n            ngForm: ngFormDirective,\n            ngHide: ngHideDirective,\n            ngIf: ngIfDirective,\n            ngInclude: ngIncludeDirective,\n            ngInit: ngInitDirective,\n            ngNonBindable: ngNonBindableDirective,\n            ngPluralize: ngPluralizeDirective,\n            ngRepeat: ngRepeatDirective,\n            ngShow: ngShowDirective,\n            ngStyle: ngStyleDirective,\n            ngSwitch: ngSwitchDirective,\n            ngSwitchWhen: ngSwitchWhenDirective,\n            ngSwitchDefault: ngSwitchDefaultDirective,\n            ngOptions: ngOptionsDirective,\n            ngTransclude: ngTranscludeDirective,\n            ngModel: ngModelDirective,\n            ngList: ngListDirective,\n            ngChange: ngChangeDirective,\n            pattern: patternDirective,\n            ngPattern: patternDirective,\n            required: requiredDirective,\n            ngRequired: requiredDirective,\n            minlength: minlengthDirective,\n            ngMinlength: minlengthDirective,\n            maxlength: maxlengthDirective,\n            ngMaxlength: maxlengthDirective,\n            ngValue: ngValueDirective,\n            ngModelOptions: ngModelOptionsDirective\n        }).\n        directive({\n          ngInclude: ngIncludeFillContentDirective\n        }).\n        directive(ngAttributeAliasDirectives).\n        directive(ngEventDirectives);\n      $provide.provider({\n        $anchorScroll: $AnchorScrollProvider,\n        $animate: $AnimateProvider,\n        $browser: $BrowserProvider,\n        $cacheFactory: $CacheFactoryProvider,\n        $controller: $ControllerProvider,\n        $document: $DocumentProvider,\n        $exceptionHandler: $ExceptionHandlerProvider,\n        $filter: $FilterProvider,\n        $interpolate: $InterpolateProvider,\n        $interval: $IntervalProvider,\n        $http: $HttpProvider,\n        $httpBackend: $HttpBackendProvider,\n        $location: $LocationProvider,\n        $log: $LogProvider,\n        $parse: $ParseProvider,\n        $rootScope: $RootScopeProvider,\n        $q: $QProvider,\n        $$q: $$QProvider,\n        $sce: $SceProvider,\n        $sceDelegate: $SceDelegateProvider,\n        $sniffer: $SnifferProvider,\n        $templateCache: $TemplateCacheProvider,\n        $templateRequest: $TemplateRequestProvider,\n        $$testability: $$TestabilityProvider,\n        $timeout: $TimeoutProvider,\n        $window: $WindowProvider,\n        $$rAF: $$RAFProvider,\n        $$asyncCallback: $$AsyncCallbackProvider,\n        $$jqLite: $$jqLiteProvider\n      });\n    }\n  ]);\n}\n\n/* global JQLitePrototype: true,\n  addEventListenerFn: true,\n  removeEventListenerFn: true,\n  BOOLEAN_ATTR: true,\n  ALIASED_ATTR: true,\n*/\n\n//////////////////////////////////\n//JQLite\n//////////////////////////////////\n\n/**\n * @ngdoc function\n * @name angular.element\n * @module ng\n * @kind function\n *\n * @description\n * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.\n *\n * If jQuery is available, `angular.element` is an alias for the\n * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`\n * delegates to Angular's built-in subset of jQuery, called \"jQuery lite\" or \"jqLite.\"\n *\n * <div class=\"alert alert-success\">jqLite is a tiny, API-compatible subset of jQuery that allows\n * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most\n * commonly needed functionality with the goal of having a very small footprint.</div>\n *\n * To use jQuery, simply load it before `DOMContentLoaded` event fired.\n *\n * <div class=\"alert\">**Note:** all element references in Angular are always wrapped with jQuery or\n * jqLite; they are never raw DOM references.</div>\n *\n * ## Angular's jqLite\n * jqLite provides only the following jQuery methods:\n *\n * - [`addClass()`](http://api.jquery.com/addClass/)\n * - [`after()`](http://api.jquery.com/after/)\n * - [`append()`](http://api.jquery.com/append/)\n * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters\n * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData\n * - [`children()`](http://api.jquery.com/children/) - Does not support selectors\n * - [`clone()`](http://api.jquery.com/clone/)\n * - [`contents()`](http://api.jquery.com/contents/)\n * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`\n * - [`data()`](http://api.jquery.com/data/)\n * - [`detach()`](http://api.jquery.com/detach/)\n * - [`empty()`](http://api.jquery.com/empty/)\n * - [`eq()`](http://api.jquery.com/eq/)\n * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name\n * - [`hasClass()`](http://api.jquery.com/hasClass/)\n * - [`html()`](http://api.jquery.com/html/)\n * - [`next()`](http://api.jquery.com/next/) - Does not support selectors\n * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData\n * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors\n * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors\n * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors\n * - [`prepend()`](http://api.jquery.com/prepend/)\n * - [`prop()`](http://api.jquery.com/prop/)\n * - [`ready()`](http://api.jquery.com/ready/)\n * - [`remove()`](http://api.jquery.com/remove/)\n * - [`removeAttr()`](http://api.jquery.com/removeAttr/)\n * - [`removeClass()`](http://api.jquery.com/removeClass/)\n * - [`removeData()`](http://api.jquery.com/removeData/)\n * - [`replaceWith()`](http://api.jquery.com/replaceWith/)\n * - [`text()`](http://api.jquery.com/text/)\n * - [`toggleClass()`](http://api.jquery.com/toggleClass/)\n * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.\n * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces\n * - [`val()`](http://api.jquery.com/val/)\n * - [`wrap()`](http://api.jquery.com/wrap/)\n *\n * ## jQuery/jqLite Extras\n * Angular also provides the following additional methods and events to both jQuery and jqLite:\n *\n * ### Events\n * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event\n *    on all DOM nodes being removed.  This can be used to clean up any 3rd party bindings to the DOM\n *    element before it is removed.\n *\n * ### Methods\n * - `controller(name)` - retrieves the controller of the current element or its parent. By default\n *   retrieves controller associated with the `ngController` directive. If `name` is provided as\n *   camelCase directive name, then the controller for this directive will be retrieved (e.g.\n *   `'ngModel'`).\n * - `injector()` - retrieves the injector of the current element or its parent.\n * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current\n *   element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to\n *   be enabled.\n * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the\n *   current element. This getter should be used only on elements that contain a directive which starts a new isolate\n *   scope. Calling `scope()` on this element always returns the original non-isolate scope.\n *   Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.\n * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top\n *   parent element is reached.\n *\n * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.\n * @returns {Object} jQuery object.\n */\n\nJQLite.expando = 'ng339';\n\nvar jqCache = JQLite.cache = {},\n    jqId = 1,\n    addEventListenerFn = function(element, type, fn) {\n      element.addEventListener(type, fn, false);\n    },\n    removeEventListenerFn = function(element, type, fn) {\n      element.removeEventListener(type, fn, false);\n    };\n\n/*\n * !!! This is an undocumented \"private\" function !!!\n */\nJQLite._data = function(node) {\n  //jQuery always returns an object on cache miss\n  return this.cache[node[this.expando]] || {};\n};\n\nfunction jqNextId() { return ++jqId; }\n\n\nvar SPECIAL_CHARS_REGEXP = /([\\:\\-\\_]+(.))/g;\nvar MOZ_HACK_REGEXP = /^moz([A-Z])/;\nvar MOUSE_EVENT_MAP= { mouseleave: \"mouseout\", mouseenter: \"mouseover\"};\nvar jqLiteMinErr = minErr('jqLite');\n\n/**\n * Converts snake_case to camelCase.\n * Also there is special case for Moz prefix starting with upper case letter.\n * @param name Name to normalize\n */\nfunction camelCase(name) {\n  return name.\n    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {\n      return offset ? letter.toUpperCase() : letter;\n    }).\n    replace(MOZ_HACK_REGEXP, 'Moz$1');\n}\n\nvar SINGLE_TAG_REGEXP = /^<(\\w+)\\s*\\/?>(?:<\\/\\1>|)$/;\nvar HTML_REGEXP = /<|&#?\\w+;/;\nvar TAG_NAME_REGEXP = /<([\\w:]+)/;\nvar XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:]+)[^>]*)\\/>/gi;\n\nvar wrapMap = {\n  'option': [1, '<select multiple=\"multiple\">', '</select>'],\n\n  'thead': [1, '<table>', '</table>'],\n  'col': [2, '<table><colgroup>', '</colgroup></table>'],\n  'tr': [2, '<table><tbody>', '</tbody></table>'],\n  'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],\n  '_default': [0, \"\", \"\"]\n};\n\nwrapMap.optgroup = wrapMap.option;\nwrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;\nwrapMap.th = wrapMap.td;\n\n\nfunction jqLiteIsTextNode(html) {\n  return !HTML_REGEXP.test(html);\n}\n\nfunction jqLiteAcceptsData(node) {\n  // The window object can accept data but has no nodeType\n  // Otherwise we are only interested in elements (1) and documents (9)\n  var nodeType = node.nodeType;\n  return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;\n}\n\nfunction jqLiteBuildFragment(html, context) {\n  var tmp, tag, wrap,\n      fragment = context.createDocumentFragment(),\n      nodes = [], i;\n\n  if (jqLiteIsTextNode(html)) {\n    // Convert non-html into a text node\n    nodes.push(context.createTextNode(html));\n  } else {\n    // Convert html into DOM nodes\n    tmp = tmp || fragment.appendChild(context.createElement(\"div\"));\n    tag = (TAG_NAME_REGEXP.exec(html) || [\"\", \"\"])[1].toLowerCase();\n    wrap = wrapMap[tag] || wrapMap._default;\n    tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, \"<$1></$2>\") + wrap[2];\n\n    // Descend through wrappers to the right content\n    i = wrap[0];\n    while (i--) {\n      tmp = tmp.lastChild;\n    }\n\n    nodes = concat(nodes, tmp.childNodes);\n\n    tmp = fragment.firstChild;\n    tmp.textContent = \"\";\n  }\n\n  // Remove wrapper from fragment\n  fragment.textContent = \"\";\n  fragment.innerHTML = \"\"; // Clear inner HTML\n  forEach(nodes, function(node) {\n    fragment.appendChild(node);\n  });\n\n  return fragment;\n}\n\nfunction jqLiteParseHTML(html, context) {\n  context = context || document;\n  var parsed;\n\n  if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {\n    return [context.createElement(parsed[1])];\n  }\n\n  if ((parsed = jqLiteBuildFragment(html, context))) {\n    return parsed.childNodes;\n  }\n\n  return [];\n}\n\n/////////////////////////////////////////////\nfunction JQLite(element) {\n  if (element instanceof JQLite) {\n    return element;\n  }\n\n  var argIsString;\n\n  if (isString(element)) {\n    element = trim(element);\n    argIsString = true;\n  }\n  if (!(this instanceof JQLite)) {\n    if (argIsString && element.charAt(0) != '<') {\n      throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');\n    }\n    return new JQLite(element);\n  }\n\n  if (argIsString) {\n    jqLiteAddNodes(this, jqLiteParseHTML(element));\n  } else {\n    jqLiteAddNodes(this, element);\n  }\n}\n\nfunction jqLiteClone(element) {\n  return element.cloneNode(true);\n}\n\nfunction jqLiteDealoc(element, onlyDescendants) {\n  if (!onlyDescendants) jqLiteRemoveData(element);\n\n  if (element.querySelectorAll) {\n    var descendants = element.querySelectorAll('*');\n    for (var i = 0, l = descendants.length; i < l; i++) {\n      jqLiteRemoveData(descendants[i]);\n    }\n  }\n}\n\nfunction jqLiteOff(element, type, fn, unsupported) {\n  if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');\n\n  var expandoStore = jqLiteExpandoStore(element);\n  var events = expandoStore && expandoStore.events;\n  var handle = expandoStore && expandoStore.handle;\n\n  if (!handle) return; //no listeners registered\n\n  if (!type) {\n    for (type in events) {\n      if (type !== '$destroy') {\n        removeEventListenerFn(element, type, handle);\n      }\n      delete events[type];\n    }\n  } else {\n    forEach(type.split(' '), function(type) {\n      if (isDefined(fn)) {\n        var listenerFns = events[type];\n        arrayRemove(listenerFns || [], fn);\n        if (listenerFns && listenerFns.length > 0) {\n          return;\n        }\n      }\n\n      removeEventListenerFn(element, type, handle);\n      delete events[type];\n    });\n  }\n}\n\nfunction jqLiteRemoveData(element, name) {\n  var expandoId = element.ng339;\n  var expandoStore = expandoId && jqCache[expandoId];\n\n  if (expandoStore) {\n    if (name) {\n      delete expandoStore.data[name];\n      return;\n    }\n\n    if (expandoStore.handle) {\n      if (expandoStore.events.$destroy) {\n        expandoStore.handle({}, '$destroy');\n      }\n      jqLiteOff(element);\n    }\n    delete jqCache[expandoId];\n    element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it\n  }\n}\n\n\nfunction jqLiteExpandoStore(element, createIfNecessary) {\n  var expandoId = element.ng339,\n      expandoStore = expandoId && jqCache[expandoId];\n\n  if (createIfNecessary && !expandoStore) {\n    element.ng339 = expandoId = jqNextId();\n    expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};\n  }\n\n  return expandoStore;\n}\n\n\nfunction jqLiteData(element, key, value) {\n  if (jqLiteAcceptsData(element)) {\n\n    var isSimpleSetter = isDefined(value);\n    var isSimpleGetter = !isSimpleSetter && key && !isObject(key);\n    var massGetter = !key;\n    var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);\n    var data = expandoStore && expandoStore.data;\n\n    if (isSimpleSetter) { // data('key', value)\n      data[key] = value;\n    } else {\n      if (massGetter) {  // data()\n        return data;\n      } else {\n        if (isSimpleGetter) { // data('key')\n          // don't force creation of expandoStore if it doesn't exist yet\n          return data && data[key];\n        } else { // mass-setter: data({key1: val1, key2: val2})\n          extend(data, key);\n        }\n      }\n    }\n  }\n}\n\nfunction jqLiteHasClass(element, selector) {\n  if (!element.getAttribute) return false;\n  return ((\" \" + (element.getAttribute('class') || '') + \" \").replace(/[\\n\\t]/g, \" \").\n      indexOf(\" \" + selector + \" \") > -1);\n}\n\nfunction jqLiteRemoveClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    forEach(cssClasses.split(' '), function(cssClass) {\n      element.setAttribute('class', trim(\n          (\" \" + (element.getAttribute('class') || '') + \" \")\n          .replace(/[\\n\\t]/g, \" \")\n          .replace(\" \" + trim(cssClass) + \" \", \" \"))\n      );\n    });\n  }\n}\n\nfunction jqLiteAddClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\n                            .replace(/[\\n\\t]/g, \" \");\n\n    forEach(cssClasses.split(' '), function(cssClass) {\n      cssClass = trim(cssClass);\n      if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\n        existingClasses += cssClass + ' ';\n      }\n    });\n\n    element.setAttribute('class', trim(existingClasses));\n  }\n}\n\n\nfunction jqLiteAddNodes(root, elements) {\n  // THIS CODE IS VERY HOT. Don't make changes without benchmarking.\n\n  if (elements) {\n\n    // if a Node (the most common case)\n    if (elements.nodeType) {\n      root[root.length++] = elements;\n    } else {\n      var length = elements.length;\n\n      // if an Array or NodeList and not a Window\n      if (typeof length === 'number' && elements.window !== elements) {\n        if (length) {\n          for (var i = 0; i < length; i++) {\n            root[root.length++] = elements[i];\n          }\n        }\n      } else {\n        root[root.length++] = elements;\n      }\n    }\n  }\n}\n\n\nfunction jqLiteController(element, name) {\n  return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');\n}\n\nfunction jqLiteInheritedData(element, name, value) {\n  // if element is the document object work with the html element instead\n  // this makes $(document).scope() possible\n  if (element.nodeType == NODE_TYPE_DOCUMENT) {\n    element = element.documentElement;\n  }\n  var names = isArray(name) ? name : [name];\n\n  while (element) {\n    for (var i = 0, ii = names.length; i < ii; i++) {\n      if ((value = jqLite.data(element, names[i])) !== undefined) return value;\n    }\n\n    // If dealing with a document fragment node with a host element, and no parent, use the host\n    // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM\n    // to lookup parent controllers.\n    element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);\n  }\n}\n\nfunction jqLiteEmpty(element) {\n  jqLiteDealoc(element, true);\n  while (element.firstChild) {\n    element.removeChild(element.firstChild);\n  }\n}\n\nfunction jqLiteRemove(element, keepData) {\n  if (!keepData) jqLiteDealoc(element);\n  var parent = element.parentNode;\n  if (parent) parent.removeChild(element);\n}\n\n\nfunction jqLiteDocumentLoaded(action, win) {\n  win = win || window;\n  if (win.document.readyState === 'complete') {\n    // Force the action to be run async for consistent behaviour\n    // from the action's point of view\n    // i.e. it will definitely not be in a $apply\n    win.setTimeout(action);\n  } else {\n    // No need to unbind this handler as load is only ever called once\n    jqLite(win).on('load', action);\n  }\n}\n\n//////////////////////////////////////////\n// Functions which are declared directly.\n//////////////////////////////////////////\nvar JQLitePrototype = JQLite.prototype = {\n  ready: function(fn) {\n    var fired = false;\n\n    function trigger() {\n      if (fired) return;\n      fired = true;\n      fn();\n    }\n\n    // check if document is already loaded\n    if (document.readyState === 'complete') {\n      setTimeout(trigger);\n    } else {\n      this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9\n      // we can not use jqLite since we are not done loading and jQuery could be loaded later.\n      // jshint -W064\n      JQLite(window).on('load', trigger); // fallback to window.onload for others\n      // jshint +W064\n    }\n  },\n  toString: function() {\n    var value = [];\n    forEach(this, function(e) { value.push('' + e);});\n    return '[' + value.join(', ') + ']';\n  },\n\n  eq: function(index) {\n      return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);\n  },\n\n  length: 0,\n  push: push,\n  sort: [].sort,\n  splice: [].splice\n};\n\n//////////////////////////////////////////\n// Functions iterating getter/setters.\n// these functions return self on setter and\n// value on get.\n//////////////////////////////////////////\nvar BOOLEAN_ATTR = {};\nforEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {\n  BOOLEAN_ATTR[lowercase(value)] = value;\n});\nvar BOOLEAN_ELEMENTS = {};\nforEach('input,select,option,textarea,button,form,details'.split(','), function(value) {\n  BOOLEAN_ELEMENTS[value] = true;\n});\nvar ALIASED_ATTR = {\n  'ngMinlength': 'minlength',\n  'ngMaxlength': 'maxlength',\n  'ngMin': 'min',\n  'ngMax': 'max',\n  'ngPattern': 'pattern'\n};\n\nfunction getBooleanAttrName(element, name) {\n  // check dom last since we will most likely fail on name\n  var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];\n\n  // booleanAttr is here twice to minimize DOM access\n  return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;\n}\n\nfunction getAliasedAttrName(element, name) {\n  var nodeName = element.nodeName;\n  return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];\n}\n\nforEach({\n  data: jqLiteData,\n  removeData: jqLiteRemoveData\n}, function(fn, name) {\n  JQLite[name] = fn;\n});\n\nforEach({\n  data: jqLiteData,\n  inheritedData: jqLiteInheritedData,\n\n  scope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);\n  },\n\n  isolateScope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');\n  },\n\n  controller: jqLiteController,\n\n  injector: function(element) {\n    return jqLiteInheritedData(element, '$injector');\n  },\n\n  removeAttr: function(element, name) {\n    element.removeAttribute(name);\n  },\n\n  hasClass: jqLiteHasClass,\n\n  css: function(element, name, value) {\n    name = camelCase(name);\n\n    if (isDefined(value)) {\n      element.style[name] = value;\n    } else {\n      return element.style[name];\n    }\n  },\n\n  attr: function(element, name, value) {\n    var lowercasedName = lowercase(name);\n    if (BOOLEAN_ATTR[lowercasedName]) {\n      if (isDefined(value)) {\n        if (!!value) {\n          element[name] = true;\n          element.setAttribute(name, lowercasedName);\n        } else {\n          element[name] = false;\n          element.removeAttribute(lowercasedName);\n        }\n      } else {\n        return (element[name] ||\n                 (element.attributes.getNamedItem(name) || noop).specified)\n               ? lowercasedName\n               : undefined;\n      }\n    } else if (isDefined(value)) {\n      element.setAttribute(name, value);\n    } else if (element.getAttribute) {\n      // the extra argument \"2\" is to get the right thing for a.href in IE, see jQuery code\n      // some elements (e.g. Document) don't have get attribute, so return undefined\n      var ret = element.getAttribute(name, 2);\n      // normalize non-existing attributes to undefined (as jQuery)\n      return ret === null ? undefined : ret;\n    }\n  },\n\n  prop: function(element, name, value) {\n    if (isDefined(value)) {\n      element[name] = value;\n    } else {\n      return element[name];\n    }\n  },\n\n  text: (function() {\n    getText.$dv = '';\n    return getText;\n\n    function getText(element, value) {\n      if (isUndefined(value)) {\n        var nodeType = element.nodeType;\n        return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';\n      }\n      element.textContent = value;\n    }\n  })(),\n\n  val: function(element, value) {\n    if (isUndefined(value)) {\n      if (element.multiple && nodeName_(element) === 'select') {\n        var result = [];\n        forEach(element.options, function(option) {\n          if (option.selected) {\n            result.push(option.value || option.text);\n          }\n        });\n        return result.length === 0 ? null : result;\n      }\n      return element.value;\n    }\n    element.value = value;\n  },\n\n  html: function(element, value) {\n    if (isUndefined(value)) {\n      return element.innerHTML;\n    }\n    jqLiteDealoc(element, true);\n    element.innerHTML = value;\n  },\n\n  empty: jqLiteEmpty\n}, function(fn, name) {\n  /**\n   * Properties: writes return selection, reads return first value\n   */\n  JQLite.prototype[name] = function(arg1, arg2) {\n    var i, key;\n    var nodeCount = this.length;\n\n    // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it\n    // in a way that survives minification.\n    // jqLiteEmpty takes no arguments but is a setter.\n    if (fn !== jqLiteEmpty &&\n        (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {\n      if (isObject(arg1)) {\n\n        // we are a write, but the object properties are the key/values\n        for (i = 0; i < nodeCount; i++) {\n          if (fn === jqLiteData) {\n            // data() takes the whole object in jQuery\n            fn(this[i], arg1);\n          } else {\n            for (key in arg1) {\n              fn(this[i], key, arg1[key]);\n            }\n          }\n        }\n        // return self for chaining\n        return this;\n      } else {\n        // we are a read, so read the first child.\n        // TODO: do we still need this?\n        var value = fn.$dv;\n        // Only if we have $dv do we iterate over all, otherwise it is just the first element.\n        var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;\n        for (var j = 0; j < jj; j++) {\n          var nodeValue = fn(this[j], arg1, arg2);\n          value = value ? value + nodeValue : nodeValue;\n        }\n        return value;\n      }\n    } else {\n      // we are a write, so apply to all children\n      for (i = 0; i < nodeCount; i++) {\n        fn(this[i], arg1, arg2);\n      }\n      // return self for chaining\n      return this;\n    }\n  };\n});\n\nfunction createEventHandler(element, events) {\n  var eventHandler = function(event, type) {\n    // jQuery specific api\n    event.isDefaultPrevented = function() {\n      return event.defaultPrevented;\n    };\n\n    var eventFns = events[type || event.type];\n    var eventFnsLength = eventFns ? eventFns.length : 0;\n\n    if (!eventFnsLength) return;\n\n    if (isUndefined(event.immediatePropagationStopped)) {\n      var originalStopImmediatePropagation = event.stopImmediatePropagation;\n      event.stopImmediatePropagation = function() {\n        event.immediatePropagationStopped = true;\n\n        if (event.stopPropagation) {\n          event.stopPropagation();\n        }\n\n        if (originalStopImmediatePropagation) {\n          originalStopImmediatePropagation.call(event);\n        }\n      };\n    }\n\n    event.isImmediatePropagationStopped = function() {\n      return event.immediatePropagationStopped === true;\n    };\n\n    // Copy event handlers in case event handlers array is modified during execution.\n    if ((eventFnsLength > 1)) {\n      eventFns = shallowCopy(eventFns);\n    }\n\n    for (var i = 0; i < eventFnsLength; i++) {\n      if (!event.isImmediatePropagationStopped()) {\n        eventFns[i].call(element, event);\n      }\n    }\n  };\n\n  // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all\n  //       events on `element`\n  eventHandler.elem = element;\n  return eventHandler;\n}\n\n//////////////////////////////////////////\n// Functions iterating traversal.\n// These functions chain results into a single\n// selector.\n//////////////////////////////////////////\nforEach({\n  removeData: jqLiteRemoveData,\n\n  on: function jqLiteOn(element, type, fn, unsupported) {\n    if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');\n\n    // Do not add event handlers to non-elements because they will not be cleaned up.\n    if (!jqLiteAcceptsData(element)) {\n      return;\n    }\n\n    var expandoStore = jqLiteExpandoStore(element, true);\n    var events = expandoStore.events;\n    var handle = expandoStore.handle;\n\n    if (!handle) {\n      handle = expandoStore.handle = createEventHandler(element, events);\n    }\n\n    // http://jsperf.com/string-indexof-vs-split\n    var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];\n    var i = types.length;\n\n    while (i--) {\n      type = types[i];\n      var eventFns = events[type];\n\n      if (!eventFns) {\n        events[type] = [];\n\n        if (type === 'mouseenter' || type === 'mouseleave') {\n          // Refer to jQuery's implementation of mouseenter & mouseleave\n          // Read about mouseenter and mouseleave:\n          // http://www.quirksmode.org/js/events_mouse.html#link8\n\n          jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {\n            var target = this, related = event.relatedTarget;\n            // For mousenter/leave call the handler if related is outside the target.\n            // NB: No relatedTarget if the mouse left/entered the browser window\n            if (!related || (related !== target && !target.contains(related))) {\n              handle(event, type);\n            }\n          });\n\n        } else {\n          if (type !== '$destroy') {\n            addEventListenerFn(element, type, handle);\n          }\n        }\n        eventFns = events[type];\n      }\n      eventFns.push(fn);\n    }\n  },\n\n  off: jqLiteOff,\n\n  one: function(element, type, fn) {\n    element = jqLite(element);\n\n    //add the listener twice so that when it is called\n    //you can remove the original function and still be\n    //able to call element.off(ev, fn) normally\n    element.on(type, function onFn() {\n      element.off(type, fn);\n      element.off(type, onFn);\n    });\n    element.on(type, fn);\n  },\n\n  replaceWith: function(element, replaceNode) {\n    var index, parent = element.parentNode;\n    jqLiteDealoc(element);\n    forEach(new JQLite(replaceNode), function(node) {\n      if (index) {\n        parent.insertBefore(node, index.nextSibling);\n      } else {\n        parent.replaceChild(node, element);\n      }\n      index = node;\n    });\n  },\n\n  children: function(element) {\n    var children = [];\n    forEach(element.childNodes, function(element) {\n      if (element.nodeType === NODE_TYPE_ELEMENT)\n        children.push(element);\n    });\n    return children;\n  },\n\n  contents: function(element) {\n    return element.contentDocument || element.childNodes || [];\n  },\n\n  append: function(element, node) {\n    var nodeType = element.nodeType;\n    if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;\n\n    node = new JQLite(node);\n\n    for (var i = 0, ii = node.length; i < ii; i++) {\n      var child = node[i];\n      element.appendChild(child);\n    }\n  },\n\n  prepend: function(element, node) {\n    if (element.nodeType === NODE_TYPE_ELEMENT) {\n      var index = element.firstChild;\n      forEach(new JQLite(node), function(child) {\n        element.insertBefore(child, index);\n      });\n    }\n  },\n\n  wrap: function(element, wrapNode) {\n    wrapNode = jqLite(wrapNode).eq(0).clone()[0];\n    var parent = element.parentNode;\n    if (parent) {\n      parent.replaceChild(wrapNode, element);\n    }\n    wrapNode.appendChild(element);\n  },\n\n  remove: jqLiteRemove,\n\n  detach: function(element) {\n    jqLiteRemove(element, true);\n  },\n\n  after: function(element, newElement) {\n    var index = element, parent = element.parentNode;\n    newElement = new JQLite(newElement);\n\n    for (var i = 0, ii = newElement.length; i < ii; i++) {\n      var node = newElement[i];\n      parent.insertBefore(node, index.nextSibling);\n      index = node;\n    }\n  },\n\n  addClass: jqLiteAddClass,\n  removeClass: jqLiteRemoveClass,\n\n  toggleClass: function(element, selector, condition) {\n    if (selector) {\n      forEach(selector.split(' '), function(className) {\n        var classCondition = condition;\n        if (isUndefined(classCondition)) {\n          classCondition = !jqLiteHasClass(element, className);\n        }\n        (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);\n      });\n    }\n  },\n\n  parent: function(element) {\n    var parent = element.parentNode;\n    return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;\n  },\n\n  next: function(element) {\n    return element.nextElementSibling;\n  },\n\n  find: function(element, selector) {\n    if (element.getElementsByTagName) {\n      return element.getElementsByTagName(selector);\n    } else {\n      return [];\n    }\n  },\n\n  clone: jqLiteClone,\n\n  triggerHandler: function(element, event, extraParameters) {\n\n    var dummyEvent, eventFnsCopy, handlerArgs;\n    var eventName = event.type || event;\n    var expandoStore = jqLiteExpandoStore(element);\n    var events = expandoStore && expandoStore.events;\n    var eventFns = events && events[eventName];\n\n    if (eventFns) {\n      // Create a dummy event to pass to the handlers\n      dummyEvent = {\n        preventDefault: function() { this.defaultPrevented = true; },\n        isDefaultPrevented: function() { return this.defaultPrevented === true; },\n        stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },\n        isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },\n        stopPropagation: noop,\n        type: eventName,\n        target: element\n      };\n\n      // If a custom event was provided then extend our dummy event with it\n      if (event.type) {\n        dummyEvent = extend(dummyEvent, event);\n      }\n\n      // Copy event handlers in case event handlers array is modified during execution.\n      eventFnsCopy = shallowCopy(eventFns);\n      handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];\n\n      forEach(eventFnsCopy, function(fn) {\n        if (!dummyEvent.isImmediatePropagationStopped()) {\n          fn.apply(element, handlerArgs);\n        }\n      });\n    }\n  }\n}, function(fn, name) {\n  /**\n   * chaining functions\n   */\n  JQLite.prototype[name] = function(arg1, arg2, arg3) {\n    var value;\n\n    for (var i = 0, ii = this.length; i < ii; i++) {\n      if (isUndefined(value)) {\n        value = fn(this[i], arg1, arg2, arg3);\n        if (isDefined(value)) {\n          // any function which returns a value needs to be wrapped\n          value = jqLite(value);\n        }\n      } else {\n        jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));\n      }\n    }\n    return isDefined(value) ? value : this;\n  };\n\n  // bind legacy bind/unbind to on/off\n  JQLite.prototype.bind = JQLite.prototype.on;\n  JQLite.prototype.unbind = JQLite.prototype.off;\n});\n\n\n// Provider for private $$jqLite service\nfunction $$jqLiteProvider() {\n  this.$get = function $$jqLite() {\n    return extend(JQLite, {\n      hasClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteHasClass(node, classes);\n      },\n      addClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteAddClass(node, classes);\n      },\n      removeClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteRemoveClass(node, classes);\n      }\n    });\n  };\n}\n\n/**\n * Computes a hash of an 'obj'.\n * Hash of a:\n *  string is string\n *  number is number as string\n *  object is either result of calling $$hashKey function on the object or uniquely generated id,\n *         that is also assigned to the $$hashKey property of the object.\n *\n * @param obj\n * @returns {string} hash string such that the same input will have the same hash string.\n *         The resulting string key is in 'type:hashKey' format.\n */\nfunction hashKey(obj, nextUidFn) {\n  var key = obj && obj.$$hashKey;\n\n  if (key) {\n    if (typeof key === 'function') {\n      key = obj.$$hashKey();\n    }\n    return key;\n  }\n\n  var objType = typeof obj;\n  if (objType == 'function' || (objType == 'object' && obj !== null)) {\n    key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();\n  } else {\n    key = objType + ':' + obj;\n  }\n\n  return key;\n}\n\n/**\n * HashMap which can use objects as keys\n */\nfunction HashMap(array, isolatedUid) {\n  if (isolatedUid) {\n    var uid = 0;\n    this.nextUid = function() {\n      return ++uid;\n    };\n  }\n  forEach(array, this.put, this);\n}\nHashMap.prototype = {\n  /**\n   * Store key value pair\n   * @param key key to store can be any type\n   * @param value value to store can be any type\n   */\n  put: function(key, value) {\n    this[hashKey(key, this.nextUid)] = value;\n  },\n\n  /**\n   * @param key\n   * @returns {Object} the value for the key\n   */\n  get: function(key) {\n    return this[hashKey(key, this.nextUid)];\n  },\n\n  /**\n   * Remove the key/value pair\n   * @param key\n   */\n  remove: function(key) {\n    var value = this[key = hashKey(key, this.nextUid)];\n    delete this[key];\n    return value;\n  }\n};\n\n/**\n * @ngdoc function\n * @module ng\n * @name angular.injector\n * @kind function\n *\n * @description\n * Creates an injector object that can be used for retrieving services as well as for\n * dependency injection (see {@link guide/di dependency injection}).\n *\n * @param {Array.<string|Function>} modules A list of module functions or their aliases. See\n *     {@link angular.module}. The `ng` module must be explicitly added.\n * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which\n *     disallows argument name annotation inference.\n * @returns {injector} Injector object. See {@link auto.$injector $injector}.\n *\n * @example\n * Typical usage\n * ```js\n *   // create an injector\n *   var $injector = angular.injector(['ng']);\n *\n *   // use the injector to kick off your application\n *   // use the type inference to auto inject arguments, or use implicit injection\n *   $injector.invoke(function($rootScope, $compile, $document) {\n *     $compile($document)($rootScope);\n *     $rootScope.$digest();\n *   });\n * ```\n *\n * Sometimes you want to get access to the injector of a currently running Angular app\n * from outside Angular. Perhaps, you want to inject and compile some markup after the\n * application has been bootstrapped. You can do this using the extra `injector()` added\n * to JQuery/jqLite elements. See {@link angular.element}.\n *\n * *This is fairly rare but could be the case if a third party library is injecting the\n * markup.*\n *\n * In the following example a new block of HTML containing a `ng-controller`\n * directive is added to the end of the document body by JQuery. We then compile and link\n * it into the current AngularJS scope.\n *\n * ```js\n * var $div = $('<div ng-controller=\"MyCtrl\">{{content.label}}</div>');\n * $(document.body).append($div);\n *\n * angular.element(document).injector().invoke(function($compile) {\n *   var scope = angular.element($div).scope();\n *   $compile($div)(scope);\n * });\n * ```\n */\n\n\n/**\n * @ngdoc module\n * @name auto\n * @description\n *\n * Implicit module which gets automatically added to each {@link auto.$injector $injector}.\n */\n\nvar FN_ARGS = /^function\\s*[^\\(]*\\(\\s*([^\\)]*)\\)/m;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nvar $injectorMinErr = minErr('$injector');\n\nfunction anonFn(fn) {\n  // For anonymous functions, showing at the very least the function signature can help in\n  // debugging.\n  var fnText = fn.toString().replace(STRIP_COMMENTS, ''),\n      args = fnText.match(FN_ARGS);\n  if (args) {\n    return 'function(' + (args[1] || '').replace(/[\\s\\r\\n]+/, ' ') + ')';\n  }\n  return 'fn';\n}\n\nfunction annotate(fn, strictDi, name) {\n  var $inject,\n      fnText,\n      argDecl,\n      last;\n\n  if (typeof fn === 'function') {\n    if (!($inject = fn.$inject)) {\n      $inject = [];\n      if (fn.length) {\n        if (strictDi) {\n          if (!isString(name) || !name) {\n            name = fn.name || anonFn(fn);\n          }\n          throw $injectorMinErr('strictdi',\n            '{0} is not using explicit annotation and cannot be invoked in strict mode', name);\n        }\n        fnText = fn.toString().replace(STRIP_COMMENTS, '');\n        argDecl = fnText.match(FN_ARGS);\n        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n          arg.replace(FN_ARG, function(all, underscore, name) {\n            $inject.push(name);\n          });\n        });\n      }\n      fn.$inject = $inject;\n    }\n  } else if (isArray(fn)) {\n    last = fn.length - 1;\n    assertArgFn(fn[last], 'fn');\n    $inject = fn.slice(0, last);\n  } else {\n    assertArgFn(fn, 'fn', true);\n  }\n  return $inject;\n}\n\n///////////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $injector\n *\n * @description\n *\n * `$injector` is used to retrieve object instances as defined by\n * {@link auto.$provide provider}, instantiate types, invoke methods,\n * and load modules.\n *\n * The following always holds true:\n *\n * ```js\n *   var $injector = angular.injector();\n *   expect($injector.get('$injector')).toBe($injector);\n *   expect($injector.invoke(function($injector) {\n *     return $injector;\n *   })).toBe($injector);\n * ```\n *\n * # Injection Function Annotation\n *\n * JavaScript does not have annotations, and annotations are needed for dependency injection. The\n * following are all valid ways of annotating function with injection arguments and are equivalent.\n *\n * ```js\n *   // inferred (only works if code not minified/obfuscated)\n *   $injector.invoke(function(serviceA){});\n *\n *   // annotated\n *   function explicit(serviceA) {};\n *   explicit.$inject = ['serviceA'];\n *   $injector.invoke(explicit);\n *\n *   // inline\n *   $injector.invoke(['serviceA', function(serviceA){}]);\n * ```\n *\n * ## Inference\n *\n * In JavaScript calling `toString()` on a function returns the function definition. The definition\n * can then be parsed and the function arguments can be extracted. This method of discovering\n * annotations is disallowed when the injector is in strict mode.\n * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the\n * argument names.\n *\n * ## `$inject` Annotation\n * By adding an `$inject` property onto a function the injection parameters can be specified.\n *\n * ## Inline\n * As an array of injection names, where the last item in the array is the function to call.\n */\n\n/**\n * @ngdoc method\n * @name $injector#get\n *\n * @description\n * Return an instance of the service.\n *\n * @param {string} name The name of the instance to retrieve.\n * @param {string} caller An optional string to provide the origin of the function call for error messages.\n * @return {*} The instance.\n */\n\n/**\n * @ngdoc method\n * @name $injector#invoke\n *\n * @description\n * Invoke the method and supply the method arguments from the `$injector`.\n *\n * @param {!Function} fn The function to invoke. Function parameters are injected according to the\n *   {@link guide/di $inject Annotation} rules.\n * @param {Object=} self The `this` for the invoked method.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n *                         object first, before the `$injector` is consulted.\n * @returns {*} the value returned by the invoked `fn` function.\n */\n\n/**\n * @ngdoc method\n * @name $injector#has\n *\n * @description\n * Allows the user to query if the particular service exists.\n *\n * @param {string} name Name of the service to query.\n * @returns {boolean} `true` if injector has given service.\n */\n\n/**\n * @ngdoc method\n * @name $injector#instantiate\n * @description\n * Create a new instance of JS type. The method takes a constructor function, invokes the new\n * operator, and supplies all of the arguments to the constructor function as specified by the\n * constructor annotation.\n *\n * @param {Function} Type Annotated constructor function.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {Object} new instance of `Type`.\n */\n\n/**\n * @ngdoc method\n * @name $injector#annotate\n *\n * @description\n * Returns an array of service names which the function is requesting for injection. This API is\n * used by the injector to determine which services need to be injected into the function when the\n * function is invoked. There are three ways in which the function can be annotated with the needed\n * dependencies.\n *\n * # Argument names\n *\n * The simplest form is to extract the dependencies from the arguments of the function. This is done\n * by converting the function into a string using `toString()` method and extracting the argument\n * names.\n * ```js\n *   // Given\n *   function MyController($scope, $route) {\n *     // ...\n *   }\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * You can disallow this method by using strict injection mode.\n *\n * This method does not work with code minification / obfuscation. For this reason the following\n * annotation strategies are supported.\n *\n * # The `$inject` property\n *\n * If a function has an `$inject` property and its value is an array of strings, then the strings\n * represent names of services to be injected into the function.\n * ```js\n *   // Given\n *   var MyController = function(obfuscatedScope, obfuscatedRoute) {\n *     // ...\n *   }\n *   // Define function dependencies\n *   MyController['$inject'] = ['$scope', '$route'];\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * # The array notation\n *\n * It is often desirable to inline Injected functions and that's when setting the `$inject` property\n * is very inconvenient. In these situations using the array notation to specify the dependencies in\n * a way that survives minification is a better choice:\n *\n * ```js\n *   // We wish to write this (not minification / obfuscation safe)\n *   injector.invoke(function($compile, $rootScope) {\n *     // ...\n *   });\n *\n *   // We are forced to write break inlining\n *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {\n *     // ...\n *   };\n *   tmpFn.$inject = ['$compile', '$rootScope'];\n *   injector.invoke(tmpFn);\n *\n *   // To better support inline function the inline annotation is supported\n *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {\n *     // ...\n *   }]);\n *\n *   // Therefore\n *   expect(injector.annotate(\n *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])\n *    ).toEqual(['$compile', '$rootScope']);\n * ```\n *\n * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to\n * be retrieved as described above.\n *\n * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.\n *\n * @returns {Array.<string>} The names of the services which the function requires.\n */\n\n\n\n\n/**\n * @ngdoc service\n * @name $provide\n *\n * @description\n *\n * The {@link auto.$provide $provide} service has a number of methods for registering components\n * with the {@link auto.$injector $injector}. Many of these functions are also exposed on\n * {@link angular.Module}.\n *\n * An Angular **service** is a singleton object created by a **service factory**.  These **service\n * factories** are functions which, in turn, are created by a **service provider**.\n * The **service providers** are constructor functions. When instantiated they must contain a\n * property called `$get`, which holds the **service factory** function.\n *\n * When you request a service, the {@link auto.$injector $injector} is responsible for finding the\n * correct **service provider**, instantiating it and then calling its `$get` **service factory**\n * function to get the instance of the **service**.\n *\n * Often services have no configuration options and there is no need to add methods to the service\n * provider.  The provider will be no more than a constructor function with a `$get` property. For\n * these cases the {@link auto.$provide $provide} service has additional helper methods to register\n * services without specifying a provider.\n *\n * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the\n *     {@link auto.$injector $injector}\n * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by\n *     providers and services.\n * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by\n *     services, not providers.\n * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,\n *     that will be wrapped in a **service provider** object, whose `$get` property will contain the\n *     given factory function.\n * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`\n *     that will be wrapped in a **service provider** object, whose `$get` property will instantiate\n *      a new object using the given constructor function.\n *\n * See the individual methods for more information and examples.\n */\n\n/**\n * @ngdoc method\n * @name $provide#provider\n * @description\n *\n * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions\n * are constructor functions, whose instances are responsible for \"providing\" a factory for a\n * service.\n *\n * Service provider names start with the name of the service they provide followed by `Provider`.\n * For example, the {@link ng.$log $log} service has a provider called\n * {@link ng.$logProvider $logProvider}.\n *\n * Service provider objects can have additional methods which allow configuration of the provider\n * and its service. Importantly, you can configure what kind of service is created by the `$get`\n * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a\n * method {@link ng.$logProvider#debugEnabled debugEnabled}\n * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the\n * console or not.\n *\n * @param {string} name The name of the instance. NOTE: the provider will be available under `name +\n                        'Provider'` key.\n * @param {(Object|function())} provider If the provider is:\n *\n *   - `Object`: then it should have a `$get` method. The `$get` method will be invoked using\n *     {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.\n *   - `Constructor`: a new instance of the provider will be created using\n *     {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.\n *\n * @returns {Object} registered provider instance\n\n * @example\n *\n * The following example shows how to create a simple event tracking service and register it using\n * {@link auto.$provide#provider $provide.provider()}.\n *\n * ```js\n *  // Define the eventTracker provider\n *  function EventTrackerProvider() {\n *    var trackingUrl = '/track';\n *\n *    // A provider method for configuring where the tracked events should been saved\n *    this.setTrackingUrl = function(url) {\n *      trackingUrl = url;\n *    };\n *\n *    // The service factory function\n *    this.$get = ['$http', function($http) {\n *      var trackedEvents = {};\n *      return {\n *        // Call this to track an event\n *        event: function(event) {\n *          var count = trackedEvents[event] || 0;\n *          count += 1;\n *          trackedEvents[event] = count;\n *          return count;\n *        },\n *        // Call this to save the tracked events to the trackingUrl\n *        save: function() {\n *          $http.post(trackingUrl, trackedEvents);\n *        }\n *      };\n *    }];\n *  }\n *\n *  describe('eventTracker', function() {\n *    var postSpy;\n *\n *    beforeEach(module(function($provide) {\n *      // Register the eventTracker provider\n *      $provide.provider('eventTracker', EventTrackerProvider);\n *    }));\n *\n *    beforeEach(module(function(eventTrackerProvider) {\n *      // Configure eventTracker provider\n *      eventTrackerProvider.setTrackingUrl('/custom-track');\n *    }));\n *\n *    it('tracks events', inject(function(eventTracker) {\n *      expect(eventTracker.event('login')).toEqual(1);\n *      expect(eventTracker.event('login')).toEqual(2);\n *    }));\n *\n *    it('saves to the tracking url', inject(function(eventTracker, $http) {\n *      postSpy = spyOn($http, 'post');\n *      eventTracker.event('login');\n *      eventTracker.save();\n *      expect(postSpy).toHaveBeenCalled();\n *      expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');\n *      expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');\n *      expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });\n *    }));\n *  });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $provide#factory\n * @description\n *\n * Register a **service factory**, which will be called to return the service instance.\n * This is short for registering a service where its provider consists of only a `$get` property,\n * which is the given service factory function.\n * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to\n * configure your service in a provider.\n *\n * @param {string} name The name of the instance.\n * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand\n *                            for `$provide.provider(name, {$get: $getFn})`.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service\n * ```js\n *   $provide.factory('ping', ['$http', function($http) {\n *     return function ping() {\n *       return $http.send('/ping');\n *     };\n *   }]);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#service\n * @description\n *\n * Register a **service constructor**, which will be invoked with `new` to create the service\n * instance.\n * This is short for registering a service where its provider's `$get` property is the service\n * constructor function that will be used to instantiate the service instance.\n *\n * You should use {@link auto.$provide#service $provide.service(class)} if you define your service\n * as a type/class.\n *\n * @param {string} name The name of the instance.\n * @param {Function} constructor A class (constructor function) that will be instantiated.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service using\n * {@link auto.$provide#service $provide.service(class)}.\n * ```js\n *   var Ping = function($http) {\n *     this.$http = $http;\n *   };\n *\n *   Ping.$inject = ['$http'];\n *\n *   Ping.prototype.send = function() {\n *     return this.$http.get('/ping');\n *   };\n *   $provide.service('ping', Ping);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping.send();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#value\n * @description\n *\n * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a\n * number, an array, an object or a function.  This is short for registering a service where its\n * provider's `$get` property is a factory function that takes no arguments and returns the **value\n * service**.\n *\n * Value services are similar to constant services, except that they cannot be injected into a\n * module configuration function (see {@link angular.Module#config}) but they can be overridden by\n * an Angular\n * {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the instance.\n * @param {*} value The value.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here are some examples of creating value services.\n * ```js\n *   $provide.value('ADMIN_USER', 'admin');\n *\n *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });\n *\n *   $provide.value('halfOf', function(value) {\n *     return value / 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#constant\n * @description\n *\n * Register a **constant service**, such as a string, a number, an array, an object or a function,\n * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be\n * injected into a module configuration function (see {@link angular.Module#config}) and it cannot\n * be overridden by an Angular {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the constant.\n * @param {*} value The constant value.\n * @returns {Object} registered instance\n *\n * @example\n * Here a some examples of creating constants:\n * ```js\n *   $provide.constant('SHARD_HEIGHT', 306);\n *\n *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);\n *\n *   $provide.constant('double', function(value) {\n *     return value * 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#decorator\n * @description\n *\n * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator\n * intercepts the creation of a service, allowing it to override or modify the behaviour of the\n * service. The object returned by the decorator may be the original service, or a new service\n * object which replaces or wraps and delegates to the original service.\n *\n * @param {string} name The name of the service to decorate.\n * @param {function()} decorator This function will be invoked when the service needs to be\n *    instantiated and should return the decorated service instance. The function is called using\n *    the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.\n *    Local injection arguments:\n *\n *    * `$delegate` - The original service instance, which can be monkey patched, configured,\n *      decorated or delegated to.\n *\n * @example\n * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting\n * calls to {@link ng.$log#error $log.warn()}.\n * ```js\n *   $provide.decorator('$log', ['$delegate', function($delegate) {\n *     $delegate.warn = $delegate.error;\n *     return $delegate;\n *   }]);\n * ```\n */\n\n\nfunction createInjector(modulesToLoad, strictDi) {\n  strictDi = (strictDi === true);\n  var INSTANTIATING = {},\n      providerSuffix = 'Provider',\n      path = [],\n      loadedModules = new HashMap([], true),\n      providerCache = {\n        $provide: {\n            provider: supportObject(provider),\n            factory: supportObject(factory),\n            service: supportObject(service),\n            value: supportObject(value),\n            constant: supportObject(constant),\n            decorator: decorator\n          }\n      },\n      providerInjector = (providerCache.$injector =\n          createInternalInjector(providerCache, function(serviceName, caller) {\n            if (angular.isString(caller)) {\n              path.push(caller);\n            }\n            throw $injectorMinErr('unpr', \"Unknown provider: {0}\", path.join(' <- '));\n          })),\n      instanceCache = {},\n      instanceInjector = (instanceCache.$injector =\n          createInternalInjector(instanceCache, function(serviceName, caller) {\n            var provider = providerInjector.get(serviceName + providerSuffix, caller);\n            return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);\n          }));\n\n\n  forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });\n\n  return instanceInjector;\n\n  ////////////////////////////////////\n  // $provider\n  ////////////////////////////////////\n\n  function supportObject(delegate) {\n    return function(key, value) {\n      if (isObject(key)) {\n        forEach(key, reverseParams(delegate));\n      } else {\n        return delegate(key, value);\n      }\n    };\n  }\n\n  function provider(name, provider_) {\n    assertNotHasOwnProperty(name, 'service');\n    if (isFunction(provider_) || isArray(provider_)) {\n      provider_ = providerInjector.instantiate(provider_);\n    }\n    if (!provider_.$get) {\n      throw $injectorMinErr('pget', \"Provider '{0}' must define $get factory method.\", name);\n    }\n    return providerCache[name + providerSuffix] = provider_;\n  }\n\n  function enforceReturnValue(name, factory) {\n    return function enforcedReturnValue() {\n      var result = instanceInjector.invoke(factory, this);\n      if (isUndefined(result)) {\n        throw $injectorMinErr('undef', \"Provider '{0}' must return a value from $get factory method.\", name);\n      }\n      return result;\n    };\n  }\n\n  function factory(name, factoryFn, enforce) {\n    return provider(name, {\n      $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn\n    });\n  }\n\n  function service(name, constructor) {\n    return factory(name, ['$injector', function($injector) {\n      return $injector.instantiate(constructor);\n    }]);\n  }\n\n  function value(name, val) { return factory(name, valueFn(val), false); }\n\n  function constant(name, value) {\n    assertNotHasOwnProperty(name, 'constant');\n    providerCache[name] = value;\n    instanceCache[name] = value;\n  }\n\n  function decorator(serviceName, decorFn) {\n    var origProvider = providerInjector.get(serviceName + providerSuffix),\n        orig$get = origProvider.$get;\n\n    origProvider.$get = function() {\n      var origInstance = instanceInjector.invoke(orig$get, origProvider);\n      return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});\n    };\n  }\n\n  ////////////////////////////////////\n  // Module Loading\n  ////////////////////////////////////\n  function loadModules(modulesToLoad) {\n    var runBlocks = [], moduleFn;\n    forEach(modulesToLoad, function(module) {\n      if (loadedModules.get(module)) return;\n      loadedModules.put(module, true);\n\n      function runInvokeQueue(queue) {\n        var i, ii;\n        for (i = 0, ii = queue.length; i < ii; i++) {\n          var invokeArgs = queue[i],\n              provider = providerInjector.get(invokeArgs[0]);\n\n          provider[invokeArgs[1]].apply(provider, invokeArgs[2]);\n        }\n      }\n\n      try {\n        if (isString(module)) {\n          moduleFn = angularModule(module);\n          runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);\n          runInvokeQueue(moduleFn._invokeQueue);\n          runInvokeQueue(moduleFn._configBlocks);\n        } else if (isFunction(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else if (isArray(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else {\n          assertArgFn(module, 'module');\n        }\n      } catch (e) {\n        if (isArray(module)) {\n          module = module[module.length - 1];\n        }\n        if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {\n          // Safari & FF's stack traces don't contain error.message content\n          // unlike those of Chrome and IE\n          // So if stack doesn't contain message, we create a new string that contains both.\n          // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.\n          /* jshint -W022 */\n          e = e.message + '\\n' + e.stack;\n        }\n        throw $injectorMinErr('modulerr', \"Failed to instantiate module {0} due to:\\n{1}\",\n                  module, e.stack || e.message || e);\n      }\n    });\n    return runBlocks;\n  }\n\n  ////////////////////////////////////\n  // internal Injector\n  ////////////////////////////////////\n\n  function createInternalInjector(cache, factory) {\n\n    function getService(serviceName, caller) {\n      if (cache.hasOwnProperty(serviceName)) {\n        if (cache[serviceName] === INSTANTIATING) {\n          throw $injectorMinErr('cdep', 'Circular dependency found: {0}',\n                    serviceName + ' <- ' + path.join(' <- '));\n        }\n        return cache[serviceName];\n      } else {\n        try {\n          path.unshift(serviceName);\n          cache[serviceName] = INSTANTIATING;\n          return cache[serviceName] = factory(serviceName, caller);\n        } catch (err) {\n          if (cache[serviceName] === INSTANTIATING) {\n            delete cache[serviceName];\n          }\n          throw err;\n        } finally {\n          path.shift();\n        }\n      }\n    }\n\n    function invoke(fn, self, locals, serviceName) {\n      if (typeof locals === 'string') {\n        serviceName = locals;\n        locals = null;\n      }\n\n      var args = [],\n          $inject = createInjector.$$annotate(fn, strictDi, serviceName),\n          length, i,\n          key;\n\n      for (i = 0, length = $inject.length; i < length; i++) {\n        key = $inject[i];\n        if (typeof key !== 'string') {\n          throw $injectorMinErr('itkn',\n                  'Incorrect injection token! Expected service name as string, got {0}', key);\n        }\n        args.push(\n          locals && locals.hasOwnProperty(key)\n          ? locals[key]\n          : getService(key, serviceName)\n        );\n      }\n      if (isArray(fn)) {\n        fn = fn[length];\n      }\n\n      // http://jsperf.com/angularjs-invoke-apply-vs-switch\n      // #5388\n      return fn.apply(self, args);\n    }\n\n    function instantiate(Type, locals, serviceName) {\n      // Check if Type is annotated and use just the given function at n-1 as parameter\n      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);\n      // Object creation: http://jsperf.com/create-constructor/2\n      var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);\n      var returnedValue = invoke(Type, instance, locals, serviceName);\n\n      return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;\n    }\n\n    return {\n      invoke: invoke,\n      instantiate: instantiate,\n      get: getService,\n      annotate: createInjector.$$annotate,\n      has: function(name) {\n        return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);\n      }\n    };\n  }\n}\n\ncreateInjector.$$annotate = annotate;\n\n/**\n * @ngdoc provider\n * @name $anchorScrollProvider\n *\n * @description\n * Use `$anchorScrollProvider` to disable automatic scrolling whenever\n * {@link ng.$location#hash $location.hash()} changes.\n */\nfunction $AnchorScrollProvider() {\n\n  var autoScrollingEnabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $anchorScrollProvider#disableAutoScrolling\n   *\n   * @description\n   * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to\n   * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />\n   * Use this method to disable automatic scrolling.\n   *\n   * If automatic scrolling is disabled, one must explicitly call\n   * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the\n   * current hash.\n   */\n  this.disableAutoScrolling = function() {\n    autoScrollingEnabled = false;\n  };\n\n  /**\n   * @ngdoc service\n   * @name $anchorScroll\n   * @kind function\n   * @requires $window\n   * @requires $location\n   * @requires $rootScope\n   *\n   * @description\n   * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and\n   * scrolls to the related element, according to the rules specified in the\n   * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).\n   *\n   * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to\n   * match any anchor whenever it changes. This can be disabled by calling\n   * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.\n   *\n   * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a\n   * vertical scroll-offset (either fixed or dynamic).\n   *\n   * @property {(number|function|jqLite)} yOffset\n   * If set, specifies a vertical scroll-offset. This is often useful when there are fixed\n   * positioned elements at the top of the page, such as navbars, headers etc.\n   *\n   * `yOffset` can be specified in various ways:\n   * - **number**: A fixed number of pixels to be used as offset.<br /><br />\n   * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return\n   *   a number representing the offset (in pixels).<br /><br />\n   * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from\n   *   the top of the page to the element's bottom will be used as offset.<br />\n   *   **Note**: The element will be taken into account only as long as its `position` is set to\n   *   `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust\n   *   their height and/or positioning according to the viewport's size.\n   *\n   * <br />\n   * <div class=\"alert alert-warning\">\n   * In order for `yOffset` to work properly, scrolling should take place on the document's root and\n   * not some child element.\n   * </div>\n   *\n   * @example\n     <example module=\"anchorScrollExample\">\n       <file name=\"index.html\">\n         <div id=\"scrollArea\" ng-controller=\"ScrollController\">\n           <a ng-click=\"gotoBottom()\">Go to bottom</a>\n           <a id=\"bottom\"></a> You're at the bottom!\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollExample', [])\n           .controller('ScrollController', ['$scope', '$location', '$anchorScroll',\n             function ($scope, $location, $anchorScroll) {\n               $scope.gotoBottom = function() {\n                 // set the location.hash to the id of\n                 // the element you wish to scroll to.\n                 $location.hash('bottom');\n\n                 // call $anchorScroll()\n                 $anchorScroll();\n               };\n             }]);\n       </file>\n       <file name=\"style.css\">\n         #scrollArea {\n           height: 280px;\n           overflow: auto;\n         }\n\n         #bottom {\n           display: block;\n           margin-top: 2000px;\n         }\n       </file>\n     </example>\n   *\n   * <hr />\n   * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).\n   * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.\n   *\n   * @example\n     <example module=\"anchorScrollOffsetExample\">\n       <file name=\"index.html\">\n         <div class=\"fixed-header\" ng-controller=\"headerCtrl\">\n           <a href=\"\" ng-click=\"gotoAnchor(x)\" ng-repeat=\"x in [1,2,3,4,5]\">\n             Go to anchor {{x}}\n           </a>\n         </div>\n         <div id=\"anchor{{x}}\" class=\"anchor\" ng-repeat=\"x in [1,2,3,4,5]\">\n           Anchor {{x}} of 5\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollOffsetExample', [])\n           .run(['$anchorScroll', function($anchorScroll) {\n             $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels\n           }])\n           .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',\n             function ($anchorScroll, $location, $scope) {\n               $scope.gotoAnchor = function(x) {\n                 var newHash = 'anchor' + x;\n                 if ($location.hash() !== newHash) {\n                   // set the $location.hash to `newHash` and\n                   // $anchorScroll will automatically scroll to it\n                   $location.hash('anchor' + x);\n                 } else {\n                   // call $anchorScroll() explicitly,\n                   // since $location.hash hasn't changed\n                   $anchorScroll();\n                 }\n               };\n             }\n           ]);\n       </file>\n       <file name=\"style.css\">\n         body {\n           padding-top: 50px;\n         }\n\n         .anchor {\n           border: 2px dashed DarkOrchid;\n           padding: 10px 10px 200px 10px;\n         }\n\n         .fixed-header {\n           background-color: rgba(0, 0, 0, 0.2);\n           height: 50px;\n           position: fixed;\n           top: 0; left: 0; right: 0;\n         }\n\n         .fixed-header > a {\n           display: inline-block;\n           margin: 5px 15px;\n         }\n       </file>\n     </example>\n   */\n  this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {\n    var document = $window.document;\n\n    // Helper function to get first anchor from a NodeList\n    // (using `Array#some()` instead of `angular#forEach()` since it's more performant\n    //  and working in all supported browsers.)\n    function getFirstAnchor(list) {\n      var result = null;\n      Array.prototype.some.call(list, function(element) {\n        if (nodeName_(element) === 'a') {\n          result = element;\n          return true;\n        }\n      });\n      return result;\n    }\n\n    function getYOffset() {\n\n      var offset = scroll.yOffset;\n\n      if (isFunction(offset)) {\n        offset = offset();\n      } else if (isElement(offset)) {\n        var elem = offset[0];\n        var style = $window.getComputedStyle(elem);\n        if (style.position !== 'fixed') {\n          offset = 0;\n        } else {\n          offset = elem.getBoundingClientRect().bottom;\n        }\n      } else if (!isNumber(offset)) {\n        offset = 0;\n      }\n\n      return offset;\n    }\n\n    function scrollTo(elem) {\n      if (elem) {\n        elem.scrollIntoView();\n\n        var offset = getYOffset();\n\n        if (offset) {\n          // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.\n          // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the\n          // top of the viewport.\n          //\n          // IF the number of pixels from the top of `elem` to the end of the page's content is less\n          // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some\n          // way down the page.\n          //\n          // This is often the case for elements near the bottom of the page.\n          //\n          // In such cases we do not need to scroll the whole `offset` up, just the difference between\n          // the top of the element and the offset, which is enough to align the top of `elem` at the\n          // desired position.\n          var elemTop = elem.getBoundingClientRect().top;\n          $window.scrollBy(0, elemTop - offset);\n        }\n      } else {\n        $window.scrollTo(0, 0);\n      }\n    }\n\n    function scroll() {\n      var hash = $location.hash(), elm;\n\n      // empty hash, scroll to the top of the page\n      if (!hash) scrollTo(null);\n\n      // element with given id\n      else if ((elm = document.getElementById(hash))) scrollTo(elm);\n\n      // first anchor with given name :-D\n      else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);\n\n      // no element and hash == 'top', scroll to the top of the page\n      else if (hash === 'top') scrollTo(null);\n    }\n\n    // does not scroll when user clicks on anchor link that is currently on\n    // (no url change, no $location.hash() change), browser native does scroll\n    if (autoScrollingEnabled) {\n      $rootScope.$watch(function autoScrollWatch() {return $location.hash();},\n        function autoScrollWatchAction(newVal, oldVal) {\n          // skip the initial scroll if $location.hash is empty\n          if (newVal === oldVal && newVal === '') return;\n\n          jqLiteDocumentLoaded(function() {\n            $rootScope.$evalAsync(scroll);\n          });\n        });\n    }\n\n    return scroll;\n  }];\n}\n\nvar $animateMinErr = minErr('$animate');\n\n/**\n * @ngdoc provider\n * @name $animateProvider\n *\n * @description\n * Default implementation of $animate that doesn't perform any animations, instead just\n * synchronously performs DOM\n * updates and calls done() callbacks.\n *\n * In order to enable animations the ngAnimate module has to be loaded.\n *\n * To see the functional implementation check out src/ngAnimate/animate.js\n */\nvar $AnimateProvider = ['$provide', function($provide) {\n\n\n  this.$$selectors = {};\n\n\n  /**\n   * @ngdoc method\n   * @name $animateProvider#register\n   *\n   * @description\n   * Registers a new injectable animation factory function. The factory function produces the\n   * animation object which contains callback functions for each event that is expected to be\n   * animated.\n   *\n   *   * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`\n   *   must be called once the element animation is complete. If a function is returned then the\n   *   animation service will use this function to cancel the animation whenever a cancel event is\n   *   triggered.\n   *\n   *\n   * ```js\n   *   return {\n     *     eventFn : function(element, done) {\n     *       //code to run the animation\n     *       //once complete, then run done()\n     *       return function cancellationFunction() {\n     *         //code to cancel the animation\n     *       }\n     *     }\n     *   }\n   * ```\n   *\n   * @param {string} name The name of the animation.\n   * @param {Function} factory The factory function that will be executed to return the animation\n   *                           object.\n   */\n  this.register = function(name, factory) {\n    var key = name + '-animation';\n    if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',\n        \"Expecting class selector starting with '.' got '{0}'.\", name);\n    this.$$selectors[name.substr(1)] = key;\n    $provide.factory(key, factory);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $animateProvider#classNameFilter\n   *\n   * @description\n   * Sets and/or returns the CSS class regular expression that is checked when performing\n   * an animation. Upon bootstrap the classNameFilter value is not set at all and will\n   * therefore enable $animate to attempt to perform an animation on any element.\n   * When setting the classNameFilter value, animations will only be performed on elements\n   * that successfully match the filter expression. This in turn can boost performance\n   * for low-powered devices as well as applications containing a lot of structural operations.\n   * @param {RegExp=} expression The className expression which will be checked against all animations\n   * @return {RegExp} The current CSS className expression value. If null then there is no expression value\n   */\n  this.classNameFilter = function(expression) {\n    if (arguments.length === 1) {\n      this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;\n    }\n    return this.$$classNameFilter;\n  };\n\n  this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {\n\n    var currentDefer;\n\n    function runAnimationPostDigest(fn) {\n      var cancelFn, defer = $$q.defer();\n      defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {\n        cancelFn && cancelFn();\n      };\n\n      $rootScope.$$postDigest(function ngAnimatePostDigest() {\n        cancelFn = fn(function ngAnimateNotifyComplete() {\n          defer.resolve();\n        });\n      });\n\n      return defer.promise;\n    }\n\n    function resolveElementClasses(element, classes) {\n      var toAdd = [], toRemove = [];\n\n      var hasClasses = createMap();\n      forEach((element.attr('class') || '').split(/\\s+/), function(className) {\n        hasClasses[className] = true;\n      });\n\n      forEach(classes, function(status, className) {\n        var hasClass = hasClasses[className];\n\n        // If the most recent class manipulation (via $animate) was to remove the class, and the\n        // element currently has the class, the class is scheduled for removal. Otherwise, if\n        // the most recent class manipulation (via $animate) was to add the class, and the\n        // element does not currently have the class, the class is scheduled to be added.\n        if (status === false && hasClass) {\n          toRemove.push(className);\n        } else if (status === true && !hasClass) {\n          toAdd.push(className);\n        }\n      });\n\n      return (toAdd.length + toRemove.length) > 0 &&\n        [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];\n    }\n\n    function cachedClassManipulation(cache, classes, op) {\n      for (var i=0, ii = classes.length; i < ii; ++i) {\n        var className = classes[i];\n        cache[className] = op;\n      }\n    }\n\n    function asyncPromise() {\n      // only serve one instance of a promise in order to save CPU cycles\n      if (!currentDefer) {\n        currentDefer = $$q.defer();\n        $$asyncCallback(function() {\n          currentDefer.resolve();\n          currentDefer = null;\n        });\n      }\n      return currentDefer.promise;\n    }\n\n    function applyStyles(element, options) {\n      if (angular.isObject(options)) {\n        var styles = extend(options.from || {}, options.to || {});\n        element.css(styles);\n      }\n    }\n\n    /**\n     *\n     * @ngdoc service\n     * @name $animate\n     * @description The $animate service provides rudimentary DOM manipulation functions to\n     * insert, remove and move elements within the DOM, as well as adding and removing classes.\n     * This service is the core service used by the ngAnimate $animator service which provides\n     * high-level animation hooks for CSS and JavaScript.\n     *\n     * $animate is available in the AngularJS core, however, the ngAnimate module must be included\n     * to enable full out animation support. Otherwise, $animate will only perform simple DOM\n     * manipulation operations.\n     *\n     * To learn more about enabling animation support, click here to visit the {@link ngAnimate\n     * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service\n     * page}.\n     */\n    return {\n      animate: function(element, from, to) {\n        applyStyles(element, { from: from, to: to });\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#enter\n       * @kind function\n       * @description Inserts the element into the DOM either after the `after` element or\n       * as the first child within the `parent` element. When the function is called a promise\n       * is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will be inserted into the DOM\n       * @param {DOMElement} parent the parent element which will append the element as\n       *   a child (if the after element is not present)\n       * @param {DOMElement} after the sibling element which will append the element\n       *   after itself\n       * @param {object=} options an optional collection of styles that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      enter: function(element, parent, after, options) {\n        applyStyles(element, options);\n        after ? after.after(element)\n              : parent.prepend(element);\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#leave\n       * @kind function\n       * @description Removes the element from the DOM. When the function is called a promise\n       * is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will be removed from the DOM\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      leave: function(element, options) {\n        element.remove();\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#move\n       * @kind function\n       * @description Moves the position of the provided element within the DOM to be placed\n       * either after the `after` element or inside of the `parent` element. When the function\n       * is called a promise is returned that will be resolved at a later time.\n       *\n       * @param {DOMElement} element the element which will be moved around within the\n       *   DOM\n       * @param {DOMElement} parent the parent element where the element will be\n       *   inserted into (if the after element is not present)\n       * @param {DOMElement} after the sibling element where the element will be\n       *   positioned next to\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      move: function(element, parent, after, options) {\n        // Do not remove element before insert. Removing will cause data associated with the\n        // element to be dropped. Insert will implicitly do the remove.\n        return this.enter(element, parent, after, options);\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#addClass\n       * @kind function\n       * @description Adds the provided className CSS class value to the provided element.\n       * When the function is called a promise is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will have the className value\n       *   added to it\n       * @param {string} className the CSS class which will be added to the element\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      addClass: function(element, className, options) {\n        return this.setClass(element, className, [], options);\n      },\n\n      $$addClassImmediately: function(element, className, options) {\n        element = jqLite(element);\n        className = !isString(className)\n                        ? (isArray(className) ? className.join(' ') : '')\n                        : className;\n        forEach(element, function(element) {\n          jqLiteAddClass(element, className);\n        });\n        applyStyles(element, options);\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#removeClass\n       * @kind function\n       * @description Removes the provided className CSS class value from the provided element.\n       * When the function is called a promise is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will have the className value\n       *   removed from it\n       * @param {string} className the CSS class which will be removed from the element\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      removeClass: function(element, className, options) {\n        return this.setClass(element, [], className, options);\n      },\n\n      $$removeClassImmediately: function(element, className, options) {\n        element = jqLite(element);\n        className = !isString(className)\n                        ? (isArray(className) ? className.join(' ') : '')\n                        : className;\n        forEach(element, function(element) {\n          jqLiteRemoveClass(element, className);\n        });\n        applyStyles(element, options);\n        return asyncPromise();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#setClass\n       * @kind function\n       * @description Adds and/or removes the given CSS classes to and from the element.\n       * When the function is called a promise is returned that will be resolved at a later time.\n       * @param {DOMElement} element the element which will have its CSS classes changed\n       *   removed from it\n       * @param {string} add the CSS classes which will be added to the element\n       * @param {string} remove the CSS class which will be removed from the element\n       * @param {object=} options an optional collection of options that will be applied to the element.\n       * @return {Promise} the animation callback promise\n       */\n      setClass: function(element, add, remove, options) {\n        var self = this;\n        var STORAGE_KEY = '$$animateClasses';\n        var createdCache = false;\n        element = jqLite(element);\n\n        var cache = element.data(STORAGE_KEY);\n        if (!cache) {\n          cache = {\n            classes: {},\n            options: options\n          };\n          createdCache = true;\n        } else if (options && cache.options) {\n          cache.options = angular.extend(cache.options || {}, options);\n        }\n\n        var classes = cache.classes;\n\n        add = isArray(add) ? add : add.split(' ');\n        remove = isArray(remove) ? remove : remove.split(' ');\n        cachedClassManipulation(classes, add, true);\n        cachedClassManipulation(classes, remove, false);\n\n        if (createdCache) {\n          cache.promise = runAnimationPostDigest(function(done) {\n            var cache = element.data(STORAGE_KEY);\n            element.removeData(STORAGE_KEY);\n\n            // in the event that the element is removed before postDigest\n            // is run then the cache will be undefined and there will be\n            // no need anymore to add or remove and of the element classes\n            if (cache) {\n              var classes = resolveElementClasses(element, cache.classes);\n              if (classes) {\n                self.$$setClassImmediately(element, classes[0], classes[1], cache.options);\n              }\n            }\n\n            done();\n          });\n          element.data(STORAGE_KEY, cache);\n        }\n\n        return cache.promise;\n      },\n\n      $$setClassImmediately: function(element, add, remove, options) {\n        add && this.$$addClassImmediately(element, add);\n        remove && this.$$removeClassImmediately(element, remove);\n        applyStyles(element, options);\n        return asyncPromise();\n      },\n\n      enabled: noop,\n      cancel: noop\n    };\n  }];\n}];\n\nfunction $$AsyncCallbackProvider() {\n  this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {\n    return $$rAF.supported\n      ? function(fn) { return $$rAF(fn); }\n      : function(fn) {\n        return $timeout(fn, 0, false);\n      };\n  }];\n}\n\n/* global stripHash: true */\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n * @requires $log\n * @description\n * This object has two goals:\n *\n * - hide all the global state in the browser caused by the window object\n * - abstract away all the browser specific features and inconsistencies\n *\n * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`\n * service, which can be used for convenient testing of the application without the interaction with\n * the real browser apis.\n */\n/**\n * @param {object} window The global window object.\n * @param {object} document jQuery wrapped document.\n * @param {object} $log window.console or an object with the same interface.\n * @param {object} $sniffer $sniffer service\n */\nfunction Browser(window, document, $log, $sniffer) {\n  var self = this,\n      rawDocument = document[0],\n      location = window.location,\n      history = window.history,\n      setTimeout = window.setTimeout,\n      clearTimeout = window.clearTimeout,\n      pendingDeferIds = {};\n\n  self.isMock = false;\n\n  var outstandingRequestCount = 0;\n  var outstandingRequestCallbacks = [];\n\n  // TODO(vojta): remove this temporary api\n  self.$$completeOutstandingRequest = completeOutstandingRequest;\n  self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };\n\n  /**\n   * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`\n   * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.\n   */\n  function completeOutstandingRequest(fn) {\n    try {\n      fn.apply(null, sliceArgs(arguments, 1));\n    } finally {\n      outstandingRequestCount--;\n      if (outstandingRequestCount === 0) {\n        while (outstandingRequestCallbacks.length) {\n          try {\n            outstandingRequestCallbacks.pop()();\n          } catch (e) {\n            $log.error(e);\n          }\n        }\n      }\n    }\n  }\n\n  function getHash(url) {\n    var index = url.indexOf('#');\n    return index === -1 ? '' : url.substr(index + 1);\n  }\n\n  /**\n   * @private\n   * Note: this method is used only by scenario runner\n   * TODO(vojta): prefix this method with $$ ?\n   * @param {function()} callback Function that will be called when no outstanding request\n   */\n  self.notifyWhenNoOutstandingRequests = function(callback) {\n    // force browser to execute all pollFns - this is needed so that cookies and other pollers fire\n    // at some deterministic time in respect to the test runner's actions. Leaving things up to the\n    // regular poller would result in flaky tests.\n    forEach(pollFns, function(pollFn) { pollFn(); });\n\n    if (outstandingRequestCount === 0) {\n      callback();\n    } else {\n      outstandingRequestCallbacks.push(callback);\n    }\n  };\n\n  //////////////////////////////////////////////////////////////\n  // Poll Watcher API\n  //////////////////////////////////////////////////////////////\n  var pollFns = [],\n      pollTimeout;\n\n  /**\n   * @name $browser#addPollFn\n   *\n   * @param {function()} fn Poll function to add\n   *\n   * @description\n   * Adds a function to the list of functions that poller periodically executes,\n   * and starts polling if not started yet.\n   *\n   * @returns {function()} the added function\n   */\n  self.addPollFn = function(fn) {\n    if (isUndefined(pollTimeout)) startPoller(100, setTimeout);\n    pollFns.push(fn);\n    return fn;\n  };\n\n  /**\n   * @param {number} interval How often should browser call poll functions (ms)\n   * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.\n   *\n   * @description\n   * Configures the poller to run in the specified intervals, using the specified\n   * setTimeout fn and kicks it off.\n   */\n  function startPoller(interval, setTimeout) {\n    (function check() {\n      forEach(pollFns, function(pollFn) { pollFn(); });\n      pollTimeout = setTimeout(check, interval);\n    })();\n  }\n\n  //////////////////////////////////////////////////////////////\n  // URL API\n  //////////////////////////////////////////////////////////////\n\n  var cachedState, lastHistoryState,\n      lastBrowserUrl = location.href,\n      baseElement = document.find('base'),\n      reloadLocation = null;\n\n  cacheState();\n  lastHistoryState = cachedState;\n\n  /**\n   * @name $browser#url\n   *\n   * @description\n   * GETTER:\n   * Without any argument, this method just returns current value of location.href.\n   *\n   * SETTER:\n   * With at least one argument, this method sets url to new value.\n   * If html5 history api supported, pushState/replaceState is used, otherwise\n   * location.href/location.replace is used.\n   * Returns its own instance to allow chaining\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to change url.\n   *\n   * @param {string} url New url (when used as setter)\n   * @param {boolean=} replace Should new url replace current history record?\n   * @param {object=} state object to use with pushState/replaceState\n   */\n  self.url = function(url, replace, state) {\n    // In modern browsers `history.state` is `null` by default; treating it separately\n    // from `undefined` would cause `$browser.url('/foo')` to change `history.state`\n    // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.\n    if (isUndefined(state)) {\n      state = null;\n    }\n\n    // Android Browser BFCache causes location, history reference to become stale.\n    if (location !== window.location) location = window.location;\n    if (history !== window.history) history = window.history;\n\n    // setter\n    if (url) {\n      var sameState = lastHistoryState === state;\n\n      // Don't change anything if previous and current URLs and states match. This also prevents\n      // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.\n      // See https://github.com/angular/angular.js/commit/ffb2701\n      if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {\n        return self;\n      }\n      var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);\n      lastBrowserUrl = url;\n      lastHistoryState = state;\n      // Don't use history API if only the hash changed\n      // due to a bug in IE10/IE11 which leads\n      // to not firing a `hashchange` nor `popstate` event\n      // in some cases (see #9143).\n      if ($sniffer.history && (!sameBase || !sameState)) {\n        history[replace ? 'replaceState' : 'pushState'](state, '', url);\n        cacheState();\n        // Do the assignment again so that those two variables are referentially identical.\n        lastHistoryState = cachedState;\n      } else {\n        if (!sameBase) {\n          reloadLocation = url;\n        }\n        if (replace) {\n          location.replace(url);\n        } else if (!sameBase) {\n          location.href = url;\n        } else {\n          location.hash = getHash(url);\n        }\n      }\n      return self;\n    // getter\n    } else {\n      // - reloadLocation is needed as browsers don't allow to read out\n      //   the new location.href if a reload happened.\n      // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172\n      return reloadLocation || location.href.replace(/%27/g,\"'\");\n    }\n  };\n\n  /**\n   * @name $browser#state\n   *\n   * @description\n   * This method is a getter.\n   *\n   * Return history.state or null if history.state is undefined.\n   *\n   * @returns {object} state\n   */\n  self.state = function() {\n    return cachedState;\n  };\n\n  var urlChangeListeners = [],\n      urlChangeInit = false;\n\n  function cacheStateAndFireUrlChange() {\n    cacheState();\n    fireUrlChange();\n  }\n\n  // This variable should be used *only* inside the cacheState function.\n  var lastCachedState = null;\n  function cacheState() {\n    // This should be the only place in $browser where `history.state` is read.\n    cachedState = window.history.state;\n    cachedState = isUndefined(cachedState) ? null : cachedState;\n\n    // Prevent callbacks fo fire twice if both hashchange & popstate were fired.\n    if (equals(cachedState, lastCachedState)) {\n      cachedState = lastCachedState;\n    }\n    lastCachedState = cachedState;\n  }\n\n  function fireUrlChange() {\n    if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {\n      return;\n    }\n\n    lastBrowserUrl = self.url();\n    lastHistoryState = cachedState;\n    forEach(urlChangeListeners, function(listener) {\n      listener(self.url(), cachedState);\n    });\n  }\n\n  /**\n   * @name $browser#onUrlChange\n   *\n   * @description\n   * Register callback function that will be called, when url changes.\n   *\n   * It's only called when the url is changed from outside of angular:\n   * - user types different url into address bar\n   * - user clicks on history (forward/back) button\n   * - user clicks on a link\n   *\n   * It's not called when url is changed by $browser.url() method\n   *\n   * The listener gets called with new url as parameter.\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to monitor url changes in angular apps.\n   *\n   * @param {function(string)} listener Listener function to be called when url changes.\n   * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\n   */\n  self.onUrlChange = function(callback) {\n    // TODO(vojta): refactor to use node's syntax for events\n    if (!urlChangeInit) {\n      // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)\n      // don't fire popstate when user change the address bar and don't fire hashchange when url\n      // changed by push/replaceState\n\n      // html5 history api - popstate event\n      if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);\n      // hashchange event\n      jqLite(window).on('hashchange', cacheStateAndFireUrlChange);\n\n      urlChangeInit = true;\n    }\n\n    urlChangeListeners.push(callback);\n    return callback;\n  };\n\n  /**\n   * Checks whether the url has changed outside of Angular.\n   * Needs to be exported to be able to check for changes that have been done in sync,\n   * as hashchange/popstate events fire in async.\n   */\n  self.$$checkUrlChange = fireUrlChange;\n\n  //////////////////////////////////////////////////////////////\n  // Misc API\n  //////////////////////////////////////////////////////////////\n\n  /**\n   * @name $browser#baseHref\n   *\n   * @description\n   * Returns current <base href>\n   * (always relative - without domain)\n   *\n   * @returns {string} The current base href\n   */\n  self.baseHref = function() {\n    var href = baseElement.attr('href');\n    return href ? href.replace(/^(https?\\:)?\\/\\/[^\\/]*/, '') : '';\n  };\n\n  //////////////////////////////////////////////////////////////\n  // Cookies API\n  //////////////////////////////////////////////////////////////\n  var lastCookies = {};\n  var lastCookieString = '';\n  var cookiePath = self.baseHref();\n\n  function safeDecodeURIComponent(str) {\n    try {\n      return decodeURIComponent(str);\n    } catch (e) {\n      return str;\n    }\n  }\n\n  /**\n   * @name $browser#cookies\n   *\n   * @param {string=} name Cookie name\n   * @param {string=} value Cookie value\n   *\n   * @description\n   * The cookies method provides a 'private' low level access to browser cookies.\n   * It is not meant to be used directly, use the $cookie service instead.\n   *\n   * The return values vary depending on the arguments that the method was called with as follows:\n   *\n   * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify\n   *   it\n   * - cookies(name, value) -> set name to value, if value is undefined delete the cookie\n   * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that\n   *   way)\n   *\n   * @returns {Object} Hash of all cookies (if called without any parameter)\n   */\n  self.cookies = function(name, value) {\n    var cookieLength, cookieArray, cookie, i, index;\n\n    if (name) {\n      if (value === undefined) {\n        rawDocument.cookie = encodeURIComponent(name) + \"=;path=\" + cookiePath +\n                                \";expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n      } else {\n        if (isString(value)) {\n          cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +\n                                ';path=' + cookiePath).length + 1;\n\n          // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:\n          // - 300 cookies\n          // - 20 cookies per unique domain\n          // - 4096 bytes per cookie\n          if (cookieLength > 4096) {\n            $log.warn(\"Cookie '\" + name +\n              \"' possibly not set or overflowed because it was too large (\" +\n              cookieLength + \" > 4096 bytes)!\");\n          }\n        }\n      }\n    } else {\n      if (rawDocument.cookie !== lastCookieString) {\n        lastCookieString = rawDocument.cookie;\n        cookieArray = lastCookieString.split(\"; \");\n        lastCookies = {};\n\n        for (i = 0; i < cookieArray.length; i++) {\n          cookie = cookieArray[i];\n          index = cookie.indexOf('=');\n          if (index > 0) { //ignore nameless cookies\n            name = safeDecodeURIComponent(cookie.substring(0, index));\n            // the first value that is seen for a cookie is the most\n            // specific one.  values for the same cookie name that\n            // follow are for less specific paths.\n            if (lastCookies[name] === undefined) {\n              lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));\n            }\n          }\n        }\n      }\n      return lastCookies;\n    }\n  };\n\n\n  /**\n   * @name $browser#defer\n   * @param {function()} fn A function, who's execution should be deferred.\n   * @param {number=} [delay=0] of milliseconds to defer the function execution.\n   * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\n   *\n   * @description\n   * Executes a fn asynchronously via `setTimeout(fn, delay)`.\n   *\n   * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\n   * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\n   * via `$browser.defer.flush()`.\n   *\n   */\n  self.defer = function(fn, delay) {\n    var timeoutId;\n    outstandingRequestCount++;\n    timeoutId = setTimeout(function() {\n      delete pendingDeferIds[timeoutId];\n      completeOutstandingRequest(fn);\n    }, delay || 0);\n    pendingDeferIds[timeoutId] = true;\n    return timeoutId;\n  };\n\n\n  /**\n   * @name $browser#defer.cancel\n   *\n   * @description\n   * Cancels a deferred task identified with `deferId`.\n   *\n   * @param {*} deferId Token returned by the `$browser.defer` function.\n   * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n   *                    canceled.\n   */\n  self.defer.cancel = function(deferId) {\n    if (pendingDeferIds[deferId]) {\n      delete pendingDeferIds[deferId];\n      clearTimeout(deferId);\n      completeOutstandingRequest(noop);\n      return true;\n    }\n    return false;\n  };\n\n}\n\nfunction $BrowserProvider() {\n  this.$get = ['$window', '$log', '$sniffer', '$document',\n      function($window, $log, $sniffer, $document) {\n        return new Browser($window, $document, $log, $sniffer);\n      }];\n}\n\n/**\n * @ngdoc service\n * @name $cacheFactory\n *\n * @description\n * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to\n * them.\n *\n * ```js\n *\n *  var cache = $cacheFactory('cacheId');\n *  expect($cacheFactory.get('cacheId')).toBe(cache);\n *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();\n *\n *  cache.put(\"key\", \"value\");\n *  cache.put(\"another key\", \"another value\");\n *\n *  // We've specified no options on creation\n *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});\n *\n * ```\n *\n *\n * @param {string} cacheId Name or id of the newly created cache.\n * @param {object=} options Options object that specifies the cache behavior. Properties:\n *\n *   - `{number=}` `capacity` — turns the cache into LRU cache.\n *\n * @returns {object} Newly created cache object with the following set of methods:\n *\n * - `{object}` `info()` — Returns id, size, and options of cache.\n * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns\n *   it.\n * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.\n * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.\n * - `{void}` `removeAll()` — Removes all cached values.\n * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.\n *\n * @example\n   <example module=\"cacheExampleApp\">\n     <file name=\"index.html\">\n       <div ng-controller=\"CacheController\">\n         <input ng-model=\"newCacheKey\" placeholder=\"Key\">\n         <input ng-model=\"newCacheValue\" placeholder=\"Value\">\n         <button ng-click=\"put(newCacheKey, newCacheValue)\">Cache</button>\n\n         <p ng-if=\"keys.length\">Cached Values</p>\n         <div ng-repeat=\"key in keys\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"cache.get(key)\"></b>\n         </div>\n\n         <p>Cache Info</p>\n         <div ng-repeat=\"(key, value) in cache.info()\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"value\"></b>\n         </div>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('cacheExampleApp', []).\n         controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {\n           $scope.keys = [];\n           $scope.cache = $cacheFactory('cacheId');\n           $scope.put = function(key, value) {\n             if ($scope.cache.get(key) === undefined) {\n               $scope.keys.push(key);\n             }\n             $scope.cache.put(key, value === undefined ? null : value);\n           };\n         }]);\n     </file>\n     <file name=\"style.css\">\n       p {\n         margin: 10px 0 3px;\n       }\n     </file>\n   </example>\n */\nfunction $CacheFactoryProvider() {\n\n  this.$get = function() {\n    var caches = {};\n\n    function cacheFactory(cacheId, options) {\n      if (cacheId in caches) {\n        throw minErr('$cacheFactory')('iid', \"CacheId '{0}' is already taken!\", cacheId);\n      }\n\n      var size = 0,\n          stats = extend({}, options, {id: cacheId}),\n          data = {},\n          capacity = (options && options.capacity) || Number.MAX_VALUE,\n          lruHash = {},\n          freshEnd = null,\n          staleEnd = null;\n\n      /**\n       * @ngdoc type\n       * @name $cacheFactory.Cache\n       *\n       * @description\n       * A cache object used to store and retrieve data, primarily used by\n       * {@link $http $http} and the {@link ng.directive:script script} directive to cache\n       * templates and other data.\n       *\n       * ```js\n       *  angular.module('superCache')\n       *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {\n       *      return $cacheFactory('super-cache');\n       *    }]);\n       * ```\n       *\n       * Example test:\n       *\n       * ```js\n       *  it('should behave like a cache', inject(function(superCache) {\n       *    superCache.put('key', 'value');\n       *    superCache.put('another key', 'another value');\n       *\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 2\n       *    });\n       *\n       *    superCache.remove('another key');\n       *    expect(superCache.get('another key')).toBeUndefined();\n       *\n       *    superCache.removeAll();\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 0\n       *    });\n       *  }));\n       * ```\n       */\n      return caches[cacheId] = {\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#put\n         * @kind function\n         *\n         * @description\n         * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be\n         * retrieved later, and incrementing the size of the cache if the key was not already\n         * present in the cache. If behaving like an LRU cache, it will also remove stale\n         * entries from the set.\n         *\n         * It will not insert undefined values into the cache.\n         *\n         * @param {string} key the key under which the cached data is stored.\n         * @param {*} value the value to store alongside the key. If it is undefined, the key\n         *    will not be stored.\n         * @returns {*} the value stored.\n         */\n        put: function(key, value) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key] || (lruHash[key] = {key: key});\n\n            refresh(lruEntry);\n          }\n\n          if (isUndefined(value)) return;\n          if (!(key in data)) size++;\n          data[key] = value;\n\n          if (size > capacity) {\n            this.remove(staleEnd.key);\n          }\n\n          return value;\n        },\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#get\n         * @kind function\n         *\n         * @description\n         * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the data to be retrieved\n         * @returns {*} the value stored.\n         */\n        get: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            refresh(lruEntry);\n          }\n\n          return data[key];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#remove\n         * @kind function\n         *\n         * @description\n         * Removes an entry from the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the entry to be removed\n         */\n        remove: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            if (lruEntry == freshEnd) freshEnd = lruEntry.p;\n            if (lruEntry == staleEnd) staleEnd = lruEntry.n;\n            link(lruEntry.n,lruEntry.p);\n\n            delete lruHash[key];\n          }\n\n          delete data[key];\n          size--;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#removeAll\n         * @kind function\n         *\n         * @description\n         * Clears the cache object of any entries.\n         */\n        removeAll: function() {\n          data = {};\n          size = 0;\n          lruHash = {};\n          freshEnd = staleEnd = null;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#destroy\n         * @kind function\n         *\n         * @description\n         * Destroys the {@link $cacheFactory.Cache Cache} object entirely,\n         * removing it from the {@link $cacheFactory $cacheFactory} set.\n         */\n        destroy: function() {\n          data = null;\n          stats = null;\n          lruHash = null;\n          delete caches[cacheId];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#info\n         * @kind function\n         *\n         * @description\n         * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.\n         *\n         * @returns {object} an object with the following properties:\n         *   <ul>\n         *     <li>**id**: the id of the cache instance</li>\n         *     <li>**size**: the number of entries kept in the cache instance</li>\n         *     <li>**...**: any additional properties from the options object when creating the\n         *       cache.</li>\n         *   </ul>\n         */\n        info: function() {\n          return extend({}, stats, {size: size});\n        }\n      };\n\n\n      /**\n       * makes the `entry` the freshEnd of the LRU linked list\n       */\n      function refresh(entry) {\n        if (entry != freshEnd) {\n          if (!staleEnd) {\n            staleEnd = entry;\n          } else if (staleEnd == entry) {\n            staleEnd = entry.n;\n          }\n\n          link(entry.n, entry.p);\n          link(entry, freshEnd);\n          freshEnd = entry;\n          freshEnd.n = null;\n        }\n      }\n\n\n      /**\n       * bidirectionally links two entries of the LRU linked list\n       */\n      function link(nextEntry, prevEntry) {\n        if (nextEntry != prevEntry) {\n          if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify\n          if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify\n        }\n      }\n    }\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#info\n   *\n   * @description\n   * Get information about all the caches that have been created\n   *\n   * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`\n   */\n    cacheFactory.info = function() {\n      var info = {};\n      forEach(caches, function(cache, cacheId) {\n        info[cacheId] = cache.info();\n      });\n      return info;\n    };\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#get\n   *\n   * @description\n   * Get access to a cache object by the `cacheId` used when it was created.\n   *\n   * @param {string} cacheId Name or id of a cache to access.\n   * @returns {object} Cache object identified by the cacheId or undefined if no such cache.\n   */\n    cacheFactory.get = function(cacheId) {\n      return caches[cacheId];\n    };\n\n\n    return cacheFactory;\n  };\n}\n\n/**\n * @ngdoc service\n * @name $templateCache\n *\n * @description\n * The first time a template is used, it is loaded in the template cache for quick retrieval. You\n * can load templates directly into the cache in a `script` tag, or by consuming the\n * `$templateCache` service directly.\n *\n * Adding via the `script` tag:\n *\n * ```html\n *   <script type=\"text/ng-template\" id=\"templateId.html\">\n *     <p>This is the content of the template</p>\n *   </script>\n * ```\n *\n * **Note:** the `script` tag containing the template does not need to be included in the `head` of\n * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,\n * element with ng-app attribute), otherwise the template will be ignored.\n *\n * Adding via the $templateCache service:\n *\n * ```js\n * var myApp = angular.module('myApp', []);\n * myApp.run(function($templateCache) {\n *   $templateCache.put('templateId.html', 'This is the content of the template');\n * });\n * ```\n *\n * To retrieve the template later, simply use it in your HTML:\n * ```html\n * <div ng-include=\" 'templateId.html' \"></div>\n * ```\n *\n * or get it via Javascript:\n * ```js\n * $templateCache.get('templateId.html')\n * ```\n *\n * See {@link ng.$cacheFactory $cacheFactory}.\n *\n */\nfunction $TemplateCacheProvider() {\n  this.$get = ['$cacheFactory', function($cacheFactory) {\n    return $cacheFactory('templates');\n  }];\n}\n\n/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!\n *\n * DOM-related variables:\n *\n * - \"node\" - DOM Node\n * - \"element\" - DOM Element or Node\n * - \"$node\" or \"$element\" - jqLite-wrapped node or element\n *\n *\n * Compiler related stuff:\n *\n * - \"linkFn\" - linking fn of a single directive\n * - \"nodeLinkFn\" - function that aggregates all linking fns for a particular node\n * - \"childLinkFn\" -  function that aggregates all linking fns for child nodes of a particular node\n * - \"compositeLinkFn\" - function that aggregates all linking fns for a compilation root (nodeList)\n */\n\n\n/**\n * @ngdoc service\n * @name $compile\n * @kind function\n *\n * @description\n * Compiles an HTML string or DOM into a template and produces a template function, which\n * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.\n *\n * The compilation is a process of walking the DOM tree and matching DOM elements to\n * {@link ng.$compileProvider#directive directives}.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** This document is an in-depth reference of all directive options.\n * For a gentle introduction to directives with examples of common use cases,\n * see the {@link guide/directive directive guide}.\n * </div>\n *\n * ## Comprehensive Directive API\n *\n * There are many different options for a directive.\n *\n * The difference resides in the return value of the factory function.\n * You can either return a \"Directive Definition Object\" (see below) that defines the directive properties,\n * or just the `postLink` function (all other properties will have the default values).\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's recommended to use the \"directive definition object\" form.\n * </div>\n *\n * Here's an example directive declared with a Directive Definition Object:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       priority: 0,\n *       template: '<div></div>', // or // function(tElement, tAttrs) { ... },\n *       // or\n *       // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },\n *       transclude: false,\n *       restrict: 'A',\n *       templateNamespace: 'html',\n *       scope: false,\n *       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },\n *       controllerAs: 'stringAlias',\n *       require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],\n *       compile: function compile(tElement, tAttrs, transclude) {\n *         return {\n *           pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *           post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *         }\n *         // or\n *         // return function postLink( ... ) { ... }\n *       },\n *       // or\n *       // link: {\n *       //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *       //  post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *       // }\n *       // or\n *       // link: function postLink( ... ) { ... }\n *     };\n *     return directiveDefinitionObject;\n *   });\n * ```\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Any unspecified options will use the default value. You can see the default values below.\n * </div>\n *\n * Therefore the above can be simplified as:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       link: function postLink(scope, iElement, iAttrs) { ... }\n *     };\n *     return directiveDefinitionObject;\n *     // or\n *     // return function postLink(scope, iElement, iAttrs) { ... }\n *   });\n * ```\n *\n *\n *\n * ### Directive Definition Object\n *\n * The directive definition object provides instructions to the {@link ng.$compile\n * compiler}. The attributes are:\n *\n * #### `multiElement`\n * When this property is set to true, the HTML compiler will collect DOM nodes between\n * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them\n * together as the directive elements. It is recommended that this feature be used on directives\n * which are not strictly behavioural (such as {@link ngClick}), and which\n * do not manipulate or replace child nodes (such as {@link ngInclude}).\n *\n * #### `priority`\n * When there are multiple directives defined on a single DOM element, sometimes it\n * is necessary to specify the order in which the directives are applied. The `priority` is used\n * to sort the directives before their `compile` functions get called. Priority is defined as a\n * number. Directives with greater numerical `priority` are compiled first. Pre-link functions\n * are also run in priority order, but post-link functions are run in reverse order. The order\n * of directives with the same priority is undefined. The default priority is `0`.\n *\n * #### `terminal`\n * If set to true then the current `priority` will be the last set of directives\n * which will execute (any directives at the current priority will still execute\n * as the order of execution on same `priority` is undefined). Note that expressions\n * and other directives used in the directive's template will also be excluded from execution.\n *\n * #### `scope`\n * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the\n * same element request a new scope, only one new scope is created. The new scope rule does not\n * apply for the root of the template since the root of the template always gets a new scope.\n *\n * **If set to `{}` (object hash),** then a new \"isolate\" scope is created. The 'isolate' scope differs from\n * normal scope in that it does not prototypically inherit from the parent scope. This is useful\n * when creating reusable components, which should not accidentally read or modify data in the\n * parent scope.\n *\n * The 'isolate' scope takes an object hash which defines a set of local scope properties\n * derived from the parent scope. These local properties are useful for aliasing values for\n * templates. Locals definition is a hash of local scope property to its source:\n *\n * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is\n *   always a string since DOM attributes are strings. If no `attr` name is specified  then the\n *   attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"hello {{name}}\">` and widget definition\n *   of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect\n *   the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the\n *   `localName` property on the widget scope. The `name` is read from the parent scope (not\n *   component scope).\n *\n * * `=` or `=attr` - set up bi-directional binding between a local scope property and the\n *   parent scope property of name defined via the value of the `attr` attribute. If no `attr`\n *   name is specified then the attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"parentModel\">` and widget definition of\n *   `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the\n *   value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected\n *   in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent\n *   scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You\n *   can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If\n *   you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use\n *   `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).\n *\n * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.\n *   If no `attr` name is specified then the attribute name is assumed to be the same as the\n *   local name. Given `<widget my-attr=\"count = count + value\">` and widget definition of\n *   `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to\n *   a function wrapper for the `count = count + value` expression. Often it's desirable to\n *   pass data from the isolated scope via an expression to the parent scope, this can be\n *   done by passing a map of local variable names and values into the expression wrapper fn.\n *   For example, if the expression is `increment(amount)` then we can specify the amount value\n *   by calling the `localFn` as `localFn({amount: 22})`.\n *\n *\n * #### `bindToController`\n * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will\n * allow a component to have its properties bound to the controller, rather than to scope. When the controller\n * is instantiated, the initial values of the isolate scope bindings are already available.\n *\n * #### `controller`\n * Controller constructor function. The controller is instantiated before the\n * pre-linking phase and it is shared with other directives (see\n * `require` attribute). This allows the directives to communicate with each other and augment\n * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:\n *\n * * `$scope` - Current scope associated with the element\n * * `$element` - Current element\n * * `$attrs` - Current attributes object for the element\n * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:\n *   `function([scope], cloneLinkingFn, futureParentElement)`.\n *    * `scope`: optional argument to override the scope.\n *    * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.\n *    * `futureParentElement`:\n *        * defines the parent to which the `cloneLinkingFn` will add the cloned elements.\n *        * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.\n *        * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)\n *          and when the `cloneLinkinFn` is passed,\n *          as those elements need to created and cloned in a special way when they are defined outside their\n *          usual containers (e.g. like `<svg>`).\n *        * See also the `directive.templateNamespace` property.\n *\n *\n * #### `require`\n * Require another directive and inject its controller as the fourth argument to the linking function. The\n * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the\n * injected argument will be an array in corresponding order. If no such directive can be\n * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:\n *\n * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.\n * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.\n * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.\n * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.\n * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass\n *   `null` to the `link` fn if not found.\n * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass\n *   `null` to the `link` fn if not found.\n *\n *\n * #### `controllerAs`\n * Controller alias at the directive scope. An alias for the controller so it\n * can be referenced at the directive template. The directive needs to define a scope for this\n * configuration to be used. Useful in the case when directive is used as component.\n *\n *\n * #### `restrict`\n * String of subset of `EACM` which restricts the directive to a specific directive\n * declaration style. If omitted, the defaults (elements and attributes) are used.\n *\n * * `E` - Element name (default): `<my-directive></my-directive>`\n * * `A` - Attribute (default): `<div my-directive=\"exp\"></div>`\n * * `C` - Class: `<div class=\"my-directive: exp;\"></div>`\n * * `M` - Comment: `<!-- directive: my-directive exp -->`\n *\n *\n * #### `templateNamespace`\n * String representing the document type used by the markup in the template.\n * AngularJS needs this information as those elements need to be created and cloned\n * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.\n *\n * * `html` - All root nodes in the template are HTML. Root nodes may also be\n *   top-level elements such as `<svg>` or `<math>`.\n * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).\n * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).\n *\n * If no `templateNamespace` is specified, then the namespace is considered to be `html`.\n *\n * #### `template`\n * HTML markup that may:\n * * Replace the contents of the directive's element (default).\n * * Replace the directive's element itself (if `replace` is true - DEPRECATED).\n * * Wrap the contents of the directive's element (if `transclude` is true).\n *\n * Value may be:\n *\n * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.\n * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`\n *   function api below) and returns a string value.\n *\n *\n * #### `templateUrl`\n * This is similar to `template` but the template is loaded from the specified URL, asynchronously.\n *\n * Because template loading is asynchronous the compiler will suspend compilation of directives on that element\n * for later when the template has been resolved.  In the meantime it will continue to compile and link\n * sibling and parent elements as though this element had not contained any directives.\n *\n * The compiler does not suspend the entire compilation to wait for templates to be loaded because this\n * would result in the whole app \"stalling\" until all templates are loaded asynchronously - even in the\n * case when only one deeply nested directive has `templateUrl`.\n *\n * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}\n *\n * You can specify `templateUrl` as a string representing the URL or as a function which takes two\n * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns\n * a string value representing the url.  In either case, the template URL is passed through {@link\n * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.\n *\n *\n * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)\n * specify what the template should replace. Defaults to `false`.\n *\n * * `true` - the template will replace the directive's element.\n * * `false` - the template will replace the contents of the directive's element.\n *\n * The replacement process migrates all of the attributes / classes from the old element to the new\n * one. See the {@link guide/directive#template-expanding-directive\n * Directives Guide} for an example.\n *\n * There are very few scenarios where element replacement is required for the application function,\n * the main one being reusable custom components that are used within SVG contexts\n * (because SVG doesn't work with custom elements in the DOM tree).\n *\n * #### `transclude`\n * Extract the contents of the element where the directive appears and make it available to the directive.\n * The contents are compiled and provided to the directive as a **transclusion function**. See the\n * {@link $compile#transclusion Transclusion} section below.\n *\n * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the\n * directive's element or the entire element:\n *\n * * `true` - transclude the content (i.e. the child nodes) of the directive's element.\n * * `'element'` - transclude the whole of the directive's element including any directives on this\n *   element that defined at a lower priority than this directive. When used, the `template`\n *   property is ignored.\n *\n *\n * #### `compile`\n *\n * ```js\n *   function compile(tElement, tAttrs, transclude) { ... }\n * ```\n *\n * The compile function deals with transforming the template DOM. Since most directives do not do\n * template transformation, it is not used often. The compile function takes the following arguments:\n *\n *   * `tElement` - template element - The element where the directive has been declared. It is\n *     safe to do template transformation on the element and child elements only.\n *\n *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared\n *     between all directive compile functions.\n *\n *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`\n *\n * <div class=\"alert alert-warning\">\n * **Note:** The template instance and the link instance may be different objects if the template has\n * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that\n * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration\n * should be done in a linking function rather than in a compile function.\n * </div>\n\n * <div class=\"alert alert-warning\">\n * **Note:** The compile function cannot handle directives that recursively use themselves in their\n * own templates or compile functions. Compiling these directives results in an infinite loop and a\n * stack overflow errors.\n *\n * This can be avoided by manually using $compile in the postLink function to imperatively compile\n * a directive's template instead of relying on automatic template compilation via `template` or\n * `templateUrl` declaration or manual compilation inside the compile function.\n * </div>\n *\n * <div class=\"alert alert-error\">\n * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it\n *   e.g. does not know about the right outer scope. Please use the transclude function that is passed\n *   to the link function instead.\n * </div>\n\n * A compile function can have a return value which can be either a function or an object.\n *\n * * returning a (post-link) function - is equivalent to registering the linking function via the\n *   `link` property of the config object when the compile function is empty.\n *\n * * returning an object with function(s) registered via `pre` and `post` properties - allows you to\n *   control when a linking function should be called during the linking phase. See info about\n *   pre-linking and post-linking functions below.\n *\n *\n * #### `link`\n * This property is used only if the `compile` property is not defined.\n *\n * ```js\n *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }\n * ```\n *\n * The link function is responsible for registering DOM listeners as well as updating the DOM. It is\n * executed after the template has been cloned. This is where most of the directive logic will be\n * put.\n *\n *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the\n *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.\n *\n *   * `iElement` - instance element - The element where the directive is to be used. It is safe to\n *     manipulate the children of the element only in `postLink` function since the children have\n *     already been linked.\n *\n *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared\n *     between all directive linking functions.\n *\n *   * `controller` - a controller instance - A controller instance if at least one directive on the\n *     element defines a controller. The controller is shared among all the directives, which allows\n *     the directives to use the controllers as a communication channel.\n *\n *   * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.\n *     This is the same as the `$transclude`\n *     parameter of directive controllers, see there for details.\n *     `function([scope], cloneLinkingFn, futureParentElement)`.\n *\n * #### Pre-linking function\n *\n * Executed before the child elements are linked. Not safe to do DOM transformation since the\n * compiler linking function will fail to locate the correct elements for linking.\n *\n * #### Post-linking function\n *\n * Executed after the child elements are linked.\n *\n * Note that child elements that contain `templateUrl` directives will not have been compiled\n * and linked since they are waiting for their template to load asynchronously and their own\n * compilation and linking has been suspended until that occurs.\n *\n * It is safe to do DOM transformation in the post-linking function on elements that are not waiting\n * for their async templates to be resolved.\n *\n *\n * ### Transclusion\n *\n * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and\n * copying them to another part of the DOM, while maintaining their connection to the original AngularJS\n * scope from where they were taken.\n *\n * Transclusion is used (often with {@link ngTransclude}) to insert the\n * original contents of a directive's element into a specified place in the template of the directive.\n * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded\n * content has access to the properties on the scope from which it was taken, even if the directive\n * has isolated scope.\n * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.\n *\n * This makes it possible for the widget to have private state for its template, while the transcluded\n * content has access to its originating scope.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** When testing an element transclude directive you must not place the directive at the root of the\n * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives\n * Testing Transclusion Directives}.\n * </div>\n *\n * #### Transclusion Functions\n *\n * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion\n * function** to the directive's `link` function and `controller`. This transclusion function is a special\n * **linking function** that will return the compiled contents linked to a new transclusion scope.\n *\n * <div class=\"alert alert-info\">\n * If you are just using {@link ngTransclude} then you don't need to worry about this function, since\n * ngTransclude will deal with it for us.\n * </div>\n *\n * If you want to manually control the insertion and removal of the transcluded content in your directive\n * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery\n * object that contains the compiled DOM, which is linked to the correct transclusion scope.\n *\n * When you call a transclusion function you can pass in a **clone attach function**. This function accepts\n * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded\n * content and the `scope` is the newly created transclusion scope, to which the clone is bound.\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function\n * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.\n * </div>\n *\n * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone\n * attach function**:\n *\n * ```js\n * var transcludedContent, transclusionScope;\n *\n * $transclude(function(clone, scope) {\n *   element.append(clone);\n *   transcludedContent = clone;\n *   transclusionScope = scope;\n * });\n * ```\n *\n * Later, if you want to remove the transcluded content from your DOM then you should also destroy the\n * associated transclusion scope:\n *\n * ```js\n * transcludedContent.remove();\n * transclusionScope.$destroy();\n * ```\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: if you intend to add and remove transcluded content manually in your directive\n * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),\n * then you are also responsible for calling `$destroy` on the transclusion scope.\n * </div>\n *\n * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}\n * automatically destroy their transluded clones as necessary so you do not need to worry about this if\n * you are simply using {@link ngTransclude} to inject the transclusion into your directive.\n *\n *\n * #### Transclusion Scopes\n *\n * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion\n * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed\n * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it\n * was taken.\n *\n * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look\n * like this:\n *\n * ```html\n * <div ng-app>\n *   <div isolate>\n *     <div transclusion>\n *     </div>\n *   </div>\n * </div>\n * ```\n *\n * The `$parent` scope hierarchy will look like this:\n *\n * ```\n * - $rootScope\n *   - isolate\n *     - transclusion\n * ```\n *\n * but the scopes will inherit prototypically from different scopes to their `$parent`.\n *\n * ```\n * - $rootScope\n *   - transclusion\n * - isolate\n * ```\n *\n *\n * ### Attributes\n *\n * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the\n * `link()` or `compile()` functions. It has a variety of uses.\n *\n * accessing *Normalized attribute names:*\n * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.\n * the attributes object allows for normalized access to\n *   the attributes.\n *\n * * *Directive inter-communication:* All directives share the same instance of the attributes\n *   object which allows the directives to use the attributes object as inter directive\n *   communication.\n *\n * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object\n *   allowing other directives to read the interpolated value.\n *\n * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes\n *   that contain interpolation (e.g. `src=\"{{bar}}\"`). Not only is this very efficient but it's also\n *   the only way to easily get the actual value because during the linking phase the interpolation\n *   hasn't been evaluated yet and so the value is at this time set to `undefined`.\n *\n * ```js\n * function linkingFn(scope, elm, attrs, ctrl) {\n *   // get the attribute value\n *   console.log(attrs.ngModel);\n *\n *   // change the attribute\n *   attrs.$set('ngModel', 'new value');\n *\n *   // observe changes to interpolated attribute\n *   attrs.$observe('ngModel', function(value) {\n *     console.log('ngModel has changed value to ' + value);\n *   });\n * }\n * ```\n *\n * ## Example\n *\n * <div class=\"alert alert-warning\">\n * **Note**: Typically directives are registered with `module.directive`. The example below is\n * to illustrate how `$compile` works.\n * </div>\n *\n <example module=\"compileExample\">\n   <file name=\"index.html\">\n    <script>\n      angular.module('compileExample', [], function($compileProvider) {\n        // configure new 'compile' directive by passing a directive\n        // factory function. The factory function injects the '$compile'\n        $compileProvider.directive('compile', function($compile) {\n          // directive factory creates a link function\n          return function(scope, element, attrs) {\n            scope.$watch(\n              function(scope) {\n                 // watch the 'compile' expression for changes\n                return scope.$eval(attrs.compile);\n              },\n              function(value) {\n                // when the 'compile' expression changes\n                // assign it into the current DOM\n                element.html(value);\n\n                // compile the new DOM and link it to the current\n                // scope.\n                // NOTE: we only compile .childNodes so that\n                // we don't get into infinite loop compiling ourselves\n                $compile(element.contents())(scope);\n              }\n            );\n          };\n        });\n      })\n      .controller('GreeterController', ['$scope', function($scope) {\n        $scope.name = 'Angular';\n        $scope.html = 'Hello {{name}}';\n      }]);\n    </script>\n    <div ng-controller=\"GreeterController\">\n      <input ng-model=\"name\"> <br>\n      <textarea ng-model=\"html\"></textarea> <br>\n      <div compile=\"html\"></div>\n    </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should auto compile', function() {\n       var textarea = $('textarea');\n       var output = $('div[compile]');\n       // The initial state reads 'Hello Angular'.\n       expect(output.getText()).toBe('Hello Angular');\n       textarea.clear();\n       textarea.sendKeys('{{name}}!');\n       expect(output.getText()).toBe('Angular!');\n     });\n   </file>\n </example>\n\n *\n *\n * @param {string|DOMElement} element Element or HTML string to compile into a template function.\n * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.\n *\n * <div class=\"alert alert-error\">\n * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it\n *   e.g. will not use the right outer scope. Please pass the transclude function as a\n *   `parentBoundTranscludeFn` to the link function instead.\n * </div>\n *\n * @param {number} maxPriority only apply directives lower than given priority (Only effects the\n *                 root element(s), not their children)\n * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template\n * (a DOM element/tree) to a scope. Where:\n *\n *  * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.\n *  * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the\n *  `template` and call the `cloneAttachFn` function allowing the caller to attach the\n *  cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is\n *  called as: <br> `cloneAttachFn(clonedElement, scope)` where:\n *\n *      * `clonedElement` - is a clone of the original `element` passed into the compiler.\n *      * `scope` - is the current scope with which the linking function is working with.\n *\n *  * `options` - An optional object hash with linking options. If `options` is provided, then the following\n *  keys may be used to control linking behavior:\n *\n *      * `parentBoundTranscludeFn` - the transclude function made available to\n *        directives; if given, it will be passed through to the link functions of\n *        directives found in `element` during compilation.\n *      * `transcludeControllers` - an object hash with keys that map controller names\n *        to controller instances; if given, it will make the controllers\n *        available to directives.\n *      * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add\n *        the cloned elements; only needed for transcludes that are allowed to contain non html\n *        elements (e.g. SVG elements). See also the directive.controller property.\n *\n * Calling the linking function returns the element of the template. It is either the original\n * element passed in, or the clone of the element if the `cloneAttachFn` is provided.\n *\n * After linking the view is not updated until after a call to $digest which typically is done by\n * Angular automatically.\n *\n * If you need access to the bound view, there are two ways to do it:\n *\n * - If you are not asking the linking function to clone the template, create the DOM element(s)\n *   before you send them to the compiler and keep this reference around.\n *   ```js\n *     var element = $compile('<p>{{total}}</p>')(scope);\n *   ```\n *\n * - if on the other hand, you need the element to be cloned, the view reference from the original\n *   example would not point to the clone, but rather to the original template that was cloned. In\n *   this case, you can access the clone via the cloneAttachFn:\n *   ```js\n *     var templateElement = angular.element('<p>{{total}}</p>'),\n *         scope = ....;\n *\n *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {\n *       //attach the clone to DOM document at the right place\n *     });\n *\n *     //now we have reference to the cloned DOM via `clonedElement`\n *   ```\n *\n *\n * For information on how the compiler works, see the\n * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.\n */\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc provider\n * @name $compileProvider\n *\n * @description\n */\n$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];\nfunction $CompileProvider($provide, $$sanitizeUriProvider) {\n  var hasDirectives = {},\n      Suffix = 'Directive',\n      COMMENT_DIRECTIVE_REGEXP = /^\\s*directive\\:\\s*([\\w\\-]+)\\s+(.*)$/,\n      CLASS_DIRECTIVE_REGEXP = /(([\\w\\-]+)(?:\\:([^;]+))?;?)/,\n      ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),\n      REQUIRE_PREFIX_REGEXP = /^(?:(\\^\\^?)?(\\?)?(\\^\\^?)?)?/;\n\n  // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes\n  // The assumption is that future DOM event attribute names will begin with\n  // 'on' and be composed of only English letters.\n  var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;\n\n  function parseIsolateBindings(scope, directiveName) {\n    var LOCAL_REGEXP = /^\\s*([@&]|=(\\*?))(\\??)\\s*(\\w*)\\s*$/;\n\n    var bindings = {};\n\n    forEach(scope, function(definition, scopeName) {\n      var match = definition.match(LOCAL_REGEXP);\n\n      if (!match) {\n        throw $compileMinErr('iscp',\n            \"Invalid isolate scope definition for directive '{0}'.\" +\n            \" Definition: {... {1}: '{2}' ...}\",\n            directiveName, scopeName, definition);\n      }\n\n      bindings[scopeName] = {\n        mode: match[1][0],\n        collection: match[2] === '*',\n        optional: match[3] === '?',\n        attrName: match[4] || scopeName\n      };\n    });\n\n    return bindings;\n  }\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#directive\n   * @kind function\n   *\n   * @description\n   * Register a new directive with the compiler.\n   *\n   * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which\n   *    will match as <code>ng-bind</code>), or an object map of directives where the keys are the\n   *    names and the values are the factories.\n   * @param {Function|Array} directiveFactory An injectable directive factory function. See\n   *    {@link guide/directive} for more info.\n   * @returns {ng.$compileProvider} Self for chaining.\n   */\n   this.directive = function registerDirective(name, directiveFactory) {\n    assertNotHasOwnProperty(name, 'directive');\n    if (isString(name)) {\n      assertArg(directiveFactory, 'directiveFactory');\n      if (!hasDirectives.hasOwnProperty(name)) {\n        hasDirectives[name] = [];\n        $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',\n          function($injector, $exceptionHandler) {\n            var directives = [];\n            forEach(hasDirectives[name], function(directiveFactory, index) {\n              try {\n                var directive = $injector.invoke(directiveFactory);\n                if (isFunction(directive)) {\n                  directive = { compile: valueFn(directive) };\n                } else if (!directive.compile && directive.link) {\n                  directive.compile = valueFn(directive.link);\n                }\n                directive.priority = directive.priority || 0;\n                directive.index = index;\n                directive.name = directive.name || name;\n                directive.require = directive.require || (directive.controller && directive.name);\n                directive.restrict = directive.restrict || 'EA';\n                if (isObject(directive.scope)) {\n                  directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);\n                }\n                directives.push(directive);\n              } catch (e) {\n                $exceptionHandler(e);\n              }\n            });\n            return directives;\n          }]);\n      }\n      hasDirectives[name].push(directiveFactory);\n    } else {\n      forEach(name, reverseParams(registerDirective));\n    }\n    return this;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#aHrefSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at preventing XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.aHrefSanitizationWhitelist();\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#imgSrcSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name  $compileProvider#debugInfoEnabled\n   *\n   * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the\n   * current debugInfoEnabled state\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   *\n   * @kind function\n   *\n   * @description\n   * Call this method to enable/disable various debug runtime information in the compiler such as adding\n   * binding information and a reference to the current scope on to DOM elements.\n   * If enabled, the compiler will add the following to DOM elements that have been bound to the scope\n   * * `ng-binding` CSS class\n   * * `$binding` data property containing an array of the binding expressions\n   *\n   * You may want to disable this in production for a significant performance boost. See\n   * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.\n   *\n   * The default value is true.\n   */\n  var debugInfoEnabled = true;\n  this.debugInfoEnabled = function(enabled) {\n    if (isDefined(enabled)) {\n      debugInfoEnabled = enabled;\n      return this;\n    }\n    return debugInfoEnabled;\n  };\n\n  this.$get = [\n            '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',\n            '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',\n    function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,\n             $controller,   $rootScope,   $document,   $sce,   $animate,   $$sanitizeUri) {\n\n    var Attributes = function(element, attributesToCopy) {\n      if (attributesToCopy) {\n        var keys = Object.keys(attributesToCopy);\n        var i, l, key;\n\n        for (i = 0, l = keys.length; i < l; i++) {\n          key = keys[i];\n          this[key] = attributesToCopy[key];\n        }\n      } else {\n        this.$attr = {};\n      }\n\n      this.$$element = element;\n    };\n\n    Attributes.prototype = {\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$normalize\n       * @kind function\n       *\n       * @description\n       * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or\n       * `data-`) to its normalized, camelCase form.\n       *\n       * Also there is special case for Moz prefix starting with upper case letter.\n       *\n       * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\n       *\n       * @param {string} name Name to normalize\n       */\n      $normalize: directiveNormalize,\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$addClass\n       * @kind function\n       *\n       * @description\n       * Adds the CSS class value specified by the classVal parameter to the element. If animations\n       * are enabled then an animation will be triggered for the class addition.\n       *\n       * @param {string} classVal The className value that will be added to the element\n       */\n      $addClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.addClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$removeClass\n       * @kind function\n       *\n       * @description\n       * Removes the CSS class value specified by the classVal parameter from the element. If\n       * animations are enabled then an animation will be triggered for the class removal.\n       *\n       * @param {string} classVal The className value that will be removed from the element\n       */\n      $removeClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.removeClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$updateClass\n       * @kind function\n       *\n       * @description\n       * Adds and removes the appropriate CSS class values to the element based on the difference\n       * between the new and old CSS class values (specified as newClasses and oldClasses).\n       *\n       * @param {string} newClasses The current CSS className value\n       * @param {string} oldClasses The former CSS className value\n       */\n      $updateClass: function(newClasses, oldClasses) {\n        var toAdd = tokenDifference(newClasses, oldClasses);\n        if (toAdd && toAdd.length) {\n          $animate.addClass(this.$$element, toAdd);\n        }\n\n        var toRemove = tokenDifference(oldClasses, newClasses);\n        if (toRemove && toRemove.length) {\n          $animate.removeClass(this.$$element, toRemove);\n        }\n      },\n\n      /**\n       * Set a normalized attribute on the element in a way such that all directives\n       * can share the attribute. This function properly handles boolean attributes.\n       * @param {string} key Normalized key. (ie ngAttribute)\n       * @param {string|boolean} value The value to set. If `null` attribute will be deleted.\n       * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.\n       *     Defaults to true.\n       * @param {string=} attrName Optional none normalized name. Defaults to key.\n       */\n      $set: function(key, value, writeAttr, attrName) {\n        // TODO: decide whether or not to throw an error if \"class\"\n        //is set through this function since it may cause $updateClass to\n        //become unstable.\n\n        var node = this.$$element[0],\n            booleanKey = getBooleanAttrName(node, key),\n            aliasedKey = getAliasedAttrName(node, key),\n            observer = key,\n            nodeName;\n\n        if (booleanKey) {\n          this.$$element.prop(key, value);\n          attrName = booleanKey;\n        } else if (aliasedKey) {\n          this[aliasedKey] = value;\n          observer = aliasedKey;\n        }\n\n        this[key] = value;\n\n        // translate normalized key to actual key\n        if (attrName) {\n          this.$attr[key] = attrName;\n        } else {\n          attrName = this.$attr[key];\n          if (!attrName) {\n            this.$attr[key] = attrName = snake_case(key, '-');\n          }\n        }\n\n        nodeName = nodeName_(this.$$element);\n\n        if ((nodeName === 'a' && key === 'href') ||\n            (nodeName === 'img' && key === 'src')) {\n          // sanitize a[href] and img[src] values\n          this[key] = value = $$sanitizeUri(value, key === 'src');\n        } else if (nodeName === 'img' && key === 'srcset') {\n          // sanitize img[srcset] values\n          var result = \"\";\n\n          // first check if there are spaces because it's not the same pattern\n          var trimmedSrcset = trim(value);\n          //                (   999x   ,|   999w   ,|   ,|,   )\n          var srcPattern = /(\\s+\\d+x\\s*,|\\s+\\d+w\\s*,|\\s+,|,\\s+)/;\n          var pattern = /\\s/.test(trimmedSrcset) ? srcPattern : /(,)/;\n\n          // split srcset into tuple of uri and descriptor except for the last item\n          var rawUris = trimmedSrcset.split(pattern);\n\n          // for each tuples\n          var nbrUrisWith2parts = Math.floor(rawUris.length / 2);\n          for (var i = 0; i < nbrUrisWith2parts; i++) {\n            var innerIdx = i * 2;\n            // sanitize the uri\n            result += $$sanitizeUri(trim(rawUris[innerIdx]), true);\n            // add the descriptor\n            result += (\" \" + trim(rawUris[innerIdx + 1]));\n          }\n\n          // split the last item into uri and descriptor\n          var lastTuple = trim(rawUris[i * 2]).split(/\\s/);\n\n          // sanitize the last uri\n          result += $$sanitizeUri(trim(lastTuple[0]), true);\n\n          // and add the last descriptor if any\n          if (lastTuple.length === 2) {\n            result += (\" \" + trim(lastTuple[1]));\n          }\n          this[key] = value = result;\n        }\n\n        if (writeAttr !== false) {\n          if (value === null || value === undefined) {\n            this.$$element.removeAttr(attrName);\n          } else {\n            this.$$element.attr(attrName, value);\n          }\n        }\n\n        // fire observers\n        var $$observers = this.$$observers;\n        $$observers && forEach($$observers[observer], function(fn) {\n          try {\n            fn(value);\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        });\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$observe\n       * @kind function\n       *\n       * @description\n       * Observes an interpolated attribute.\n       *\n       * The observer function will be invoked once during the next `$digest` following\n       * compilation. The observer is then invoked whenever the interpolated value\n       * changes.\n       *\n       * @param {string} key Normalized key. (ie ngAttribute) .\n       * @param {function(interpolatedValue)} fn Function that will be called whenever\n                the interpolated value of the attribute changes.\n       *        See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.\n       * @returns {function()} Returns a deregistration function for this observer.\n       */\n      $observe: function(key, fn) {\n        var attrs = this,\n            $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),\n            listeners = ($$observers[key] || ($$observers[key] = []));\n\n        listeners.push(fn);\n        $rootScope.$evalAsync(function() {\n          if (!listeners.$$inter && attrs.hasOwnProperty(key)) {\n            // no one registered attribute interpolation function, so lets call it manually\n            fn(attrs[key]);\n          }\n        });\n\n        return function() {\n          arrayRemove(listeners, fn);\n        };\n      }\n    };\n\n\n    function safeAddClass($element, className) {\n      try {\n        $element.addClass(className);\n      } catch (e) {\n        // ignore, since it means that we are trying to set class on\n        // SVG element, where class name is read-only.\n      }\n    }\n\n\n    var startSymbol = $interpolate.startSymbol(),\n        endSymbol = $interpolate.endSymbol(),\n        denormalizeTemplate = (startSymbol == '{{' || endSymbol  == '}}')\n            ? identity\n            : function denormalizeTemplate(template) {\n              return template.replace(/\\{\\{/g, startSymbol).replace(/}}/g, endSymbol);\n        },\n        NG_ATTR_BINDING = /^ngAttr[A-Z]/;\n\n    compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {\n      var bindings = $element.data('$binding') || [];\n\n      if (isArray(binding)) {\n        bindings = bindings.concat(binding);\n      } else {\n        bindings.push(binding);\n      }\n\n      $element.data('$binding', bindings);\n    } : noop;\n\n    compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {\n      safeAddClass($element, 'ng-binding');\n    } : noop;\n\n    compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {\n      var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n      $element.data(dataName, scope);\n    } : noop;\n\n    compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {\n      safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');\n    } : noop;\n\n    return compile;\n\n    //================================\n\n    function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,\n                        previousCompileContext) {\n      if (!($compileNodes instanceof jqLite)) {\n        // jquery always rewraps, whereas we need to preserve the original selector so that we can\n        // modify it.\n        $compileNodes = jqLite($compileNodes);\n      }\n      // We can not compile top level text elements since text nodes can be merged and we will\n      // not be able to attach scope data to them, so we will wrap them in <span>\n      forEach($compileNodes, function(node, index) {\n        if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\\S+/) /* non-empty */ ) {\n          $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];\n        }\n      });\n      var compositeLinkFn =\n              compileNodes($compileNodes, transcludeFn, $compileNodes,\n                           maxPriority, ignoreDirective, previousCompileContext);\n      compile.$$addScopeClass($compileNodes);\n      var namespace = null;\n      return function publicLinkFn(scope, cloneConnectFn, options) {\n        assertArg(scope, 'scope');\n\n        options = options || {};\n        var parentBoundTranscludeFn = options.parentBoundTranscludeFn,\n          transcludeControllers = options.transcludeControllers,\n          futureParentElement = options.futureParentElement;\n\n        // When `parentBoundTranscludeFn` is passed, it is a\n        // `controllersBoundTransclude` function (it was previously passed\n        // as `transclude` to directive.link) so we must unwrap it to get\n        // its `boundTranscludeFn`\n        if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {\n          parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;\n        }\n\n        if (!namespace) {\n          namespace = detectNamespaceForChildElements(futureParentElement);\n        }\n        var $linkNode;\n        if (namespace !== 'html') {\n          // When using a directive with replace:true and templateUrl the $compileNodes\n          // (or a child element inside of them)\n          // might change, so we need to recreate the namespace adapted compileNodes\n          // for call to the link function.\n          // Note: This will already clone the nodes...\n          $linkNode = jqLite(\n            wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())\n          );\n        } else if (cloneConnectFn) {\n          // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart\n          // and sometimes changes the structure of the DOM.\n          $linkNode = JQLitePrototype.clone.call($compileNodes);\n        } else {\n          $linkNode = $compileNodes;\n        }\n\n        if (transcludeControllers) {\n          for (var controllerName in transcludeControllers) {\n            $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);\n          }\n        }\n\n        compile.$$addScopeInfo($linkNode, scope);\n\n        if (cloneConnectFn) cloneConnectFn($linkNode, scope);\n        if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);\n        return $linkNode;\n      };\n    }\n\n    function detectNamespaceForChildElements(parentElement) {\n      // TODO: Make this detect MathML as well...\n      var node = parentElement && parentElement[0];\n      if (!node) {\n        return 'html';\n      } else {\n        return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';\n      }\n    }\n\n    /**\n     * Compile function matches each node in nodeList against the directives. Once all directives\n     * for a particular node are collected their compile functions are executed. The compile\n     * functions return values - the linking functions - are combined into a composite linking\n     * function, which is the a linking function for the node.\n     *\n     * @param {NodeList} nodeList an array of nodes or NodeList to compile\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *        scope argument is auto-generated to the new child of the transcluded parent scope.\n     * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then\n     *        the rootElement must be set the jqLite collection of the compile root. This is\n     *        needed so that the jqLite collection items can be replaced with widgets.\n     * @param {number=} maxPriority Max directive priority.\n     * @returns {Function} A composite linking function of all of the matched directives or null.\n     */\n    function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,\n                            previousCompileContext) {\n      var linkFns = [],\n          attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;\n\n      for (var i = 0; i < nodeList.length; i++) {\n        attrs = new Attributes();\n\n        // we must always refer to nodeList[i] since the nodes can be replaced underneath us.\n        directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,\n                                        ignoreDirective);\n\n        nodeLinkFn = (directives.length)\n            ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,\n                                      null, [], [], previousCompileContext)\n            : null;\n\n        if (nodeLinkFn && nodeLinkFn.scope) {\n          compile.$$addScopeClass(attrs.$$element);\n        }\n\n        childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||\n                      !(childNodes = nodeList[i].childNodes) ||\n                      !childNodes.length)\n            ? null\n            : compileNodes(childNodes,\n                 nodeLinkFn ? (\n                  (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)\n                     && nodeLinkFn.transclude) : transcludeFn);\n\n        if (nodeLinkFn || childLinkFn) {\n          linkFns.push(i, nodeLinkFn, childLinkFn);\n          linkFnFound = true;\n          nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;\n        }\n\n        //use the previous context only for the first element in the virtual group\n        previousCompileContext = null;\n      }\n\n      // return a linking function if we have found anything, null otherwise\n      return linkFnFound ? compositeLinkFn : null;\n\n      function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {\n        var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;\n        var stableNodeList;\n\n\n        if (nodeLinkFnFound) {\n          // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our\n          // offsets don't get screwed up\n          var nodeListLength = nodeList.length;\n          stableNodeList = new Array(nodeListLength);\n\n          // create a sparse array by only copying the elements which have a linkFn\n          for (i = 0; i < linkFns.length; i+=3) {\n            idx = linkFns[i];\n            stableNodeList[idx] = nodeList[idx];\n          }\n        } else {\n          stableNodeList = nodeList;\n        }\n\n        for (i = 0, ii = linkFns.length; i < ii;) {\n          node = stableNodeList[linkFns[i++]];\n          nodeLinkFn = linkFns[i++];\n          childLinkFn = linkFns[i++];\n\n          if (nodeLinkFn) {\n            if (nodeLinkFn.scope) {\n              childScope = scope.$new();\n              compile.$$addScopeInfo(jqLite(node), childScope);\n            } else {\n              childScope = scope;\n            }\n\n            if (nodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(\n                  scope, nodeLinkFn.transclude, parentBoundTranscludeFn,\n                  nodeLinkFn.elementTranscludeOnThisElement);\n\n            } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {\n              childBoundTranscludeFn = parentBoundTranscludeFn;\n\n            } else if (!parentBoundTranscludeFn && transcludeFn) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);\n\n            } else {\n              childBoundTranscludeFn = null;\n            }\n\n            nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);\n\n          } else if (childLinkFn) {\n            childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);\n          }\n        }\n      }\n    }\n\n    function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {\n\n      var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {\n\n        if (!transcludedScope) {\n          transcludedScope = scope.$new(false, containingScope);\n          transcludedScope.$$transcluded = true;\n        }\n\n        return transcludeFn(transcludedScope, cloneFn, {\n          parentBoundTranscludeFn: previousBoundTranscludeFn,\n          transcludeControllers: controllers,\n          futureParentElement: futureParentElement\n        });\n      };\n\n      return boundTranscludeFn;\n    }\n\n    /**\n     * Looks for directives on the given node and adds them to the directive collection which is\n     * sorted.\n     *\n     * @param node Node to search.\n     * @param directives An array to which the directives are added to. This array is sorted before\n     *        the function returns.\n     * @param attrs The shared attrs object which is used to populate the normalized attributes.\n     * @param {number=} maxPriority Max directive priority.\n     */\n    function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n      var nodeType = node.nodeType,\n          attrsMap = attrs.$attr,\n          match,\n          className;\n\n      switch (nodeType) {\n        case NODE_TYPE_ELEMENT: /* Element */\n          // use the node name: <directive>\n          addDirective(directives,\n              directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);\n\n          // iterate over the attributes\n          for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,\n                   j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {\n            var attrStartName = false;\n            var attrEndName = false;\n\n            attr = nAttrs[j];\n            name = attr.name;\n            value = trim(attr.value);\n\n            // support ngAttr attribute binding\n            ngAttrName = directiveNormalize(name);\n            if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {\n              name = name.replace(PREFIX_REGEXP, '')\n                .substr(8).replace(/_(.)/g, function(match, letter) {\n                  return letter.toUpperCase();\n                });\n            }\n\n            var directiveNName = ngAttrName.replace(/(Start|End)$/, '');\n            if (directiveIsMultiElement(directiveNName)) {\n              if (ngAttrName === directiveNName + 'Start') {\n                attrStartName = name;\n                attrEndName = name.substr(0, name.length - 5) + 'end';\n                name = name.substr(0, name.length - 6);\n              }\n            }\n\n            nName = directiveNormalize(name.toLowerCase());\n            attrsMap[nName] = name;\n            if (isNgAttr || !attrs.hasOwnProperty(nName)) {\n                attrs[nName] = value;\n                if (getBooleanAttrName(node, nName)) {\n                  attrs[nName] = true; // presence means true\n                }\n            }\n            addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);\n            addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,\n                          attrEndName);\n          }\n\n          // use class as directive\n          className = node.className;\n          if (isObject(className)) {\n              // Maybe SVGAnimatedString\n              className = className.animVal;\n          }\n          if (isString(className) && className !== '') {\n            while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {\n              nName = directiveNormalize(match[2]);\n              if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[3]);\n              }\n              className = className.substr(match.index + match[0].length);\n            }\n          }\n          break;\n        case NODE_TYPE_TEXT: /* Text Node */\n          addTextInterpolateDirective(directives, node.nodeValue);\n          break;\n        case NODE_TYPE_COMMENT: /* Comment */\n          try {\n            match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);\n            if (match) {\n              nName = directiveNormalize(match[1]);\n              if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[2]);\n              }\n            }\n          } catch (e) {\n            // turns out that under some circumstances IE9 throws errors when one attempts to read\n            // comment's node value.\n            // Just ignore it and continue. (Can't seem to reproduce in test case.)\n          }\n          break;\n      }\n\n      directives.sort(byPriority);\n      return directives;\n    }\n\n    /**\n     * Given a node with an directive-start it collects all of the siblings until it finds\n     * directive-end.\n     * @param node\n     * @param attrStart\n     * @param attrEnd\n     * @returns {*}\n     */\n    function groupScan(node, attrStart, attrEnd) {\n      var nodes = [];\n      var depth = 0;\n      if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {\n        do {\n          if (!node) {\n            throw $compileMinErr('uterdir',\n                      \"Unterminated attribute, found '{0}' but no matching '{1}' found.\",\n                      attrStart, attrEnd);\n          }\n          if (node.nodeType == NODE_TYPE_ELEMENT) {\n            if (node.hasAttribute(attrStart)) depth++;\n            if (node.hasAttribute(attrEnd)) depth--;\n          }\n          nodes.push(node);\n          node = node.nextSibling;\n        } while (depth > 0);\n      } else {\n        nodes.push(node);\n      }\n\n      return jqLite(nodes);\n    }\n\n    /**\n     * Wrapper for linking function which converts normal linking function into a grouped\n     * linking function.\n     * @param linkFn\n     * @param attrStart\n     * @param attrEnd\n     * @returns {Function}\n     */\n    function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {\n      return function(scope, element, attrs, controllers, transcludeFn) {\n        element = groupScan(element[0], attrStart, attrEnd);\n        return linkFn(scope, element, attrs, controllers, transcludeFn);\n      };\n    }\n\n    /**\n     * Once the directives have been collected, their compile functions are executed. This method\n     * is responsible for inlining directive templates as well as terminating the application\n     * of the directives if the terminal directive has been reached.\n     *\n     * @param {Array} directives Array of collected directives to execute their compile function.\n     *        this needs to be pre-sorted by priority order.\n     * @param {Node} compileNode The raw DOM node to apply the compile functions to\n     * @param {Object} templateAttrs The shared attribute function\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *                                                  scope argument is auto-generated to the new\n     *                                                  child of the transcluded parent scope.\n     * @param {JQLite} jqCollection If we are working on the root of the compile tree then this\n     *                              argument has the root jqLite array so that we can replace nodes\n     *                              on it.\n     * @param {Object=} originalReplaceDirective An optional directive that will be ignored when\n     *                                           compiling the transclusion.\n     * @param {Array.<Function>} preLinkFns\n     * @param {Array.<Function>} postLinkFns\n     * @param {Object} previousCompileContext Context used for previous compilation of the current\n     *                                        node\n     * @returns {Function} linkFn\n     */\n    function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,\n                                   jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,\n                                   previousCompileContext) {\n      previousCompileContext = previousCompileContext || {};\n\n      var terminalPriority = -Number.MAX_VALUE,\n          newScopeDirective,\n          controllerDirectives = previousCompileContext.controllerDirectives,\n          controllers,\n          newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,\n          templateDirective = previousCompileContext.templateDirective,\n          nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,\n          hasTranscludeDirective = false,\n          hasTemplate = false,\n          hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,\n          $compileNode = templateAttrs.$$element = jqLite(compileNode),\n          directive,\n          directiveName,\n          $template,\n          replaceDirective = originalReplaceDirective,\n          childTranscludeFn = transcludeFn,\n          linkFn,\n          directiveValue;\n\n      // executes all directives on the current element\n      for (var i = 0, ii = directives.length; i < ii; i++) {\n        directive = directives[i];\n        var attrStart = directive.$$start;\n        var attrEnd = directive.$$end;\n\n        // collect multiblock sections\n        if (attrStart) {\n          $compileNode = groupScan(compileNode, attrStart, attrEnd);\n        }\n        $template = undefined;\n\n        if (terminalPriority > directive.priority) {\n          break; // prevent further processing of directives\n        }\n\n        if (directiveValue = directive.scope) {\n\n          // skip the check for directives with async templates, we'll check the derived sync\n          // directive when the template arrives\n          if (!directive.templateUrl) {\n            if (isObject(directiveValue)) {\n              // This directive is trying to add an isolated scope.\n              // Check that there is no scope of any kind already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,\n                                directive, $compileNode);\n              newIsolateScopeDirective = directive;\n            } else {\n              // This directive is trying to add a child scope.\n              // Check that there is no isolated scope already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,\n                                $compileNode);\n            }\n          }\n\n          newScopeDirective = newScopeDirective || directive;\n        }\n\n        directiveName = directive.name;\n\n        if (!directive.templateUrl && directive.controller) {\n          directiveValue = directive.controller;\n          controllerDirectives = controllerDirectives || {};\n          assertNoDuplicate(\"'\" + directiveName + \"' controller\",\n              controllerDirectives[directiveName], directive, $compileNode);\n          controllerDirectives[directiveName] = directive;\n        }\n\n        if (directiveValue = directive.transclude) {\n          hasTranscludeDirective = true;\n\n          // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.\n          // This option should only be used by directives that know how to safely handle element transclusion,\n          // where the transcluded nodes are added or replaced after linking.\n          if (!directive.$$tlb) {\n            assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);\n            nonTlbTranscludeDirective = directive;\n          }\n\n          if (directiveValue == 'element') {\n            hasElementTranscludeDirective = true;\n            terminalPriority = directive.priority;\n            $template = $compileNode;\n            $compileNode = templateAttrs.$$element =\n                jqLite(document.createComment(' ' + directiveName + ': ' +\n                                              templateAttrs[directiveName] + ' '));\n            compileNode = $compileNode[0];\n            replaceWith(jqCollection, sliceArgs($template), compileNode);\n\n            childTranscludeFn = compile($template, transcludeFn, terminalPriority,\n                                        replaceDirective && replaceDirective.name, {\n                                          // Don't pass in:\n                                          // - controllerDirectives - otherwise we'll create duplicates controllers\n                                          // - newIsolateScopeDirective or templateDirective - combining templates with\n                                          //   element transclusion doesn't make sense.\n                                          //\n                                          // We need only nonTlbTranscludeDirective so that we prevent putting transclusion\n                                          // on the same element more than once.\n                                          nonTlbTranscludeDirective: nonTlbTranscludeDirective\n                                        });\n          } else {\n            $template = jqLite(jqLiteClone(compileNode)).contents();\n            $compileNode.empty(); // clear contents\n            childTranscludeFn = compile($template, transcludeFn);\n          }\n        }\n\n        if (directive.template) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          directiveValue = (isFunction(directive.template))\n              ? directive.template($compileNode, templateAttrs)\n              : directive.template;\n\n          directiveValue = denormalizeTemplate(directiveValue);\n\n          if (directive.replace) {\n            replaceDirective = directive;\n            if (jqLiteIsTextNode(directiveValue)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  directiveName, '');\n            }\n\n            replaceWith(jqCollection, $compileNode, compileNode);\n\n            var newTemplateAttrs = {$attr: {}};\n\n            // combine directives from the original node and from the template:\n            // - take the array of directives for this element\n            // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)\n            // - collect directives from the template and sort them by priority\n            // - combine directives as: processed + template + unprocessed\n            var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);\n            var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));\n\n            if (newIsolateScopeDirective) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = directives.concat(templateDirectives).concat(unprocessedDirectives);\n            mergeTemplateAttributes(templateAttrs, newTemplateAttrs);\n\n            ii = directives.length;\n          } else {\n            $compileNode.html(directiveValue);\n          }\n        }\n\n        if (directive.templateUrl) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          if (directive.replace) {\n            replaceDirective = directive;\n          }\n\n          nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,\n              templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {\n                controllerDirectives: controllerDirectives,\n                newIsolateScopeDirective: newIsolateScopeDirective,\n                templateDirective: templateDirective,\n                nonTlbTranscludeDirective: nonTlbTranscludeDirective\n              });\n          ii = directives.length;\n        } else if (directive.compile) {\n          try {\n            linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);\n            if (isFunction(linkFn)) {\n              addLinkFns(null, linkFn, attrStart, attrEnd);\n            } else if (linkFn) {\n              addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);\n            }\n          } catch (e) {\n            $exceptionHandler(e, startingTag($compileNode));\n          }\n        }\n\n        if (directive.terminal) {\n          nodeLinkFn.terminal = true;\n          terminalPriority = Math.max(terminalPriority, directive.priority);\n        }\n\n      }\n\n      nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;\n      nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;\n      nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;\n      nodeLinkFn.templateOnThisElement = hasTemplate;\n      nodeLinkFn.transclude = childTranscludeFn;\n\n      previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;\n\n      // might be normal or delayed nodeLinkFn depending on if templateUrl is present\n      return nodeLinkFn;\n\n      ////////////////////\n\n      function addLinkFns(pre, post, attrStart, attrEnd) {\n        if (pre) {\n          if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);\n          pre.require = directive.require;\n          pre.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            pre = cloneAndAnnotateFn(pre, {isolateScope: true});\n          }\n          preLinkFns.push(pre);\n        }\n        if (post) {\n          if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);\n          post.require = directive.require;\n          post.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            post = cloneAndAnnotateFn(post, {isolateScope: true});\n          }\n          postLinkFns.push(post);\n        }\n      }\n\n\n      function getControllers(directiveName, require, $element, elementControllers) {\n        var value, retrievalMethod = 'data', optional = false;\n        var $searchElement = $element;\n        var match;\n        if (isString(require)) {\n          match = require.match(REQUIRE_PREFIX_REGEXP);\n          require = require.substring(match[0].length);\n\n          if (match[3]) {\n            if (match[1]) match[3] = null;\n            else match[1] = match[3];\n          }\n          if (match[1] === '^') {\n            retrievalMethod = 'inheritedData';\n          } else if (match[1] === '^^') {\n            retrievalMethod = 'inheritedData';\n            $searchElement = $element.parent();\n          }\n          if (match[2] === '?') {\n            optional = true;\n          }\n\n          value = null;\n\n          if (elementControllers && retrievalMethod === 'data') {\n            if (value = elementControllers[require]) {\n              value = value.instance;\n            }\n          }\n          value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');\n\n          if (!value && !optional) {\n            throw $compileMinErr('ctreq',\n                \"Controller '{0}', required by directive '{1}', can't be found!\",\n                require, directiveName);\n          }\n          return value || null;\n        } else if (isArray(require)) {\n          value = [];\n          forEach(require, function(require) {\n            value.push(getControllers(directiveName, require, $element, elementControllers));\n          });\n        }\n        return value;\n      }\n\n\n      function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {\n        var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,\n            attrs;\n\n        if (compileNode === linkNode) {\n          attrs = templateAttrs;\n          $element = templateAttrs.$$element;\n        } else {\n          $element = jqLite(linkNode);\n          attrs = new Attributes($element, templateAttrs);\n        }\n\n        if (newIsolateScopeDirective) {\n          isolateScope = scope.$new(true);\n        }\n\n        if (boundTranscludeFn) {\n          // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`\n          // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`\n          transcludeFn = controllersBoundTransclude;\n          transcludeFn.$$boundTransclude = boundTranscludeFn;\n        }\n\n        if (controllerDirectives) {\n          // TODO: merge `controllers` and `elementControllers` into single object.\n          controllers = {};\n          elementControllers = {};\n          forEach(controllerDirectives, function(directive) {\n            var locals = {\n              $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,\n              $element: $element,\n              $attrs: attrs,\n              $transclude: transcludeFn\n            }, controllerInstance;\n\n            controller = directive.controller;\n            if (controller == '@') {\n              controller = attrs[directive.name];\n            }\n\n            controllerInstance = $controller(controller, locals, true, directive.controllerAs);\n\n            // For directives with element transclusion the element is a comment,\n            // but jQuery .data doesn't support attaching data to comment nodes as it's hard to\n            // clean up (http://bugs.jquery.com/ticket/8335).\n            // Instead, we save the controllers for the element in a local hash and attach to .data\n            // later, once we have the actual element.\n            elementControllers[directive.name] = controllerInstance;\n            if (!hasElementTranscludeDirective) {\n              $element.data('$' + directive.name + 'Controller', controllerInstance.instance);\n            }\n\n            controllers[directive.name] = controllerInstance;\n          });\n        }\n\n        if (newIsolateScopeDirective) {\n          compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||\n              templateDirective === newIsolateScopeDirective.$$originalDirective)));\n          compile.$$addScopeClass($element, true);\n\n          var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];\n          var isolateBindingContext = isolateScope;\n          if (isolateScopeController && isolateScopeController.identifier &&\n              newIsolateScopeDirective.bindToController === true) {\n            isolateBindingContext = isolateScopeController.instance;\n          }\n\n          forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {\n            var attrName = definition.attrName,\n                optional = definition.optional,\n                mode = definition.mode, // @, =, or &\n                lastValue,\n                parentGet, parentSet, compare;\n\n            switch (mode) {\n\n              case '@':\n                attrs.$observe(attrName, function(value) {\n                  isolateBindingContext[scopeName] = value;\n                });\n                attrs.$$observers[attrName].$$scope = scope;\n                if (attrs[attrName]) {\n                  // If the attribute has been provided then we trigger an interpolation to ensure\n                  // the value is there for use in the link fn\n                  isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);\n                }\n                break;\n\n              case '=':\n                if (optional && !attrs[attrName]) {\n                  return;\n                }\n                parentGet = $parse(attrs[attrName]);\n                if (parentGet.literal) {\n                  compare = equals;\n                } else {\n                  compare = function(a, b) { return a === b || (a !== a && b !== b); };\n                }\n                parentSet = parentGet.assign || function() {\n                  // reset the change, or we will throw this exception on every $digest\n                  lastValue = isolateBindingContext[scopeName] = parentGet(scope);\n                  throw $compileMinErr('nonassign',\n                      \"Expression '{0}' used with directive '{1}' is non-assignable!\",\n                      attrs[attrName], newIsolateScopeDirective.name);\n                };\n                lastValue = isolateBindingContext[scopeName] = parentGet(scope);\n                var parentValueWatch = function parentValueWatch(parentValue) {\n                  if (!compare(parentValue, isolateBindingContext[scopeName])) {\n                    // we are out of sync and need to copy\n                    if (!compare(parentValue, lastValue)) {\n                      // parent changed and it has precedence\n                      isolateBindingContext[scopeName] = parentValue;\n                    } else {\n                      // if the parent can be assigned then do so\n                      parentSet(scope, parentValue = isolateBindingContext[scopeName]);\n                    }\n                  }\n                  return lastValue = parentValue;\n                };\n                parentValueWatch.$stateful = true;\n                var unwatch;\n                if (definition.collection) {\n                  unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);\n                } else {\n                  unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);\n                }\n                isolateScope.$on('$destroy', unwatch);\n                break;\n\n              case '&':\n                parentGet = $parse(attrs[attrName]);\n                isolateBindingContext[scopeName] = function(locals) {\n                  return parentGet(scope, locals);\n                };\n                break;\n            }\n          });\n        }\n        if (controllers) {\n          forEach(controllers, function(controller) {\n            controller();\n          });\n          controllers = null;\n        }\n\n        // PRELINKING\n        for (i = 0, ii = preLinkFns.length; i < ii; i++) {\n          linkFn = preLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // RECURSION\n        // We only pass the isolate scope, if the isolate directive has a template,\n        // otherwise the child elements do not belong to the isolate directive.\n        var scopeToChild = scope;\n        if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {\n          scopeToChild = isolateScope;\n        }\n        childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);\n\n        // POSTLINKING\n        for (i = postLinkFns.length - 1; i >= 0; i--) {\n          linkFn = postLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // This is the function that is injected as `$transclude`.\n        // Note: all arguments are optional!\n        function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {\n          var transcludeControllers;\n\n          // No scope passed in:\n          if (!isScope(scope)) {\n            futureParentElement = cloneAttachFn;\n            cloneAttachFn = scope;\n            scope = undefined;\n          }\n\n          if (hasElementTranscludeDirective) {\n            transcludeControllers = elementControllers;\n          }\n          if (!futureParentElement) {\n            futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;\n          }\n          return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n        }\n      }\n    }\n\n    function markDirectivesAsIsolate(directives) {\n      // mark all directives as needing isolate scope.\n      for (var j = 0, jj = directives.length; j < jj; j++) {\n        directives[j] = inherit(directives[j], {$$isolateScope: true});\n      }\n    }\n\n    /**\n     * looks up the directive and decorates it with exception handling and proper parameters. We\n     * call this the boundDirective.\n     *\n     * @param {string} name name of the directive to look up.\n     * @param {string} location The directive must be found in specific format.\n     *   String containing any of theses characters:\n     *\n     *   * `E`: element name\n     *   * `A': attribute\n     *   * `C`: class\n     *   * `M`: comment\n     * @returns {boolean} true if directive was added.\n     */\n    function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,\n                          endAttrName) {\n      if (name === ignoreDirective) return null;\n      var match = null;\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          try {\n            directive = directives[i];\n            if ((maxPriority === undefined || maxPriority > directive.priority) &&\n                 directive.restrict.indexOf(location) != -1) {\n              if (startAttrName) {\n                directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});\n              }\n              tDirectives.push(directive);\n              match = directive;\n            }\n          } catch (e) { $exceptionHandler(e); }\n        }\n      }\n      return match;\n    }\n\n\n    /**\n     * looks up the directive and returns true if it is a multi-element directive,\n     * and therefore requires DOM nodes between -start and -end markers to be grouped\n     * together.\n     *\n     * @param {string} name name of the directive to look up.\n     * @returns true if directive was registered as multi-element.\n     */\n    function directiveIsMultiElement(name) {\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          directive = directives[i];\n          if (directive.multiElement) {\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n\n    /**\n     * When the element is replaced with HTML template then the new attributes\n     * on the template need to be merged with the existing attributes in the DOM.\n     * The desired effect is to have both of the attributes present.\n     *\n     * @param {object} dst destination attributes (original DOM)\n     * @param {object} src source attributes (from the directive template)\n     */\n    function mergeTemplateAttributes(dst, src) {\n      var srcAttr = src.$attr,\n          dstAttr = dst.$attr,\n          $element = dst.$$element;\n\n      // reapply the old attributes to the new element\n      forEach(dst, function(value, key) {\n        if (key.charAt(0) != '$') {\n          if (src[key] && src[key] !== value) {\n            value += (key === 'style' ? ';' : ' ') + src[key];\n          }\n          dst.$set(key, value, true, srcAttr[key]);\n        }\n      });\n\n      // copy the new attributes on the old attrs object\n      forEach(src, function(value, key) {\n        if (key == 'class') {\n          safeAddClass($element, value);\n          dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;\n        } else if (key == 'style') {\n          $element.attr('style', $element.attr('style') + ';' + value);\n          dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;\n          // `dst` will never contain hasOwnProperty as DOM parser won't let it.\n          // You will get an \"InvalidCharacterError: DOM Exception 5\" error if you\n          // have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.\n        } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {\n          dst[key] = value;\n          dstAttr[key] = srcAttr[key];\n        }\n      });\n    }\n\n\n    function compileTemplateUrl(directives, $compileNode, tAttrs,\n        $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {\n      var linkQueue = [],\n          afterTemplateNodeLinkFn,\n          afterTemplateChildLinkFn,\n          beforeTemplateCompileNode = $compileNode[0],\n          origAsyncDirective = directives.shift(),\n          derivedSyncDirective = inherit(origAsyncDirective, {\n            templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective\n          }),\n          templateUrl = (isFunction(origAsyncDirective.templateUrl))\n              ? origAsyncDirective.templateUrl($compileNode, tAttrs)\n              : origAsyncDirective.templateUrl,\n          templateNamespace = origAsyncDirective.templateNamespace;\n\n      $compileNode.empty();\n\n      $templateRequest($sce.getTrustedResourceUrl(templateUrl))\n        .then(function(content) {\n          var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;\n\n          content = denormalizeTemplate(content);\n\n          if (origAsyncDirective.replace) {\n            if (jqLiteIsTextNode(content)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(templateNamespace, trim(content)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  origAsyncDirective.name, templateUrl);\n            }\n\n            tempTemplateAttrs = {$attr: {}};\n            replaceWith($rootElement, $compileNode, compileNode);\n            var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);\n\n            if (isObject(origAsyncDirective.scope)) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = templateDirectives.concat(directives);\n            mergeTemplateAttributes(tAttrs, tempTemplateAttrs);\n          } else {\n            compileNode = beforeTemplateCompileNode;\n            $compileNode.html(content);\n          }\n\n          directives.unshift(derivedSyncDirective);\n\n          afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,\n              childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,\n              previousCompileContext);\n          forEach($rootElement, function(node, i) {\n            if (node == compileNode) {\n              $rootElement[i] = $compileNode[0];\n            }\n          });\n          afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);\n\n          while (linkQueue.length) {\n            var scope = linkQueue.shift(),\n                beforeTemplateLinkNode = linkQueue.shift(),\n                linkRootElement = linkQueue.shift(),\n                boundTranscludeFn = linkQueue.shift(),\n                linkNode = $compileNode[0];\n\n            if (scope.$$destroyed) continue;\n\n            if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {\n              var oldClasses = beforeTemplateLinkNode.className;\n\n              if (!(previousCompileContext.hasElementTranscludeDirective &&\n                  origAsyncDirective.replace)) {\n                // it was cloned therefore we have to clone as well.\n                linkNode = jqLiteClone(compileNode);\n              }\n              replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);\n\n              // Copy in CSS classes from original node\n              safeAddClass(jqLite(linkNode), oldClasses);\n            }\n            if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n            } else {\n              childBoundTranscludeFn = boundTranscludeFn;\n            }\n            afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,\n              childBoundTranscludeFn);\n          }\n          linkQueue = null;\n        });\n\n      return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {\n        var childBoundTranscludeFn = boundTranscludeFn;\n        if (scope.$$destroyed) return;\n        if (linkQueue) {\n          linkQueue.push(scope,\n                         node,\n                         rootElement,\n                         childBoundTranscludeFn);\n        } else {\n          if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n            childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n          }\n          afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);\n        }\n      };\n    }\n\n\n    /**\n     * Sorting function for bound directives.\n     */\n    function byPriority(a, b) {\n      var diff = b.priority - a.priority;\n      if (diff !== 0) return diff;\n      if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;\n      return a.index - b.index;\n    }\n\n\n    function assertNoDuplicate(what, previousDirective, directive, element) {\n      if (previousDirective) {\n        throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',\n            previousDirective.name, directive.name, what, startingTag(element));\n      }\n    }\n\n\n    function addTextInterpolateDirective(directives, text) {\n      var interpolateFn = $interpolate(text, true);\n      if (interpolateFn) {\n        directives.push({\n          priority: 0,\n          compile: function textInterpolateCompileFn(templateNode) {\n            var templateNodeParent = templateNode.parent(),\n                hasCompileParent = !!templateNodeParent.length;\n\n            // When transcluding a template that has bindings in the root\n            // we don't have a parent and thus need to add the class during linking fn.\n            if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);\n\n            return function textInterpolateLinkFn(scope, node) {\n              var parent = node.parent();\n              if (!hasCompileParent) compile.$$addBindingClass(parent);\n              compile.$$addBindingInfo(parent, interpolateFn.expressions);\n              scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {\n                node[0].nodeValue = value;\n              });\n            };\n          }\n        });\n      }\n    }\n\n\n    function wrapTemplate(type, template) {\n      type = lowercase(type || 'html');\n      switch (type) {\n      case 'svg':\n      case 'math':\n        var wrapper = document.createElement('div');\n        wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';\n        return wrapper.childNodes[0].childNodes;\n      default:\n        return template;\n      }\n    }\n\n\n    function getTrustedContext(node, attrNormalizedName) {\n      if (attrNormalizedName == \"srcdoc\") {\n        return $sce.HTML;\n      }\n      var tag = nodeName_(node);\n      // maction[xlink:href] can source SVG.  It's not limited to <maction>.\n      if (attrNormalizedName == \"xlinkHref\" ||\n          (tag == \"form\" && attrNormalizedName == \"action\") ||\n          (tag != \"img\" && (attrNormalizedName == \"src\" ||\n                            attrNormalizedName == \"ngSrc\"))) {\n        return $sce.RESOURCE_URL;\n      }\n    }\n\n\n    function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {\n      var trustedContext = getTrustedContext(node, name);\n      allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;\n\n      var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);\n\n      // no interpolation found -> ignore\n      if (!interpolateFn) return;\n\n\n      if (name === \"multiple\" && nodeName_(node) === \"select\") {\n        throw $compileMinErr(\"selmulti\",\n            \"Binding to the 'multiple' attribute is not supported. Element: {0}\",\n            startingTag(node));\n      }\n\n      directives.push({\n        priority: 100,\n        compile: function() {\n            return {\n              pre: function attrInterpolatePreLinkFn(scope, element, attr) {\n                var $$observers = (attr.$$observers || (attr.$$observers = {}));\n\n                if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {\n                  throw $compileMinErr('nodomevents',\n                      \"Interpolations for HTML DOM event attributes are disallowed.  Please use the \" +\n                          \"ng- versions (such as ng-click instead of onclick) instead.\");\n                }\n\n                // If the attribute has changed since last $interpolate()ed\n                var newValue = attr[name];\n                if (newValue !== value) {\n                  // we need to interpolate again since the attribute value has been updated\n                  // (e.g. by another directive's compile function)\n                  // ensure unset/empty values make interpolateFn falsy\n                  interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);\n                  value = newValue;\n                }\n\n                // if attribute was updated so that there is no interpolation going on we don't want to\n                // register any observers\n                if (!interpolateFn) return;\n\n                // initialize attr object so that it's ready in case we need the value for isolate\n                // scope initialization, otherwise the value would not be available from isolate\n                // directive's linking fn during linking phase\n                attr[name] = interpolateFn(scope);\n\n                ($$observers[name] || ($$observers[name] = [])).$$inter = true;\n                (attr.$$observers && attr.$$observers[name].$$scope || scope).\n                  $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {\n                    //special case for class attribute addition + removal\n                    //so that class changes can tap into the animation\n                    //hooks provided by the $animate service. Be sure to\n                    //skip animations when the first digest occurs (when\n                    //both the new and the old values are the same) since\n                    //the CSS classes are the non-interpolated values\n                    if (name === 'class' && newValue != oldValue) {\n                      attr.$updateClass(newValue, oldValue);\n                    } else {\n                      attr.$set(name, newValue);\n                    }\n                  });\n              }\n            };\n          }\n      });\n    }\n\n\n    /**\n     * This is a special jqLite.replaceWith, which can replace items which\n     * have no parents, provided that the containing jqLite collection is provided.\n     *\n     * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes\n     *                               in the root of the tree.\n     * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep\n     *                                  the shell, but replace its DOM node reference.\n     * @param {Node} newNode The new DOM node.\n     */\n    function replaceWith($rootElement, elementsToRemove, newNode) {\n      var firstElementToRemove = elementsToRemove[0],\n          removeCount = elementsToRemove.length,\n          parent = firstElementToRemove.parentNode,\n          i, ii;\n\n      if ($rootElement) {\n        for (i = 0, ii = $rootElement.length; i < ii; i++) {\n          if ($rootElement[i] == firstElementToRemove) {\n            $rootElement[i++] = newNode;\n            for (var j = i, j2 = j + removeCount - 1,\n                     jj = $rootElement.length;\n                 j < jj; j++, j2++) {\n              if (j2 < jj) {\n                $rootElement[j] = $rootElement[j2];\n              } else {\n                delete $rootElement[j];\n              }\n            }\n            $rootElement.length -= removeCount - 1;\n\n            // If the replaced element is also the jQuery .context then replace it\n            // .context is a deprecated jQuery api, so we should set it only when jQuery set it\n            // http://api.jquery.com/context/\n            if ($rootElement.context === firstElementToRemove) {\n              $rootElement.context = newNode;\n            }\n            break;\n          }\n        }\n      }\n\n      if (parent) {\n        parent.replaceChild(newNode, firstElementToRemove);\n      }\n\n      // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?\n      var fragment = document.createDocumentFragment();\n      fragment.appendChild(firstElementToRemove);\n\n      // Copy over user data (that includes Angular's $scope etc.). Don't copy private\n      // data here because there's no public interface in jQuery to do that and copying over\n      // event listeners (which is the main use of private data) wouldn't work anyway.\n      jqLite(newNode).data(jqLite(firstElementToRemove).data());\n\n      // Remove data of the replaced element. We cannot just call .remove()\n      // on the element it since that would deallocate scope that is needed\n      // for the new node. Instead, remove the data \"manually\".\n      if (!jQuery) {\n        delete jqLite.cache[firstElementToRemove[jqLite.expando]];\n      } else {\n        // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after\n        // the replaced element. The cleanData version monkey-patched by Angular would cause\n        // the scope to be trashed and we do need the very same scope to work with the new\n        // element. However, we cannot just cache the non-patched version and use it here as\n        // that would break if another library patches the method after Angular does (one\n        // example is jQuery UI). Instead, set a flag indicating scope destroying should be\n        // skipped this one time.\n        skipDestroyOnNextJQueryCleanData = true;\n        jQuery.cleanData([firstElementToRemove]);\n      }\n\n      for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {\n        var element = elementsToRemove[k];\n        jqLite(element).remove(); // must do this way to clean up expando\n        fragment.appendChild(element);\n        delete elementsToRemove[k];\n      }\n\n      elementsToRemove[0] = newNode;\n      elementsToRemove.length = 1;\n    }\n\n\n    function cloneAndAnnotateFn(fn, annotation) {\n      return extend(function() { return fn.apply(null, arguments); }, fn, annotation);\n    }\n\n\n    function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {\n      try {\n        linkFn(scope, $element, attrs, controllers, transcludeFn);\n      } catch (e) {\n        $exceptionHandler(e, startingTag($element));\n      }\n    }\n  }];\n}\n\nvar PREFIX_REGEXP = /^((?:x|data)[\\:\\-_])/i;\n/**\n * Converts all accepted directives format into proper directive name.\n * @param name Name to normalize\n */\nfunction directiveNormalize(name) {\n  return camelCase(name.replace(PREFIX_REGEXP, ''));\n}\n\n/**\n * @ngdoc type\n * @name $compile.directive.Attributes\n *\n * @description\n * A shared object between directive compile / linking functions which contains normalized DOM\n * element attributes. The values reflect current binding state `{{ }}`. The normalization is\n * needed since all of these are treated as equivalent in Angular:\n *\n * ```\n *    <span ng:bind=\"a\" ng-bind=\"a\" data-ng-bind=\"a\" x-ng-bind=\"a\">\n * ```\n */\n\n/**\n * @ngdoc property\n * @name $compile.directive.Attributes#$attr\n *\n * @description\n * A map of DOM element attribute names to the normalized name. This is\n * needed to do reverse lookup from normalized name back to actual name.\n */\n\n\n/**\n * @ngdoc method\n * @name $compile.directive.Attributes#$set\n * @kind function\n *\n * @description\n * Set DOM element attribute value.\n *\n *\n * @param {string} name Normalized element attribute name of the property to modify. The name is\n *          reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}\n *          property to the original name.\n * @param {string} value Value to set the attribute to. The value can be an interpolated string.\n */\n\n\n\n/**\n * Closure compiler type information\n */\n\nfunction nodesetLinkingFn(\n  /* angular.Scope */ scope,\n  /* NodeList */ nodeList,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction directiveLinkingFn(\n  /* nodesetLinkingFn */ nodesetLinkingFn,\n  /* angular.Scope */ scope,\n  /* Node */ node,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction tokenDifference(str1, str2) {\n  var values = '',\n      tokens1 = str1.split(/\\s+/),\n      tokens2 = str2.split(/\\s+/);\n\n  outer:\n  for (var i = 0; i < tokens1.length; i++) {\n    var token = tokens1[i];\n    for (var j = 0; j < tokens2.length; j++) {\n      if (token == tokens2[j]) continue outer;\n    }\n    values += (values.length > 0 ? ' ' : '') + token;\n  }\n  return values;\n}\n\nfunction removeComments(jqNodes) {\n  jqNodes = jqLite(jqNodes);\n  var i = jqNodes.length;\n\n  if (i <= 1) {\n    return jqNodes;\n  }\n\n  while (i--) {\n    var node = jqNodes[i];\n    if (node.nodeType === NODE_TYPE_COMMENT) {\n      splice.call(jqNodes, i, 1);\n    }\n  }\n  return jqNodes;\n}\n\nvar $controllerMinErr = minErr('$controller');\n\n/**\n * @ngdoc provider\n * @name $controllerProvider\n * @description\n * The {@link ng.$controller $controller service} is used by Angular to create new\n * controllers.\n *\n * This provider allows controller registration via the\n * {@link ng.$controllerProvider#register register} method.\n */\nfunction $ControllerProvider() {\n  var controllers = {},\n      globals = false,\n      CNTRL_REG = /^(\\S+)(\\s+as\\s+(\\w+))?$/;\n\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#register\n   * @param {string|Object} name Controller name, or an object map of controllers where the keys are\n   *    the names and the values are the constructors.\n   * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\n   *    annotations in the array notation).\n   */\n  this.register = function(name, constructor) {\n    assertNotHasOwnProperty(name, 'controller');\n    if (isObject(name)) {\n      extend(controllers, name);\n    } else {\n      controllers[name] = constructor;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#allowGlobals\n   * @description If called, allows `$controller` to find controller constructors on `window`\n   */\n  this.allowGlobals = function() {\n    globals = true;\n  };\n\n\n  this.$get = ['$injector', '$window', function($injector, $window) {\n\n    /**\n     * @ngdoc service\n     * @name $controller\n     * @requires $injector\n     *\n     * @param {Function|string} constructor If called with a function then it's considered to be the\n     *    controller constructor function. Otherwise it's considered to be a string which is used\n     *    to retrieve the controller constructor using the following steps:\n     *\n     *    * check if a controller with given name is registered via `$controllerProvider`\n     *    * check if evaluating the string on the current scope returns a constructor\n     *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\n     *      `window` object (not recommended)\n     *\n     *    The string can use the `controller as property` syntax, where the controller instance is published\n     *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n     *    to work correctly.\n     *\n     * @param {Object} locals Injection locals for Controller.\n     * @return {Object} Instance of given controller.\n     *\n     * @description\n     * `$controller` service is responsible for instantiating controllers.\n     *\n     * It's just a simple call to {@link auto.$injector $injector}, but extracted into\n     * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).\n     */\n    return function(expression, locals, later, ident) {\n      // PRIVATE API:\n      //   param `later` --- indicates that the controller's constructor is invoked at a later time.\n      //                     If true, $controller will allocate the object with the correct\n      //                     prototype chain, but will not invoke the controller until a returned\n      //                     callback is invoked.\n      //   param `ident` --- An optional label which overrides the label parsed from the controller\n      //                     expression, if any.\n      var instance, match, constructor, identifier;\n      later = later === true;\n      if (ident && isString(ident)) {\n        identifier = ident;\n      }\n\n      if (isString(expression)) {\n        match = expression.match(CNTRL_REG);\n        if (!match) {\n          throw $controllerMinErr('ctrlfmt',\n            \"Badly formed controller string '{0}'. \" +\n            \"Must match `__name__ as __id__` or `__name__`.\", expression);\n        }\n        constructor = match[1],\n        identifier = identifier || match[3];\n        expression = controllers.hasOwnProperty(constructor)\n            ? controllers[constructor]\n            : getter(locals.$scope, constructor, true) ||\n                (globals ? getter($window, constructor, true) : undefined);\n\n        assertArgFn(expression, constructor, true);\n      }\n\n      if (later) {\n        // Instantiate controller later:\n        // This machinery is used to create an instance of the object before calling the\n        // controller's constructor itself.\n        //\n        // This allows properties to be added to the controller before the constructor is\n        // invoked. Primarily, this is used for isolate scope bindings in $compile.\n        //\n        // This feature is not intended for use by applications, and is thus not documented\n        // publicly.\n        // Object creation: http://jsperf.com/create-constructor/2\n        var controllerPrototype = (isArray(expression) ?\n          expression[expression.length - 1] : expression).prototype;\n        instance = Object.create(controllerPrototype || null);\n\n        if (identifier) {\n          addIdentifier(locals, identifier, instance, constructor || expression.name);\n        }\n\n        return extend(function() {\n          $injector.invoke(expression, instance, locals, constructor);\n          return instance;\n        }, {\n          instance: instance,\n          identifier: identifier\n        });\n      }\n\n      instance = $injector.instantiate(expression, locals, constructor);\n\n      if (identifier) {\n        addIdentifier(locals, identifier, instance, constructor || expression.name);\n      }\n\n      return instance;\n    };\n\n    function addIdentifier(locals, identifier, instance, name) {\n      if (!(locals && isObject(locals.$scope))) {\n        throw minErr('$controller')('noscp',\n          \"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.\",\n          name, identifier);\n      }\n\n      locals.$scope[identifier] = instance;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $document\n * @requires $window\n *\n * @description\n * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.\n *\n * @example\n   <example module=\"documentExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <p>$document title: <b ng-bind=\"title\"></b></p>\n         <p>window.document title: <b ng-bind=\"windowTitle\"></b></p>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('documentExample', [])\n         .controller('ExampleController', ['$scope', '$document', function($scope, $document) {\n           $scope.title = $document[0].title;\n           $scope.windowTitle = angular.element(window.document)[0].title;\n         }]);\n     </file>\n   </example>\n */\nfunction $DocumentProvider() {\n  this.$get = ['$window', function(window) {\n    return jqLite(window.document);\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n * @requires ng.$log\n *\n * @description\n * Any uncaught exception in angular expressions is delegated to this service.\n * The default implementation simply delegates to `$log.error` which logs it into\n * the browser console.\n *\n * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by\n * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.\n *\n * ## Example:\n *\n * ```js\n *   angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {\n *     return function(exception, cause) {\n *       exception.message += ' (caused by \"' + cause + '\")';\n *       throw exception;\n *     };\n *   });\n * ```\n *\n * This example will override the normal action of `$exceptionHandler`, to make angular\n * exceptions fail hard when they happen, instead of just logging to the console.\n *\n * <hr />\n * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`\n * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}\n * (unless executed during a digest).\n *\n * If you wish, you can manually delegate exceptions, e.g.\n * `try { ... } catch(e) { $exceptionHandler(e); }`\n *\n * @param {Error} exception Exception associated with the error.\n * @param {string=} cause optional information about the context in which\n *       the error was thrown.\n *\n */\nfunction $ExceptionHandlerProvider() {\n  this.$get = ['$log', function($log) {\n    return function(exception, cause) {\n      $log.error.apply($log, arguments);\n    };\n  }];\n}\n\nvar APPLICATION_JSON = 'application/json';\nvar CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};\nvar JSON_START = /^\\[|^\\{(?!\\{)/;\nvar JSON_ENDS = {\n  '[': /]$/,\n  '{': /}$/\n};\nvar JSON_PROTECTION_PREFIX = /^\\)\\]\\}',?\\n/;\n\nfunction defaultHttpResponseTransform(data, headers) {\n  if (isString(data)) {\n    // Strip json vulnerability protection prefix and trim whitespace\n    var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();\n\n    if (tempData) {\n      var contentType = headers('Content-Type');\n      if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {\n        data = fromJson(tempData);\n      }\n    }\n  }\n\n  return data;\n}\n\nfunction isJsonLike(str) {\n    var jsonStart = str.match(JSON_START);\n    return jsonStart && JSON_ENDS[jsonStart[0]].test(str);\n}\n\n/**\n * Parse headers into key value object\n *\n * @param {string} headers Raw headers as a string\n * @returns {Object} Parsed headers as key value object\n */\nfunction parseHeaders(headers) {\n  var parsed = createMap(), key, val, i;\n\n  if (!headers) return parsed;\n\n  forEach(headers.split('\\n'), function(line) {\n    i = line.indexOf(':');\n    key = lowercase(trim(line.substr(0, i)));\n    val = trim(line.substr(i + 1));\n\n    if (key) {\n      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n    }\n  });\n\n  return parsed;\n}\n\n\n/**\n * Returns a function that provides access to parsed headers.\n *\n * Headers are lazy parsed when first requested.\n * @see parseHeaders\n *\n * @param {(string|Object)} headers Headers to provide access to.\n * @returns {function(string=)} Returns a getter function which if called with:\n *\n *   - if called with single an argument returns a single header value or null\n *   - if called with no arguments returns an object containing all headers.\n */\nfunction headersGetter(headers) {\n  var headersObj = isObject(headers) ? headers : undefined;\n\n  return function(name) {\n    if (!headersObj) headersObj =  parseHeaders(headers);\n\n    if (name) {\n      var value = headersObj[lowercase(name)];\n      if (value === void 0) {\n        value = null;\n      }\n      return value;\n    }\n\n    return headersObj;\n  };\n}\n\n\n/**\n * Chain all given functions\n *\n * This function is used for both request and response transforming\n *\n * @param {*} data Data to transform.\n * @param {function(string=)} headers HTTP headers getter fn.\n * @param {number} status HTTP status code of the response.\n * @param {(Function|Array.<Function>)} fns Function or an array of functions.\n * @returns {*} Transformed data.\n */\nfunction transformData(data, headers, status, fns) {\n  if (isFunction(fns))\n    return fns(data, headers, status);\n\n  forEach(fns, function(fn) {\n    data = fn(data, headers, status);\n  });\n\n  return data;\n}\n\n\nfunction isSuccess(status) {\n  return 200 <= status && status < 300;\n}\n\n\n/**\n * @ngdoc provider\n * @name $httpProvider\n * @description\n * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.\n * */\nfunction $HttpProvider() {\n  /**\n   * @ngdoc property\n   * @name $httpProvider#defaults\n   * @description\n   *\n   * Object containing default values for all {@link ng.$http $http} requests.\n   *\n   * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}\n   * that will provide the cache for all requests who set their `cache` property to `true`.\n   * If you set the `default.cache = false` then only requests that specify their own custom\n   * cache object will be cached. See {@link $http#caching $http Caching} for more information.\n   *\n   * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.\n   * Defaults value is `'XSRF-TOKEN'`.\n   *\n   * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the\n   * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.\n   *\n   * - **`defaults.headers`** - {Object} - Default headers for all $http requests.\n   * Refer to {@link ng.$http#setting-http-headers $http} for documentation on\n   * setting default headers.\n   *     - **`defaults.headers.common`**\n   *     - **`defaults.headers.post`**\n   *     - **`defaults.headers.put`**\n   *     - **`defaults.headers.patch`**\n   *\n   **/\n  var defaults = this.defaults = {\n    // transform incoming response data\n    transformResponse: [defaultHttpResponseTransform],\n\n    // transform outgoing request data\n    transformRequest: [function(d) {\n      return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;\n    }],\n\n    // default headers\n    headers: {\n      common: {\n        'Accept': 'application/json, text/plain, */*'\n      },\n      post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)\n    },\n\n    xsrfCookieName: 'XSRF-TOKEN',\n    xsrfHeaderName: 'X-XSRF-TOKEN'\n  };\n\n  var useApplyAsync = false;\n  /**\n   * @ngdoc method\n   * @name $httpProvider#useApplyAsync\n   * @description\n   *\n   * Configure $http service to combine processing of multiple http responses received at around\n   * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in\n   * significant performance improvement for bigger applications that make many HTTP requests\n   * concurrently (common during application bootstrap).\n   *\n   * Defaults to false. If no value is specifed, returns the current configured value.\n   *\n   * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred\n   *    \"apply\" on the next tick, giving time for subsequent requests in a roughly ~10ms window\n   *    to load and share the same digest cycle.\n   *\n   * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n   *    otherwise, returns the current configured value.\n   **/\n  this.useApplyAsync = function(value) {\n    if (isDefined(value)) {\n      useApplyAsync = !!value;\n      return this;\n    }\n    return useApplyAsync;\n  };\n\n  /**\n   * @ngdoc property\n   * @name $httpProvider#interceptors\n   * @description\n   *\n   * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}\n   * pre-processing of request or postprocessing of responses.\n   *\n   * These service factories are ordered by request, i.e. they are applied in the same order as the\n   * array, on request, but reverse order, on response.\n   *\n   * {@link ng.$http#interceptors Interceptors detailed info}\n   **/\n  var interceptorFactories = this.interceptors = [];\n\n  this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',\n      function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {\n\n    var defaultCache = $cacheFactory('$http');\n\n    /**\n     * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\n     * The reversal is needed so that we can build up the interception chain around the\n     * server request.\n     */\n    var reversedInterceptors = [];\n\n    forEach(interceptorFactories, function(interceptorFactory) {\n      reversedInterceptors.unshift(isString(interceptorFactory)\n          ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\n    });\n\n    /**\n     * @ngdoc service\n     * @kind function\n     * @name $http\n     * @requires ng.$httpBackend\n     * @requires $cacheFactory\n     * @requires $rootScope\n     * @requires $q\n     * @requires $injector\n     *\n     * @description\n     * The `$http` service is a core Angular service that facilitates communication with the remote\n     * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)\n     * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).\n     *\n     * For unit testing applications that use `$http` service, see\n     * {@link ngMock.$httpBackend $httpBackend mock}.\n     *\n     * For a higher level of abstraction, please check out the {@link ngResource.$resource\n     * $resource} service.\n     *\n     * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by\n     * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage\n     * it is important to familiarize yourself with these APIs and the guarantees they provide.\n     *\n     *\n     * ## General usage\n     * The `$http` service is a function which takes a single argument — a configuration object —\n     * that is used to generate an HTTP request and returns  a {@link ng.$q promise}\n     * with two $http specific methods: `success` and `error`.\n     *\n     * ```js\n     *   // Simple GET request example :\n     *   $http.get('/someUrl').\n     *     success(function(data, status, headers, config) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }).\n     *     error(function(data, status, headers, config) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     * ```js\n     *   // Simple POST request example (passing data) :\n     *   $http.post('/someUrl', {msg:'hello word!'}).\n     *     success(function(data, status, headers, config) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }).\n     *     error(function(data, status, headers, config) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     *\n     * Since the returned value of calling the $http function is a `promise`, you can also use\n     * the `then` method to register callbacks, and these callbacks will receive a single argument –\n     * an object representing the response. See the API signature and type info below for more\n     * details.\n     *\n     * A response status code between 200 and 299 is considered a success status and\n     * will result in the success callback being called. Note that if the response is a redirect,\n     * XMLHttpRequest will transparently follow it, meaning that the error callback will not be\n     * called for such responses.\n     *\n     * ## Writing Unit Tests that use $http\n     * When unit testing (using {@link ngMock ngMock}), it is necessary to call\n     * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending\n     * request using trained responses.\n     *\n     * ```\n     * $httpBackend.expectGET(...);\n     * $http.get(...);\n     * $httpBackend.flush();\n     * ```\n     *\n     * ## Shortcut methods\n     *\n     * Shortcut methods are also available. All shortcut methods require passing in the URL, and\n     * request data must be passed in for POST/PUT requests.\n     *\n     * ```js\n     *   $http.get('/someUrl').success(successCallback);\n     *   $http.post('/someUrl', data).success(successCallback);\n     * ```\n     *\n     * Complete list of shortcut methods:\n     *\n     * - {@link ng.$http#get $http.get}\n     * - {@link ng.$http#head $http.head}\n     * - {@link ng.$http#post $http.post}\n     * - {@link ng.$http#put $http.put}\n     * - {@link ng.$http#delete $http.delete}\n     * - {@link ng.$http#jsonp $http.jsonp}\n     * - {@link ng.$http#patch $http.patch}\n     *\n     *\n     * ## Setting HTTP Headers\n     *\n     * The $http service will automatically add certain HTTP headers to all requests. These defaults\n     * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration\n     * object, which currently contains this default configuration:\n     *\n     * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):\n     *   - `Accept: application/json, text/plain, * / *`\n     * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)\n     *   - `Content-Type: application/json`\n     * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)\n     *   - `Content-Type: application/json`\n     *\n     * To add or overwrite these defaults, simply add or remove a property from these configuration\n     * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object\n     * with the lowercased HTTP method name as the key, e.g.\n     * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.\n     *\n     * The defaults can also be set at runtime via the `$http.defaults` object in the same\n     * fashion. For example:\n     *\n     * ```\n     * module.run(function($http) {\n     *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'\n     * });\n     * ```\n     *\n     * In addition, you can supply a `headers` property in the config object passed when\n     * calling `$http(config)`, which overrides the defaults without changing them globally.\n     *\n     * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,\n     * Use the `headers` property, setting the desired header to `undefined`. For example:\n     *\n     * ```js\n     * var req = {\n     *  method: 'POST',\n     *  url: 'http://example.com',\n     *  headers: {\n     *    'Content-Type': undefined\n     *  },\n     *  data: { test: 'test' },\n     * }\n     *\n     * $http(req).success(function(){...}).error(function(){...});\n     * ```\n     *\n     * ## Transforming Requests and Responses\n     *\n     * Both requests and responses can be transformed using transformation functions: `transformRequest`\n     * and `transformResponse`. These properties can be a single function that returns\n     * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,\n     * which allows you to `push` or `unshift` a new transformation function into the transformation chain.\n     *\n     * ### Default Transformations\n     *\n     * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and\n     * `defaults.transformResponse` properties. If a request does not provide its own transformations\n     * then these will be applied.\n     *\n     * You can augment or replace the default transformations by modifying these properties by adding to or\n     * replacing the array.\n     *\n     * Angular provides the following default transformations:\n     *\n     * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):\n     *\n     * - If the `data` property of the request configuration object contains an object, serialize it\n     *   into JSON format.\n     *\n     * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):\n     *\n     *  - If XSRF prefix is detected, strip it (see Security Considerations section below).\n     *  - If JSON response is detected, deserialize it using a JSON parser.\n     *\n     *\n     * ### Overriding the Default Transformations Per Request\n     *\n     * If you wish override the request/response transformations only for a single request then provide\n     * `transformRequest` and/or `transformResponse` properties on the configuration object passed\n     * into `$http`.\n     *\n     * Note that if you provide these properties on the config object the default transformations will be\n     * overwritten. If you wish to augment the default transformations then you must include them in your\n     * local transformation array.\n     *\n     * The following code demonstrates adding a new response transformation to be run after the default response\n     * transformations have been run.\n     *\n     * ```js\n     * function appendTransform(defaults, transform) {\n     *\n     *   // We can't guarantee that the default transformation is an array\n     *   defaults = angular.isArray(defaults) ? defaults : [defaults];\n     *\n     *   // Append the new transformation to the defaults\n     *   return defaults.concat(transform);\n     * }\n     *\n     * $http({\n     *   url: '...',\n     *   method: 'GET',\n     *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {\n     *     return doTransform(value);\n     *   })\n     * });\n     * ```\n     *\n     *\n     * ## Caching\n     *\n     * To enable caching, set the request configuration `cache` property to `true` (to use default\n     * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).\n     * When the cache is enabled, `$http` stores the response from the server in the specified\n     * cache. The next time the same request is made, the response is served from the cache without\n     * sending a request to the server.\n     *\n     * Note that even if the response is served from cache, delivery of the data is asynchronous in\n     * the same way that real requests are.\n     *\n     * If there are multiple GET requests for the same URL that should be cached using the same\n     * cache, but the cache is not populated yet, only one request to the server will be made and\n     * the remaining requests will be fulfilled using the response from the first request.\n     *\n     * You can change the default cache to a new object (built with\n     * {@link ng.$cacheFactory `$cacheFactory`}) by updating the\n     * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set\n     * their `cache` property to `true` will now use this cache object.\n     *\n     * If you set the default cache to `false` then only requests that specify their own custom\n     * cache object will be cached.\n     *\n     * ## Interceptors\n     *\n     * Before you start creating interceptors, be sure to understand the\n     * {@link ng.$q $q and deferred/promise APIs}.\n     *\n     * For purposes of global error handling, authentication, or any kind of synchronous or\n     * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be\n     * able to intercept requests before they are handed to the server and\n     * responses before they are handed over to the application code that\n     * initiated these requests. The interceptors leverage the {@link ng.$q\n     * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.\n     *\n     * The interceptors are service factories that are registered with the `$httpProvider` by\n     * adding them to the `$httpProvider.interceptors` array. The factory is called and\n     * injected with dependencies (if specified) and returns the interceptor.\n     *\n     * There are two kinds of interceptors (and two kinds of rejection interceptors):\n     *\n     *   * `request`: interceptors get called with a http `config` object. The function is free to\n     *     modify the `config` object or create a new one. The function needs to return the `config`\n     *     object directly, or a promise containing the `config` or a new `config` object.\n     *   * `requestError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *   * `response`: interceptors get called with http `response` object. The function is free to\n     *     modify the `response` object or create a new one. The function needs to return the `response`\n     *     object directly, or as a promise containing the `response` or a new `response` object.\n     *   * `responseError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *\n     *\n     * ```js\n     *   // register the interceptor as a service\n     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {\n     *     return {\n     *       // optional method\n     *       'request': function(config) {\n     *         // do something on success\n     *         return config;\n     *       },\n     *\n     *       // optional method\n     *      'requestError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       },\n     *\n     *\n     *\n     *       // optional method\n     *       'response': function(response) {\n     *         // do something on success\n     *         return response;\n     *       },\n     *\n     *       // optional method\n     *      'responseError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       }\n     *     };\n     *   });\n     *\n     *   $httpProvider.interceptors.push('myHttpInterceptor');\n     *\n     *\n     *   // alternatively, register the interceptor via an anonymous factory\n     *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {\n     *     return {\n     *      'request': function(config) {\n     *          // same as above\n     *       },\n     *\n     *       'response': function(response) {\n     *          // same as above\n     *       }\n     *     };\n     *   });\n     * ```\n     *\n     * ## Security Considerations\n     *\n     * When designing web applications, consider security threats from:\n     *\n     * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\n     *\n     * Both server and the client must cooperate in order to eliminate these threats. Angular comes\n     * pre-configured with strategies that address these issues, but for this to work backend server\n     * cooperation is required.\n     *\n     * ### JSON Vulnerability Protection\n     *\n     * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * allows third party website to turn your JSON resource URL into\n     * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To\n     * counter this your server can prefix all JSON requests with following string `\")]}',\\n\"`.\n     * Angular will automatically strip the prefix before processing it as JSON.\n     *\n     * For example if your server needs to return:\n     * ```js\n     * ['one','two']\n     * ```\n     *\n     * which is vulnerable to attack, your server can return:\n     * ```js\n     * )]}',\n     * ['one','two']\n     * ```\n     *\n     * Angular will strip the prefix, before processing the JSON.\n     *\n     *\n     * ### Cross Site Request Forgery (XSRF) Protection\n     *\n     * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which\n     * an unauthorized site can gain your user's private data. Angular provides a mechanism\n     * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie\n     * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only\n     * JavaScript that runs on your domain could read the cookie, your server can be assured that\n     * the XHR came from JavaScript running on your domain. The header will not be set for\n     * cross-domain requests.\n     *\n     * To take advantage of this, your server needs to set a token in a JavaScript readable session\n     * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the\n     * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure\n     * that only JavaScript running on your domain could have sent the request. The token must be\n     * unique for each user and must be verifiable by the server (to prevent the JavaScript from\n     * making up its own tokens). We recommend that the token is a digest of your site's\n     * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)\n     * for added security.\n     *\n     * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName\n     * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,\n     * or the per-request config object.\n     *\n     *\n     * @param {object} config Object describing the request to be made and how it should be\n     *    processed. The object has following properties:\n     *\n     *    - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)\n     *    - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.\n     *    - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned\n     *      to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be\n     *      JSONified.\n     *    - **data** – `{string|Object}` – Data to be sent as the request message data.\n     *    - **headers** – `{Object}` – Map of strings or functions which return strings representing\n     *      HTTP headers to send to the server. If the return value of a function is null, the\n     *      header will not be sent.\n     *    - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.\n     *    - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.\n     *    - **transformRequest** –\n     *      `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      request body and headers and returns its transformed (typically serialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default Transformations}\n     *    - **transformResponse** –\n     *      `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      response body, headers and status and returns its transformed (typically deserialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default Transformations}\n     *    - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\n     *      GET request, otherwise if a cache instance built with\n     *      {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\n     *      caching.\n     *    - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}\n     *      that should abort the request when resolved.\n     *    - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the\n     *      XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)\n     *      for more information.\n     *    - **responseType** - `{string}` - see\n     *      [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).\n     *\n     * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the\n     *   standard `then` method and two http specific methods: `success` and `error`. The `then`\n     *   method takes two arguments a success and an error callback which will be called with a\n     *   response object. The `success` and `error` methods take a single argument - a function that\n     *   will be called when the request succeeds or fails respectively. The arguments passed into\n     *   these functions are destructured representation of the response object passed into the\n     *   `then` method. The response object has these properties:\n     *\n     *   - **data** – `{string|Object}` – The response body transformed with the transform\n     *     functions.\n     *   - **status** – `{number}` – HTTP status code of the response.\n     *   - **headers** – `{function([headerName])}` – Header getter function.\n     *   - **config** – `{Object}` – The configuration object that was used to generate the request.\n     *   - **statusText** – `{string}` – HTTP status text of the response.\n     *\n     * @property {Array.<Object>} pendingRequests Array of config objects for currently pending\n     *   requests. This is primarily meant to be used for debugging purposes.\n     *\n     *\n     * @example\n<example module=\"httpExample\">\n<file name=\"index.html\">\n  <div ng-controller=\"FetchController\">\n    <select ng-model=\"method\">\n      <option>GET</option>\n      <option>JSONP</option>\n    </select>\n    <input type=\"text\" ng-model=\"url\" size=\"80\"/>\n    <button id=\"fetchbtn\" ng-click=\"fetch()\">fetch</button><br>\n    <button id=\"samplegetbtn\" ng-click=\"updateModel('GET', 'http-hello.html')\">Sample GET</button>\n    <button id=\"samplejsonpbtn\"\n      ng-click=\"updateModel('JSONP',\n                    'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')\">\n      Sample JSONP\n    </button>\n    <button id=\"invalidjsonpbtn\"\n      ng-click=\"updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')\">\n        Invalid JSONP\n      </button>\n    <pre>http status code: {{status}}</pre>\n    <pre>http response data: {{data}}</pre>\n  </div>\n</file>\n<file name=\"script.js\">\n  angular.module('httpExample', [])\n    .controller('FetchController', ['$scope', '$http', '$templateCache',\n      function($scope, $http, $templateCache) {\n        $scope.method = 'GET';\n        $scope.url = 'http-hello.html';\n\n        $scope.fetch = function() {\n          $scope.code = null;\n          $scope.response = null;\n\n          $http({method: $scope.method, url: $scope.url, cache: $templateCache}).\n            success(function(data, status) {\n              $scope.status = status;\n              $scope.data = data;\n            }).\n            error(function(data, status) {\n              $scope.data = data || \"Request failed\";\n              $scope.status = status;\n          });\n        };\n\n        $scope.updateModel = function(method, url) {\n          $scope.method = method;\n          $scope.url = url;\n        };\n      }]);\n</file>\n<file name=\"http-hello.html\">\n  Hello, $http!\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  var status = element(by.binding('status'));\n  var data = element(by.binding('data'));\n  var fetchBtn = element(by.id('fetchbtn'));\n  var sampleGetBtn = element(by.id('samplegetbtn'));\n  var sampleJsonpBtn = element(by.id('samplejsonpbtn'));\n  var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));\n\n  it('should make an xhr GET request', function() {\n    sampleGetBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('200');\n    expect(data.getText()).toMatch(/Hello, \\$http!/);\n  });\n\n// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185\n// it('should make a JSONP request to angularjs.org', function() {\n//   sampleJsonpBtn.click();\n//   fetchBtn.click();\n//   expect(status.getText()).toMatch('200');\n//   expect(data.getText()).toMatch(/Super Hero!/);\n// });\n\n  it('should make JSONP request to invalid URL and invoke the error handler',\n      function() {\n    invalidJsonpBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('0');\n    expect(data.getText()).toMatch('Request failed');\n  });\n</file>\n</example>\n     */\n    function $http(requestConfig) {\n\n      if (!angular.isObject(requestConfig)) {\n        throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);\n      }\n\n      var config = extend({\n        method: 'get',\n        transformRequest: defaults.transformRequest,\n        transformResponse: defaults.transformResponse\n      }, requestConfig);\n\n      config.headers = mergeHeaders(requestConfig);\n      config.method = uppercase(config.method);\n\n      var serverRequest = function(config) {\n        var headers = config.headers;\n        var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);\n\n        // strip content-type if data is undefined\n        if (isUndefined(reqData)) {\n          forEach(headers, function(value, header) {\n            if (lowercase(header) === 'content-type') {\n                delete headers[header];\n            }\n          });\n        }\n\n        if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {\n          config.withCredentials = defaults.withCredentials;\n        }\n\n        // send request\n        return sendReq(config, reqData).then(transformResponse, transformResponse);\n      };\n\n      var chain = [serverRequest, undefined];\n      var promise = $q.when(config);\n\n      // apply interceptors\n      forEach(reversedInterceptors, function(interceptor) {\n        if (interceptor.request || interceptor.requestError) {\n          chain.unshift(interceptor.request, interceptor.requestError);\n        }\n        if (interceptor.response || interceptor.responseError) {\n          chain.push(interceptor.response, interceptor.responseError);\n        }\n      });\n\n      while (chain.length) {\n        var thenFn = chain.shift();\n        var rejectFn = chain.shift();\n\n        promise = promise.then(thenFn, rejectFn);\n      }\n\n      promise.success = function(fn) {\n        promise.then(function(response) {\n          fn(response.data, response.status, response.headers, config);\n        });\n        return promise;\n      };\n\n      promise.error = function(fn) {\n        promise.then(null, function(response) {\n          fn(response.data, response.status, response.headers, config);\n        });\n        return promise;\n      };\n\n      return promise;\n\n      function transformResponse(response) {\n        // make a copy since the response must be cacheable\n        var resp = extend({}, response);\n        if (!response.data) {\n          resp.data = response.data;\n        } else {\n          resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);\n        }\n        return (isSuccess(response.status))\n          ? resp\n          : $q.reject(resp);\n      }\n\n      function executeHeaderFns(headers) {\n        var headerContent, processedHeaders = {};\n\n        forEach(headers, function(headerFn, header) {\n          if (isFunction(headerFn)) {\n            headerContent = headerFn();\n            if (headerContent != null) {\n              processedHeaders[header] = headerContent;\n            }\n          } else {\n            processedHeaders[header] = headerFn;\n          }\n        });\n\n        return processedHeaders;\n      }\n\n      function mergeHeaders(config) {\n        var defHeaders = defaults.headers,\n            reqHeaders = extend({}, config.headers),\n            defHeaderName, lowercaseDefHeaderName, reqHeaderName;\n\n        defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);\n\n        // using for-in instead of forEach to avoid unecessary iteration after header has been found\n        defaultHeadersIteration:\n        for (defHeaderName in defHeaders) {\n          lowercaseDefHeaderName = lowercase(defHeaderName);\n\n          for (reqHeaderName in reqHeaders) {\n            if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {\n              continue defaultHeadersIteration;\n            }\n          }\n\n          reqHeaders[defHeaderName] = defHeaders[defHeaderName];\n        }\n\n        // execute if header value is a function for merged headers\n        return executeHeaderFns(reqHeaders);\n      }\n    }\n\n    $http.pendingRequests = [];\n\n    /**\n     * @ngdoc method\n     * @name $http#get\n     *\n     * @description\n     * Shortcut method to perform `GET` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#delete\n     *\n     * @description\n     * Shortcut method to perform `DELETE` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#head\n     *\n     * @description\n     * Shortcut method to perform `HEAD` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#jsonp\n     *\n     * @description\n     * Shortcut method to perform `JSONP` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request.\n     *                     The name of the callback should be the string `JSON_CALLBACK`.\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n    createShortMethods('get', 'delete', 'head', 'jsonp');\n\n    /**\n     * @ngdoc method\n     * @name $http#post\n     *\n     * @description\n     * Shortcut method to perform `POST` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#put\n     *\n     * @description\n     * Shortcut method to perform `PUT` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n     /**\n      * @ngdoc method\n      * @name $http#patch\n      *\n      * @description\n      * Shortcut method to perform `PATCH` request.\n      *\n      * @param {string} url Relative or absolute URL specifying the destination of the request\n      * @param {*} data Request content\n      * @param {Object=} config Optional configuration object\n      * @returns {HttpPromise} Future object\n      */\n    createShortMethodsWithData('post', 'put', 'patch');\n\n        /**\n         * @ngdoc property\n         * @name $http#defaults\n         *\n         * @description\n         * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of\n         * default headers, withCredentials as well as request and response transformations.\n         *\n         * See \"Setting HTTP Headers\" and \"Transforming Requests and Responses\" sections above.\n         */\n    $http.defaults = defaults;\n\n\n    return $http;\n\n\n    function createShortMethods(names) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, config) {\n          return $http(extend(config || {}, {\n            method: name,\n            url: url\n          }));\n        };\n      });\n    }\n\n\n    function createShortMethodsWithData(name) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, data, config) {\n          return $http(extend(config || {}, {\n            method: name,\n            url: url,\n            data: data\n          }));\n        };\n      });\n    }\n\n\n    /**\n     * Makes the request.\n     *\n     * !!! ACCESSES CLOSURE VARS:\n     * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests\n     */\n    function sendReq(config, reqData) {\n      var deferred = $q.defer(),\n          promise = deferred.promise,\n          cache,\n          cachedResp,\n          reqHeaders = config.headers,\n          url = buildUrl(config.url, config.params);\n\n      $http.pendingRequests.push(config);\n      promise.then(removePendingReq, removePendingReq);\n\n\n      if ((config.cache || defaults.cache) && config.cache !== false &&\n          (config.method === 'GET' || config.method === 'JSONP')) {\n        cache = isObject(config.cache) ? config.cache\n              : isObject(defaults.cache) ? defaults.cache\n              : defaultCache;\n      }\n\n      if (cache) {\n        cachedResp = cache.get(url);\n        if (isDefined(cachedResp)) {\n          if (isPromiseLike(cachedResp)) {\n            // cached request has already been sent, but there is no response yet\n            cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);\n          } else {\n            // serving from cache\n            if (isArray(cachedResp)) {\n              resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);\n            } else {\n              resolvePromise(cachedResp, 200, {}, 'OK');\n            }\n          }\n        } else {\n          // put the promise for the non-transformed response into cache as a placeholder\n          cache.put(url, promise);\n        }\n      }\n\n\n      // if we won't have the response in cache, set the xsrf headers and\n      // send the request to the backend\n      if (isUndefined(cachedResp)) {\n        var xsrfValue = urlIsSameOrigin(config.url)\n            ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]\n            : undefined;\n        if (xsrfValue) {\n          reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;\n        }\n\n        $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,\n            config.withCredentials, config.responseType);\n      }\n\n      return promise;\n\n\n      /**\n       * Callback registered to $httpBackend():\n       *  - caches the response if desired\n       *  - resolves the raw $http promise\n       *  - calls $apply\n       */\n      function done(status, response, headersString, statusText) {\n        if (cache) {\n          if (isSuccess(status)) {\n            cache.put(url, [status, response, parseHeaders(headersString), statusText]);\n          } else {\n            // remove promise from the cache\n            cache.remove(url);\n          }\n        }\n\n        function resolveHttpPromise() {\n          resolvePromise(response, status, headersString, statusText);\n        }\n\n        if (useApplyAsync) {\n          $rootScope.$applyAsync(resolveHttpPromise);\n        } else {\n          resolveHttpPromise();\n          if (!$rootScope.$$phase) $rootScope.$apply();\n        }\n      }\n\n\n      /**\n       * Resolves the raw $http promise.\n       */\n      function resolvePromise(response, status, headers, statusText) {\n        // normalize internal statuses to 0\n        status = Math.max(status, 0);\n\n        (isSuccess(status) ? deferred.resolve : deferred.reject)({\n          data: response,\n          status: status,\n          headers: headersGetter(headers),\n          config: config,\n          statusText: statusText\n        });\n      }\n\n      function resolvePromiseWithResult(result) {\n        resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);\n      }\n\n      function removePendingReq() {\n        var idx = $http.pendingRequests.indexOf(config);\n        if (idx !== -1) $http.pendingRequests.splice(idx, 1);\n      }\n    }\n\n\n    function buildUrl(url, params) {\n      if (!params) return url;\n      var parts = [];\n      forEachSorted(params, function(value, key) {\n        if (value === null || isUndefined(value)) return;\n        if (!isArray(value)) value = [value];\n\n        forEach(value, function(v) {\n          if (isObject(v)) {\n            if (isDate(v)) {\n              v = v.toISOString();\n            } else {\n              v = toJson(v);\n            }\n          }\n          parts.push(encodeUriQuery(key) + '=' +\n                     encodeUriQuery(v));\n        });\n      });\n      if (parts.length > 0) {\n        url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');\n      }\n      return url;\n    }\n  }];\n}\n\nfunction createXhr() {\n    return new window.XMLHttpRequest();\n}\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @requires $window\n * @requires $document\n *\n * @description\n * HTTP backend used by the {@link ng.$http service} that delegates to\n * XMLHttpRequest object or JSONP and deals with browser incompatibilities.\n *\n * You should never need to use this service directly, instead use the higher-level abstractions:\n * {@link ng.$http $http} or {@link ngResource.$resource $resource}.\n *\n * During testing this implementation is swapped with {@link ngMock.$httpBackend mock\n * $httpBackend} which can be trained with responses.\n */\nfunction $HttpBackendProvider() {\n  this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {\n    return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);\n  }];\n}\n\nfunction createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {\n  // TODO(vojta): fix the signature\n  return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {\n    $browser.$$incOutstandingRequestCount();\n    url = url || $browser.url();\n\n    if (lowercase(method) == 'jsonp') {\n      var callbackId = '_' + (callbacks.counter++).toString(36);\n      callbacks[callbackId] = function(data) {\n        callbacks[callbackId].data = data;\n        callbacks[callbackId].called = true;\n      };\n\n      var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),\n          callbackId, function(status, text) {\n        completeRequest(callback, status, callbacks[callbackId].data, \"\", text);\n        callbacks[callbackId] = noop;\n      });\n    } else {\n\n      var xhr = createXhr();\n\n      xhr.open(method, url, true);\n      forEach(headers, function(value, key) {\n        if (isDefined(value)) {\n            xhr.setRequestHeader(key, value);\n        }\n      });\n\n      xhr.onload = function requestLoaded() {\n        var statusText = xhr.statusText || '';\n\n        // responseText is the old-school way of retrieving response (supported by IE8 & 9)\n        // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)\n        var response = ('response' in xhr) ? xhr.response : xhr.responseText;\n\n        // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)\n        var status = xhr.status === 1223 ? 204 : xhr.status;\n\n        // fix status code when it is 0 (0 status is undocumented).\n        // Occurs when accessing file resources or on Android 4.1 stock browser\n        // while retrieving files from application cache.\n        if (status === 0) {\n          status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;\n        }\n\n        completeRequest(callback,\n            status,\n            response,\n            xhr.getAllResponseHeaders(),\n            statusText);\n      };\n\n      var requestError = function() {\n        // The response is always empty\n        // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\n        completeRequest(callback, -1, null, null, '');\n      };\n\n      xhr.onerror = requestError;\n      xhr.onabort = requestError;\n\n      if (withCredentials) {\n        xhr.withCredentials = true;\n      }\n\n      if (responseType) {\n        try {\n          xhr.responseType = responseType;\n        } catch (e) {\n          // WebKit added support for the json responseType value on 09/03/2013\n          // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are\n          // known to throw when setting the value \"json\" as the response type. Other older\n          // browsers implementing the responseType\n          //\n          // The json response type can be ignored if not supported, because JSON payloads are\n          // parsed on the client-side regardless.\n          if (responseType !== 'json') {\n            throw e;\n          }\n        }\n      }\n\n      xhr.send(post || null);\n    }\n\n    if (timeout > 0) {\n      var timeoutId = $browserDefer(timeoutRequest, timeout);\n    } else if (isPromiseLike(timeout)) {\n      timeout.then(timeoutRequest);\n    }\n\n\n    function timeoutRequest() {\n      jsonpDone && jsonpDone();\n      xhr && xhr.abort();\n    }\n\n    function completeRequest(callback, status, response, headersString, statusText) {\n      // cancel timeout and subsequent timeout promise resolution\n      if (timeoutId !== undefined) {\n        $browserDefer.cancel(timeoutId);\n      }\n      jsonpDone = xhr = null;\n\n      callback(status, response, headersString, statusText);\n      $browser.$$completeOutstandingRequest(noop);\n    }\n  };\n\n  function jsonpReq(url, callbackId, done) {\n    // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:\n    // - fetches local scripts via XHR and evals them\n    // - adds and immediately removes script elements from the document\n    var script = rawDocument.createElement('script'), callback = null;\n    script.type = \"text/javascript\";\n    script.src = url;\n    script.async = true;\n\n    callback = function(event) {\n      removeEventListenerFn(script, \"load\", callback);\n      removeEventListenerFn(script, \"error\", callback);\n      rawDocument.body.removeChild(script);\n      script = null;\n      var status = -1;\n      var text = \"unknown\";\n\n      if (event) {\n        if (event.type === \"load\" && !callbacks[callbackId].called) {\n          event = { type: \"error\" };\n        }\n        text = event.type;\n        status = event.type === \"error\" ? 404 : 200;\n      }\n\n      if (done) {\n        done(status, text);\n      }\n    };\n\n    addEventListenerFn(script, \"load\", callback);\n    addEventListenerFn(script, \"error\", callback);\n    rawDocument.body.appendChild(script);\n    return callback;\n  }\n}\n\nvar $interpolateMinErr = minErr('$interpolate');\n\n/**\n * @ngdoc provider\n * @name $interpolateProvider\n *\n * @description\n *\n * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.\n *\n * @example\n<example module=\"customInterpolationApp\">\n<file name=\"index.html\">\n<script>\n  var customInterpolationApp = angular.module('customInterpolationApp', []);\n\n  customInterpolationApp.config(function($interpolateProvider) {\n    $interpolateProvider.startSymbol('//');\n    $interpolateProvider.endSymbol('//');\n  });\n\n\n  customInterpolationApp.controller('DemoController', function() {\n      this.label = \"This binding is brought you by // interpolation symbols.\";\n  });\n</script>\n<div ng-app=\"App\" ng-controller=\"DemoController as demo\">\n    //demo.label//\n</div>\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  it('should interpolate binding with custom symbols', function() {\n    expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');\n  });\n</file>\n</example>\n */\nfunction $InterpolateProvider() {\n  var startSymbol = '{{';\n  var endSymbol = '}}';\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#startSymbol\n   * @description\n   * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.\n   *\n   * @param {string=} value new value to set the starting symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.startSymbol = function(value) {\n    if (value) {\n      startSymbol = value;\n      return this;\n    } else {\n      return startSymbol;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#endSymbol\n   * @description\n   * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n   *\n   * @param {string=} value new value to set the ending symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.endSymbol = function(value) {\n    if (value) {\n      endSymbol = value;\n      return this;\n    } else {\n      return endSymbol;\n    }\n  };\n\n\n  this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {\n    var startSymbolLength = startSymbol.length,\n        endSymbolLength = endSymbol.length,\n        escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),\n        escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');\n\n    function escape(ch) {\n      return '\\\\\\\\\\\\' + ch;\n    }\n\n    /**\n     * @ngdoc service\n     * @name $interpolate\n     * @kind function\n     *\n     * @requires $parse\n     * @requires $sce\n     *\n     * @description\n     *\n     * Compiles a string with markup into an interpolation function. This service is used by the\n     * HTML {@link ng.$compile $compile} service for data binding. See\n     * {@link ng.$interpolateProvider $interpolateProvider} for configuring the\n     * interpolation markup.\n     *\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var exp = $interpolate('Hello {{name | uppercase}}!');\n     *   expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');\n     * ```\n     *\n     * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is\n     * `true`, the interpolation function will return `undefined` unless all embedded expressions\n     * evaluate to a value other than `undefined`.\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var context = {greeting: 'Hello', name: undefined };\n     *\n     *   // default \"forgiving\" mode\n     *   var exp = $interpolate('{{greeting}} {{name}}!');\n     *   expect(exp(context)).toEqual('Hello !');\n     *\n     *   // \"allOrNothing\" mode\n     *   exp = $interpolate('{{greeting}} {{name}}!', false, null, true);\n     *   expect(exp(context)).toBeUndefined();\n     *   context.name = 'Angular';\n     *   expect(exp(context)).toEqual('Hello Angular!');\n     * ```\n     *\n     * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.\n     *\n     * ####Escaped Interpolation\n     * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers\n     * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).\n     * It will be rendered as a regular start/end marker, and will not be interpreted as an expression\n     * or binding.\n     *\n     * This enables web-servers to prevent script injection attacks and defacing attacks, to some\n     * degree, while also enabling code examples to work without relying on the\n     * {@link ng.directive:ngNonBindable ngNonBindable} directive.\n     *\n     * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,\n     * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all\n     * interpolation start/end markers with their escaped counterparts.**\n     *\n     * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered\n     * output when the $interpolate service processes the text. So, for HTML elements interpolated\n     * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter\n     * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,\n     * this is typically useful only when user-data is used in rendering a template from the server, or\n     * when otherwise untrusted data is used by a directive.\n     *\n     * <example>\n     *  <file name=\"index.html\">\n     *    <div ng-init=\"username='A user'\">\n     *      <p ng-init=\"apptitle='Escaping demo'\">{{apptitle}}: \\{\\{ username = \"defaced value\"; \\}\\}\n     *        </p>\n     *      <p><strong>{{username}}</strong> attempts to inject code which will deface the\n     *        application, but fails to accomplish their task, because the server has correctly\n     *        escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)\n     *        characters.</p>\n     *      <p>Instead, the result of the attempted script injection is visible, and can be removed\n     *        from the database by an administrator.</p>\n     *    </div>\n     *  </file>\n     * </example>\n     *\n     * @param {string} text The text with markup to interpolate.\n     * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have\n     *    embedded expression in order to return an interpolation function. Strings with no\n     *    embedded expression will return null for the interpolation function.\n     * @param {string=} trustedContext when provided, the returned function passes the interpolated\n     *    result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,\n     *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that\n     *    provides Strict Contextual Escaping for details.\n     * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined\n     *    unless all embedded expressions evaluate to a value other than `undefined`.\n     * @returns {function(context)} an interpolation function which is used to compute the\n     *    interpolated string. The function has these parameters:\n     *\n     * - `context`: evaluation context for all expressions embedded in the interpolated text\n     */\n    function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {\n      allOrNothing = !!allOrNothing;\n      var startIndex,\n          endIndex,\n          index = 0,\n          expressions = [],\n          parseFns = [],\n          textLength = text.length,\n          exp,\n          concat = [],\n          expressionPositions = [];\n\n      while (index < textLength) {\n        if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&\n             ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {\n          if (index !== startIndex) {\n            concat.push(unescapeText(text.substring(index, startIndex)));\n          }\n          exp = text.substring(startIndex + startSymbolLength, endIndex);\n          expressions.push(exp);\n          parseFns.push($parse(exp, parseStringifyInterceptor));\n          index = endIndex + endSymbolLength;\n          expressionPositions.push(concat.length);\n          concat.push('');\n        } else {\n          // we did not find an interpolation, so we have to add the remainder to the separators array\n          if (index !== textLength) {\n            concat.push(unescapeText(text.substring(index)));\n          }\n          break;\n        }\n      }\n\n      // Concatenating expressions makes it hard to reason about whether some combination of\n      // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a\n      // single expression be used for iframe[src], object[src], etc., we ensure that the value\n      // that's used is assigned or constructed by some JS code somewhere that is more testable or\n      // make it obvious that you bound the value to some user controlled value.  This helps reduce\n      // the load when auditing for XSS issues.\n      if (trustedContext && concat.length > 1) {\n          throw $interpolateMinErr('noconcat',\n              \"Error while interpolating: {0}\\nStrict Contextual Escaping disallows \" +\n              \"interpolations that concatenate multiple expressions when a trusted value is \" +\n              \"required.  See http://docs.angularjs.org/api/ng.$sce\", text);\n      }\n\n      if (!mustHaveExpression || expressions.length) {\n        var compute = function(values) {\n          for (var i = 0, ii = expressions.length; i < ii; i++) {\n            if (allOrNothing && isUndefined(values[i])) return;\n            concat[expressionPositions[i]] = values[i];\n          }\n          return concat.join('');\n        };\n\n        var getValue = function(value) {\n          return trustedContext ?\n            $sce.getTrusted(trustedContext, value) :\n            $sce.valueOf(value);\n        };\n\n        var stringify = function(value) {\n          if (value == null) { // null || undefined\n            return '';\n          }\n          switch (typeof value) {\n            case 'string':\n              break;\n            case 'number':\n              value = '' + value;\n              break;\n            default:\n              value = toJson(value);\n          }\n\n          return value;\n        };\n\n        return extend(function interpolationFn(context) {\n            var i = 0;\n            var ii = expressions.length;\n            var values = new Array(ii);\n\n            try {\n              for (; i < ii; i++) {\n                values[i] = parseFns[i](context);\n              }\n\n              return compute(values);\n            } catch (err) {\n              var newErr = $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text,\n                  err.toString());\n              $exceptionHandler(newErr);\n            }\n\n          }, {\n          // all of these properties are undocumented for now\n          exp: text, //just for compatibility with regular watchers created via $watch\n          expressions: expressions,\n          $$watchDelegate: function(scope, listener, objectEquality) {\n            var lastValue;\n            return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {\n              var currValue = compute(values);\n              if (isFunction(listener)) {\n                listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);\n              }\n              lastValue = currValue;\n            }, objectEquality);\n          }\n        });\n      }\n\n      function unescapeText(text) {\n        return text.replace(escapedStartRegexp, startSymbol).\n          replace(escapedEndRegexp, endSymbol);\n      }\n\n      function parseStringifyInterceptor(value) {\n        try {\n          value = getValue(value);\n          return allOrNothing && !isDefined(value) ? value : stringify(value);\n        } catch (err) {\n          var newErr = $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text,\n            err.toString());\n          $exceptionHandler(newErr);\n        }\n      }\n    }\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#startSymbol\n     * @description\n     * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.\n     *\n     * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} start symbol.\n     */\n    $interpolate.startSymbol = function() {\n      return startSymbol;\n    };\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#endSymbol\n     * @description\n     * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n     *\n     * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} end symbol.\n     */\n    $interpolate.endSymbol = function() {\n      return endSymbol;\n    };\n\n    return $interpolate;\n  }];\n}\n\nfunction $IntervalProvider() {\n  this.$get = ['$rootScope', '$window', '$q', '$$q',\n       function($rootScope,   $window,   $q,   $$q) {\n    var intervals = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $interval\n      *\n      * @description\n      * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`\n      * milliseconds.\n      *\n      * The return value of registering an interval function is a promise. This promise will be\n      * notified upon each tick of the interval, and will be resolved after `count` iterations, or\n      * run indefinitely if `count` is not defined. The value of the notification will be the\n      * number of iterations that have run.\n      * To cancel an interval, call `$interval.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n      * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n      * time.\n      *\n      * <div class=\"alert alert-warning\">\n      * **Note**: Intervals created by this service must be explicitly destroyed when you are finished\n      * with them.  In particular they are not automatically destroyed when a controller's scope or a\n      * directive's element are destroyed.\n      * You should take this into consideration and make sure to always cancel the interval at the\n      * appropriate moment.  See the example below for more details on how and when to do this.\n      * </div>\n      *\n      * @param {function()} fn A function that should be called repeatedly.\n      * @param {number} delay Number of milliseconds between each function call.\n      * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n      *   indefinitely.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @returns {promise} A promise which will be notified on each iteration.\n      *\n      * @example\n      * <example module=\"intervalExample\">\n      * <file name=\"index.html\">\n      *   <script>\n      *     angular.module('intervalExample', [])\n      *       .controller('ExampleController', ['$scope', '$interval',\n      *         function($scope, $interval) {\n      *           $scope.format = 'M/d/yy h:mm:ss a';\n      *           $scope.blood_1 = 100;\n      *           $scope.blood_2 = 120;\n      *\n      *           var stop;\n      *           $scope.fight = function() {\n      *             // Don't start a new fight if we are already fighting\n      *             if ( angular.isDefined(stop) ) return;\n      *\n      *             stop = $interval(function() {\n      *               if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {\n      *                 $scope.blood_1 = $scope.blood_1 - 3;\n      *                 $scope.blood_2 = $scope.blood_2 - 4;\n      *               } else {\n      *                 $scope.stopFight();\n      *               }\n      *             }, 100);\n      *           };\n      *\n      *           $scope.stopFight = function() {\n      *             if (angular.isDefined(stop)) {\n      *               $interval.cancel(stop);\n      *               stop = undefined;\n      *             }\n      *           };\n      *\n      *           $scope.resetFight = function() {\n      *             $scope.blood_1 = 100;\n      *             $scope.blood_2 = 120;\n      *           };\n      *\n      *           $scope.$on('$destroy', function() {\n      *             // Make sure that the interval is destroyed too\n      *             $scope.stopFight();\n      *           });\n      *         }])\n      *       // Register the 'myCurrentTime' directive factory method.\n      *       // We inject $interval and dateFilter service since the factory method is DI.\n      *       .directive('myCurrentTime', ['$interval', 'dateFilter',\n      *         function($interval, dateFilter) {\n      *           // return the directive link function. (compile function not needed)\n      *           return function(scope, element, attrs) {\n      *             var format,  // date format\n      *                 stopTime; // so that we can cancel the time updates\n      *\n      *             // used to update the UI\n      *             function updateTime() {\n      *               element.text(dateFilter(new Date(), format));\n      *             }\n      *\n      *             // watch the expression, and update the UI on change.\n      *             scope.$watch(attrs.myCurrentTime, function(value) {\n      *               format = value;\n      *               updateTime();\n      *             });\n      *\n      *             stopTime = $interval(updateTime, 1000);\n      *\n      *             // listen on DOM destroy (removal) event, and cancel the next UI update\n      *             // to prevent updating time after the DOM element was removed.\n      *             element.on('$destroy', function() {\n      *               $interval.cancel(stopTime);\n      *             });\n      *           }\n      *         }]);\n      *   </script>\n      *\n      *   <div>\n      *     <div ng-controller=\"ExampleController\">\n      *       Date format: <input ng-model=\"format\"> <hr/>\n      *       Current time is: <span my-current-time=\"format\"></span>\n      *       <hr/>\n      *       Blood 1 : <font color='red'>{{blood_1}}</font>\n      *       Blood 2 : <font color='red'>{{blood_2}}</font>\n      *       <button type=\"button\" data-ng-click=\"fight()\">Fight</button>\n      *       <button type=\"button\" data-ng-click=\"stopFight()\">StopFight</button>\n      *       <button type=\"button\" data-ng-click=\"resetFight()\">resetFight</button>\n      *     </div>\n      *   </div>\n      *\n      * </file>\n      * </example>\n      */\n    function interval(fn, delay, count, invokeApply) {\n      var setInterval = $window.setInterval,\n          clearInterval = $window.clearInterval,\n          iteration = 0,\n          skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise;\n\n      count = isDefined(count) ? count : 0;\n\n      promise.then(null, null, fn);\n\n      promise.$$intervalId = setInterval(function tick() {\n        deferred.notify(iteration++);\n\n        if (count > 0 && iteration >= count) {\n          deferred.resolve(iteration);\n          clearInterval(promise.$$intervalId);\n          delete intervals[promise.$$intervalId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n\n      }, delay);\n\n      intervals[promise.$$intervalId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $interval#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`.\n      *\n      * @param {promise} promise returned by the `$interval` function.\n      * @returns {boolean} Returns `true` if the task was successfully canceled.\n      */\n    interval.cancel = function(promise) {\n      if (promise && promise.$$intervalId in intervals) {\n        intervals[promise.$$intervalId].reject('canceled');\n        $window.clearInterval(promise.$$intervalId);\n        delete intervals[promise.$$intervalId];\n        return true;\n      }\n      return false;\n    };\n\n    return interval;\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $locale\n *\n * @description\n * $locale service provides localization rules for various Angular components. As of right now the\n * only public api is:\n *\n * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)\n */\nfunction $LocaleProvider() {\n  this.$get = function() {\n    return {\n      id: 'en-us',\n\n      NUMBER_FORMATS: {\n        DECIMAL_SEP: '.',\n        GROUP_SEP: ',',\n        PATTERNS: [\n          { // Decimal Pattern\n            minInt: 1,\n            minFrac: 0,\n            maxFrac: 3,\n            posPre: '',\n            posSuf: '',\n            negPre: '-',\n            negSuf: '',\n            gSize: 3,\n            lgSize: 3\n          },{ //Currency Pattern\n            minInt: 1,\n            minFrac: 2,\n            maxFrac: 2,\n            posPre: '\\u00A4',\n            posSuf: '',\n            negPre: '(\\u00A4',\n            negSuf: ')',\n            gSize: 3,\n            lgSize: 3\n          }\n        ],\n        CURRENCY_SYM: '$'\n      },\n\n      DATETIME_FORMATS: {\n        MONTH:\n            'January,February,March,April,May,June,July,August,September,October,November,December'\n            .split(','),\n        SHORTMONTH:  'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),\n        DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),\n        SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),\n        AMPMS: ['AM','PM'],\n        medium: 'MMM d, y h:mm:ss a',\n        'short': 'M/d/yy h:mm a',\n        fullDate: 'EEEE, MMMM d, y',\n        longDate: 'MMMM d, y',\n        mediumDate: 'MMM d, y',\n        shortDate: 'M/d/yy',\n        mediumTime: 'h:mm:ss a',\n        shortTime: 'h:mm a'\n      },\n\n      pluralCat: function(num) {\n        if (num === 1) {\n          return 'one';\n        }\n        return 'other';\n      }\n    };\n  };\n}\n\nvar PATH_MATCH = /^([^\\?#]*)(\\?([^#]*))?(#(.*))?$/,\n    DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};\nvar $locationMinErr = minErr('$location');\n\n\n/**\n * Encode path using encodeUriSegment, ignoring forward slashes\n *\n * @param {string} path Path to encode\n * @returns {string}\n */\nfunction encodePath(path) {\n  var segments = path.split('/'),\n      i = segments.length;\n\n  while (i--) {\n    segments[i] = encodeUriSegment(segments[i]);\n  }\n\n  return segments.join('/');\n}\n\nfunction parseAbsoluteUrl(absoluteUrl, locationObj) {\n  var parsedUrl = urlResolve(absoluteUrl);\n\n  locationObj.$$protocol = parsedUrl.protocol;\n  locationObj.$$host = parsedUrl.hostname;\n  locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;\n}\n\n\nfunction parseAppUrl(relativeUrl, locationObj) {\n  var prefixed = (relativeUrl.charAt(0) !== '/');\n  if (prefixed) {\n    relativeUrl = '/' + relativeUrl;\n  }\n  var match = urlResolve(relativeUrl);\n  locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?\n      match.pathname.substring(1) : match.pathname);\n  locationObj.$$search = parseKeyValue(match.search);\n  locationObj.$$hash = decodeURIComponent(match.hash);\n\n  // make sure path starts with '/';\n  if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {\n    locationObj.$$path = '/' + locationObj.$$path;\n  }\n}\n\n\n/**\n *\n * @param {string} begin\n * @param {string} whole\n * @returns {string} returns text from whole after begin or undefined if it does not begin with\n *                   expected string.\n */\nfunction beginsWith(begin, whole) {\n  if (whole.indexOf(begin) === 0) {\n    return whole.substr(begin.length);\n  }\n}\n\n\nfunction stripHash(url) {\n  var index = url.indexOf('#');\n  return index == -1 ? url : url.substr(0, index);\n}\n\nfunction trimEmptyHash(url) {\n  return url.replace(/(#.+)|#$/, '$1');\n}\n\n\nfunction stripFile(url) {\n  return url.substr(0, stripHash(url).lastIndexOf('/') + 1);\n}\n\n/* return the server only (scheme://host:port) */\nfunction serverBase(url) {\n  return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));\n}\n\n\n/**\n * LocationHtml5Url represents an url\n * This object is exposed as $location service when HTML5 mode is enabled and supported\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} basePrefix url path prefix\n */\nfunction LocationHtml5Url(appBase, basePrefix) {\n  this.$$html5 = true;\n  basePrefix = basePrefix || '';\n  var appBaseNoFile = stripFile(appBase);\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given html5 (regular) url string into properties\n   * @param {string} url HTML5 url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var pathUrl = beginsWith(appBaseNoFile, url);\n    if (!isString(pathUrl)) {\n      throw $locationMinErr('ipthprfx', 'Invalid url \"{0}\", missing path prefix \"{1}\".', url,\n          appBaseNoFile);\n    }\n\n    parseAppUrl(pathUrl, this);\n\n    if (!this.$$path) {\n      this.$$path = '/';\n    }\n\n    this.$$compose();\n  };\n\n  /**\n   * Compose url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n    var appUrl, prevAppUrl;\n    var rewrittenUrl;\n\n    if ((appUrl = beginsWith(appBase, url)) !== undefined) {\n      prevAppUrl = appUrl;\n      if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {\n        rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);\n      } else {\n        rewrittenUrl = appBase + prevAppUrl;\n      }\n    } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {\n      rewrittenUrl = appBaseNoFile + appUrl;\n    } else if (appBaseNoFile == url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when developer doesn't opt into html5 mode.\n * It also serves as the base class for html5 mode fallback on legacy browsers.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangUrl(appBase, hashPrefix) {\n  var appBaseNoFile = stripFile(appBase);\n\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given hashbang url into properties\n   * @param {string} url Hashbang url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);\n    var withoutHashUrl;\n\n    if (withoutBaseUrl.charAt(0) === '#') {\n\n      // The rest of the url starts with a hash so we have\n      // got either a hashbang path or a plain hash fragment\n      withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);\n      if (isUndefined(withoutHashUrl)) {\n        // There was no hashbang prefix so we just have a hash fragment\n        withoutHashUrl = withoutBaseUrl;\n      }\n\n    } else {\n      // There was no hashbang path nor hash fragment:\n      // If we are in HTML5 mode we use what is left as the path;\n      // Otherwise we ignore what is left\n      withoutHashUrl = this.$$html5 ? withoutBaseUrl : '';\n    }\n\n    parseAppUrl(withoutHashUrl, this);\n\n    this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);\n\n    this.$$compose();\n\n    /*\n     * In Windows, on an anchor node on documents loaded from\n     * the filesystem, the browser will return a pathname\n     * prefixed with the drive name ('/C:/path') when a\n     * pathname without a drive is set:\n     *  * a.setAttribute('href', '/foo')\n     *   * a.pathname === '/C:/foo' //true\n     *\n     * Inside of Angular, we're always using pathnames that\n     * do not include drive names for routing.\n     */\n    function removeWindowsDriveName(path, url, base) {\n      /*\n      Matches paths for file protocol on windows,\n      such as /C:/foo/bar, and captures only /foo/bar.\n      */\n      var windowsFilePathExp = /^\\/[A-Z]:(\\/.*)/;\n\n      var firstPathSegmentMatch;\n\n      //Get the relative path from the input URL.\n      if (url.indexOf(base) === 0) {\n        url = url.replace(base, '');\n      }\n\n      // The input URL intentionally contains a first path segment that ends with a colon.\n      if (windowsFilePathExp.exec(url)) {\n        return path;\n      }\n\n      firstPathSegmentMatch = windowsFilePathExp.exec(path);\n      return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;\n    }\n  };\n\n  /**\n   * Compose hashbang url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (stripHash(appBase) == stripHash(url)) {\n      this.$$parse(url);\n      return true;\n    }\n    return false;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when html5 history api is enabled but the browser\n * does not support it.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangInHtml5Url(appBase, hashPrefix) {\n  this.$$html5 = true;\n  LocationHashbangUrl.apply(this, arguments);\n\n  var appBaseNoFile = stripFile(appBase);\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n\n    var rewrittenUrl;\n    var appUrl;\n\n    if (appBase == stripHash(url)) {\n      rewrittenUrl = url;\n    } else if ((appUrl = beginsWith(appBaseNoFile, url))) {\n      rewrittenUrl = appBase + hashPrefix + appUrl;\n    } else if (appBaseNoFile === url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'\n    this.$$absUrl = appBase + hashPrefix + this.$$url;\n  };\n\n}\n\n\nvar locationPrototype = {\n\n  /**\n   * Are we in html5 mode?\n   * @private\n   */\n  $$html5: false,\n\n  /**\n   * Has any change been replacing?\n   * @private\n   */\n  $$replace: false,\n\n  /**\n   * @ngdoc method\n   * @name $location#absUrl\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return full url representation with all segments encoded according to rules specified in\n   * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var absUrl = $location.absUrl();\n   * // => \"http://example.com/#/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @return {string} full url\n   */\n  absUrl: locationGetter('$$absUrl'),\n\n  /**\n   * @ngdoc method\n   * @name $location#url\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return url (e.g. `/path?a=b#hash`) when called without any parameter.\n   *\n   * Change path, search and hash, when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var url = $location.url();\n   * // => \"/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)\n   * @return {string} url\n   */\n  url: function(url) {\n    if (isUndefined(url))\n      return this.$$url;\n\n    var match = PATH_MATCH.exec(url);\n    if (match[1] || url === '') this.path(decodeURIComponent(match[1]));\n    if (match[2] || match[1] || url === '') this.search(match[3] || '');\n    this.hash(match[5] || '');\n\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#protocol\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return protocol of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var protocol = $location.protocol();\n   * // => \"http\"\n   * ```\n   *\n   * @return {string} protocol of current url\n   */\n  protocol: locationGetter('$$protocol'),\n\n  /**\n   * @ngdoc method\n   * @name $location#host\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return host of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var host = $location.host();\n   * // => \"example.com\"\n   * ```\n   *\n   * @return {string} host of current url.\n   */\n  host: locationGetter('$$host'),\n\n  /**\n   * @ngdoc method\n   * @name $location#port\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return port of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var port = $location.port();\n   * // => 80\n   * ```\n   *\n   * @return {Number} port\n   */\n  port: locationGetter('$$port'),\n\n  /**\n   * @ngdoc method\n   * @name $location#path\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return path of current url when called without any parameter.\n   *\n   * Change path when called with parameter and return `$location`.\n   *\n   * Note: Path should always begin with forward slash (/), this method will add the forward slash\n   * if it is missing.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var path = $location.path();\n   * // => \"/some/path\"\n   * ```\n   *\n   * @param {(string|number)=} path New path\n   * @return {string} path\n   */\n  path: locationGetterSetter('$$path', function(path) {\n    path = path !== null ? path.toString() : '';\n    return path.charAt(0) == '/' ? path : '/' + path;\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#search\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return search part (as object) of current url when called without any parameter.\n   *\n   * Change search part when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var searchObject = $location.search();\n   * // => {foo: 'bar', baz: 'xoxo'}\n   *\n   * // set foo to 'yipee'\n   * $location.search('foo', 'yipee');\n   * // $location.search() => {foo: 'yipee', baz: 'xoxo'}\n   * ```\n   *\n   * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or\n   * hash object.\n   *\n   * When called with a single argument the method acts as a setter, setting the `search` component\n   * of `$location` to the specified value.\n   *\n   * If the argument is a hash object containing an array of values, these values will be encoded\n   * as duplicate search parameters in the url.\n   *\n   * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`\n   * will override only a single search property.\n   *\n   * If `paramValue` is an array, it will override the property of the `search` component of\n   * `$location` specified via the first argument.\n   *\n   * If `paramValue` is `null`, the property specified via the first argument will be deleted.\n   *\n   * If `paramValue` is `true`, the property specified via the first argument will be added with no\n   * value nor trailing equal sign.\n   *\n   * @return {Object} If called with no arguments returns the parsed `search` object. If called with\n   * one or more arguments returns `$location` object itself.\n   */\n  search: function(search, paramValue) {\n    switch (arguments.length) {\n      case 0:\n        return this.$$search;\n      case 1:\n        if (isString(search) || isNumber(search)) {\n          search = search.toString();\n          this.$$search = parseKeyValue(search);\n        } else if (isObject(search)) {\n          search = copy(search, {});\n          // remove object undefined or null properties\n          forEach(search, function(value, key) {\n            if (value == null) delete search[key];\n          });\n\n          this.$$search = search;\n        } else {\n          throw $locationMinErr('isrcharg',\n              'The first argument of the `$location#search()` call must be a string or an object.');\n        }\n        break;\n      default:\n        if (isUndefined(paramValue) || paramValue === null) {\n          delete this.$$search[search];\n        } else {\n          this.$$search[search] = paramValue;\n        }\n    }\n\n    this.$$compose();\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#hash\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return hash fragment when called without any parameter.\n   *\n   * Change hash fragment when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue\n   * var hash = $location.hash();\n   * // => \"hashValue\"\n   * ```\n   *\n   * @param {(string|number)=} hash New hash fragment\n   * @return {string} hash\n   */\n  hash: locationGetterSetter('$$hash', function(hash) {\n    return hash !== null ? hash.toString() : '';\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#replace\n   *\n   * @description\n   * If called, all changes to $location during current `$digest` will be replacing current history\n   * record, instead of adding new one.\n   */\n  replace: function() {\n    this.$$replace = true;\n    return this;\n  }\n};\n\nforEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {\n  Location.prototype = Object.create(locationPrototype);\n\n  /**\n   * @ngdoc method\n   * @name $location#state\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return the history state object when called without any parameter.\n   *\n   * Change the history state object when called with one parameter and return `$location`.\n   * The state object is later passed to `pushState` or `replaceState`.\n   *\n   * NOTE: This method is supported only in HTML5 mode and only in browsers supporting\n   * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support\n   * older browsers (like IE9 or Android < 4.0), don't use this method.\n   *\n   * @param {object=} state State object for pushState or replaceState\n   * @return {object} state\n   */\n  Location.prototype.state = function(state) {\n    if (!arguments.length)\n      return this.$$state;\n\n    if (Location !== LocationHtml5Url || !this.$$html5) {\n      throw $locationMinErr('nostate', 'History API state support is available only ' +\n        'in HTML5 mode and only in browsers supporting HTML5 History API');\n    }\n    // The user might modify `stateObject` after invoking `$location.state(stateObject)`\n    // but we're changing the $$state reference to $browser.state() during the $digest\n    // so the modification window is narrow.\n    this.$$state = isUndefined(state) ? null : state;\n\n    return this;\n  };\n});\n\n\nfunction locationGetter(property) {\n  return function() {\n    return this[property];\n  };\n}\n\n\nfunction locationGetterSetter(property, preprocess) {\n  return function(value) {\n    if (isUndefined(value))\n      return this[property];\n\n    this[property] = preprocess(value);\n    this.$$compose();\n\n    return this;\n  };\n}\n\n\n/**\n * @ngdoc service\n * @name $location\n *\n * @requires $rootElement\n *\n * @description\n * The $location service parses the URL in the browser address bar (based on the\n * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL\n * available to your application. Changes to the URL in the address bar are reflected into\n * $location service and changes to $location are reflected into the browser address bar.\n *\n * **The $location service:**\n *\n * - Exposes the current URL in the browser address bar, so you can\n *   - Watch and observe the URL.\n *   - Change the URL.\n * - Synchronizes the URL with the browser when the user\n *   - Changes the address bar.\n *   - Clicks the back or forward button (or clicks a History link).\n *   - Clicks on a link.\n * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).\n *\n * For more information see {@link guide/$location Developer Guide: Using $location}\n */\n\n/**\n * @ngdoc provider\n * @name $locationProvider\n * @description\n * Use the `$locationProvider` to configure how the application deep linking paths are stored.\n */\nfunction $LocationProvider() {\n  var hashPrefix = '',\n      html5Mode = {\n        enabled: false,\n        requireBase: true,\n        rewriteLinks: true\n      };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#hashPrefix\n   * @description\n   * @param {string=} prefix Prefix for hash part (containing path and search)\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.hashPrefix = function(prefix) {\n    if (isDefined(prefix)) {\n      hashPrefix = prefix;\n      return this;\n    } else {\n      return hashPrefix;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#html5Mode\n   * @description\n   * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.\n   *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported\n   *   properties:\n   *   - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to\n   *     change urls where supported. Will fall back to hash-prefixed paths in browsers that do not\n   *     support `pushState`.\n   *   - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies\n   *     whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are\n   *     true, and a base tag is not present, an error will be thrown when `$location` is injected.\n   *     See the {@link guide/$location $location guide for more information}\n   *   - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,\n   *     enables/disables url rewriting for relative links.\n   *\n   * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter\n   */\n  this.html5Mode = function(mode) {\n    if (isBoolean(mode)) {\n      html5Mode.enabled = mode;\n      return this;\n    } else if (isObject(mode)) {\n\n      if (isBoolean(mode.enabled)) {\n        html5Mode.enabled = mode.enabled;\n      }\n\n      if (isBoolean(mode.requireBase)) {\n        html5Mode.requireBase = mode.requireBase;\n      }\n\n      if (isBoolean(mode.rewriteLinks)) {\n        html5Mode.rewriteLinks = mode.rewriteLinks;\n      }\n\n      return this;\n    } else {\n      return html5Mode;\n    }\n  };\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeStart\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted before a URL will change.\n   *\n   * This change can be prevented by calling\n   * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more\n   * details about event object. Upon successful change\n   * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeSuccess\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted after a URL was changed.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',\n      function($rootScope, $browser, $sniffer, $rootElement, $window) {\n    var $location,\n        LocationMode,\n        baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''\n        initialUrl = $browser.url(),\n        appBase;\n\n    if (html5Mode.enabled) {\n      if (!baseHref && html5Mode.requireBase) {\n        throw $locationMinErr('nobase',\n          \"$location in HTML5 mode requires a <base> tag to be present!\");\n      }\n      appBase = serverBase(initialUrl) + (baseHref || '/');\n      LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;\n    } else {\n      appBase = stripHash(initialUrl);\n      LocationMode = LocationHashbangUrl;\n    }\n    $location = new LocationMode(appBase, '#' + hashPrefix);\n    $location.$$parseLinkUrl(initialUrl, initialUrl);\n\n    $location.$$state = $browser.state();\n\n    var IGNORE_URI_REGEXP = /^\\s*(javascript|mailto):/i;\n\n    function setBrowserUrlWithFallback(url, replace, state) {\n      var oldUrl = $location.url();\n      var oldState = $location.$$state;\n      try {\n        $browser.url(url, replace, state);\n\n        // Make sure $location.state() returns referentially identical (not just deeply equal)\n        // state object; this makes possible quick checking if the state changed in the digest\n        // loop. Checking deep equality would be too expensive.\n        $location.$$state = $browser.state();\n      } catch (e) {\n        // Restore old values if pushState fails\n        $location.url(oldUrl);\n        $location.$$state = oldState;\n\n        throw e;\n      }\n    }\n\n    $rootElement.on('click', function(event) {\n      // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)\n      // currently we open nice url link and redirect then\n\n      if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;\n\n      var elm = jqLite(event.target);\n\n      // traverse the DOM up to find first A tag\n      while (nodeName_(elm[0]) !== 'a') {\n        // ignore rewriting if no A tag (reached root element, or no parent - removed from document)\n        if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;\n      }\n\n      var absHref = elm.prop('href');\n      // get the actual href attribute - see\n      // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx\n      var relHref = elm.attr('href') || elm.attr('xlink:href');\n\n      if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {\n        // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during\n        // an animation.\n        absHref = urlResolve(absHref.animVal).href;\n      }\n\n      // Ignore when url is started with javascript: or mailto:\n      if (IGNORE_URI_REGEXP.test(absHref)) return;\n\n      if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {\n        if ($location.$$parseLinkUrl(absHref, relHref)) {\n          // We do a preventDefault for all urls that are part of the angular application,\n          // in html5mode and also without, so that we are able to abort navigation without\n          // getting double entries in the location history.\n          event.preventDefault();\n          // update location manually\n          if ($location.absUrl() != $browser.url()) {\n            $rootScope.$apply();\n            // hack to work around FF6 bug 684208 when scenario runner clicks on links\n            $window.angular['ff-684208-preventDefault'] = true;\n          }\n        }\n      }\n    });\n\n\n    // rewrite hashbang url <> html5 url\n    if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {\n      $browser.url($location.absUrl(), true);\n    }\n\n    var initializing = true;\n\n    // update $location when $browser url changes\n    $browser.onUrlChange(function(newUrl, newState) {\n      $rootScope.$evalAsync(function() {\n        var oldUrl = $location.absUrl();\n        var oldState = $location.$$state;\n        var defaultPrevented;\n\n        $location.$$parse(newUrl);\n        $location.$$state = newState;\n\n        defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n            newState, oldState).defaultPrevented;\n\n        // if the location was changed by a `$locationChangeStart` handler then stop\n        // processing this location change\n        if ($location.absUrl() !== newUrl) return;\n\n        if (defaultPrevented) {\n          $location.$$parse(oldUrl);\n          $location.$$state = oldState;\n          setBrowserUrlWithFallback(oldUrl, false, oldState);\n        } else {\n          initializing = false;\n          afterLocationChange(oldUrl, oldState);\n        }\n      });\n      if (!$rootScope.$$phase) $rootScope.$digest();\n    });\n\n    // update browser\n    $rootScope.$watch(function $locationWatch() {\n      var oldUrl = trimEmptyHash($browser.url());\n      var newUrl = trimEmptyHash($location.absUrl());\n      var oldState = $browser.state();\n      var currentReplace = $location.$$replace;\n      var urlOrStateChanged = oldUrl !== newUrl ||\n        ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);\n\n      if (initializing || urlOrStateChanged) {\n        initializing = false;\n\n        $rootScope.$evalAsync(function() {\n          var newUrl = $location.absUrl();\n          var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n              $location.$$state, oldState).defaultPrevented;\n\n          // if the location was changed by a `$locationChangeStart` handler then stop\n          // processing this location change\n          if ($location.absUrl() !== newUrl) return;\n\n          if (defaultPrevented) {\n            $location.$$parse(oldUrl);\n            $location.$$state = oldState;\n          } else {\n            if (urlOrStateChanged) {\n              setBrowserUrlWithFallback(newUrl, currentReplace,\n                                        oldState === $location.$$state ? null : $location.$$state);\n            }\n            afterLocationChange(oldUrl, oldState);\n          }\n        });\n      }\n\n      $location.$$replace = false;\n\n      // we don't need to return anything because $evalAsync will make the digest loop dirty when\n      // there is a change\n    });\n\n    return $location;\n\n    function afterLocationChange(oldUrl, oldState) {\n      $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,\n        $location.$$state, oldState);\n    }\n}];\n}\n\n/**\n * @ngdoc service\n * @name $log\n * @requires $window\n *\n * @description\n * Simple service for logging. Default implementation safely writes the message\n * into the browser's console (if present).\n *\n * The main purpose of this service is to simplify debugging and troubleshooting.\n *\n * The default is to log `debug` messages. You can use\n * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.\n *\n * @example\n   <example module=\"logExample\">\n     <file name=\"script.js\">\n       angular.module('logExample', [])\n         .controller('LogController', ['$scope', '$log', function($scope, $log) {\n           $scope.$log = $log;\n           $scope.message = 'Hello World!';\n         }]);\n     </file>\n     <file name=\"index.html\">\n       <div ng-controller=\"LogController\">\n         <p>Reload this page with open console, enter text and hit the log button...</p>\n         Message:\n         <input type=\"text\" ng-model=\"message\"/>\n         <button ng-click=\"$log.log(message)\">log</button>\n         <button ng-click=\"$log.warn(message)\">warn</button>\n         <button ng-click=\"$log.info(message)\">info</button>\n         <button ng-click=\"$log.error(message)\">error</button>\n       </div>\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc provider\n * @name $logProvider\n * @description\n * Use the `$logProvider` to configure how the application logs messages\n */\nfunction $LogProvider() {\n  var debug = true,\n      self = this;\n\n  /**\n   * @ngdoc method\n   * @name $logProvider#debugEnabled\n   * @description\n   * @param {boolean=} flag enable or disable debug level messages\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.debugEnabled = function(flag) {\n    if (isDefined(flag)) {\n      debug = flag;\n    return this;\n    } else {\n      return debug;\n    }\n  };\n\n  this.$get = ['$window', function($window) {\n    return {\n      /**\n       * @ngdoc method\n       * @name $log#log\n       *\n       * @description\n       * Write a log message\n       */\n      log: consoleLog('log'),\n\n      /**\n       * @ngdoc method\n       * @name $log#info\n       *\n       * @description\n       * Write an information message\n       */\n      info: consoleLog('info'),\n\n      /**\n       * @ngdoc method\n       * @name $log#warn\n       *\n       * @description\n       * Write a warning message\n       */\n      warn: consoleLog('warn'),\n\n      /**\n       * @ngdoc method\n       * @name $log#error\n       *\n       * @description\n       * Write an error message\n       */\n      error: consoleLog('error'),\n\n      /**\n       * @ngdoc method\n       * @name $log#debug\n       *\n       * @description\n       * Write a debug message\n       */\n      debug: (function() {\n        var fn = consoleLog('debug');\n\n        return function() {\n          if (debug) {\n            fn.apply(self, arguments);\n          }\n        };\n      }())\n    };\n\n    function formatError(arg) {\n      if (arg instanceof Error) {\n        if (arg.stack) {\n          arg = (arg.message && arg.stack.indexOf(arg.message) === -1)\n              ? 'Error: ' + arg.message + '\\n' + arg.stack\n              : arg.stack;\n        } else if (arg.sourceURL) {\n          arg = arg.message + '\\n' + arg.sourceURL + ':' + arg.line;\n        }\n      }\n      return arg;\n    }\n\n    function consoleLog(type) {\n      var console = $window.console || {},\n          logFn = console[type] || console.log || noop,\n          hasApply = false;\n\n      // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.\n      // The reason behind this is that console.log has type \"object\" in IE8...\n      try {\n        hasApply = !!logFn.apply;\n      } catch (e) {}\n\n      if (hasApply) {\n        return function() {\n          var args = [];\n          forEach(arguments, function(arg) {\n            args.push(formatError(arg));\n          });\n          return logFn.apply(console, args);\n        };\n      }\n\n      // we are IE which either doesn't have window.console => this is noop and we do nothing,\n      // or we are IE where console.log doesn't have apply so we log at least first 2 args\n      return function(arg1, arg2) {\n        logFn(arg1, arg2 == null ? '' : arg2);\n      };\n    }\n  }];\n}\n\nvar $parseMinErr = minErr('$parse');\n\n// Sandboxing Angular Expressions\n// ------------------------------\n// Angular expressions are generally considered safe because these expressions only have direct\n// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by\n// obtaining a reference to native JS functions such as the Function constructor.\n//\n// As an example, consider the following Angular expression:\n//\n//   {}.toString.constructor('alert(\"evil JS code\")')\n//\n// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits\n// against the expression language, but not to prevent exploits that were enabled by exposing\n// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good\n// practice and therefore we are not even trying to protect against interaction with an object\n// explicitly exposed in this way.\n//\n// In general, it is not possible to access a Window object from an angular expression unless a\n// window or some DOM object that has a reference to window is published onto a Scope.\n// Similarly we prevent invocations of function known to be dangerous, as well as assignments to\n// native objects.\n//\n// See https://docs.angularjs.org/guide/security\n\n\nfunction ensureSafeMemberName(name, fullExpression) {\n  if (name === \"__defineGetter__\" || name === \"__defineSetter__\"\n      || name === \"__lookupGetter__\" || name === \"__lookupSetter__\"\n      || name === \"__proto__\") {\n    throw $parseMinErr('isecfld',\n        'Attempting to access a disallowed field in Angular expressions! '\n        + 'Expression: {0}', fullExpression);\n  }\n  return name;\n}\n\nfunction ensureSafeObject(obj, fullExpression) {\n  // nifty check if obj is Function that is fast and works across iframes and other contexts\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n          'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isWindow(obj)\n        obj.window === obj) {\n      throw $parseMinErr('isecwindow',\n          'Referencing the Window in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isElement(obj)\n        obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {\n      throw $parseMinErr('isecdom',\n          'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// block Object so that we can't get hold of dangerous Object.* methods\n        obj === Object) {\n      throw $parseMinErr('isecobj',\n          'Referencing Object in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    }\n  }\n  return obj;\n}\n\nvar CALL = Function.prototype.call;\nvar APPLY = Function.prototype.apply;\nvar BIND = Function.prototype.bind;\n\nfunction ensureSafeFunction(obj, fullExpression) {\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n        'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    } else if (obj === CALL || obj === APPLY || obj === BIND) {\n      throw $parseMinErr('isecff',\n        'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    }\n  }\n}\n\n//Keyword constants\nvar CONSTANTS = createMap();\nforEach({\n  'null': function() { return null; },\n  'true': function() { return true; },\n  'false': function() { return false; },\n  'undefined': function() {}\n}, function(constantGetter, name) {\n  constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;\n  CONSTANTS[name] = constantGetter;\n});\n\n//Not quite a constant, but can be lex/parsed the same\nCONSTANTS['this'] = function(self) { return self; };\nCONSTANTS['this'].sharedGetter = true;\n\n\n//Operators - will be wrapped by binaryFn/unaryFn/assignment/filter\nvar OPERATORS = extend(createMap(), {\n    '+':function(self, locals, a, b) {\n      a=a(self, locals); b=b(self, locals);\n      if (isDefined(a)) {\n        if (isDefined(b)) {\n          return a + b;\n        }\n        return a;\n      }\n      return isDefined(b) ? b : undefined;},\n    '-':function(self, locals, a, b) {\n          a=a(self, locals); b=b(self, locals);\n          return (isDefined(a) ? a : 0) - (isDefined(b) ? b : 0);\n        },\n    '*':function(self, locals, a, b) {return a(self, locals) * b(self, locals);},\n    '/':function(self, locals, a, b) {return a(self, locals) / b(self, locals);},\n    '%':function(self, locals, a, b) {return a(self, locals) % b(self, locals);},\n    '===':function(self, locals, a, b) {return a(self, locals) === b(self, locals);},\n    '!==':function(self, locals, a, b) {return a(self, locals) !== b(self, locals);},\n    '==':function(self, locals, a, b) {return a(self, locals) == b(self, locals);},\n    '!=':function(self, locals, a, b) {return a(self, locals) != b(self, locals);},\n    '<':function(self, locals, a, b) {return a(self, locals) < b(self, locals);},\n    '>':function(self, locals, a, b) {return a(self, locals) > b(self, locals);},\n    '<=':function(self, locals, a, b) {return a(self, locals) <= b(self, locals);},\n    '>=':function(self, locals, a, b) {return a(self, locals) >= b(self, locals);},\n    '&&':function(self, locals, a, b) {return a(self, locals) && b(self, locals);},\n    '||':function(self, locals, a, b) {return a(self, locals) || b(self, locals);},\n    '!':function(self, locals, a) {return !a(self, locals);},\n\n    //Tokenized as operators but parsed as assignment/filters\n    '=':true,\n    '|':true\n});\nvar ESCAPE = {\"n\":\"\\n\", \"f\":\"\\f\", \"r\":\"\\r\", \"t\":\"\\t\", \"v\":\"\\v\", \"'\":\"'\", '\"':'\"'};\n\n\n/////////////////////////////////////////\n\n\n/**\n * @constructor\n */\nvar Lexer = function(options) {\n  this.options = options;\n};\n\nLexer.prototype = {\n  constructor: Lexer,\n\n  lex: function(text) {\n    this.text = text;\n    this.index = 0;\n    this.tokens = [];\n\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (ch === '\"' || ch === \"'\") {\n        this.readString(ch);\n      } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\n        this.readNumber();\n      } else if (this.isIdent(ch)) {\n        this.readIdent();\n      } else if (this.is(ch, '(){}[].,;:?')) {\n        this.tokens.push({index: this.index, text: ch});\n        this.index++;\n      } else if (this.isWhitespace(ch)) {\n        this.index++;\n      } else {\n        var ch2 = ch + this.peek();\n        var ch3 = ch2 + this.peek(2);\n        var op1 = OPERATORS[ch];\n        var op2 = OPERATORS[ch2];\n        var op3 = OPERATORS[ch3];\n        if (op1 || op2 || op3) {\n          var token = op3 ? ch3 : (op2 ? ch2 : ch);\n          this.tokens.push({index: this.index, text: token, operator: true});\n          this.index += token.length;\n        } else {\n          this.throwError('Unexpected next character ', this.index, this.index + 1);\n        }\n      }\n    }\n    return this.tokens;\n  },\n\n  is: function(ch, chars) {\n    return chars.indexOf(ch) !== -1;\n  },\n\n  peek: function(i) {\n    var num = i || 1;\n    return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\n  },\n\n  isNumber: function(ch) {\n    return ('0' <= ch && ch <= '9') && typeof ch === \"string\";\n  },\n\n  isWhitespace: function(ch) {\n    // IE treats non-breaking space as \\u00A0\n    return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\n            ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\n  },\n\n  isIdent: function(ch) {\n    return ('a' <= ch && ch <= 'z' ||\n            'A' <= ch && ch <= 'Z' ||\n            '_' === ch || ch === '$');\n  },\n\n  isExpOperator: function(ch) {\n    return (ch === '-' || ch === '+' || this.isNumber(ch));\n  },\n\n  throwError: function(error, start, end) {\n    end = end || this.index;\n    var colStr = (isDefined(start)\n            ? 's ' + start +  '-' + this.index + ' [' + this.text.substring(start, end) + ']'\n            : ' ' + end);\n    throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\n        error, colStr, this.text);\n  },\n\n  readNumber: function() {\n    var number = '';\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = lowercase(this.text.charAt(this.index));\n      if (ch == '.' || this.isNumber(ch)) {\n        number += ch;\n      } else {\n        var peekCh = this.peek();\n        if (ch == 'e' && this.isExpOperator(peekCh)) {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            peekCh && this.isNumber(peekCh) &&\n            number.charAt(number.length - 1) == 'e') {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            (!peekCh || !this.isNumber(peekCh)) &&\n            number.charAt(number.length - 1) == 'e') {\n          this.throwError('Invalid exponent');\n        } else {\n          break;\n        }\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: number,\n      constant: true,\n      value: Number(number)\n    });\n  },\n\n  readIdent: function() {\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (!(this.isIdent(ch) || this.isNumber(ch))) {\n        break;\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: this.text.slice(start, this.index),\n      identifier: true\n    });\n  },\n\n  readString: function(quote) {\n    var start = this.index;\n    this.index++;\n    var string = '';\n    var rawString = quote;\n    var escape = false;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      rawString += ch;\n      if (escape) {\n        if (ch === 'u') {\n          var hex = this.text.substring(this.index + 1, this.index + 5);\n          if (!hex.match(/[\\da-f]{4}/i))\n            this.throwError('Invalid unicode escape [\\\\u' + hex + ']');\n          this.index += 4;\n          string += String.fromCharCode(parseInt(hex, 16));\n        } else {\n          var rep = ESCAPE[ch];\n          string = string + (rep || ch);\n        }\n        escape = false;\n      } else if (ch === '\\\\') {\n        escape = true;\n      } else if (ch === quote) {\n        this.index++;\n        this.tokens.push({\n          index: start,\n          text: rawString,\n          constant: true,\n          value: string\n        });\n        return;\n      } else {\n        string += ch;\n      }\n      this.index++;\n    }\n    this.throwError('Unterminated quote', start);\n  }\n};\n\n\nfunction isConstant(exp) {\n  return exp.constant;\n}\n\n/**\n * @constructor\n */\nvar Parser = function(lexer, $filter, options) {\n  this.lexer = lexer;\n  this.$filter = $filter;\n  this.options = options;\n};\n\nParser.ZERO = extend(function() {\n  return 0;\n}, {\n  sharedGetter: true,\n  constant: true\n});\n\nParser.prototype = {\n  constructor: Parser,\n\n  parse: function(text) {\n    this.text = text;\n    this.tokens = this.lexer.lex(text);\n\n    var value = this.statements();\n\n    if (this.tokens.length !== 0) {\n      this.throwError('is an unexpected token', this.tokens[0]);\n    }\n\n    value.literal = !!value.literal;\n    value.constant = !!value.constant;\n\n    return value;\n  },\n\n  primary: function() {\n    var primary;\n    if (this.expect('(')) {\n      primary = this.filterChain();\n      this.consume(')');\n    } else if (this.expect('[')) {\n      primary = this.arrayDeclaration();\n    } else if (this.expect('{')) {\n      primary = this.object();\n    } else if (this.peek().identifier && this.peek().text in CONSTANTS) {\n      primary = CONSTANTS[this.consume().text];\n    } else if (this.peek().identifier) {\n      primary = this.identifier();\n    } else if (this.peek().constant) {\n      primary = this.constant();\n    } else {\n      this.throwError('not a primary expression', this.peek());\n    }\n\n    var next, context;\n    while ((next = this.expect('(', '[', '.'))) {\n      if (next.text === '(') {\n        primary = this.functionCall(primary, context);\n        context = null;\n      } else if (next.text === '[') {\n        context = primary;\n        primary = this.objectIndex(primary);\n      } else if (next.text === '.') {\n        context = primary;\n        primary = this.fieldAccess(primary);\n      } else {\n        this.throwError('IMPOSSIBLE');\n      }\n    }\n    return primary;\n  },\n\n  throwError: function(msg, token) {\n    throw $parseMinErr('syntax',\n        'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\n          token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\n  },\n\n  peekToken: function() {\n    if (this.tokens.length === 0)\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    return this.tokens[0];\n  },\n\n  peek: function(e1, e2, e3, e4) {\n    return this.peekAhead(0, e1, e2, e3, e4);\n  },\n  peekAhead: function(i, e1, e2, e3, e4) {\n    if (this.tokens.length > i) {\n      var token = this.tokens[i];\n      var t = token.text;\n      if (t === e1 || t === e2 || t === e3 || t === e4 ||\n          (!e1 && !e2 && !e3 && !e4)) {\n        return token;\n      }\n    }\n    return false;\n  },\n\n  expect: function(e1, e2, e3, e4) {\n    var token = this.peek(e1, e2, e3, e4);\n    if (token) {\n      this.tokens.shift();\n      return token;\n    }\n    return false;\n  },\n\n  consume: function(e1) {\n    if (this.tokens.length === 0) {\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    }\n\n    var token = this.expect(e1);\n    if (!token) {\n      this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\n    }\n    return token;\n  },\n\n  unaryFn: function(op, right) {\n    var fn = OPERATORS[op];\n    return extend(function $parseUnaryFn(self, locals) {\n      return fn(self, locals, right);\n    }, {\n      constant:right.constant,\n      inputs: [right]\n    });\n  },\n\n  binaryFn: function(left, op, right, isBranching) {\n    var fn = OPERATORS[op];\n    return extend(function $parseBinaryFn(self, locals) {\n      return fn(self, locals, left, right);\n    }, {\n      constant: left.constant && right.constant,\n      inputs: !isBranching && [left, right]\n    });\n  },\n\n  identifier: function() {\n    var id = this.consume().text;\n\n    //Continue reading each `.identifier` unless it is a method invocation\n    while (this.peek('.') && this.peekAhead(1).identifier && !this.peekAhead(2, '(')) {\n      id += this.consume().text + this.consume().text;\n    }\n\n    return getterFn(id, this.options, this.text);\n  },\n\n  constant: function() {\n    var value = this.consume().value;\n\n    return extend(function $parseConstant() {\n      return value;\n    }, {\n      constant: true,\n      literal: true\n    });\n  },\n\n  statements: function() {\n    var statements = [];\n    while (true) {\n      if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))\n        statements.push(this.filterChain());\n      if (!this.expect(';')) {\n        // optimize for the common case where there is only one statement.\n        // TODO(size): maybe we should not support multiple statements?\n        return (statements.length === 1)\n            ? statements[0]\n            : function $parseStatements(self, locals) {\n                var value;\n                for (var i = 0, ii = statements.length; i < ii; i++) {\n                  value = statements[i](self, locals);\n                }\n                return value;\n              };\n      }\n    }\n  },\n\n  filterChain: function() {\n    var left = this.expression();\n    var token;\n    while ((token = this.expect('|'))) {\n      left = this.filter(left);\n    }\n    return left;\n  },\n\n  filter: function(inputFn) {\n    var fn = this.$filter(this.consume().text);\n    var argsFn;\n    var args;\n\n    if (this.peek(':')) {\n      argsFn = [];\n      args = []; // we can safely reuse the array\n      while (this.expect(':')) {\n        argsFn.push(this.expression());\n      }\n    }\n\n    var inputs = [inputFn].concat(argsFn || []);\n\n    return extend(function $parseFilter(self, locals) {\n      var input = inputFn(self, locals);\n      if (args) {\n        args[0] = input;\n\n        var i = argsFn.length;\n        while (i--) {\n          args[i + 1] = argsFn[i](self, locals);\n        }\n\n        return fn.apply(undefined, args);\n      }\n\n      return fn(input);\n    }, {\n      constant: !fn.$stateful && inputs.every(isConstant),\n      inputs: !fn.$stateful && inputs\n    });\n  },\n\n  expression: function() {\n    return this.assignment();\n  },\n\n  assignment: function() {\n    var left = this.ternary();\n    var right;\n    var token;\n    if ((token = this.expect('='))) {\n      if (!left.assign) {\n        this.throwError('implies assignment but [' +\n            this.text.substring(0, token.index) + '] can not be assigned to', token);\n      }\n      right = this.ternary();\n      return extend(function $parseAssignment(scope, locals) {\n        return left.assign(scope, right(scope, locals), locals);\n      }, {\n        inputs: [left, right]\n      });\n    }\n    return left;\n  },\n\n  ternary: function() {\n    var left = this.logicalOR();\n    var middle;\n    var token;\n    if ((token = this.expect('?'))) {\n      middle = this.assignment();\n      if (this.consume(':')) {\n        var right = this.assignment();\n\n        return extend(function $parseTernary(self, locals) {\n          return left(self, locals) ? middle(self, locals) : right(self, locals);\n        }, {\n          constant: left.constant && middle.constant && right.constant\n        });\n      }\n    }\n\n    return left;\n  },\n\n  logicalOR: function() {\n    var left = this.logicalAND();\n    var token;\n    while ((token = this.expect('||'))) {\n      left = this.binaryFn(left, token.text, this.logicalAND(), true);\n    }\n    return left;\n  },\n\n  logicalAND: function() {\n    var left = this.equality();\n    var token;\n    while ((token = this.expect('&&'))) {\n      left = this.binaryFn(left, token.text, this.equality(), true);\n    }\n    return left;\n  },\n\n  equality: function() {\n    var left = this.relational();\n    var token;\n    while ((token = this.expect('==','!=','===','!=='))) {\n      left = this.binaryFn(left, token.text, this.relational());\n    }\n    return left;\n  },\n\n  relational: function() {\n    var left = this.additive();\n    var token;\n    while ((token = this.expect('<', '>', '<=', '>='))) {\n      left = this.binaryFn(left, token.text, this.additive());\n    }\n    return left;\n  },\n\n  additive: function() {\n    var left = this.multiplicative();\n    var token;\n    while ((token = this.expect('+','-'))) {\n      left = this.binaryFn(left, token.text, this.multiplicative());\n    }\n    return left;\n  },\n\n  multiplicative: function() {\n    var left = this.unary();\n    var token;\n    while ((token = this.expect('*','/','%'))) {\n      left = this.binaryFn(left, token.text, this.unary());\n    }\n    return left;\n  },\n\n  unary: function() {\n    var token;\n    if (this.expect('+')) {\n      return this.primary();\n    } else if ((token = this.expect('-'))) {\n      return this.binaryFn(Parser.ZERO, token.text, this.unary());\n    } else if ((token = this.expect('!'))) {\n      return this.unaryFn(token.text, this.unary());\n    } else {\n      return this.primary();\n    }\n  },\n\n  fieldAccess: function(object) {\n    var getter = this.identifier();\n\n    return extend(function $parseFieldAccess(scope, locals, self) {\n      var o = self || object(scope, locals);\n      return (o == null) ? undefined : getter(o);\n    }, {\n      assign: function(scope, value, locals) {\n        var o = object(scope, locals);\n        if (!o) object.assign(scope, o = {}, locals);\n        return getter.assign(o, value);\n      }\n    });\n  },\n\n  objectIndex: function(obj) {\n    var expression = this.text;\n\n    var indexFn = this.expression();\n    this.consume(']');\n\n    return extend(function $parseObjectIndex(self, locals) {\n      var o = obj(self, locals),\n          i = indexFn(self, locals),\n          v;\n\n      ensureSafeMemberName(i, expression);\n      if (!o) return undefined;\n      v = ensureSafeObject(o[i], expression);\n      return v;\n    }, {\n      assign: function(self, value, locals) {\n        var key = ensureSafeMemberName(indexFn(self, locals), expression);\n        // prevent overwriting of Function.constructor which would break ensureSafeObject check\n        var o = ensureSafeObject(obj(self, locals), expression);\n        if (!o) obj.assign(self, o = {}, locals);\n        return o[key] = value;\n      }\n    });\n  },\n\n  functionCall: function(fnGetter, contextGetter) {\n    var argsFn = [];\n    if (this.peekToken().text !== ')') {\n      do {\n        argsFn.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume(')');\n\n    var expressionText = this.text;\n    // we can safely reuse the array across invocations\n    var args = argsFn.length ? [] : null;\n\n    return function $parseFunctionCall(scope, locals) {\n      var context = contextGetter ? contextGetter(scope, locals) : isDefined(contextGetter) ? undefined : scope;\n      var fn = fnGetter(scope, locals, context) || noop;\n\n      if (args) {\n        var i = argsFn.length;\n        while (i--) {\n          args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);\n        }\n      }\n\n      ensureSafeObject(context, expressionText);\n      ensureSafeFunction(fn, expressionText);\n\n      // IE doesn't have apply for some native functions\n      var v = fn.apply\n            ? fn.apply(context, args)\n            : fn(args[0], args[1], args[2], args[3], args[4]);\n\n      if (args) {\n        // Free-up the memory (arguments of the last function call).\n        args.length = 0;\n      }\n\n      return ensureSafeObject(v, expressionText);\n      };\n  },\n\n  // This is used with json array declaration\n  arrayDeclaration: function() {\n    var elementFns = [];\n    if (this.peekToken().text !== ']') {\n      do {\n        if (this.peek(']')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        elementFns.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume(']');\n\n    return extend(function $parseArrayLiteral(self, locals) {\n      var array = [];\n      for (var i = 0, ii = elementFns.length; i < ii; i++) {\n        array.push(elementFns[i](self, locals));\n      }\n      return array;\n    }, {\n      literal: true,\n      constant: elementFns.every(isConstant),\n      inputs: elementFns\n    });\n  },\n\n  object: function() {\n    var keys = [], valueFns = [];\n    if (this.peekToken().text !== '}') {\n      do {\n        if (this.peek('}')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        var token = this.consume();\n        if (token.constant) {\n          keys.push(token.value);\n        } else if (token.identifier) {\n          keys.push(token.text);\n        } else {\n          this.throwError(\"invalid key\", token);\n        }\n        this.consume(':');\n        valueFns.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume('}');\n\n    return extend(function $parseObjectLiteral(self, locals) {\n      var object = {};\n      for (var i = 0, ii = valueFns.length; i < ii; i++) {\n        object[keys[i]] = valueFns[i](self, locals);\n      }\n      return object;\n    }, {\n      literal: true,\n      constant: valueFns.every(isConstant),\n      inputs: valueFns\n    });\n  }\n};\n\n\n//////////////////////////////////////////////////\n// Parser helper functions\n//////////////////////////////////////////////////\n\nfunction setter(obj, locals, path, setValue, fullExp) {\n  ensureSafeObject(obj, fullExp);\n  ensureSafeObject(locals, fullExp);\n\n  var element = path.split('.'), key;\n  for (var i = 0; element.length > 1; i++) {\n    key = ensureSafeMemberName(element.shift(), fullExp);\n    var propertyObj = (i === 0 && locals && locals[key]) || obj[key];\n    if (!propertyObj) {\n      propertyObj = {};\n      obj[key] = propertyObj;\n    }\n    obj = ensureSafeObject(propertyObj, fullExp);\n  }\n  key = ensureSafeMemberName(element.shift(), fullExp);\n  ensureSafeObject(obj[key], fullExp);\n  obj[key] = setValue;\n  return setValue;\n}\n\nvar getterFnCacheDefault = createMap();\nvar getterFnCacheExpensive = createMap();\n\nfunction isPossiblyDangerousMemberName(name) {\n  return name == 'constructor';\n}\n\n/**\n * Implementation of the \"Black Hole\" variant from:\n * - http://jsperf.com/angularjs-parse-getter/4\n * - http://jsperf.com/path-evaluation-simplified/7\n */\nfunction cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, expensiveChecks) {\n  ensureSafeMemberName(key0, fullExp);\n  ensureSafeMemberName(key1, fullExp);\n  ensureSafeMemberName(key2, fullExp);\n  ensureSafeMemberName(key3, fullExp);\n  ensureSafeMemberName(key4, fullExp);\n  var eso = function(o) {\n    return ensureSafeObject(o, fullExp);\n  };\n  var eso0 = (expensiveChecks || isPossiblyDangerousMemberName(key0)) ? eso : identity;\n  var eso1 = (expensiveChecks || isPossiblyDangerousMemberName(key1)) ? eso : identity;\n  var eso2 = (expensiveChecks || isPossiblyDangerousMemberName(key2)) ? eso : identity;\n  var eso3 = (expensiveChecks || isPossiblyDangerousMemberName(key3)) ? eso : identity;\n  var eso4 = (expensiveChecks || isPossiblyDangerousMemberName(key4)) ? eso : identity;\n\n  return function cspSafeGetter(scope, locals) {\n    var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;\n\n    if (pathVal == null) return pathVal;\n    pathVal = eso0(pathVal[key0]);\n\n    if (!key1) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso1(pathVal[key1]);\n\n    if (!key2) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso2(pathVal[key2]);\n\n    if (!key3) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso3(pathVal[key3]);\n\n    if (!key4) return pathVal;\n    if (pathVal == null) return undefined;\n    pathVal = eso4(pathVal[key4]);\n\n    return pathVal;\n  };\n}\n\nfunction getterFnWithEnsureSafeObject(fn, fullExpression) {\n  return function(s, l) {\n    return fn(s, l, ensureSafeObject, fullExpression);\n  };\n}\n\nfunction getterFn(path, options, fullExp) {\n  var expensiveChecks = options.expensiveChecks;\n  var getterFnCache = (expensiveChecks ? getterFnCacheExpensive : getterFnCacheDefault);\n  var fn = getterFnCache[path];\n  if (fn) return fn;\n\n\n  var pathKeys = path.split('.'),\n      pathKeysLength = pathKeys.length;\n\n  // http://jsperf.com/angularjs-parse-getter/6\n  if (options.csp) {\n    if (pathKeysLength < 6) {\n      fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp, expensiveChecks);\n    } else {\n      fn = function cspSafeGetter(scope, locals) {\n        var i = 0, val;\n        do {\n          val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],\n                                pathKeys[i++], fullExp, expensiveChecks)(scope, locals);\n\n          locals = undefined; // clear after first iteration\n          scope = val;\n        } while (i < pathKeysLength);\n        return val;\n      };\n    }\n  } else {\n    var code = '';\n    if (expensiveChecks) {\n      code += 's = eso(s, fe);\\nl = eso(l, fe);\\n';\n    }\n    var needsEnsureSafeObject = expensiveChecks;\n    forEach(pathKeys, function(key, index) {\n      ensureSafeMemberName(key, fullExp);\n      var lookupJs = (index\n                      // we simply dereference 's' on any .dot notation\n                      ? 's'\n                      // but if we are first then we check locals first, and if so read it first\n                      : '((l&&l.hasOwnProperty(\"' + key + '\"))?l:s)') + '.' + key;\n      if (expensiveChecks || isPossiblyDangerousMemberName(key)) {\n        lookupJs = 'eso(' + lookupJs + ', fe)';\n        needsEnsureSafeObject = true;\n      }\n      code += 'if(s == null) return undefined;\\n' +\n              's=' + lookupJs + ';\\n';\n    });\n    code += 'return s;';\n\n    /* jshint -W054 */\n    var evaledFnGetter = new Function('s', 'l', 'eso', 'fe', code); // s=scope, l=locals, eso=ensureSafeObject\n    /* jshint +W054 */\n    evaledFnGetter.toString = valueFn(code);\n    if (needsEnsureSafeObject) {\n      evaledFnGetter = getterFnWithEnsureSafeObject(evaledFnGetter, fullExp);\n    }\n    fn = evaledFnGetter;\n  }\n\n  fn.sharedGetter = true;\n  fn.assign = function(self, value, locals) {\n    return setter(self, locals, path, value, path);\n  };\n  getterFnCache[path] = fn;\n  return fn;\n}\n\nvar objectValueOf = Object.prototype.valueOf;\n\nfunction getValueOf(value) {\n  return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);\n}\n\n///////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $parse\n * @kind function\n *\n * @description\n *\n * Converts Angular {@link guide/expression expression} into a function.\n *\n * ```js\n *   var getter = $parse('user.name');\n *   var setter = getter.assign;\n *   var context = {user:{name:'angular'}};\n *   var locals = {user:{name:'local'}};\n *\n *   expect(getter(context)).toEqual('angular');\n *   setter(context, 'newValue');\n *   expect(context.user.name).toEqual('newValue');\n *   expect(getter(context, locals)).toEqual('local');\n * ```\n *\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n *      are evaluated against (typically a scope object).\n *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n *      `context`.\n *\n *    The returned function also has the following properties:\n *      * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript\n *        literal.\n *      * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript\n *        constant literals.\n *      * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be\n *        set to a function to change its value on the given context.\n *\n */\n\n\n/**\n * @ngdoc provider\n * @name $parseProvider\n *\n * @description\n * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}\n *  service.\n */\nfunction $ParseProvider() {\n  var cacheDefault = createMap();\n  var cacheExpensive = createMap();\n\n\n\n  this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {\n    var $parseOptions = {\n          csp: $sniffer.csp,\n          expensiveChecks: false\n        },\n        $parseOptionsExpensive = {\n          csp: $sniffer.csp,\n          expensiveChecks: true\n        };\n\n    function wrapSharedExpression(exp) {\n      var wrapped = exp;\n\n      if (exp.sharedGetter) {\n        wrapped = function $parseWrapper(self, locals) {\n          return exp(self, locals);\n        };\n        wrapped.literal = exp.literal;\n        wrapped.constant = exp.constant;\n        wrapped.assign = exp.assign;\n      }\n\n      return wrapped;\n    }\n\n    return function $parse(exp, interceptorFn, expensiveChecks) {\n      var parsedExpression, oneTime, cacheKey;\n\n      switch (typeof exp) {\n        case 'string':\n          cacheKey = exp = exp.trim();\n\n          var cache = (expensiveChecks ? cacheExpensive : cacheDefault);\n          parsedExpression = cache[cacheKey];\n\n          if (!parsedExpression) {\n            if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {\n              oneTime = true;\n              exp = exp.substring(2);\n            }\n\n            var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;\n            var lexer = new Lexer(parseOptions);\n            var parser = new Parser(lexer, $filter, parseOptions);\n            parsedExpression = parser.parse(exp);\n\n            if (parsedExpression.constant) {\n              parsedExpression.$$watchDelegate = constantWatchDelegate;\n            } else if (oneTime) {\n              //oneTime is not part of the exp passed to the Parser so we may have to\n              //wrap the parsedExpression before adding a $$watchDelegate\n              parsedExpression = wrapSharedExpression(parsedExpression);\n              parsedExpression.$$watchDelegate = parsedExpression.literal ?\n                oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;\n            } else if (parsedExpression.inputs) {\n              parsedExpression.$$watchDelegate = inputsWatchDelegate;\n            }\n\n            cache[cacheKey] = parsedExpression;\n          }\n          return addInterceptor(parsedExpression, interceptorFn);\n\n        case 'function':\n          return addInterceptor(exp, interceptorFn);\n\n        default:\n          return addInterceptor(noop, interceptorFn);\n      }\n    };\n\n    function collectExpressionInputs(inputs, list) {\n      for (var i = 0, ii = inputs.length; i < ii; i++) {\n        var input = inputs[i];\n        if (!input.constant) {\n          if (input.inputs) {\n            collectExpressionInputs(input.inputs, list);\n          } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?\n            list.push(input);\n          }\n        }\n      }\n\n      return list;\n    }\n\n    function expressionInputDirtyCheck(newValue, oldValueOfValue) {\n\n      if (newValue == null || oldValueOfValue == null) { // null/undefined\n        return newValue === oldValueOfValue;\n      }\n\n      if (typeof newValue === 'object') {\n\n        // attempt to convert the value to a primitive type\n        // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can\n        //             be cheaply dirty-checked\n        newValue = getValueOf(newValue);\n\n        if (typeof newValue === 'object') {\n          // objects/arrays are not supported - deep-watching them would be too expensive\n          return false;\n        }\n\n        // fall-through to the primitive equality check\n      }\n\n      //Primitive or NaN\n      return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);\n    }\n\n    function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var inputExpressions = parsedExpression.$$inputs ||\n                    (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));\n\n      var lastResult;\n\n      if (inputExpressions.length === 1) {\n        var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails\n        inputExpressions = inputExpressions[0];\n        return scope.$watch(function expressionInputWatch(scope) {\n          var newInputValue = inputExpressions(scope);\n          if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {\n            lastResult = parsedExpression(scope);\n            oldInputValue = newInputValue && getValueOf(newInputValue);\n          }\n          return lastResult;\n        }, listener, objectEquality);\n      }\n\n      var oldInputValueOfValues = [];\n      for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n        oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails\n      }\n\n      return scope.$watch(function expressionInputsWatch(scope) {\n        var changed = false;\n\n        for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n          var newInputValue = inputExpressions[i](scope);\n          if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {\n            oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\n          }\n        }\n\n        if (changed) {\n          lastResult = parsedExpression(scope);\n        }\n\n        return lastResult;\n      }, listener, objectEquality);\n    }\n\n    function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        if (isDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isDefined(lastValue)) {\n              unwatch();\n            }\n          });\n        }\n      }, objectEquality);\n    }\n\n    function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.call(this, value, old, scope);\n        }\n        if (isAllDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isAllDefined(lastValue)) unwatch();\n          });\n        }\n      }, objectEquality);\n\n      function isAllDefined(value) {\n        var allDefined = true;\n        forEach(value, function(val) {\n          if (!isDefined(val)) allDefined = false;\n        });\n        return allDefined;\n      }\n    }\n\n    function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch;\n      return unwatch = scope.$watch(function constantWatch(scope) {\n        return parsedExpression(scope);\n      }, function constantListener(value, old, scope) {\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        unwatch();\n      }, objectEquality);\n    }\n\n    function addInterceptor(parsedExpression, interceptorFn) {\n      if (!interceptorFn) return parsedExpression;\n      var watchDelegate = parsedExpression.$$watchDelegate;\n\n      var regularWatch =\n          watchDelegate !== oneTimeLiteralWatchDelegate &&\n          watchDelegate !== oneTimeWatchDelegate;\n\n      var fn = regularWatch ? function regularInterceptedExpression(scope, locals) {\n        var value = parsedExpression(scope, locals);\n        return interceptorFn(value, scope, locals);\n      } : function oneTimeInterceptedExpression(scope, locals) {\n        var value = parsedExpression(scope, locals);\n        var result = interceptorFn(value, scope, locals);\n        // we only return the interceptor's result if the\n        // initial value is defined (for bind-once)\n        return isDefined(value) ? result : value;\n      };\n\n      // Propagate $$watchDelegates other then inputsWatchDelegate\n      if (parsedExpression.$$watchDelegate &&\n          parsedExpression.$$watchDelegate !== inputsWatchDelegate) {\n        fn.$$watchDelegate = parsedExpression.$$watchDelegate;\n      } else if (!interceptorFn.$stateful) {\n        // If there is an interceptor, but no watchDelegate then treat the interceptor like\n        // we treat filters - it is assumed to be a pure function unless flagged with $stateful\n        fn.$$watchDelegate = inputsWatchDelegate;\n        fn.inputs = [parsedExpression];\n      }\n\n      return fn;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $q\n * @requires $rootScope\n *\n * @description\n * A service that helps you run functions asynchronously, and use their return values (or exceptions)\n * when they are done processing.\n *\n * This is an implementation of promises/deferred objects inspired by\n * [Kris Kowal's Q](https://github.com/kriskowal/q).\n *\n * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred\n * implementations, and the other which resembles ES6 promises to some degree.\n *\n * # $q constructor\n *\n * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`\n * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,\n * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n *\n * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are\n * available yet.\n *\n * It can be used like so:\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     // perform some asynchronous operation, resolve or reject the promise when appropriate.\n *     return $q(function(resolve, reject) {\n *       setTimeout(function() {\n *         if (okToGreet(name)) {\n *           resolve('Hello, ' + name + '!');\n *         } else {\n *           reject('Greeting ' + name + ' is not allowed.');\n *         }\n *       }, 1000);\n *     });\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   });\n * ```\n *\n * Note: progress/notify callbacks are not currently supported via the ES6-style interface.\n *\n * However, the more traditional CommonJS-style usage is still available, and documented below.\n *\n * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an\n * interface for interacting with an object that represents the result of an action that is\n * performed asynchronously, and may or may not be finished at any given point in time.\n *\n * From the perspective of dealing with error handling, deferred and promise APIs are to\n * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     var deferred = $q.defer();\n *\n *     setTimeout(function() {\n *       deferred.notify('About to greet ' + name + '.');\n *\n *       if (okToGreet(name)) {\n *         deferred.resolve('Hello, ' + name + '!');\n *       } else {\n *         deferred.reject('Greeting ' + name + ' is not allowed.');\n *       }\n *     }, 1000);\n *\n *     return deferred.promise;\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   }, function(update) {\n *     alert('Got notification: ' + update);\n *   });\n * ```\n *\n * At first it might not be obvious why this extra complexity is worth the trouble. The payoff\n * comes in the way of guarantees that promise and deferred APIs make, see\n * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.\n *\n * Additionally the promise api allows for composition that is very hard to do with the\n * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.\n * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the\n * section on serial or parallel joining of promises.\n *\n * # The Deferred API\n *\n * A new instance of deferred is constructed by calling `$q.defer()`.\n *\n * The purpose of the deferred object is to expose the associated Promise instance as well as APIs\n * that can be used for signaling the successful or unsuccessful completion, as well as the status\n * of the task.\n *\n * **Methods**\n *\n * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection\n *   constructed via `$q.reject`, the promise will be rejected instead.\n * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to\n *   resolving it with a rejection constructed via `$q.reject`.\n * - `notify(value)` - provides updates on the status of the promise's execution. This may be called\n *   multiple times before the promise is either resolved or rejected.\n *\n * **Properties**\n *\n * - promise – `{Promise}` – promise object associated with this deferred.\n *\n *\n * # The Promise API\n *\n * A new promise instance is created when a deferred instance is created and can be retrieved by\n * calling `deferred.promise`.\n *\n * The purpose of the promise object is to allow for interested parties to get access to the result\n * of the deferred task when it completes.\n *\n * **Methods**\n *\n * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or\n *   will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously\n *   as soon as the result is available. The callbacks are called with a single argument: the result\n *   or rejection reason. Additionally, the notify callback may be called zero or more times to\n *   provide a progress indication, before the promise is resolved or rejected.\n *\n *   This method *returns a new promise* which is resolved or rejected via the return value of the\n *   `successCallback`, `errorCallback`. It also notifies via the return value of the\n *   `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback\n *   method.\n *\n * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`\n *\n * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,\n *   but to do so without modifying the final value. This is useful to release resources or do some\n *   clean-up that needs to be done whether the promise was rejected or resolved. See the [full\n *   specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for\n *   more information.\n *\n * # Chaining promises\n *\n * Because calling the `then` method of a promise returns a new derived promise, it is easily\n * possible to create a chain of promises:\n *\n * ```js\n *   promiseB = promiseA.then(function(result) {\n *     return result + 1;\n *   });\n *\n *   // promiseB will be resolved immediately after promiseA is resolved and its value\n *   // will be the result of promiseA incremented by 1\n * ```\n *\n * It is possible to create chains of any length and since a promise can be resolved with another\n * promise (which will defer its resolution further), it is possible to pause/defer resolution of\n * the promises at any point in the chain. This makes it possible to implement powerful APIs like\n * $http's response interceptors.\n *\n *\n * # Differences between Kris Kowal's Q and $q\n *\n *  There are two main differences:\n *\n * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation\n *   mechanism in angular, which means faster propagation of resolution or rejection into your\n *   models and avoiding unnecessary browser repaints, which would result in flickering UI.\n * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains\n *   all the important functionality needed for common async tasks.\n *\n *  # Testing\n *\n *  ```js\n *    it('should simulate promise', inject(function($q, $rootScope) {\n *      var deferred = $q.defer();\n *      var promise = deferred.promise;\n *      var resolvedValue;\n *\n *      promise.then(function(value) { resolvedValue = value; });\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Simulate resolving of promise\n *      deferred.resolve(123);\n *      // Note that the 'then' function does not get called synchronously.\n *      // This is because we want the promise API to always be async, whether or not\n *      // it got called synchronously or asynchronously.\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Propagate promise resolution to 'then' functions using $apply().\n *      $rootScope.$apply();\n *      expect(resolvedValue).toEqual(123);\n *    }));\n *  ```\n *\n * @param {function(function, function)} resolver Function which is responsible for resolving or\n *   rejecting the newly created promise. The first parameter is a function which resolves the\n *   promise, the second parameter is a function which rejects the promise.\n *\n * @returns {Promise} The newly created promise.\n */\nfunction $QProvider() {\n\n  this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $rootScope.$evalAsync(callback);\n    }, $exceptionHandler);\n  }];\n}\n\nfunction $$QProvider() {\n  this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $browser.defer(callback);\n    }, $exceptionHandler);\n  }];\n}\n\n/**\n * Constructs a promise manager.\n *\n * @param {function(function)} nextTick Function for executing functions in the next turn.\n * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for\n *     debugging purposes.\n * @returns {object} Promise manager.\n */\nfunction qFactory(nextTick, exceptionHandler) {\n  var $qMinErr = minErr('$q', TypeError);\n  function callOnce(self, resolveFn, rejectFn) {\n    var called = false;\n    function wrap(fn) {\n      return function(value) {\n        if (called) return;\n        called = true;\n        fn.call(self, value);\n      };\n    }\n\n    return [wrap(resolveFn), wrap(rejectFn)];\n  }\n\n  /**\n   * @ngdoc method\n   * @name ng.$q#defer\n   * @kind function\n   *\n   * @description\n   * Creates a `Deferred` object which represents a task which will finish in the future.\n   *\n   * @returns {Deferred} Returns a new instance of deferred.\n   */\n  var defer = function() {\n    return new Deferred();\n  };\n\n  function Promise() {\n    this.$$state = { status: 0 };\n  }\n\n  Promise.prototype = {\n    then: function(onFulfilled, onRejected, progressBack) {\n      var result = new Deferred();\n\n      this.$$state.pending = this.$$state.pending || [];\n      this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);\n      if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);\n\n      return result.promise;\n    },\n\n    \"catch\": function(callback) {\n      return this.then(null, callback);\n    },\n\n    \"finally\": function(callback, progressBack) {\n      return this.then(function(value) {\n        return handleCallback(value, true, callback);\n      }, function(error) {\n        return handleCallback(error, false, callback);\n      }, progressBack);\n    }\n  };\n\n  //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native\n  function simpleBind(context, fn) {\n    return function(value) {\n      fn.call(context, value);\n    };\n  }\n\n  function processQueue(state) {\n    var fn, promise, pending;\n\n    pending = state.pending;\n    state.processScheduled = false;\n    state.pending = undefined;\n    for (var i = 0, ii = pending.length; i < ii; ++i) {\n      promise = pending[i][0];\n      fn = pending[i][state.status];\n      try {\n        if (isFunction(fn)) {\n          promise.resolve(fn(state.value));\n        } else if (state.status === 1) {\n          promise.resolve(state.value);\n        } else {\n          promise.reject(state.value);\n        }\n      } catch (e) {\n        promise.reject(e);\n        exceptionHandler(e);\n      }\n    }\n  }\n\n  function scheduleProcessQueue(state) {\n    if (state.processScheduled || !state.pending) return;\n    state.processScheduled = true;\n    nextTick(function() { processQueue(state); });\n  }\n\n  function Deferred() {\n    this.promise = new Promise();\n    //Necessary to support unbound execution :/\n    this.resolve = simpleBind(this, this.resolve);\n    this.reject = simpleBind(this, this.reject);\n    this.notify = simpleBind(this, this.notify);\n  }\n\n  Deferred.prototype = {\n    resolve: function(val) {\n      if (this.promise.$$state.status) return;\n      if (val === this.promise) {\n        this.$$reject($qMinErr(\n          'qcycle',\n          \"Expected promise to be resolved with value other than itself '{0}'\",\n          val));\n      } else {\n        this.$$resolve(val);\n      }\n\n    },\n\n    $$resolve: function(val) {\n      var then, fns;\n\n      fns = callOnce(this, this.$$resolve, this.$$reject);\n      try {\n        if ((isObject(val) || isFunction(val))) then = val && val.then;\n        if (isFunction(then)) {\n          this.promise.$$state.status = -1;\n          then.call(val, fns[0], fns[1], this.notify);\n        } else {\n          this.promise.$$state.value = val;\n          this.promise.$$state.status = 1;\n          scheduleProcessQueue(this.promise.$$state);\n        }\n      } catch (e) {\n        fns[1](e);\n        exceptionHandler(e);\n      }\n    },\n\n    reject: function(reason) {\n      if (this.promise.$$state.status) return;\n      this.$$reject(reason);\n    },\n\n    $$reject: function(reason) {\n      this.promise.$$state.value = reason;\n      this.promise.$$state.status = 2;\n      scheduleProcessQueue(this.promise.$$state);\n    },\n\n    notify: function(progress) {\n      var callbacks = this.promise.$$state.pending;\n\n      if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {\n        nextTick(function() {\n          var callback, result;\n          for (var i = 0, ii = callbacks.length; i < ii; i++) {\n            result = callbacks[i][0];\n            callback = callbacks[i][3];\n            try {\n              result.notify(isFunction(callback) ? callback(progress) : progress);\n            } catch (e) {\n              exceptionHandler(e);\n            }\n          }\n        });\n      }\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#reject\n   * @kind function\n   *\n   * @description\n   * Creates a promise that is resolved as rejected with the specified `reason`. This api should be\n   * used to forward rejection in a chain of promises. If you are dealing with the last promise in\n   * a promise chain, you don't need to worry about it.\n   *\n   * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of\n   * `reject` as the `throw` keyword in JavaScript. This also means that if you \"catch\" an error via\n   * a promise error callback and you want to forward the error to the promise derived from the\n   * current promise, you have to \"rethrow\" the error by returning a rejection constructed via\n   * `reject`.\n   *\n   * ```js\n   *   promiseB = promiseA.then(function(result) {\n   *     // success: do something and resolve promiseB\n   *     //          with the old or a new result\n   *     return result;\n   *   }, function(reason) {\n   *     // error: handle the error if possible and\n   *     //        resolve promiseB with newPromiseOrValue,\n   *     //        otherwise forward the rejection to promiseB\n   *     if (canHandle(reason)) {\n   *      // handle the error and recover\n   *      return newPromiseOrValue;\n   *     }\n   *     return $q.reject(reason);\n   *   });\n   * ```\n   *\n   * @param {*} reason Constant, message, exception or an object representing the rejection reason.\n   * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.\n   */\n  var reject = function(reason) {\n    var result = new Deferred();\n    result.reject(reason);\n    return result.promise;\n  };\n\n  var makePromise = function makePromise(value, resolved) {\n    var result = new Deferred();\n    if (resolved) {\n      result.resolve(value);\n    } else {\n      result.reject(value);\n    }\n    return result.promise;\n  };\n\n  var handleCallback = function handleCallback(value, isResolved, callback) {\n    var callbackOutput = null;\n    try {\n      if (isFunction(callback)) callbackOutput = callback();\n    } catch (e) {\n      return makePromise(e, false);\n    }\n    if (isPromiseLike(callbackOutput)) {\n      return callbackOutput.then(function() {\n        return makePromise(value, isResolved);\n      }, function(error) {\n        return makePromise(error, false);\n      });\n    } else {\n      return makePromise(value, isResolved);\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#when\n   * @kind function\n   *\n   * @description\n   * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.\n   * This is useful when you are dealing with an object that might or might not be a promise, or if\n   * the promise comes from a source that can't be trusted.\n   *\n   * @param {*} value Value or a promise\n   * @returns {Promise} Returns a promise of the passed value or promise\n   */\n\n\n  var when = function(value, callback, errback, progressBack) {\n    var result = new Deferred();\n    result.resolve(value);\n    return result.promise.then(callback, errback, progressBack);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#all\n   * @kind function\n   *\n   * @description\n   * Combines multiple promises into a single promise that is resolved when all of the input\n   * promises are resolved.\n   *\n   * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.\n   * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,\n   *   each value corresponding to the promise at the same index/key in the `promises` array/hash.\n   *   If any of the promises is resolved with a rejection, this resulting promise will be rejected\n   *   with the same rejection value.\n   */\n\n  function all(promises) {\n    var deferred = new Deferred(),\n        counter = 0,\n        results = isArray(promises) ? [] : {};\n\n    forEach(promises, function(promise, key) {\n      counter++;\n      when(promise).then(function(value) {\n        if (results.hasOwnProperty(key)) return;\n        results[key] = value;\n        if (!(--counter)) deferred.resolve(results);\n      }, function(reason) {\n        if (results.hasOwnProperty(key)) return;\n        deferred.reject(reason);\n      });\n    });\n\n    if (counter === 0) {\n      deferred.resolve(results);\n    }\n\n    return deferred.promise;\n  }\n\n  var $Q = function Q(resolver) {\n    if (!isFunction(resolver)) {\n      throw $qMinErr('norslvr', \"Expected resolverFn, got '{0}'\", resolver);\n    }\n\n    if (!(this instanceof Q)) {\n      // More useful when $Q is the Promise itself.\n      return new Q(resolver);\n    }\n\n    var deferred = new Deferred();\n\n    function resolveFn(value) {\n      deferred.resolve(value);\n    }\n\n    function rejectFn(reason) {\n      deferred.reject(reason);\n    }\n\n    resolver(resolveFn, rejectFn);\n\n    return deferred.promise;\n  };\n\n  $Q.defer = defer;\n  $Q.reject = reject;\n  $Q.when = when;\n  $Q.all = all;\n\n  return $Q;\n}\n\nfunction $$RAFProvider() { //rAF\n  this.$get = ['$window', '$timeout', function($window, $timeout) {\n    var requestAnimationFrame = $window.requestAnimationFrame ||\n                                $window.webkitRequestAnimationFrame;\n\n    var cancelAnimationFrame = $window.cancelAnimationFrame ||\n                               $window.webkitCancelAnimationFrame ||\n                               $window.webkitCancelRequestAnimationFrame;\n\n    var rafSupported = !!requestAnimationFrame;\n    var raf = rafSupported\n      ? function(fn) {\n          var id = requestAnimationFrame(fn);\n          return function() {\n            cancelAnimationFrame(id);\n          };\n        }\n      : function(fn) {\n          var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666\n          return function() {\n            $timeout.cancel(timer);\n          };\n        };\n\n    raf.supported = rafSupported;\n\n    return raf;\n  }];\n}\n\n/**\n * DESIGN NOTES\n *\n * The design decisions behind the scope are heavily favored for speed and memory consumption.\n *\n * The typical use of scope is to watch the expressions, which most of the time return the same\n * value as last time so we optimize the operation.\n *\n * Closures construction is expensive in terms of speed as well as memory:\n *   - No closures, instead use prototypical inheritance for API\n *   - Internal state needs to be stored on scope directly, which means that private state is\n *     exposed as $$____ properties\n *\n * Loop operations are optimized by using while(count--) { ... }\n *   - this means that in order to keep the same order of execution as addition we have to add\n *     items to the array at the beginning (unshift) instead of at the end (push)\n *\n * Child scopes are created and removed often\n *   - Using an array would be slow since inserts in middle are expensive so we use linked list\n *\n * There are few watches then a lot of observers. This is why you don't want the observer to be\n * implemented in the same way as watch. Watch requires return of initialization function which\n * are expensive to construct.\n */\n\n\n/**\n * @ngdoc provider\n * @name $rootScopeProvider\n * @description\n *\n * Provider for the $rootScope service.\n */\n\n/**\n * @ngdoc method\n * @name $rootScopeProvider#digestTtl\n * @description\n *\n * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that the dependencies between `$watch`s will result in\n * several digest iterations. However if an application needs more than the default 10 digest\n * iterations for its model to stabilize then you should investigate what is causing the model to\n * continuously change during the digest.\n *\n * Increasing the TTL could have performance implications, so you should not change it without\n * proper justification.\n *\n * @param {number} limit The number of digest iterations.\n */\n\n\n/**\n * @ngdoc service\n * @name $rootScope\n * @description\n *\n * Every application has a single root {@link ng.$rootScope.Scope scope}.\n * All other scopes are descendant scopes of the root scope. Scopes provide separation\n * between the model and the view, via a mechanism for watching the model for changes.\n * They also provide an event emission/broadcast and subscription facility. See the\n * {@link guide/scope developer guide on scopes}.\n */\nfunction $RootScopeProvider() {\n  var TTL = 10;\n  var $rootScopeMinErr = minErr('$rootScope');\n  var lastDirtyWatch = null;\n  var applyAsyncId = null;\n\n  this.digestTtl = function(value) {\n    if (arguments.length) {\n      TTL = value;\n    }\n    return TTL;\n  };\n\n  this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',\n      function($injector, $exceptionHandler, $parse, $browser) {\n\n    /**\n     * @ngdoc type\n     * @name $rootScope.Scope\n     *\n     * @description\n     * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the\n     * {@link auto.$injector $injector}. Child scopes are created using the\n     * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when\n     * compiled HTML template is executed.)\n     *\n     * Here is a simple scope snippet to show how you can interact with the scope.\n     * ```html\n     * <file src=\"./test/ng/rootScopeSpec.js\" tag=\"docs1\" />\n     * ```\n     *\n     * # Inheritance\n     * A scope can inherit from a parent scope, as in this example:\n     * ```js\n         var parent = $rootScope;\n         var child = parent.$new();\n\n         parent.salutation = \"Hello\";\n         expect(child.salutation).toEqual('Hello');\n\n         child.salutation = \"Welcome\";\n         expect(child.salutation).toEqual('Welcome');\n         expect(parent.salutation).toEqual('Hello');\n     * ```\n     *\n     * When interacting with `Scope` in tests, additional helper methods are available on the\n     * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional\n     * details.\n     *\n     *\n     * @param {Object.<string, function()>=} providers Map of service factory which need to be\n     *                                       provided for the current scope. Defaults to {@link ng}.\n     * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should\n     *                              append/override services provided by `providers`. This is handy\n     *                              when unit-testing and having the need to override a default\n     *                              service.\n     * @returns {Object} Newly created scope.\n     *\n     */\n    function Scope() {\n      this.$id = nextUid();\n      this.$$phase = this.$parent = this.$$watchers =\n                     this.$$nextSibling = this.$$prevSibling =\n                     this.$$childHead = this.$$childTail = null;\n      this.$root = this;\n      this.$$destroyed = false;\n      this.$$listeners = {};\n      this.$$listenerCount = {};\n      this.$$isolateBindings = null;\n    }\n\n    /**\n     * @ngdoc property\n     * @name $rootScope.Scope#$id\n     *\n     * @description\n     * Unique scope ID (monotonically increasing) useful for debugging.\n     */\n\n     /**\n      * @ngdoc property\n      * @name $rootScope.Scope#$parent\n      *\n      * @description\n      * Reference to the parent scope.\n      */\n\n      /**\n       * @ngdoc property\n       * @name $rootScope.Scope#$root\n       *\n       * @description\n       * Reference to the root scope.\n       */\n\n    Scope.prototype = {\n      constructor: Scope,\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$new\n       * @kind function\n       *\n       * @description\n       * Creates a new child {@link ng.$rootScope.Scope scope}.\n       *\n       * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.\n       * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.\n       *\n       * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is\n       * desired for the scope and its child scopes to be permanently detached from the parent and\n       * thus stop participating in model change detection and listener notification by invoking.\n       *\n       * @param {boolean} isolate If true, then the scope does not prototypically inherit from the\n       *         parent scope. The scope is isolated, as it can not see parent scope properties.\n       *         When creating widgets, it is useful for the widget to not accidentally read parent\n       *         state.\n       *\n       * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`\n       *                              of the newly created scope. Defaults to `this` scope if not provided.\n       *                              This is used when creating a transclude scope to correctly place it\n       *                              in the scope hierarchy while maintaining the correct prototypical\n       *                              inheritance.\n       *\n       * @returns {Object} The newly created child scope.\n       *\n       */\n      $new: function(isolate, parent) {\n        var child;\n\n        parent = parent || this;\n\n        if (isolate) {\n          child = new Scope();\n          child.$root = this.$root;\n        } else {\n          // Only create a child scope class if somebody asks for one,\n          // but cache it to allow the VM to optimize lookups.\n          if (!this.$$ChildScope) {\n            this.$$ChildScope = function ChildScope() {\n              this.$$watchers = this.$$nextSibling =\n                  this.$$childHead = this.$$childTail = null;\n              this.$$listeners = {};\n              this.$$listenerCount = {};\n              this.$id = nextUid();\n              this.$$ChildScope = null;\n            };\n            this.$$ChildScope.prototype = this;\n          }\n          child = new this.$$ChildScope();\n        }\n        child.$parent = parent;\n        child.$$prevSibling = parent.$$childTail;\n        if (parent.$$childHead) {\n          parent.$$childTail.$$nextSibling = child;\n          parent.$$childTail = child;\n        } else {\n          parent.$$childHead = parent.$$childTail = child;\n        }\n\n        // When the new scope is not isolated or we inherit from `this`, and\n        // the parent scope is destroyed, the property `$$destroyed` is inherited\n        // prototypically. In all other cases, this property needs to be set\n        // when the parent scope is destroyed.\n        // The listener needs to be added after the parent is set\n        if (isolate || parent != this) child.$on('$destroy', destroyChild);\n\n        return child;\n\n        function destroyChild() {\n          child.$$destroyed = true;\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watch\n       * @kind function\n       *\n       * @description\n       * Registers a `listener` callback to be executed whenever the `watchExpression` changes.\n       *\n       * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest\n       *   $digest()} and should return the value that will be watched. (Since\n       *   {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the\n       *   `watchExpression` can execute multiple times per\n       *   {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)\n       * - The `listener` is called only when the value from the current `watchExpression` and the\n       *   previous call to `watchExpression` are not equal (with the exception of the initial run,\n       *   see below). Inequality is determined according to reference inequality,\n       *   [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)\n       *    via the `!==` Javascript operator, unless `objectEquality == true`\n       *   (see next point)\n       * - When `objectEquality == true`, inequality of the `watchExpression` is determined\n       *   according to the {@link angular.equals} function. To save the value of the object for\n       *   later comparison, the {@link angular.copy} function is used. This therefore means that\n       *   watching complex objects will have adverse memory and performance implications.\n       * - The watch `listener` may change the model, which may trigger other `listener`s to fire.\n       *   This is achieved by rerunning the watchers until no changes are detected. The rerun\n       *   iteration limit is 10 to prevent an infinite loop deadlock.\n       *\n       *\n       * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,\n       * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`\n       * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a\n       * change is detected, be prepared for multiple calls to your listener.)\n       *\n       * After a watcher is registered with the scope, the `listener` fn is called asynchronously\n       * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the\n       * watcher. In rare cases, this is undesirable because the listener is called when the result\n       * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you\n       * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the\n       * listener was called due to initialization.\n       *\n       *\n       *\n       * # Example\n       * ```js\n           // let's assume that scope was dependency injected as the $rootScope\n           var scope = $rootScope;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n\n\n\n           // Using a function as a watchExpression\n           var food;\n           scope.foodCounter = 0;\n           expect(scope.foodCounter).toEqual(0);\n           scope.$watch(\n             // This function returns the value being watched. It is called for each turn of the $digest loop\n             function() { return food; },\n             // This is the change listener, called when the value returned from the above function changes\n             function(newValue, oldValue) {\n               if ( newValue !== oldValue ) {\n                 // Only increment the counter if the value changed\n                 scope.foodCounter = scope.foodCounter + 1;\n               }\n             }\n           );\n           // No digest has been run so the counter will be zero\n           expect(scope.foodCounter).toEqual(0);\n\n           // Run the digest but since food has not changed count will still be zero\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(0);\n\n           // Update food and run digest.  Now the counter will increment\n           food = 'cheeseburger';\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(1);\n\n       * ```\n       *\n       *\n       *\n       * @param {(function()|string)} watchExpression Expression that is evaluated on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers\n       *    a call to the `listener`.\n       *\n       *    - `string`: Evaluated as {@link guide/expression expression}\n       *    - `function(scope)`: called with current `scope` as a parameter.\n       * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value\n       *    of `watchExpression` changes.\n       *\n       *    - `newVal` contains the current value of the `watchExpression`\n       *    - `oldVal` contains the previous value of the `watchExpression`\n       *    - `scope` refers to the current scope\n       * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of\n       *     comparing for reference equality.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $watch: function(watchExp, listener, objectEquality) {\n        var get = $parse(watchExp);\n\n        if (get.$$watchDelegate) {\n          return get.$$watchDelegate(this, listener, objectEquality, get);\n        }\n        var scope = this,\n            array = scope.$$watchers,\n            watcher = {\n              fn: listener,\n              last: initWatchVal,\n              get: get,\n              exp: watchExp,\n              eq: !!objectEquality\n            };\n\n        lastDirtyWatch = null;\n\n        if (!isFunction(listener)) {\n          watcher.fn = noop;\n        }\n\n        if (!array) {\n          array = scope.$$watchers = [];\n        }\n        // we use unshift since we use a while loop in $digest for speed.\n        // the while loop reads in reverse order.\n        array.unshift(watcher);\n\n        return function deregisterWatch() {\n          arrayRemove(array, watcher);\n          lastDirtyWatch = null;\n        };\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchGroup\n       * @kind function\n       *\n       * @description\n       * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.\n       * If any one expression in the collection changes the `listener` is executed.\n       *\n       * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every\n       *   call to $digest() to see if any items changes.\n       * - The `listener` is called whenever any expression in the `watchExpressions` array changes.\n       *\n       * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually\n       * watched using {@link ng.$rootScope.Scope#$watch $watch()}\n       *\n       * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any\n       *    expression in `watchExpressions` changes\n       *    The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    The `scope` refers to the current scope.\n       * @returns {function()} Returns a de-registration function for all listeners.\n       */\n      $watchGroup: function(watchExpressions, listener) {\n        var oldValues = new Array(watchExpressions.length);\n        var newValues = new Array(watchExpressions.length);\n        var deregisterFns = [];\n        var self = this;\n        var changeReactionScheduled = false;\n        var firstRun = true;\n\n        if (!watchExpressions.length) {\n          // No expressions means we call the listener ASAP\n          var shouldCall = true;\n          self.$evalAsync(function() {\n            if (shouldCall) listener(newValues, newValues, self);\n          });\n          return function deregisterWatchGroup() {\n            shouldCall = false;\n          };\n        }\n\n        if (watchExpressions.length === 1) {\n          // Special case size of one\n          return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {\n            newValues[0] = value;\n            oldValues[0] = oldValue;\n            listener(newValues, (value === oldValue) ? newValues : oldValues, scope);\n          });\n        }\n\n        forEach(watchExpressions, function(expr, i) {\n          var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {\n            newValues[i] = value;\n            oldValues[i] = oldValue;\n            if (!changeReactionScheduled) {\n              changeReactionScheduled = true;\n              self.$evalAsync(watchGroupAction);\n            }\n          });\n          deregisterFns.push(unwatchFn);\n        });\n\n        function watchGroupAction() {\n          changeReactionScheduled = false;\n\n          if (firstRun) {\n            firstRun = false;\n            listener(newValues, newValues, self);\n          } else {\n            listener(newValues, oldValues, self);\n          }\n        }\n\n        return function deregisterWatchGroup() {\n          while (deregisterFns.length) {\n            deregisterFns.shift()();\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchCollection\n       * @kind function\n       *\n       * @description\n       * Shallow watches the properties of an object and fires whenever any of the properties change\n       * (for arrays, this implies watching the array items; for object maps, this implies watching\n       * the properties). If a change is detected, the `listener` callback is fired.\n       *\n       * - The `obj` collection is observed via standard $watch operation and is examined on every\n       *   call to $digest() to see if any items have been added, removed, or moved.\n       * - The `listener` is called whenever anything within the `obj` has changed. Examples include\n       *   adding, removing, and moving items belonging to an object or array.\n       *\n       *\n       * # Example\n       * ```js\n          $scope.names = ['igor', 'matias', 'misko', 'james'];\n          $scope.dataCount = 4;\n\n          $scope.$watchCollection('names', function(newNames, oldNames) {\n            $scope.dataCount = newNames.length;\n          });\n\n          expect($scope.dataCount).toEqual(4);\n          $scope.$digest();\n\n          //still at 4 ... no changes\n          expect($scope.dataCount).toEqual(4);\n\n          $scope.names.pop();\n          $scope.$digest();\n\n          //now there's been a change\n          expect($scope.dataCount).toEqual(3);\n       * ```\n       *\n       *\n       * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The\n       *    expression value should evaluate to an object or an array which is observed on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the\n       *    collection will trigger a call to the `listener`.\n       *\n       * @param {function(newCollection, oldCollection, scope)} listener a callback function called\n       *    when a change is detected.\n       *    - The `newCollection` object is the newly modified data obtained from the `obj` expression\n       *    - The `oldCollection` object is a copy of the former collection data.\n       *      Due to performance considerations, the`oldCollection` value is computed only if the\n       *      `listener` function declares two or more arguments.\n       *    - The `scope` argument refers to the current scope.\n       *\n       * @returns {function()} Returns a de-registration function for this listener. When the\n       *    de-registration function is executed, the internal watch operation is terminated.\n       */\n      $watchCollection: function(obj, listener) {\n        $watchCollectionInterceptor.$stateful = true;\n\n        var self = this;\n        // the current value, updated on each dirty-check run\n        var newValue;\n        // a shallow copy of the newValue from the last dirty-check run,\n        // updated to match newValue during dirty-check run\n        var oldValue;\n        // a shallow copy of the newValue from when the last change happened\n        var veryOldValue;\n        // only track veryOldValue if the listener is asking for it\n        var trackVeryOldValue = (listener.length > 1);\n        var changeDetected = 0;\n        var changeDetector = $parse(obj, $watchCollectionInterceptor);\n        var internalArray = [];\n        var internalObject = {};\n        var initRun = true;\n        var oldLength = 0;\n\n        function $watchCollectionInterceptor(_value) {\n          newValue = _value;\n          var newLength, key, bothNaN, newItem, oldItem;\n\n          // If the new value is undefined, then return undefined as the watch may be a one-time watch\n          if (isUndefined(newValue)) return;\n\n          if (!isObject(newValue)) { // if primitive\n            if (oldValue !== newValue) {\n              oldValue = newValue;\n              changeDetected++;\n            }\n          } else if (isArrayLike(newValue)) {\n            if (oldValue !== internalArray) {\n              // we are transitioning from something which was not an array into array.\n              oldValue = internalArray;\n              oldLength = oldValue.length = 0;\n              changeDetected++;\n            }\n\n            newLength = newValue.length;\n\n            if (oldLength !== newLength) {\n              // if lengths do not match we need to trigger change notification\n              changeDetected++;\n              oldValue.length = oldLength = newLength;\n            }\n            // copy the items to oldValue and look for changes.\n            for (var i = 0; i < newLength; i++) {\n              oldItem = oldValue[i];\n              newItem = newValue[i];\n\n              bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n              if (!bothNaN && (oldItem !== newItem)) {\n                changeDetected++;\n                oldValue[i] = newItem;\n              }\n            }\n          } else {\n            if (oldValue !== internalObject) {\n              // we are transitioning from something which was not an object into object.\n              oldValue = internalObject = {};\n              oldLength = 0;\n              changeDetected++;\n            }\n            // copy the items to oldValue and look for changes.\n            newLength = 0;\n            for (key in newValue) {\n              if (newValue.hasOwnProperty(key)) {\n                newLength++;\n                newItem = newValue[key];\n                oldItem = oldValue[key];\n\n                if (key in oldValue) {\n                  bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n                  if (!bothNaN && (oldItem !== newItem)) {\n                    changeDetected++;\n                    oldValue[key] = newItem;\n                  }\n                } else {\n                  oldLength++;\n                  oldValue[key] = newItem;\n                  changeDetected++;\n                }\n              }\n            }\n            if (oldLength > newLength) {\n              // we used to have more keys, need to find them and destroy them.\n              changeDetected++;\n              for (key in oldValue) {\n                if (!newValue.hasOwnProperty(key)) {\n                  oldLength--;\n                  delete oldValue[key];\n                }\n              }\n            }\n          }\n          return changeDetected;\n        }\n\n        function $watchCollectionAction() {\n          if (initRun) {\n            initRun = false;\n            listener(newValue, newValue, self);\n          } else {\n            listener(newValue, veryOldValue, self);\n          }\n\n          // make a copy for the next time a collection is changed\n          if (trackVeryOldValue) {\n            if (!isObject(newValue)) {\n              //primitive\n              veryOldValue = newValue;\n            } else if (isArrayLike(newValue)) {\n              veryOldValue = new Array(newValue.length);\n              for (var i = 0; i < newValue.length; i++) {\n                veryOldValue[i] = newValue[i];\n              }\n            } else { // if object\n              veryOldValue = {};\n              for (var key in newValue) {\n                if (hasOwnProperty.call(newValue, key)) {\n                  veryOldValue[key] = newValue[key];\n                }\n              }\n            }\n          }\n        }\n\n        return this.$watch(changeDetector, $watchCollectionAction);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$digest\n       * @kind function\n       *\n       * @description\n       * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and\n       * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change\n       * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}\n       * until no more listeners are firing. This means that it is possible to get into an infinite\n       * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of\n       * iterations exceeds 10.\n       *\n       * Usually, you don't call `$digest()` directly in\n       * {@link ng.directive:ngController controllers} or in\n       * {@link ng.$compileProvider#directive directives}.\n       * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within\n       * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.\n       *\n       * If you want to be notified whenever `$digest()` is called,\n       * you can register a `watchExpression` function with\n       * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.\n       *\n       * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.\n       *\n       * # Example\n       * ```js\n           var scope = ...;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n       * ```\n       *\n       */\n      $digest: function() {\n        var watch, value, last,\n            watchers,\n            length,\n            dirty, ttl = TTL,\n            next, current, target = this,\n            watchLog = [],\n            logIdx, logMsg, asyncTask;\n\n        beginPhase('$digest');\n        // Check for changes to browser url that happened in sync before the call to $digest\n        $browser.$$checkUrlChange();\n\n        if (this === $rootScope && applyAsyncId !== null) {\n          // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then\n          // cancel the scheduled $apply and flush the queue of expressions to be evaluated.\n          $browser.defer.cancel(applyAsyncId);\n          flushApplyAsync();\n        }\n\n        lastDirtyWatch = null;\n\n        do { // \"while dirty\" loop\n          dirty = false;\n          current = target;\n\n          while (asyncQueue.length) {\n            try {\n              asyncTask = asyncQueue.shift();\n              asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n            lastDirtyWatch = null;\n          }\n\n          traverseScopesLoop:\n          do { // \"traverse the scopes\" loop\n            if ((watchers = current.$$watchers)) {\n              // process our watches\n              length = watchers.length;\n              while (length--) {\n                try {\n                  watch = watchers[length];\n                  // Most common watches are on primitives, in which case we can short\n                  // circuit it with === operator, only when === fails do we use .equals\n                  if (watch) {\n                    if ((value = watch.get(current)) !== (last = watch.last) &&\n                        !(watch.eq\n                            ? equals(value, last)\n                            : (typeof value === 'number' && typeof last === 'number'\n                               && isNaN(value) && isNaN(last)))) {\n                      dirty = true;\n                      lastDirtyWatch = watch;\n                      watch.last = watch.eq ? copy(value, null) : value;\n                      watch.fn(value, ((last === initWatchVal) ? value : last), current);\n                      if (ttl < 5) {\n                        logIdx = 4 - ttl;\n                        if (!watchLog[logIdx]) watchLog[logIdx] = [];\n                        watchLog[logIdx].push({\n                          msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,\n                          newVal: value,\n                          oldVal: last\n                        });\n                      }\n                    } else if (watch === lastDirtyWatch) {\n                      // If the most recently dirty watcher is now clean, short circuit since the remaining watchers\n                      // have already been tested.\n                      dirty = false;\n                      break traverseScopesLoop;\n                    }\n                  }\n                } catch (e) {\n                  $exceptionHandler(e);\n                }\n              }\n            }\n\n            // Insanity Warning: scope depth-first traversal\n            // yes, this code is a bit crazy, but it works and we have tests to prove it!\n            // this piece should be kept in sync with the traversal in $broadcast\n            if (!(next = (current.$$childHead ||\n                (current !== target && current.$$nextSibling)))) {\n              while (current !== target && !(next = current.$$nextSibling)) {\n                current = current.$parent;\n              }\n            }\n          } while ((current = next));\n\n          // `break traverseScopesLoop;` takes us to here\n\n          if ((dirty || asyncQueue.length) && !(ttl--)) {\n            clearPhase();\n            throw $rootScopeMinErr('infdig',\n                '{0} $digest() iterations reached. Aborting!\\n' +\n                'Watchers fired in the last 5 iterations: {1}',\n                TTL, watchLog);\n          }\n\n        } while (dirty || asyncQueue.length);\n\n        clearPhase();\n\n        while (postDigestQueue.length) {\n          try {\n            postDigestQueue.shift()();\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        }\n      },\n\n\n      /**\n       * @ngdoc event\n       * @name $rootScope.Scope#$destroy\n       * @eventType broadcast on scope being destroyed\n       *\n       * @description\n       * Broadcasted when a scope and its children are being destroyed.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$destroy\n       * @kind function\n       *\n       * @description\n       * Removes the current scope (and all of its children) from the parent scope. Removal implies\n       * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer\n       * propagate to the current scope and its children. Removal also implies that the current\n       * scope is eligible for garbage collection.\n       *\n       * The `$destroy()` is usually used by directives such as\n       * {@link ng.directive:ngRepeat ngRepeat} for managing the\n       * unrolling of the loop.\n       *\n       * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.\n       * Application code can register a `$destroy` event handler that will give it a chance to\n       * perform any necessary cleanup.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n      $destroy: function() {\n        // we can't destroy the root scope or a scope that has been already destroyed\n        if (this.$$destroyed) return;\n        var parent = this.$parent;\n\n        this.$broadcast('$destroy');\n        this.$$destroyed = true;\n        if (this === $rootScope) return;\n\n        for (var eventName in this.$$listenerCount) {\n          decrementListenerCount(this, this.$$listenerCount[eventName], eventName);\n        }\n\n        // sever all the references to parent scopes (after this cleanup, the current scope should\n        // not be retained by any of our references and should be eligible for garbage collection)\n        if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;\n        if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;\n        if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;\n        if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;\n\n        // Disable listeners, watchers and apply/digest methods\n        this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;\n        this.$on = this.$watch = this.$watchGroup = function() { return noop; };\n        this.$$listeners = {};\n\n        // All of the code below is bogus code that works around V8's memory leak via optimized code\n        // and inline caches.\n        //\n        // see:\n        // - https://code.google.com/p/v8/issues/detail?id=2073#c26\n        // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909\n        // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451\n\n        this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =\n            this.$$childTail = this.$root = this.$$watchers = null;\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$eval\n       * @kind function\n       *\n       * @description\n       * Executes the `expression` on the current scope and returns the result. Any exceptions in\n       * the expression are propagated (uncaught). This is useful when evaluating Angular\n       * expressions.\n       *\n       * # Example\n       * ```js\n           var scope = ng.$rootScope.Scope();\n           scope.a = 1;\n           scope.b = 2;\n\n           expect(scope.$eval('a+b')).toEqual(3);\n           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);\n       * ```\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       * @returns {*} The result of evaluating the expression.\n       */\n      $eval: function(expr, locals) {\n        return $parse(expr)(this, locals);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$evalAsync\n       * @kind function\n       *\n       * @description\n       * Executes the expression on the current scope at a later point in time.\n       *\n       * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only\n       * that:\n       *\n       *   - it will execute after the function that scheduled the evaluation (preferably before DOM\n       *     rendering).\n       *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after\n       *     `expression` execution.\n       *\n       * Any exceptions from the execution of the expression are forwarded to the\n       * {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle\n       * will be scheduled. However, it is encouraged to always call code that changes the model\n       * from within an `$apply` call. That includes code evaluated via `$evalAsync`.\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       */\n      $evalAsync: function(expr, locals) {\n        // if we are outside of an $digest loop and this is the first time we are scheduling async\n        // task also schedule async auto-flush\n        if (!$rootScope.$$phase && !asyncQueue.length) {\n          $browser.defer(function() {\n            if (asyncQueue.length) {\n              $rootScope.$digest();\n            }\n          });\n        }\n\n        asyncQueue.push({scope: this, expression: expr, locals: locals});\n      },\n\n      $$postDigest: function(fn) {\n        postDigestQueue.push(fn);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$apply\n       * @kind function\n       *\n       * @description\n       * `$apply()` is used to execute an expression in angular from outside of the angular\n       * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).\n       * Because we are calling into the angular framework we need to perform proper scope life\n       * cycle of {@link ng.$exceptionHandler exception handling},\n       * {@link ng.$rootScope.Scope#$digest executing watches}.\n       *\n       * ## Life cycle\n       *\n       * # Pseudo-Code of `$apply()`\n       * ```js\n           function $apply(expr) {\n             try {\n               return $eval(expr);\n             } catch (e) {\n               $exceptionHandler(e);\n             } finally {\n               $root.$digest();\n             }\n           }\n       * ```\n       *\n       *\n       * Scope's `$apply()` method transitions through the following stages:\n       *\n       * 1. The {@link guide/expression expression} is executed using the\n       *    {@link ng.$rootScope.Scope#$eval $eval()} method.\n       * 2. Any exceptions from the execution of the expression are forwarded to the\n       *    {@link ng.$exceptionHandler $exceptionHandler} service.\n       * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the\n       *    expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.\n       *\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       *\n       * @returns {*} The result of evaluating the expression.\n       */\n      $apply: function(expr) {\n        try {\n          beginPhase('$apply');\n          return this.$eval(expr);\n        } catch (e) {\n          $exceptionHandler(e);\n        } finally {\n          clearPhase();\n          try {\n            $rootScope.$digest();\n          } catch (e) {\n            $exceptionHandler(e);\n            throw e;\n          }\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$applyAsync\n       * @kind function\n       *\n       * @description\n       * Schedule the invocation of $apply to occur at a later time. The actual time difference\n       * varies across browsers, but is typically around ~10 milliseconds.\n       *\n       * This can be used to queue up multiple expressions which need to be evaluated in the same\n       * digest.\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       */\n      $applyAsync: function(expr) {\n        var scope = this;\n        expr && applyAsyncQueue.push($applyAsyncExpression);\n        scheduleApplyAsync();\n\n        function $applyAsyncExpression() {\n          scope.$eval(expr);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$on\n       * @kind function\n       *\n       * @description\n       * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for\n       * discussion of event life cycle.\n       *\n       * The event listener function format is: `function(event, args...)`. The `event` object\n       * passed into the listener has the following attributes:\n       *\n       *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or\n       *     `$broadcast`-ed.\n       *   - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the\n       *     event propagates through the scope hierarchy, this property is set to null.\n       *   - `name` - `{string}`: name of the event.\n       *   - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel\n       *     further event propagation (available only for events that were `$emit`-ed).\n       *   - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag\n       *     to true.\n       *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.\n       *\n       * @param {string} name Event name to listen on.\n       * @param {function(event, ...args)} listener Function to call when the event is emitted.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $on: function(name, listener) {\n        var namedListeners = this.$$listeners[name];\n        if (!namedListeners) {\n          this.$$listeners[name] = namedListeners = [];\n        }\n        namedListeners.push(listener);\n\n        var current = this;\n        do {\n          if (!current.$$listenerCount[name]) {\n            current.$$listenerCount[name] = 0;\n          }\n          current.$$listenerCount[name]++;\n        } while ((current = current.$parent));\n\n        var self = this;\n        return function() {\n          var indexOfListener = namedListeners.indexOf(listener);\n          if (indexOfListener !== -1) {\n            namedListeners[indexOfListener] = null;\n            decrementListenerCount(self, 1, name);\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$emit\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` upwards through the scope hierarchy notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$emit` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event traverses upwards toward the root scope and calls all\n       * registered listeners along the way. The event will stop propagating if one of the listeners\n       * cancels it.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to emit.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).\n       */\n      $emit: function(name, args) {\n        var empty = [],\n            namedListeners,\n            scope = this,\n            stopPropagation = false,\n            event = {\n              name: name,\n              targetScope: scope,\n              stopPropagation: function() {stopPropagation = true;},\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            },\n            listenerArgs = concat([event], arguments, 1),\n            i, length;\n\n        do {\n          namedListeners = scope.$$listeners[name] || empty;\n          event.currentScope = scope;\n          for (i = 0, length = namedListeners.length; i < length; i++) {\n\n            // if listeners were deregistered, defragment the array\n            if (!namedListeners[i]) {\n              namedListeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n            try {\n              //allow all listeners attached to the current scope to run\n              namedListeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n          //if any listener on the current scope stops propagation, prevent bubbling\n          if (stopPropagation) {\n            event.currentScope = null;\n            return event;\n          }\n          //traverse upwards\n          scope = scope.$parent;\n        } while (scope);\n\n        event.currentScope = null;\n\n        return event;\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$broadcast\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` downwards to all child scopes (and their children) notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$broadcast` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event propagates to all direct and indirect scopes of the current\n       * scope and calls all registered listeners along the way. The event cannot be canceled.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to broadcast.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}\n       */\n      $broadcast: function(name, args) {\n        var target = this,\n            current = target,\n            next = target,\n            event = {\n              name: name,\n              targetScope: target,\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            };\n\n        if (!target.$$listenerCount[name]) return event;\n\n        var listenerArgs = concat([event], arguments, 1),\n            listeners, i, length;\n\n        //down while you can, then up and next sibling or up and next sibling until back at root\n        while ((current = next)) {\n          event.currentScope = current;\n          listeners = current.$$listeners[name] || [];\n          for (i = 0, length = listeners.length; i < length; i++) {\n            // if listeners were deregistered, defragment the array\n            if (!listeners[i]) {\n              listeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n\n            try {\n              listeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n\n          // Insanity Warning: scope depth-first traversal\n          // yes, this code is a bit crazy, but it works and we have tests to prove it!\n          // this piece should be kept in sync with the traversal in $digest\n          // (though it differs due to having the extra check for $$listenerCount)\n          if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||\n              (current !== target && current.$$nextSibling)))) {\n            while (current !== target && !(next = current.$$nextSibling)) {\n              current = current.$parent;\n            }\n          }\n        }\n\n        event.currentScope = null;\n        return event;\n      }\n    };\n\n    var $rootScope = new Scope();\n\n    //The internal queues. Expose them on the $rootScope for debugging/testing purposes.\n    var asyncQueue = $rootScope.$$asyncQueue = [];\n    var postDigestQueue = $rootScope.$$postDigestQueue = [];\n    var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];\n\n    return $rootScope;\n\n\n    function beginPhase(phase) {\n      if ($rootScope.$$phase) {\n        throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);\n      }\n\n      $rootScope.$$phase = phase;\n    }\n\n    function clearPhase() {\n      $rootScope.$$phase = null;\n    }\n\n\n    function decrementListenerCount(current, count, name) {\n      do {\n        current.$$listenerCount[name] -= count;\n\n        if (current.$$listenerCount[name] === 0) {\n          delete current.$$listenerCount[name];\n        }\n      } while ((current = current.$parent));\n    }\n\n    /**\n     * function used as an initial value for watchers.\n     * because it's unique we can easily tell it apart from other values\n     */\n    function initWatchVal() {}\n\n    function flushApplyAsync() {\n      while (applyAsyncQueue.length) {\n        try {\n          applyAsyncQueue.shift()();\n        } catch (e) {\n          $exceptionHandler(e);\n        }\n      }\n      applyAsyncId = null;\n    }\n\n    function scheduleApplyAsync() {\n      if (applyAsyncId === null) {\n        applyAsyncId = $browser.defer(function() {\n          $rootScope.$apply(flushApplyAsync);\n        });\n      }\n    }\n  }];\n}\n\n/**\n * @description\n * Private service to sanitize uris for links and images. Used by $compile and $sanitize.\n */\nfunction $$SanitizeUriProvider() {\n  var aHrefSanitizationWhitelist = /^\\s*(https?|ftp|mailto|tel|file):/,\n    imgSrcSanitizationWhitelist = /^\\s*((https?|ftp|file|blob):|data:image\\/)/;\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      aHrefSanitizationWhitelist = regexp;\n      return this;\n    }\n    return aHrefSanitizationWhitelist;\n  };\n\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      imgSrcSanitizationWhitelist = regexp;\n      return this;\n    }\n    return imgSrcSanitizationWhitelist;\n  };\n\n  this.$get = function() {\n    return function sanitizeUri(uri, isImage) {\n      var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;\n      var normalizedVal;\n      normalizedVal = urlResolve(uri).href;\n      if (normalizedVal !== '' && !normalizedVal.match(regex)) {\n        return 'unsafe:' + normalizedVal;\n      }\n      return uri;\n    };\n  };\n}\n\nvar $sceMinErr = minErr('$sce');\n\nvar SCE_CONTEXTS = {\n  HTML: 'html',\n  CSS: 'css',\n  URL: 'url',\n  // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a\n  // url.  (e.g. ng-include, script src, templateUrl)\n  RESOURCE_URL: 'resourceUrl',\n  JS: 'js'\n};\n\n// Helper functions follow.\n\nfunction adjustMatcher(matcher) {\n  if (matcher === 'self') {\n    return matcher;\n  } else if (isString(matcher)) {\n    // Strings match exactly except for 2 wildcards - '*' and '**'.\n    // '*' matches any character except those from the set ':/.?&'.\n    // '**' matches any character (like .* in a RegExp).\n    // More than 2 *'s raises an error as it's ill defined.\n    if (matcher.indexOf('***') > -1) {\n      throw $sceMinErr('iwcard',\n          'Illegal sequence *** in string matcher.  String: {0}', matcher);\n    }\n    matcher = escapeForRegexp(matcher).\n                  replace('\\\\*\\\\*', '.*').\n                  replace('\\\\*', '[^:/.?&;]*');\n    return new RegExp('^' + matcher + '$');\n  } else if (isRegExp(matcher)) {\n    // The only other type of matcher allowed is a Regexp.\n    // Match entire URL / disallow partial matches.\n    // Flags are reset (i.e. no global, ignoreCase or multiline)\n    return new RegExp('^' + matcher.source + '$');\n  } else {\n    throw $sceMinErr('imatcher',\n        'Matchers may only be \"self\", string patterns or RegExp objects');\n  }\n}\n\n\nfunction adjustMatchers(matchers) {\n  var adjustedMatchers = [];\n  if (isDefined(matchers)) {\n    forEach(matchers, function(matcher) {\n      adjustedMatchers.push(adjustMatcher(matcher));\n    });\n  }\n  return adjustedMatchers;\n}\n\n\n/**\n * @ngdoc service\n * @name $sceDelegate\n * @kind function\n *\n * @description\n *\n * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict\n * Contextual Escaping (SCE)} services to AngularJS.\n *\n * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of\n * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS.  This is\n * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to\n * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things\n * work because `$sce` delegates to `$sceDelegate` for these operations.\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.\n *\n * The default instance of `$sceDelegate` should work out of the box with little pain.  While you\n * can override it completely to change the behavior of `$sce`, the common case would\n * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting\n * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as\n * templates.  Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist\n * $sceDelegateProvider.resourceUrlWhitelist} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n */\n\n/**\n * @ngdoc provider\n * @name $sceDelegateProvider\n * @description\n *\n * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate\n * $sceDelegate} service.  This allows one to get/set the whitelists and blacklists used to ensure\n * that the URLs used for sourcing Angular templates are safe.  Refer {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and\n * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n *\n * For the general details about this service in Angular, read the main page for {@link ng.$sce\n * Strict Contextual Escaping (SCE)}.\n *\n * **Example**:  Consider the following case. <a name=\"example\"></a>\n *\n * - your app is hosted at url `http://myapp.example.com/`\n * - but some of your templates are hosted on other domains you control such as\n *   `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.\n * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.\n *\n * Here is what a secure configuration for this scenario might look like:\n *\n * ```\n *  angular.module('myApp', []).config(function($sceDelegateProvider) {\n *    $sceDelegateProvider.resourceUrlWhitelist([\n *      // Allow same origin resource loads.\n *      'self',\n *      // Allow loading from our assets domain.  Notice the difference between * and **.\n *      'http://srv*.assets.example.com/**'\n *    ]);\n *\n *    // The blacklist overrides the whitelist so the open redirect here is blocked.\n *    $sceDelegateProvider.resourceUrlBlacklist([\n *      'http://myapp.example.com/clickThru**'\n *    ]);\n *  });\n * ```\n */\n\nfunction $SceDelegateProvider() {\n  this.SCE_CONTEXTS = SCE_CONTEXTS;\n\n  // Resource URLs can also be trusted by policy.\n  var resourceUrlWhitelist = ['self'],\n      resourceUrlBlacklist = [];\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlWhitelist\n   * @kind function\n   *\n   * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     Note: **an empty whitelist array will block all URLs**!\n   *\n   * @return {Array} the currently set whitelist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is `['self']` allowing only\n   * same origin resource requests.\n   *\n   * @description\n   * Sets/Gets the whitelist of trusted resource URLs.\n   */\n  this.resourceUrlWhitelist = function(value) {\n    if (arguments.length) {\n      resourceUrlWhitelist = adjustMatchers(value);\n    }\n    return resourceUrlWhitelist;\n  };\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlBlacklist\n   * @kind function\n   *\n   * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     The typical usage for the blacklist is to **block\n   *     [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as\n   *     these would otherwise be trusted but actually return content from the redirected domain.\n   *\n   *     Finally, **the blacklist overrides the whitelist** and has the final say.\n   *\n   * @return {Array} the currently set blacklist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there\n   * is no blacklist.)\n   *\n   * @description\n   * Sets/Gets the blacklist of trusted resource URLs.\n   */\n\n  this.resourceUrlBlacklist = function(value) {\n    if (arguments.length) {\n      resourceUrlBlacklist = adjustMatchers(value);\n    }\n    return resourceUrlBlacklist;\n  };\n\n  this.$get = ['$injector', function($injector) {\n\n    var htmlSanitizer = function htmlSanitizer(html) {\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    };\n\n    if ($injector.has('$sanitize')) {\n      htmlSanitizer = $injector.get('$sanitize');\n    }\n\n\n    function matchUrl(matcher, parsedUrl) {\n      if (matcher === 'self') {\n        return urlIsSameOrigin(parsedUrl);\n      } else {\n        // definitely a regex.  See adjustMatchers()\n        return !!matcher.exec(parsedUrl.href);\n      }\n    }\n\n    function isResourceUrlAllowedByPolicy(url) {\n      var parsedUrl = urlResolve(url.toString());\n      var i, n, allowed = false;\n      // Ensure that at least one item from the whitelist allows this url.\n      for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {\n        if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {\n          allowed = true;\n          break;\n        }\n      }\n      if (allowed) {\n        // Ensure that no item from the blacklist blocked this url.\n        for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {\n          if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {\n            allowed = false;\n            break;\n          }\n        }\n      }\n      return allowed;\n    }\n\n    function generateHolderType(Base) {\n      var holderType = function TrustedValueHolderType(trustedValue) {\n        this.$$unwrapTrustedValue = function() {\n          return trustedValue;\n        };\n      };\n      if (Base) {\n        holderType.prototype = new Base();\n      }\n      holderType.prototype.valueOf = function sceValueOf() {\n        return this.$$unwrapTrustedValue();\n      };\n      holderType.prototype.toString = function sceToString() {\n        return this.$$unwrapTrustedValue().toString();\n      };\n      return holderType;\n    }\n\n    var trustedValueHolderBase = generateHolderType(),\n        byType = {};\n\n    byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#trustAs\n     *\n     * @description\n     * Returns an object that is trusted by angular for use in specified strict\n     * contextual escaping contexts (such as ng-bind-html, ng-include, any src\n     * attribute interpolation, any dom event binding attribute interpolation\n     * such as for onclick,  etc.) that uses the provided value.\n     * See {@link ng.$sce $sce} for enabling strict contextual escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resourceUrl, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n    function trustAs(type, trustedValue) {\n      var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (!Constructor) {\n        throw $sceMinErr('icontext',\n            'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',\n            type, trustedValue);\n      }\n      if (trustedValue === null || trustedValue === undefined || trustedValue === '') {\n        return trustedValue;\n      }\n      // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting\n      // mutable objects, we ensure here that the value passed in is actually a string.\n      if (typeof trustedValue !== 'string') {\n        throw $sceMinErr('itype',\n            'Attempted to trust a non-string value in a content requiring a string: Context: {0}',\n            type);\n      }\n      return new Constructor(trustedValue);\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#valueOf\n     *\n     * @description\n     * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs\n     * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.\n     *\n     * If the passed parameter is not a value that had been returned by {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.\n     *\n     * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}\n     *      call or anything else.\n     * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if `value` is the result of such a call.  Otherwise, returns\n     *     `value` unchanged.\n     */\n    function valueOf(maybeTrusted) {\n      if (maybeTrusted instanceof trustedValueHolderBase) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      } else {\n        return maybeTrusted;\n      }\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#getTrusted\n     *\n     * @description\n     * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and\n     * returns the originally supplied value if the queried context type is a supertype of the\n     * created type.  If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} call.\n     * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if valid in this context.  Otherwise, throws an exception.\n     */\n    function getTrusted(type, maybeTrusted) {\n      if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {\n        return maybeTrusted;\n      }\n      var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (constructor && maybeTrusted instanceof constructor) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      }\n      // If we get here, then we may only take one of two actions.\n      // 1. sanitize the value for the requested type, or\n      // 2. throw an exception.\n      if (type === SCE_CONTEXTS.RESOURCE_URL) {\n        if (isResourceUrlAllowedByPolicy(maybeTrusted)) {\n          return maybeTrusted;\n        } else {\n          throw $sceMinErr('insecurl',\n              'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',\n              maybeTrusted.toString());\n        }\n      } else if (type === SCE_CONTEXTS.HTML) {\n        return htmlSanitizer(maybeTrusted);\n      }\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    }\n\n    return { trustAs: trustAs,\n             getTrusted: getTrusted,\n             valueOf: valueOf };\n  }];\n}\n\n\n/**\n * @ngdoc provider\n * @name $sceProvider\n * @description\n *\n * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.\n * -   enable/disable Strict Contextual Escaping (SCE) in a module\n * -   override the default implementation with a custom delegate\n *\n * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.\n */\n\n/* jshint maxlen: false*/\n\n/**\n * @ngdoc service\n * @name $sce\n * @kind function\n *\n * @description\n *\n * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.\n *\n * # Strict Contextual Escaping\n *\n * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain\n * contexts to result in a value that is marked as safe to use for that context.  One example of\n * such a context is binding arbitrary html controlled by the user via `ng-bind-html`.  We refer\n * to these contexts as privileged or SCE contexts.\n *\n * As of version 1.2, Angular ships with SCE enabled by default.\n *\n * Note:  When enabled (the default), IE<11 in quirks mode is not supported.  In this mode, IE<11 allow\n * one to execute arbitrary javascript by the use of the expression() syntax.  Refer\n * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.\n * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`\n * to the top of your HTML document.\n *\n * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for\n * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.\n *\n * Here's an example of a binding in a privileged context:\n *\n * ```\n * <input ng-model=\"userHtml\">\n * <div ng-bind-html=\"userHtml\"></div>\n * ```\n *\n * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user.  With SCE\n * disabled, this application allows the user to render arbitrary HTML into the DIV.\n * In a more realistic example, one may be rendering user comments, blog articles, etc. via\n * bindings.  (HTML is just one example of a context where rendering user controlled input creates\n * security vulnerabilities.)\n *\n * For the case of HTML, you might use a library, either on the client side, or on the server side,\n * to sanitize unsafe HTML before binding to the value and rendering it in the document.\n *\n * How would you ensure that every place that used these types of bindings was bound to a value that\n * was sanitized by your library (or returned as safe for rendering by your server?)  How can you\n * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some\n * properties/fields and forgot to update the binding to the sanitized value?\n *\n * To be secure by default, you want to ensure that any such bindings are disallowed unless you can\n * determine that something explicitly says it's safe to use a value for binding in that\n * context.  You can then audit your code (a simple grep would do) to ensure that this is only done\n * for those values that you can easily tell are safe - because they were received from your server,\n * sanitized by your library, etc.  You can organize your codebase to help with this - perhaps\n * allowing only the files in a specific directory to do this.  Ensuring that the internal API\n * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.\n *\n * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}\n * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to\n * obtain values that will be accepted by SCE / privileged contexts.\n *\n *\n * ## How does it work?\n *\n * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted\n * $sce.getTrusted(context, value)} rather than to the value directly.  Directives use {@link\n * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the\n * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.\n *\n * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link\n * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}.  Here's the actual code (slightly\n * simplified):\n *\n * ```\n * var ngBindHtmlDirective = ['$sce', function($sce) {\n *   return function(scope, element, attr) {\n *     scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {\n *       element.html(value || '');\n *     });\n *   };\n * }];\n * ```\n *\n * ## Impact on loading templates\n *\n * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as\n * `templateUrl`'s specified by {@link guide/directive directives}.\n *\n * By default, Angular only loads templates from the same domain and protocol as the application\n * document.  This is done by calling {@link ng.$sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on the template URL.  To load templates from other domains and/or\n * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist\n * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.\n *\n * *Please note*:\n * The browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy apply in addition to this and may further restrict whether the template is successfully\n * loaded.  This means that without the right CORS policy, loading templates from a different domain\n * won't work on all browsers.  Also, loading templates from `file://` URL does not work on some\n * browsers.\n *\n * ## This feels like too much overhead\n *\n * It's important to remember that SCE only applies to interpolation expressions.\n *\n * If your expressions are constant literals, they're automatically trusted and you don't need to\n * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.\n * `<div ng-bind-html=\"'<b>implicitly trusted</b>'\"></div>`) just works.\n *\n * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them\n * through {@link ng.$sce#getTrusted $sce.getTrusted}.  SCE doesn't play a role here.\n *\n * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load\n * templates in `ng-include` from your application's domain without having to even know about SCE.\n * It blocks loading templates from other domains or loading templates over http from an https\n * served document.  You can change these by setting your own custom {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.\n *\n * This significantly reduces the overhead.  It is far easier to pay the small overhead and have an\n * application that's secure and can be audited to verify that with much more ease than bolting\n * security onto an application later.\n *\n * <a name=\"contexts\"></a>\n * ## What trusted context types are supported?\n *\n * | Context             | Notes          |\n * |---------------------|----------------|\n * | `$sce.HTML`         | For HTML that's safe to source into the application.  The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |\n * | `$sce.CSS`          | For CSS that's safe to source into the application.  Currently unused.  Feel free to use it in your own directives. |\n * | `$sce.URL`          | For URLs that are safe to follow as links.  Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |\n * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application.  Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.)  <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |\n * | `$sce.JS`           | For JavaScript that is safe to execute in your application's context.  Currently unused.  Feel free to use it in your own directives. |\n *\n * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name=\"resourceUrlPatternItem\"></a>\n *\n *  Each element in these arrays must be one of the following:\n *\n *  - **'self'**\n *    - The special **string**, `'self'`, can be used to match against all URLs of the **same\n *      domain** as the application document using the **same protocol**.\n *  - **String** (except the special value `'self'`)\n *    - The string is matched against the full *normalized / absolute URL* of the resource\n *      being tested (substring matches are not good enough.)\n *    - There are exactly **two wildcard sequences** - `*` and `**`.  All other characters\n *      match themselves.\n *    - `*`: matches zero or more occurrences of any character other than one of the following 6\n *      characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'.  It's a useful wildcard for use\n *      in a whitelist.\n *    - `**`: matches zero or more occurrences of *any* character.  As such, it's not\n *      not appropriate to use in for a scheme, domain, etc. as it would match too much.  (e.g.\n *      http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might\n *      not have been the intention.)  Its usage at the very end of the path is ok.  (e.g.\n *      http://foo.example.com/templates/**).\n *  - **RegExp** (*see caveat below*)\n *    - *Caveat*:  While regular expressions are powerful and offer great flexibility,  their syntax\n *      (and all the inevitable escaping) makes them *harder to maintain*.  It's easy to\n *      accidentally introduce a bug when one updates a complex expression (imho, all regexes should\n *      have good test coverage.).  For instance, the use of `.` in the regex is correct only in a\n *      small number of cases.  A `.` character in the regex used when matching the scheme or a\n *      subdomain could be matched against a `:` or literal `.` that was likely not intended.   It\n *      is highly recommended to use the string patterns and only fall back to regular expressions\n *      if they as a last resort.\n *    - The regular expression must be an instance of RegExp (i.e. not a string.)  It is\n *      matched against the **entire** *normalized / absolute URL* of the resource being tested\n *      (even when the RegExp did not have the `^` and `$` codes.)  In addition, any flags\n *      present on the RegExp (such as multiline, global, ignoreCase) are ignored.\n *    - If you are generating your JavaScript from some other templating engine (not\n *      recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),\n *      remember to escape your regular expression (and be aware that you might need more than\n *      one level of escaping depending on your templating engine and the way you interpolated\n *      the value.)  Do make use of your platform's escaping mechanism as it might be good\n *      enough before coding your own.  e.g. Ruby has\n *      [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)\n *      and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).\n *      Javascript lacks a similar built in function for escaping.  Take a look at Google\n *      Closure library's [goog.string.regExpEscape(s)](\n *      http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.\n *\n * ## Show me an example using SCE.\n *\n * <example module=\"mySceApp\" deps=\"angular-sanitize.js\">\n * <file name=\"index.html\">\n *   <div ng-controller=\"AppController as myCtrl\">\n *     <i ng-bind-html=\"myCtrl.explicitlyTrustedHtml\" id=\"explicitlyTrustedHtml\"></i><br><br>\n *     <b>User comments</b><br>\n *     By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when\n *     $sanitize is available.  If $sanitize isn't available, this results in an error instead of an\n *     exploit.\n *     <div class=\"well\">\n *       <div ng-repeat=\"userComment in myCtrl.userComments\">\n *         <b>{{userComment.name}}</b>:\n *         <span ng-bind-html=\"userComment.htmlComment\" class=\"htmlComment\"></span>\n *         <br>\n *       </div>\n *     </div>\n *   </div>\n * </file>\n *\n * <file name=\"script.js\">\n *   angular.module('mySceApp', ['ngSanitize'])\n *     .controller('AppController', ['$http', '$templateCache', '$sce',\n *       function($http, $templateCache, $sce) {\n *         var self = this;\n *         $http.get(\"test_data.json\", {cache: $templateCache}).success(function(userComments) {\n *           self.userComments = userComments;\n *         });\n *         self.explicitlyTrustedHtml = $sce.trustAsHtml(\n *             '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *             'sanitization.&quot;\">Hover over this text.</span>');\n *       }]);\n * </file>\n *\n * <file name=\"test_data.json\">\n * [\n *   { \"name\": \"Alice\",\n *     \"htmlComment\":\n *         \"<span onmouseover='this.textContent=\\\"PWN3D!\\\"'>Is <i>anyone</i> reading this?</span>\"\n *   },\n *   { \"name\": \"Bob\",\n *     \"htmlComment\": \"<i>Yes!</i>  Am I the only other one?\"\n *   }\n * ]\n * </file>\n *\n * <file name=\"protractor.js\" type=\"protractor\">\n *   describe('SCE doc demo', function() {\n *     it('should sanitize untrusted values', function() {\n *       expect(element.all(by.css('.htmlComment')).first().getInnerHtml())\n *           .toBe('<span>Is <i>anyone</i> reading this?</span>');\n *     });\n *\n *     it('should NOT sanitize explicitly trusted values', function() {\n *       expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(\n *           '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *           'sanitization.&quot;\">Hover over this text.</span>');\n *     });\n *   });\n * </file>\n * </example>\n *\n *\n *\n * ## Can I disable SCE completely?\n *\n * Yes, you can.  However, this is strongly discouraged.  SCE gives you a lot of security benefits\n * for little coding overhead.  It will be much harder to take an SCE disabled application and\n * either secure it on your own or enable SCE at a later stage.  It might make sense to disable SCE\n * for cases where you have a lot of existing code that was written before SCE was introduced and\n * you're migrating them a module at a time.\n *\n * That said, here's how you can completely disable SCE:\n *\n * ```\n * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {\n *   // Completely disable SCE.  For demonstration purposes only!\n *   // Do not use in new projects.\n *   $sceProvider.enabled(false);\n * });\n * ```\n *\n */\n/* jshint maxlen: 100 */\n\nfunction $SceProvider() {\n  var enabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $sceProvider#enabled\n   * @kind function\n   *\n   * @param {boolean=} value If provided, then enables/disables SCE.\n   * @return {boolean} true if SCE is enabled, false otherwise.\n   *\n   * @description\n   * Enables/disables SCE and returns the current value.\n   */\n  this.enabled = function(value) {\n    if (arguments.length) {\n      enabled = !!value;\n    }\n    return enabled;\n  };\n\n\n  /* Design notes on the default implementation for SCE.\n   *\n   * The API contract for the SCE delegate\n   * -------------------------------------\n   * The SCE delegate object must provide the following 3 methods:\n   *\n   * - trustAs(contextEnum, value)\n   *     This method is used to tell the SCE service that the provided value is OK to use in the\n   *     contexts specified by contextEnum.  It must return an object that will be accepted by\n   *     getTrusted() for a compatible contextEnum and return this value.\n   *\n   * - valueOf(value)\n   *     For values that were not produced by trustAs(), return them as is.  For values that were\n   *     produced by trustAs(), return the corresponding input value to trustAs.  Basically, if\n   *     trustAs is wrapping the given values into some type, this operation unwraps it when given\n   *     such a value.\n   *\n   * - getTrusted(contextEnum, value)\n   *     This function should return the a value that is safe to use in the context specified by\n   *     contextEnum or throw and exception otherwise.\n   *\n   * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be\n   * opaque or wrapped in some holder object.  That happens to be an implementation detail.  For\n   * instance, an implementation could maintain a registry of all trusted objects by context.  In\n   * such a case, trustAs() would return the same object that was passed in.  getTrusted() would\n   * return the same object passed in if it was found in the registry under a compatible context or\n   * throw an exception otherwise.  An implementation might only wrap values some of the time based\n   * on some criteria.  getTrusted() might return a value and not throw an exception for special\n   * constants or objects even if not wrapped.  All such implementations fulfill this contract.\n   *\n   *\n   * A note on the inheritance model for SCE contexts\n   * ------------------------------------------------\n   * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types.  This\n   * is purely an implementation details.\n   *\n   * The contract is simply this:\n   *\n   *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)\n   *     will also succeed.\n   *\n   * Inheritance happens to capture this in a natural way.  In some future, we\n   * may not use inheritance anymore.  That is OK because no code outside of\n   * sce.js and sceSpecs.js would need to be aware of this detail.\n   */\n\n  this.$get = ['$parse', '$sceDelegate', function(\n                $parse,   $sceDelegate) {\n    // Prereq: Ensure that we're not running in IE<11 quirks mode.  In that mode, IE < 11 allow\n    // the \"expression(javascript expression)\" syntax which is insecure.\n    if (enabled && msie < 8) {\n      throw $sceMinErr('iequirks',\n        'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +\n        'mode.  You can fix this by adding the text <!doctype html> to the top of your HTML ' +\n        'document.  See http://docs.angularjs.org/api/ng.$sce for more information.');\n    }\n\n    var sce = shallowCopy(SCE_CONTEXTS);\n\n    /**\n     * @ngdoc method\n     * @name $sce#isEnabled\n     * @kind function\n     *\n     * @return {Boolean} true if SCE is enabled, false otherwise.  If you want to set the value, you\n     * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.\n     *\n     * @description\n     * Returns a boolean indicating if SCE is enabled.\n     */\n    sce.isEnabled = function() {\n      return enabled;\n    };\n    sce.trustAs = $sceDelegate.trustAs;\n    sce.getTrusted = $sceDelegate.getTrusted;\n    sce.valueOf = $sceDelegate.valueOf;\n\n    if (!enabled) {\n      sce.trustAs = sce.getTrusted = function(type, value) { return value; };\n      sce.valueOf = identity;\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAs\n     *\n     * @description\n     * Converts Angular {@link guide/expression expression} into a function.  This is like {@link\n     * ng.$parse $parse} and is identical when the expression is a literal constant.  Otherwise, it\n     * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,\n     * *result*)}\n     *\n     * @param {string} type The kind of SCE context in which this result will be used.\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n    sce.parseAs = function sceParseAs(type, expr) {\n      var parsed = $parse(expr);\n      if (parsed.literal && parsed.constant) {\n        return parsed;\n      } else {\n        return $parse(expr, function(value) {\n          return sce.getTrusted(type, value);\n        });\n      }\n    };\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAs\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.  As such,\n     * returns an object that is trusted by angular for use in specified strict contextual\n     * escaping contexts (such as ng-bind-html, ng-include, any src attribute\n     * interpolation, any dom event binding attribute interpolation such as for onclick,  etc.)\n     * that uses the provided value.  See * {@link ng.$sce $sce} for enabling strict contextual\n     * escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resource_url, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsHtml(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml\n     *     $sce.getTrustedHtml(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl\n     *     $sce.getTrustedUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl\n     *     $sce.getTrustedResourceUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the return\n     *     value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsJs(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs\n     *     $sce.getTrustedJs(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrusted\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}.  As such,\n     * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the\n     * originally supplied value if the queried context type is a supertype of the created type.\n     * If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}\n     *                         call.\n     * @returns {*} The value the was originally provided to\n     *              {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.\n     *              Otherwise, throws an exception.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedHtml(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedCss\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedCss(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sceDelegate.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedJs\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedJs(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsHtml(expression string)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsCss\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsCss(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsResourceUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsJs(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    // Shorthand delegations.\n    var parse = sce.parseAs,\n        getTrusted = sce.getTrusted,\n        trustAs = sce.trustAs;\n\n    forEach(SCE_CONTEXTS, function(enumValue, name) {\n      var lName = lowercase(name);\n      sce[camelCase(\"parse_as_\" + lName)] = function(expr) {\n        return parse(enumValue, expr);\n      };\n      sce[camelCase(\"get_trusted_\" + lName)] = function(value) {\n        return getTrusted(enumValue, value);\n      };\n      sce[camelCase(\"trust_as_\" + lName)] = function(value) {\n        return trustAs(enumValue, value);\n      };\n    });\n\n    return sce;\n  }];\n}\n\n/**\n * !!! This is an undocumented \"private\" service !!!\n *\n * @name $sniffer\n * @requires $window\n * @requires $document\n *\n * @property {boolean} history Does the browser support html5 history api ?\n * @property {boolean} transitions Does the browser support CSS transition events ?\n * @property {boolean} animations Does the browser support CSS animation events ?\n *\n * @description\n * This is very simple implementation of testing browser's features.\n */\nfunction $SnifferProvider() {\n  this.$get = ['$window', '$document', function($window, $document) {\n    var eventSupport = {},\n        android =\n          int((/android (\\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),\n        boxee = /Boxee/i.test(($window.navigator || {}).userAgent),\n        document = $document[0] || {},\n        vendorPrefix,\n        vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,\n        bodyStyle = document.body && document.body.style,\n        transitions = false,\n        animations = false,\n        match;\n\n    if (bodyStyle) {\n      for (var prop in bodyStyle) {\n        if (match = vendorRegex.exec(prop)) {\n          vendorPrefix = match[0];\n          vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);\n          break;\n        }\n      }\n\n      if (!vendorPrefix) {\n        vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';\n      }\n\n      transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));\n      animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));\n\n      if (android && (!transitions ||  !animations)) {\n        transitions = isString(document.body.style.webkitTransition);\n        animations = isString(document.body.style.webkitAnimation);\n      }\n    }\n\n\n    return {\n      // Android has history.pushState, but it does not update location correctly\n      // so let's not use the history API at all.\n      // http://code.google.com/p/android/issues/detail?id=17471\n      // https://github.com/angular/angular.js/issues/904\n\n      // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has\n      // so let's not use the history API also\n      // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined\n      // jshint -W018\n      history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),\n      // jshint +W018\n      hasEvent: function(event) {\n        // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have\n        // it. In particular the event is not fired when backspace or delete key are pressed or\n        // when cut operation is performed.\n        // IE10+ implements 'input' event but it erroneously fires under various situations,\n        // e.g. when placeholder changes, or a form is focused.\n        if (event === 'input' && msie <= 11) return false;\n\n        if (isUndefined(eventSupport[event])) {\n          var divElm = document.createElement('div');\n          eventSupport[event] = 'on' + event in divElm;\n        }\n\n        return eventSupport[event];\n      },\n      csp: csp(),\n      vendorPrefix: vendorPrefix,\n      transitions: transitions,\n      animations: animations,\n      android: android\n    };\n  }];\n}\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc service\n * @name $templateRequest\n *\n * @description\n * The `$templateRequest` service downloads the provided template using `$http` and, upon success,\n * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data\n * of the HTTP request is empty, a `$compile` error will be thrown (the exception can be thwarted\n * by setting the 2nd parameter of the function to true).\n *\n * @param {string} tpl The HTTP request template URL\n * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty\n *\n * @return {Promise} the HTTP Promise for the given.\n *\n * @property {number} totalPendingRequests total amount of pending template requests being downloaded.\n */\nfunction $TemplateRequestProvider() {\n  this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {\n    function handleRequestFn(tpl, ignoreRequestError) {\n      handleRequestFn.totalPendingRequests++;\n\n      var transformResponse = $http.defaults && $http.defaults.transformResponse;\n\n      if (isArray(transformResponse)) {\n        transformResponse = transformResponse.filter(function(transformer) {\n          return transformer !== defaultHttpResponseTransform;\n        });\n      } else if (transformResponse === defaultHttpResponseTransform) {\n        transformResponse = null;\n      }\n\n      var httpOptions = {\n        cache: $templateCache,\n        transformResponse: transformResponse\n      };\n\n      return $http.get(tpl, httpOptions)\n        ['finally'](function() {\n          handleRequestFn.totalPendingRequests--;\n        })\n        .then(function(response) {\n          return response.data;\n        }, handleError);\n\n      function handleError(resp) {\n        if (!ignoreRequestError) {\n          throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);\n        }\n        return $q.reject(resp);\n      }\n    }\n\n    handleRequestFn.totalPendingRequests = 0;\n\n    return handleRequestFn;\n  }];\n}\n\nfunction $$TestabilityProvider() {\n  this.$get = ['$rootScope', '$browser', '$location',\n       function($rootScope,   $browser,   $location) {\n\n    /**\n     * @name $testability\n     *\n     * @description\n     * The private $$testability service provides a collection of methods for use when debugging\n     * or by automated test and debugging tools.\n     */\n    var testability = {};\n\n    /**\n     * @name $$testability#findBindings\n     *\n     * @description\n     * Returns an array of elements that are bound (via ng-bind or {{}})\n     * to expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The binding expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression. Filters and whitespace are ignored.\n     */\n    testability.findBindings = function(element, expression, opt_exactMatch) {\n      var bindings = element.getElementsByClassName('ng-binding');\n      var matches = [];\n      forEach(bindings, function(binding) {\n        var dataBinding = angular.element(binding).data('$binding');\n        if (dataBinding) {\n          forEach(dataBinding, function(bindingName) {\n            if (opt_exactMatch) {\n              var matcher = new RegExp('(^|\\\\s)' + escapeForRegexp(expression) + '(\\\\s|\\\\||$)');\n              if (matcher.test(bindingName)) {\n                matches.push(binding);\n              }\n            } else {\n              if (bindingName.indexOf(expression) != -1) {\n                matches.push(binding);\n              }\n            }\n          });\n        }\n      });\n      return matches;\n    };\n\n    /**\n     * @name $$testability#findModels\n     *\n     * @description\n     * Returns an array of elements that are two-way found via ng-model to\n     * expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The model expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression.\n     */\n    testability.findModels = function(element, expression, opt_exactMatch) {\n      var prefixes = ['ng-', 'data-ng-', 'ng\\\\:'];\n      for (var p = 0; p < prefixes.length; ++p) {\n        var attributeEquals = opt_exactMatch ? '=' : '*=';\n        var selector = '[' + prefixes[p] + 'model' + attributeEquals + '\"' + expression + '\"]';\n        var elements = element.querySelectorAll(selector);\n        if (elements.length) {\n          return elements;\n        }\n      }\n    };\n\n    /**\n     * @name $$testability#getLocation\n     *\n     * @description\n     * Shortcut for getting the location in a browser agnostic way. Returns\n     *     the path, search, and hash. (e.g. /path?a=b#hash)\n     */\n    testability.getLocation = function() {\n      return $location.url();\n    };\n\n    /**\n     * @name $$testability#setLocation\n     *\n     * @description\n     * Shortcut for navigating to a location without doing a full page reload.\n     *\n     * @param {string} url The location url (path, search and hash,\n     *     e.g. /path?a=b#hash) to go to.\n     */\n    testability.setLocation = function(url) {\n      if (url !== $location.url()) {\n        $location.url(url);\n        $rootScope.$digest();\n      }\n    };\n\n    /**\n     * @name $$testability#whenStable\n     *\n     * @description\n     * Calls the callback when $timeout and $http requests are completed.\n     *\n     * @param {function} callback\n     */\n    testability.whenStable = function(callback) {\n      $browser.notifyWhenNoOutstandingRequests(callback);\n    };\n\n    return testability;\n  }];\n}\n\nfunction $TimeoutProvider() {\n  this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',\n       function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {\n    var deferreds = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $timeout\n      *\n      * @description\n      * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch\n      * block and delegates any exceptions to\n      * {@link ng.$exceptionHandler $exceptionHandler} service.\n      *\n      * The return value of registering a timeout function is a promise, which will be resolved when\n      * the timeout is reached and the timeout function is executed.\n      *\n      * To cancel a timeout request, call `$timeout.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to\n      * synchronously flush the queue of deferred functions.\n      *\n      * @param {function()} fn A function, whose execution should be delayed.\n      * @param {number=} [delay=0] Delay in milliseconds.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this\n      *   promise will be resolved with is the return value of the `fn` function.\n      *\n      */\n    function timeout(fn, delay, invokeApply) {\n      var skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise,\n          timeoutId;\n\n      timeoutId = $browser.defer(function() {\n        try {\n          deferred.resolve(fn());\n        } catch (e) {\n          deferred.reject(e);\n          $exceptionHandler(e);\n        }\n        finally {\n          delete deferreds[promise.$$timeoutId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n      }, delay);\n\n      promise.$$timeoutId = timeoutId;\n      deferreds[timeoutId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $timeout#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`. As a result of this, the promise will be\n      * resolved with a rejection.\n      *\n      * @param {Promise=} promise Promise returned by the `$timeout` function.\n      * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n      *   canceled.\n      */\n    timeout.cancel = function(promise) {\n      if (promise && promise.$$timeoutId in deferreds) {\n        deferreds[promise.$$timeoutId].reject('canceled');\n        delete deferreds[promise.$$timeoutId];\n        return $browser.defer.cancel(promise.$$timeoutId);\n      }\n      return false;\n    };\n\n    return timeout;\n  }];\n}\n\n// NOTE:  The usage of window and document instead of $window and $document here is\n// deliberate.  This service depends on the specific behavior of anchor nodes created by the\n// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and\n// cause us to break tests.  In addition, when the browser resolves a URL for XHR, it\n// doesn't know about mocked locations and resolves URLs to the real document - which is\n// exactly the behavior needed here.  There is little value is mocking these out for this\n// service.\nvar urlParsingNode = document.createElement(\"a\");\nvar originUrl = urlResolve(window.location.href);\n\n\n/**\n *\n * Implementation Notes for non-IE browsers\n * ----------------------------------------\n * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,\n * results both in the normalizing and parsing of the URL.  Normalizing means that a relative\n * URL will be resolved into an absolute URL in the context of the application document.\n * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related\n * properties are all populated to reflect the normalized URL.  This approach has wide\n * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc.  See\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *\n * Implementation Notes for IE\n * ---------------------------\n * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other\n * browsers.  However, the parsed components will not be set if the URL assigned did not specify\n * them.  (e.g. if you assign a.href = \"foo\", then a.protocol, a.host, etc. will be empty.)  We\n * work around that by performing the parsing in a 2nd step by taking a previously normalized\n * URL (e.g. by assigning to a.href) and assigning it a.href again.  This correctly populates the\n * properties such as protocol, hostname, port, etc.\n *\n * IE7 does not normalize the URL when assigned to an anchor node.  (Apparently, it does, if one\n * uses the inner HTML approach to assign the URL as part of an HTML snippet -\n * http://stackoverflow.com/a/472729)  However, setting img[src] does normalize the URL.\n * Unfortunately, setting img[src] to something like \"javascript:foo\" on IE throws an exception.\n * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that\n * method and IE < 8 is unsupported.\n *\n * References:\n *   http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement\n *   http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *   http://url.spec.whatwg.org/#urlutils\n *   https://github.com/angular/angular.js/pull/2902\n *   http://james.padolsey.com/javascript/parsing-urls-with-the-dom/\n *\n * @kind function\n * @param {string} url The URL to be parsed.\n * @description Normalizes and parses a URL.\n * @returns {object} Returns the normalized URL as a dictionary.\n *\n *   | member name   | Description    |\n *   |---------------|----------------|\n *   | href          | A normalized version of the provided URL if it was not an absolute URL |\n *   | protocol      | The protocol including the trailing colon                              |\n *   | host          | The host and port (if the port is non-default) of the normalizedUrl    |\n *   | search        | The search params, minus the question mark                             |\n *   | hash          | The hash string, minus the hash symbol\n *   | hostname      | The hostname\n *   | port          | The port, without \":\"\n *   | pathname      | The pathname, beginning with \"/\"\n *\n */\nfunction urlResolve(url) {\n  var href = url;\n\n  if (msie) {\n    // Normalize before parse.  Refer Implementation Notes on why this is\n    // done in two steps on IE.\n    urlParsingNode.setAttribute(\"href\", href);\n    href = urlParsingNode.href;\n  }\n\n  urlParsingNode.setAttribute('href', href);\n\n  // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n  return {\n    href: urlParsingNode.href,\n    protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n    host: urlParsingNode.host,\n    search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n    hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n    hostname: urlParsingNode.hostname,\n    port: urlParsingNode.port,\n    pathname: (urlParsingNode.pathname.charAt(0) === '/')\n      ? urlParsingNode.pathname\n      : '/' + urlParsingNode.pathname\n  };\n}\n\n/**\n * Parse a request URL and determine whether this is a same-origin request as the application document.\n *\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\n * or a parsed URL object.\n * @returns {boolean} Whether the request is for the same origin as the application document.\n */\nfunction urlIsSameOrigin(requestUrl) {\n  var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;\n  return (parsed.protocol === originUrl.protocol &&\n          parsed.host === originUrl.host);\n}\n\n/**\n * @ngdoc service\n * @name $window\n *\n * @description\n * A reference to the browser's `window` object. While `window`\n * is globally available in JavaScript, it causes testability problems, because\n * it is a global variable. In angular we always refer to it through the\n * `$window` service, so it may be overridden, removed or mocked for testing.\n *\n * Expressions, like the one defined for the `ngClick` directive in the example\n * below, are evaluated with respect to the current scope.  Therefore, there is\n * no risk of inadvertently coding in a dependency on a global value in such an\n * expression.\n *\n * @example\n   <example module=\"windowExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('windowExample', [])\n           .controller('ExampleController', ['$scope', '$window', function($scope, $window) {\n             $scope.greeting = 'Hello, World!';\n             $scope.doGreeting = function(greeting) {\n               $window.alert(greeting);\n             };\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"text\" ng-model=\"greeting\" />\n         <button ng-click=\"doGreeting(greeting)\">ALERT</button>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n      it('should display the greeting in the input box', function() {\n       element(by.model('greeting')).sendKeys('Hello, E2E Tests');\n       // If we click the button it will block the test runner\n       // element(':button').click();\n      });\n     </file>\n   </example>\n */\nfunction $WindowProvider() {\n  this.$get = valueFn(window);\n}\n\n/* global currencyFilter: true,\n dateFilter: true,\n filterFilter: true,\n jsonFilter: true,\n limitToFilter: true,\n lowercaseFilter: true,\n numberFilter: true,\n orderByFilter: true,\n uppercaseFilter: true,\n */\n\n/**\n * @ngdoc provider\n * @name $filterProvider\n * @description\n *\n * Filters are just functions which transform input to an output. However filters need to be\n * Dependency Injected. To achieve this a filter definition consists of a factory function which is\n * annotated with dependencies and is responsible for creating a filter function.\n *\n * ```js\n *   // Filter registration\n *   function MyModule($provide, $filterProvider) {\n *     // create a service to demonstrate injection (not always needed)\n *     $provide.value('greet', function(name){\n *       return 'Hello ' + name + '!';\n *     });\n *\n *     // register a filter factory which uses the\n *     // greet service to demonstrate DI.\n *     $filterProvider.register('greet', function(greet){\n *       // return the filter function which uses the greet service\n *       // to generate salutation\n *       return function(text) {\n *         // filters need to be forgiving so check input validity\n *         return text && greet(text) || text;\n *       };\n *     });\n *   }\n * ```\n *\n * The filter function is registered with the `$injector` under the filter name suffix with\n * `Filter`.\n *\n * ```js\n *   it('should be the same instance', inject(\n *     function($filterProvider) {\n *       $filterProvider.register('reverse', function(){\n *         return ...;\n *       });\n *     },\n *     function($filter, reverseFilter) {\n *       expect($filter('reverse')).toBe(reverseFilter);\n *     });\n * ```\n *\n *\n * For more information about how angular filters work, and how to create your own filters, see\n * {@link guide/filter Filters} in the Angular Developer Guide.\n */\n\n/**\n * @ngdoc service\n * @name $filter\n * @kind function\n * @description\n * Filters are used for formatting data displayed to the user.\n *\n * The general syntax in templates is as follows:\n *\n *         {{ expression [| filter_name[:parameter_value] ... ] }}\n *\n * @param {String} name Name of the filter function to retrieve\n * @return {Function} the filter function\n * @example\n   <example name=\"$filter\" module=\"filterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"MainCtrl\">\n        <h3>{{ originalText }}</h3>\n        <h3>{{ filteredText }}</h3>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n      angular.module('filterExample', [])\n      .controller('MainCtrl', function($scope, $filter) {\n        $scope.originalText = 'hello';\n        $scope.filteredText = $filter('uppercase')($scope.originalText);\n      });\n     </file>\n   </example>\n  */\n$FilterProvider.$inject = ['$provide'];\nfunction $FilterProvider($provide) {\n  var suffix = 'Filter';\n\n  /**\n   * @ngdoc method\n   * @name $filterProvider#register\n   * @param {string|Object} name Name of the filter function, or an object map of filters where\n   *    the keys are the filter names and the values are the filter factories.\n   * @returns {Object} Registered filter instance, or if a map of filters was provided then a map\n   *    of the registered filter instances.\n   */\n  function register(name, factory) {\n    if (isObject(name)) {\n      var filters = {};\n      forEach(name, function(filter, key) {\n        filters[key] = register(key, filter);\n      });\n      return filters;\n    } else {\n      return $provide.factory(name + suffix, factory);\n    }\n  }\n  this.register = register;\n\n  this.$get = ['$injector', function($injector) {\n    return function(name) {\n      return $injector.get(name + suffix);\n    };\n  }];\n\n  ////////////////////////////////////////\n\n  /* global\n    currencyFilter: false,\n    dateFilter: false,\n    filterFilter: false,\n    jsonFilter: false,\n    limitToFilter: false,\n    lowercaseFilter: false,\n    numberFilter: false,\n    orderByFilter: false,\n    uppercaseFilter: false,\n  */\n\n  register('currency', currencyFilter);\n  register('date', dateFilter);\n  register('filter', filterFilter);\n  register('json', jsonFilter);\n  register('limitTo', limitToFilter);\n  register('lowercase', lowercaseFilter);\n  register('number', numberFilter);\n  register('orderBy', orderByFilter);\n  register('uppercase', uppercaseFilter);\n}\n\n/**\n * @ngdoc filter\n * @name filter\n * @kind function\n *\n * @description\n * Selects a subset of items from `array` and returns it as a new array.\n *\n * @param {Array} array The source array.\n * @param {string|Object|function()} expression The predicate to be used for selecting items from\n *   `array`.\n *\n *   Can be one of:\n *\n *   - `string`: The string is used for matching against the contents of the `array`. All strings or\n *     objects with string properties in `array` that match this string will be returned. This also\n *     applies to nested object properties.\n *     The predicate can be negated by prefixing the string with `!`.\n *\n *   - `Object`: A pattern object can be used to filter specific properties on objects contained\n *     by `array`. For example `{name:\"M\", phone:\"1\"}` predicate will return an array of items\n *     which have property `name` containing \"M\" and property `phone` containing \"1\". A special\n *     property name `$` can be used (as in `{$:\"text\"}`) to accept a match against any\n *     property of the object or its nested object properties. That's equivalent to the simple\n *     substring match with a `string` as described above. The predicate can be negated by prefixing\n *     the string with `!`.\n *     For example `{name: \"!M\"}` predicate will return an array of items which have property `name`\n *     not containing \"M\".\n *\n *     Note that a named property will match properties on the same level only, while the special\n *     `$` property will match properties on the same level or deeper. E.g. an array item like\n *     `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but\n *     **will** be matched by `{$: 'John'}`.\n *\n *   - `function(value, index)`: A predicate function can be used to write arbitrary filters. The\n *     function is called for each element of `array`. The final result is an array of those\n *     elements that the predicate returned true for.\n *\n * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in\n *     determining if the expected value (from the filter expression) and actual value (from\n *     the object in the array) should be considered a match.\n *\n *   Can be one of:\n *\n *   - `function(actual, expected)`:\n *     The function will be given the object value and the predicate value to compare and\n *     should return true if both values should be considered equal.\n *\n *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.\n *     This is essentially strict comparison of expected and actual.\n *\n *   - `false|undefined`: A short hand for a function which will look for a substring match in case\n *     insensitive way.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <div ng-init=\"friends = [{name:'John', phone:'555-1276'},\n                                {name:'Mary', phone:'800-BIG-MARY'},\n                                {name:'Mike', phone:'555-4321'},\n                                {name:'Adam', phone:'555-5678'},\n                                {name:'Julie', phone:'555-8765'},\n                                {name:'Juliette', phone:'555-5678'}]\"></div>\n\n       Search: <input ng-model=\"searchText\">\n       <table id=\"searchTextResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friend in friends | filter:searchText\">\n           <td>{{friend.name}}</td>\n           <td>{{friend.phone}}</td>\n         </tr>\n       </table>\n       <hr>\n       Any: <input ng-model=\"search.$\"> <br>\n       Name only <input ng-model=\"search.name\"><br>\n       Phone only <input ng-model=\"search.phone\"><br>\n       Equality <input type=\"checkbox\" ng-model=\"strict\"><br>\n       <table id=\"searchObjResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friendObj in friends | filter:search:strict\">\n           <td>{{friendObj.name}}</td>\n           <td>{{friendObj.phone}}</td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var expectFriendNames = function(expectedNames, key) {\n         element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {\n           arr.forEach(function(wd, i) {\n             expect(wd.getText()).toMatch(expectedNames[i]);\n           });\n         });\n       };\n\n       it('should search across all fields when filtering with a string', function() {\n         var searchText = element(by.model('searchText'));\n         searchText.clear();\n         searchText.sendKeys('m');\n         expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');\n\n         searchText.clear();\n         searchText.sendKeys('76');\n         expectFriendNames(['John', 'Julie'], 'friend');\n       });\n\n       it('should search in specific fields when filtering with a predicate object', function() {\n         var searchAny = element(by.model('search.$'));\n         searchAny.clear();\n         searchAny.sendKeys('i');\n         expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');\n       });\n       it('should use a equal comparison when comparator is true', function() {\n         var searchName = element(by.model('search.name'));\n         var strict = element(by.model('strict'));\n         searchName.clear();\n         searchName.sendKeys('Julie');\n         strict.click();\n         expectFriendNames(['Julie'], 'friendObj');\n       });\n     </file>\n   </example>\n */\nfunction filterFilter() {\n  return function(array, expression, comparator) {\n    if (!isArray(array)) return array;\n\n    var predicateFn;\n    var matchAgainstAnyProp;\n\n    switch (typeof expression) {\n      case 'function':\n        predicateFn = expression;\n        break;\n      case 'boolean':\n      case 'number':\n      case 'string':\n        matchAgainstAnyProp = true;\n        //jshint -W086\n      case 'object':\n        //jshint +W086\n        predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);\n        break;\n      default:\n        return array;\n    }\n\n    return array.filter(predicateFn);\n  };\n}\n\n// Helper functions for `filterFilter`\nfunction createPredicateFn(expression, comparator, matchAgainstAnyProp) {\n  var shouldMatchPrimitives = isObject(expression) && ('$' in expression);\n  var predicateFn;\n\n  if (comparator === true) {\n    comparator = equals;\n  } else if (!isFunction(comparator)) {\n    comparator = function(actual, expected) {\n      if (isObject(actual) || isObject(expected)) {\n        // Prevent an object to be considered equal to a string like `'[object'`\n        return false;\n      }\n\n      actual = lowercase('' + actual);\n      expected = lowercase('' + expected);\n      return actual.indexOf(expected) !== -1;\n    };\n  }\n\n  predicateFn = function(item) {\n    if (shouldMatchPrimitives && !isObject(item)) {\n      return deepCompare(item, expression.$, comparator, false);\n    }\n    return deepCompare(item, expression, comparator, matchAgainstAnyProp);\n  };\n\n  return predicateFn;\n}\n\nfunction deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {\n  var actualType = typeof actual;\n  var expectedType = typeof expected;\n\n  if ((expectedType === 'string') && (expected.charAt(0) === '!')) {\n    return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);\n  } else if (isArray(actual)) {\n    // In case `actual` is an array, consider it a match\n    // if ANY of it's items matches `expected`\n    return actual.some(function(item) {\n      return deepCompare(item, expected, comparator, matchAgainstAnyProp);\n    });\n  }\n\n  switch (actualType) {\n    case 'object':\n      var key;\n      if (matchAgainstAnyProp) {\n        for (key in actual) {\n          if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {\n            return true;\n          }\n        }\n        return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);\n      } else if (expectedType === 'object') {\n        for (key in expected) {\n          var expectedVal = expected[key];\n          if (isFunction(expectedVal)) {\n            continue;\n          }\n\n          var matchAnyProperty = key === '$';\n          var actualVal = matchAnyProperty ? actual : actual[key];\n          if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {\n            return false;\n          }\n        }\n        return true;\n      } else {\n        return comparator(actual, expected);\n      }\n      break;\n    case 'function':\n      return false;\n    default:\n      return comparator(actual, expected);\n  }\n}\n\n/**\n * @ngdoc filter\n * @name currency\n * @kind function\n *\n * @description\n * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default\n * symbol for current locale is used.\n *\n * @param {number} amount Input to filter.\n * @param {string=} symbol Currency symbol or identifier to be displayed.\n * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\n * @returns {string} Formatted number.\n *\n *\n * @example\n   <example module=\"currencyExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('currencyExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.amount = 1234.56;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"number\" ng-model=\"amount\"> <br>\n         default currency symbol ($): <span id=\"currency-default\">{{amount | currency}}</span><br>\n         custom currency identifier (USD$): <span id=\"currency-custom\">{{amount | currency:\"USD$\"}}</span>\n         no fractions (0): <span id=\"currency-no-fractions\">{{amount | currency:\"USD$\":0}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should init with 1234.56', function() {\n         expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');\n         expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');\n       });\n       it('should update', function() {\n         if (browser.params.browser == 'safari') {\n           // Safari does not understand the minus key. See\n           // https://github.com/angular/protractor/issues/481\n           return;\n         }\n         element(by.model('amount')).clear();\n         element(by.model('amount')).sendKeys('-1234');\n         expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');\n         expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');\n       });\n     </file>\n   </example>\n */\ncurrencyFilter.$inject = ['$locale'];\nfunction currencyFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(amount, currencySymbol, fractionSize) {\n    if (isUndefined(currencySymbol)) {\n      currencySymbol = formats.CURRENCY_SYM;\n    }\n\n    if (isUndefined(fractionSize)) {\n      fractionSize = formats.PATTERNS[1].maxFrac;\n    }\n\n    // if null or undefined pass it through\n    return (amount == null)\n        ? amount\n        : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).\n            replace(/\\u00A4/g, currencySymbol);\n  };\n}\n\n/**\n * @ngdoc filter\n * @name number\n * @kind function\n *\n * @description\n * Formats a number as text.\n *\n * If the input is not a number an empty string is returned.\n *\n * @param {number|string} number Number to format.\n * @param {(number|string)=} fractionSize Number of decimal places to round the number to.\n * If this is not provided then the fraction size is computed from the current locale's number\n * formatting pattern. In the case of the default locale, it will be 3.\n * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.\n *\n * @example\n   <example module=\"numberFilterExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('numberFilterExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.val = 1234.56789;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         Enter number: <input ng-model='val'><br>\n         Default formatting: <span id='number-default'>{{val | number}}</span><br>\n         No fractions: <span>{{val | number:0}}</span><br>\n         Negative number: <span>{{-val | number:4}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format numbers', function() {\n         expect(element(by.id('number-default')).getText()).toBe('1,234.568');\n         expect(element(by.binding('val | number:0')).getText()).toBe('1,235');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');\n       });\n\n       it('should update', function() {\n         element(by.model('val')).clear();\n         element(by.model('val')).sendKeys('3374.333');\n         expect(element(by.id('number-default')).getText()).toBe('3,374.333');\n         expect(element(by.binding('val | number:0')).getText()).toBe('3,374');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');\n      });\n     </file>\n   </example>\n */\n\n\nnumberFilter.$inject = ['$locale'];\nfunction numberFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(number, fractionSize) {\n\n    // if null or undefined pass it through\n    return (number == null)\n        ? number\n        : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,\n                       fractionSize);\n  };\n}\n\nvar DECIMAL_SEP = '.';\nfunction formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {\n  if (!isFinite(number) || isObject(number)) return '';\n\n  var isNegative = number < 0;\n  number = Math.abs(number);\n  var numStr = number + '',\n      formatedText = '',\n      parts = [];\n\n  var hasExponent = false;\n  if (numStr.indexOf('e') !== -1) {\n    var match = numStr.match(/([\\d\\.]+)e(-?)(\\d+)/);\n    if (match && match[2] == '-' && match[3] > fractionSize + 1) {\n      number = 0;\n    } else {\n      formatedText = numStr;\n      hasExponent = true;\n    }\n  }\n\n  if (!hasExponent) {\n    var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;\n\n    // determine fractionSize if it is not specified\n    if (isUndefined(fractionSize)) {\n      fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);\n    }\n\n    // safely round numbers in JS without hitting imprecisions of floating-point arithmetics\n    // inspired by:\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\n    number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);\n\n    var fraction = ('' + number).split(DECIMAL_SEP);\n    var whole = fraction[0];\n    fraction = fraction[1] || '';\n\n    var i, pos = 0,\n        lgroup = pattern.lgSize,\n        group = pattern.gSize;\n\n    if (whole.length >= (lgroup + group)) {\n      pos = whole.length - lgroup;\n      for (i = 0; i < pos; i++) {\n        if ((pos - i) % group === 0 && i !== 0) {\n          formatedText += groupSep;\n        }\n        formatedText += whole.charAt(i);\n      }\n    }\n\n    for (i = pos; i < whole.length; i++) {\n      if ((whole.length - i) % lgroup === 0 && i !== 0) {\n        formatedText += groupSep;\n      }\n      formatedText += whole.charAt(i);\n    }\n\n    // format fraction part.\n    while (fraction.length < fractionSize) {\n      fraction += '0';\n    }\n\n    if (fractionSize && fractionSize !== \"0\") formatedText += decimalSep + fraction.substr(0, fractionSize);\n  } else {\n    if (fractionSize > 0 && number < 1) {\n      formatedText = number.toFixed(fractionSize);\n      number = parseFloat(formatedText);\n    }\n  }\n\n  if (number === 0) {\n    isNegative = false;\n  }\n\n  parts.push(isNegative ? pattern.negPre : pattern.posPre,\n             formatedText,\n             isNegative ? pattern.negSuf : pattern.posSuf);\n  return parts.join('');\n}\n\nfunction padNumber(num, digits, trim) {\n  var neg = '';\n  if (num < 0) {\n    neg =  '-';\n    num = -num;\n  }\n  num = '' + num;\n  while (num.length < digits) num = '0' + num;\n  if (trim)\n    num = num.substr(num.length - digits);\n  return neg + num;\n}\n\n\nfunction dateGetter(name, size, offset, trim) {\n  offset = offset || 0;\n  return function(date) {\n    var value = date['get' + name]();\n    if (offset > 0 || value > -offset)\n      value += offset;\n    if (value === 0 && offset == -12) value = 12;\n    return padNumber(value, size, trim);\n  };\n}\n\nfunction dateStrGetter(name, shortForm) {\n  return function(date, formats) {\n    var value = date['get' + name]();\n    var get = uppercase(shortForm ? ('SHORT' + name) : name);\n\n    return formats[get][value];\n  };\n}\n\nfunction timeZoneGetter(date) {\n  var zone = -1 * date.getTimezoneOffset();\n  var paddedZone = (zone >= 0) ? \"+\" : \"\";\n\n  paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +\n                padNumber(Math.abs(zone % 60), 2);\n\n  return paddedZone;\n}\n\nfunction getFirstThursdayOfYear(year) {\n    // 0 = index of January\n    var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();\n    // 4 = index of Thursday (+1 to account for 1st = 5)\n    // 11 = index of *next* Thursday (+1 account for 1st = 12)\n    return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);\n}\n\nfunction getThursdayThisWeek(datetime) {\n    return new Date(datetime.getFullYear(), datetime.getMonth(),\n      // 4 = index of Thursday\n      datetime.getDate() + (4 - datetime.getDay()));\n}\n\nfunction weekGetter(size) {\n   return function(date) {\n      var firstThurs = getFirstThursdayOfYear(date.getFullYear()),\n         thisThurs = getThursdayThisWeek(date);\n\n      var diff = +thisThurs - +firstThurs,\n         result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week\n\n      return padNumber(result, size);\n   };\n}\n\nfunction ampmGetter(date, formats) {\n  return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];\n}\n\nvar DATE_FORMATS = {\n  yyyy: dateGetter('FullYear', 4),\n    yy: dateGetter('FullYear', 2, 0, true),\n     y: dateGetter('FullYear', 1),\n  MMMM: dateStrGetter('Month'),\n   MMM: dateStrGetter('Month', true),\n    MM: dateGetter('Month', 2, 1),\n     M: dateGetter('Month', 1, 1),\n    dd: dateGetter('Date', 2),\n     d: dateGetter('Date', 1),\n    HH: dateGetter('Hours', 2),\n     H: dateGetter('Hours', 1),\n    hh: dateGetter('Hours', 2, -12),\n     h: dateGetter('Hours', 1, -12),\n    mm: dateGetter('Minutes', 2),\n     m: dateGetter('Minutes', 1),\n    ss: dateGetter('Seconds', 2),\n     s: dateGetter('Seconds', 1),\n     // while ISO 8601 requires fractions to be prefixed with `.` or `,`\n     // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions\n   sss: dateGetter('Milliseconds', 3),\n  EEEE: dateStrGetter('Day'),\n   EEE: dateStrGetter('Day', true),\n     a: ampmGetter,\n     Z: timeZoneGetter,\n    ww: weekGetter(2),\n     w: weekGetter(1)\n};\n\nvar DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,\n    NUMBER_STRING = /^\\-?\\d+$/;\n\n/**\n * @ngdoc filter\n * @name date\n * @kind function\n *\n * @description\n *   Formats `date` to a string based on the requested `format`.\n *\n *   `format` string can be composed of the following elements:\n *\n *   * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)\n *   * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)\n *   * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)\n *   * `'MMMM'`: Month in year (January-December)\n *   * `'MMM'`: Month in year (Jan-Dec)\n *   * `'MM'`: Month in year, padded (01-12)\n *   * `'M'`: Month in year (1-12)\n *   * `'dd'`: Day in month, padded (01-31)\n *   * `'d'`: Day in month (1-31)\n *   * `'EEEE'`: Day in Week,(Sunday-Saturday)\n *   * `'EEE'`: Day in Week, (Sun-Sat)\n *   * `'HH'`: Hour in day, padded (00-23)\n *   * `'H'`: Hour in day (0-23)\n *   * `'hh'`: Hour in AM/PM, padded (01-12)\n *   * `'h'`: Hour in AM/PM, (1-12)\n *   * `'mm'`: Minute in hour, padded (00-59)\n *   * `'m'`: Minute in hour (0-59)\n *   * `'ss'`: Second in minute, padded (00-59)\n *   * `'s'`: Second in minute (0-59)\n *   * `'sss'`: Millisecond in second, padded (000-999)\n *   * `'a'`: AM/PM marker\n *   * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)\n *   * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year\n *   * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year\n *\n *   `format` string can also be one of the following predefined\n *   {@link guide/i18n localizable formats}:\n *\n *   * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale\n *     (e.g. Sep 3, 2010 12:05:08 PM)\n *   * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US  locale (e.g. 9/3/10 12:05 PM)\n *   * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US  locale\n *     (e.g. Friday, September 3, 2010)\n *   * `'longDate'`: equivalent to `'MMMM d, y'` for en_US  locale (e.g. September 3, 2010)\n *   * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US  locale (e.g. Sep 3, 2010)\n *   * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)\n *   * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)\n *   * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)\n *\n *   `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.\n *   `\"h 'in the morning'\"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence\n *   (e.g. `\"h 'o''clock'\"`).\n *\n * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or\n *    number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its\n *    shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is\n *    specified in the string input, the time is considered to be in the local timezone.\n * @param {string=} format Formatting rules (see Description). If not specified,\n *    `mediumDate` is used.\n * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.\n *    If not specified, the timezone of the browser will be used.\n * @returns {string} Formatted string or the input if input is not recognized as date/millis.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:\n           <span>{{1288323623006 | date:'medium'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:\n          <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:\n          <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:\"MM/dd/yyyy 'at' h:mma\"}}</span>:\n          <span>{{'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"}}</span><br>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format date', function() {\n         expect(element(by.binding(\"1288323623006 | date:'medium'\")).getText()).\n            toMatch(/Oct 2\\d, 2010 \\d{1,2}:\\d{2}:\\d{2} (AM|PM)/);\n         expect(element(by.binding(\"1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'\")).getText()).\n            toMatch(/2010\\-10\\-2\\d \\d{2}:\\d{2}:\\d{2} (\\-|\\+)?\\d{4}/);\n         expect(element(by.binding(\"'1288323623006' | date:'MM/dd/yyyy @ h:mma'\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 @ \\d{1,2}:\\d{2}(AM|PM)/);\n         expect(element(by.binding(\"'1288323623006' | date:\\\"MM/dd/yyyy 'at' h:mma\\\"\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 at \\d{1,2}:\\d{2}(AM|PM)/);\n       });\n     </file>\n   </example>\n */\ndateFilter.$inject = ['$locale'];\nfunction dateFilter($locale) {\n\n\n  var R_ISO8601_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:\\.(\\d+))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d))?)?$/;\n                     // 1        2       3         4          5          6          7          8  9     10      11\n  function jsonStringToDate(string) {\n    var match;\n    if (match = string.match(R_ISO8601_STR)) {\n      var date = new Date(0),\n          tzHour = 0,\n          tzMin  = 0,\n          dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,\n          timeSetter = match[8] ? date.setUTCHours : date.setHours;\n\n      if (match[9]) {\n        tzHour = int(match[9] + match[10]);\n        tzMin = int(match[9] + match[11]);\n      }\n      dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));\n      var h = int(match[4] || 0) - tzHour;\n      var m = int(match[5] || 0) - tzMin;\n      var s = int(match[6] || 0);\n      var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);\n      timeSetter.call(date, h, m, s, ms);\n      return date;\n    }\n    return string;\n  }\n\n\n  return function(date, format, timezone) {\n    var text = '',\n        parts = [],\n        fn, match;\n\n    format = format || 'mediumDate';\n    format = $locale.DATETIME_FORMATS[format] || format;\n    if (isString(date)) {\n      date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);\n    }\n\n    if (isNumber(date)) {\n      date = new Date(date);\n    }\n\n    if (!isDate(date)) {\n      return date;\n    }\n\n    while (format) {\n      match = DATE_FORMATS_SPLIT.exec(format);\n      if (match) {\n        parts = concat(parts, match, 1);\n        format = parts.pop();\n      } else {\n        parts.push(format);\n        format = null;\n      }\n    }\n\n    if (timezone && timezone === 'UTC') {\n      date = new Date(date.getTime());\n      date.setMinutes(date.getMinutes() + date.getTimezoneOffset());\n    }\n    forEach(parts, function(value) {\n      fn = DATE_FORMATS[value];\n      text += fn ? fn(date, $locale.DATETIME_FORMATS)\n                 : value.replace(/(^'|'$)/g, '').replace(/''/g, \"'\");\n    });\n\n    return text;\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name json\n * @kind function\n *\n * @description\n *   Allows you to convert a JavaScript object into JSON string.\n *\n *   This filter is mostly useful for debugging. When using the double curly {{value}} notation\n *   the binding is automatically converted to JSON.\n *\n * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.\n * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.\n * @returns {string} JSON string.\n *\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <pre id=\"default-spacing\">{{ {'name':'value'} | json }}</pre>\n       <pre id=\"custom-spacing\">{{ {'name':'value'} | json:4 }}</pre>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should jsonify filtered objects', function() {\n         expect(element(by.id('default-spacing')).getText()).toMatch(/\\{\\n  \"name\": ?\"value\"\\n}/);\n         expect(element(by.id('custom-spacing')).getText()).toMatch(/\\{\\n    \"name\": ?\"value\"\\n}/);\n       });\n     </file>\n   </example>\n *\n */\nfunction jsonFilter() {\n  return function(object, spacing) {\n    if (isUndefined(spacing)) {\n        spacing = 2;\n    }\n    return toJson(object, spacing);\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name lowercase\n * @kind function\n * @description\n * Converts string to lowercase.\n * @see angular.lowercase\n */\nvar lowercaseFilter = valueFn(lowercase);\n\n\n/**\n * @ngdoc filter\n * @name uppercase\n * @kind function\n * @description\n * Converts string to uppercase.\n * @see angular.uppercase\n */\nvar uppercaseFilter = valueFn(uppercase);\n\n/**\n * @ngdoc filter\n * @name limitTo\n * @kind function\n *\n * @description\n * Creates a new array or string containing only a specified number of elements. The elements\n * are taken from either the beginning or the end of the source array, string or number, as specified by\n * the value and sign (positive or negative) of `limit`. If a number is used as input, it is\n * converted to a string.\n *\n * @param {Array|string|number} input Source array, string or number to be limited.\n * @param {string|number} limit The length of the returned array or string. If the `limit` number\n *     is positive, `limit` number of items from the beginning of the source array/string are copied.\n *     If the number is negative, `limit` number  of items from the end of the source array/string\n *     are copied. The `limit` will be trimmed if it exceeds `array.length`\n * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array\n *     had less than `limit` elements.\n *\n * @example\n   <example module=\"limitToExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('limitToExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.numbers = [1,2,3,4,5,6,7,8,9];\n             $scope.letters = \"abcdefghi\";\n             $scope.longNumber = 2345432342;\n             $scope.numLimit = 3;\n             $scope.letterLimit = 3;\n             $scope.longNumberLimit = 3;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         Limit {{numbers}} to: <input type=\"number\" step=\"1\" ng-model=\"numLimit\">\n         <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>\n         Limit {{letters}} to: <input type=\"number\" step=\"1\" ng-model=\"letterLimit\">\n         <p>Output letters: {{ letters | limitTo:letterLimit }}</p>\n         Limit {{longNumber}} to: <input type=\"number\" step=\"1\" ng-model=\"longNumberLimit\">\n         <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var numLimitInput = element(by.model('numLimit'));\n       var letterLimitInput = element(by.model('letterLimit'));\n       var longNumberLimitInput = element(by.model('longNumberLimit'));\n       var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));\n       var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));\n       var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));\n\n       it('should limit the number array to first three items', function() {\n         expect(numLimitInput.getAttribute('value')).toBe('3');\n         expect(letterLimitInput.getAttribute('value')).toBe('3');\n         expect(longNumberLimitInput.getAttribute('value')).toBe('3');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abc');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 234');\n       });\n\n       // There is a bug in safari and protractor that doesn't like the minus key\n       // it('should update the output when -3 is entered', function() {\n       //   numLimitInput.clear();\n       //   numLimitInput.sendKeys('-3');\n       //   letterLimitInput.clear();\n       //   letterLimitInput.sendKeys('-3');\n       //   longNumberLimitInput.clear();\n       //   longNumberLimitInput.sendKeys('-3');\n       //   expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');\n       //   expect(limitedLetters.getText()).toEqual('Output letters: ghi');\n       //   expect(limitedLongNumber.getText()).toEqual('Output long number: 342');\n       // });\n\n       it('should not exceed the maximum size of input array', function() {\n         numLimitInput.clear();\n         numLimitInput.sendKeys('100');\n         letterLimitInput.clear();\n         letterLimitInput.sendKeys('100');\n         longNumberLimitInput.clear();\n         longNumberLimitInput.sendKeys('100');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');\n       });\n     </file>\n   </example>\n*/\nfunction limitToFilter() {\n  return function(input, limit) {\n    if (isNumber(input)) input = input.toString();\n    if (!isArray(input) && !isString(input)) return input;\n\n    if (Math.abs(Number(limit)) === Infinity) {\n      limit = Number(limit);\n    } else {\n      limit = int(limit);\n    }\n\n    //NaN check on limit\n    if (limit) {\n      return limit > 0 ? input.slice(0, limit) : input.slice(limit);\n    } else {\n      return isString(input) ? \"\" : [];\n    }\n  };\n}\n\n/**\n * @ngdoc filter\n * @name orderBy\n * @kind function\n *\n * @description\n * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically\n * for strings and numerically for numbers. Note: if you notice numbers are not being sorted\n * correctly, make sure they are actually being saved as numbers and not strings.\n *\n * @param {Array} array The array to sort.\n * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be\n *    used by the comparator to determine the order of elements.\n *\n *    Can be one of:\n *\n *    - `function`: Getter function. The result of this function will be sorted using the\n *      `<`, `=`, `>` operator.\n *    - `string`: An Angular expression. The result of this expression is used to compare elements\n *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by\n *      3 first characters of a property called `name`). The result of a constant expression\n *      is interpreted as a property name to be used in comparisons (for example `\"special name\"`\n *      to sort object by the value of their `special name` property). An expression can be\n *      optionally prefixed with `+` or `-` to control ascending or descending sort order\n *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array\n *      element itself is used to compare where sorting.\n *    - `Array`: An array of function or string predicates. The first predicate in the array\n *      is used for sorting, but when two items are equivalent, the next predicate is used.\n *\n *    If the predicate is missing or empty then it defaults to `'+'`.\n *\n * @param {boolean=} reverse Reverse the order of the array.\n * @returns {Array} Sorted copy of the source array.\n *\n * @example\n   <example module=\"orderByExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('orderByExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.friends =\n                 [{name:'John', phone:'555-1212', age:10},\n                  {name:'Mary', phone:'555-9876', age:19},\n                  {name:'Mike', phone:'555-4321', age:21},\n                  {name:'Adam', phone:'555-5678', age:35},\n                  {name:'Julie', phone:'555-8765', age:29}];\n             $scope.predicate = '-age';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>\n         <hr/>\n         [ <a href=\"\" ng-click=\"predicate=''\">unsorted</a> ]\n         <table class=\"friend\">\n           <tr>\n             <th><a href=\"\" ng-click=\"predicate = 'name'; reverse=false\">Name</a>\n                 (<a href=\"\" ng-click=\"predicate = '-name'; reverse=false\">^</a>)</th>\n             <th><a href=\"\" ng-click=\"predicate = 'phone'; reverse=!reverse\">Phone Number</a></th>\n             <th><a href=\"\" ng-click=\"predicate = 'age'; reverse=!reverse\">Age</a></th>\n           </tr>\n           <tr ng-repeat=\"friend in friends | orderBy:predicate:reverse\">\n             <td>{{friend.name}}</td>\n             <td>{{friend.phone}}</td>\n             <td>{{friend.age}}</td>\n           </tr>\n         </table>\n       </div>\n     </file>\n   </example>\n *\n * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the\n * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the\n * desired parameters.\n *\n * Example:\n *\n * @example\n  <example module=\"orderByExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <table class=\"friend\">\n          <tr>\n            <th><a href=\"\" ng-click=\"reverse=false;order('name', false)\">Name</a>\n              (<a href=\"\" ng-click=\"order('-name',false)\">^</a>)</th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('phone', reverse)\">Phone Number</a></th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('age',reverse)\">Age</a></th>\n          </tr>\n          <tr ng-repeat=\"friend in friends\">\n            <td>{{friend.name}}</td>\n            <td>{{friend.phone}}</td>\n            <td>{{friend.age}}</td>\n          </tr>\n        </table>\n      </div>\n    </file>\n\n    <file name=\"script.js\">\n      angular.module('orderByExample', [])\n        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {\n          var orderBy = $filter('orderBy');\n          $scope.friends = [\n            { name: 'John',    phone: '555-1212',    age: 10 },\n            { name: 'Mary',    phone: '555-9876',    age: 19 },\n            { name: 'Mike',    phone: '555-4321',    age: 21 },\n            { name: 'Adam',    phone: '555-5678',    age: 35 },\n            { name: 'Julie',   phone: '555-8765',    age: 29 }\n          ];\n          $scope.order = function(predicate, reverse) {\n            $scope.friends = orderBy($scope.friends, predicate, reverse);\n          };\n          $scope.order('-age',false);\n        }]);\n    </file>\n</example>\n */\norderByFilter.$inject = ['$parse'];\nfunction orderByFilter($parse) {\n  return function(array, sortPredicate, reverseOrder) {\n    if (!(isArrayLike(array))) return array;\n    sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];\n    if (sortPredicate.length === 0) { sortPredicate = ['+']; }\n    sortPredicate = sortPredicate.map(function(predicate) {\n      var descending = false, get = predicate || identity;\n      if (isString(predicate)) {\n        if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {\n          descending = predicate.charAt(0) == '-';\n          predicate = predicate.substring(1);\n        }\n        if (predicate === '') {\n          // Effectively no predicate was passed so we compare identity\n          return reverseComparator(compare, descending);\n        }\n        get = $parse(predicate);\n        if (get.constant) {\n          var key = get();\n          return reverseComparator(function(a, b) {\n            return compare(a[key], b[key]);\n          }, descending);\n        }\n      }\n      return reverseComparator(function(a, b) {\n        return compare(get(a),get(b));\n      }, descending);\n    });\n    return slice.call(array).sort(reverseComparator(comparator, reverseOrder));\n\n    function comparator(o1, o2) {\n      for (var i = 0; i < sortPredicate.length; i++) {\n        var comp = sortPredicate[i](o1, o2);\n        if (comp !== 0) return comp;\n      }\n      return 0;\n    }\n    function reverseComparator(comp, descending) {\n      return descending\n          ? function(a, b) {return comp(b,a);}\n          : comp;\n    }\n\n    function isPrimitive(value) {\n      switch (typeof value) {\n        case 'number': /* falls through */\n        case 'boolean': /* falls through */\n        case 'string':\n          return true;\n        default:\n          return false;\n      }\n    }\n\n    function objectToString(value) {\n      if (value === null) return 'null';\n      if (typeof value.valueOf === 'function') {\n        value = value.valueOf();\n        if (isPrimitive(value)) return value;\n      }\n      if (typeof value.toString === 'function') {\n        value = value.toString();\n        if (isPrimitive(value)) return value;\n      }\n      return '';\n    }\n\n    function compare(v1, v2) {\n      var t1 = typeof v1;\n      var t2 = typeof v2;\n      if (t1 === t2 && t1 === \"object\") {\n        v1 = objectToString(v1);\n        v2 = objectToString(v2);\n      }\n      if (t1 === t2) {\n        if (t1 === \"string\") {\n           v1 = v1.toLowerCase();\n           v2 = v2.toLowerCase();\n        }\n        if (v1 === v2) return 0;\n        return v1 < v2 ? -1 : 1;\n      } else {\n        return t1 < t2 ? -1 : 1;\n      }\n    }\n  };\n}\n\nfunction ngDirective(directive) {\n  if (isFunction(directive)) {\n    directive = {\n      link: directive\n    };\n  }\n  directive.restrict = directive.restrict || 'AC';\n  return valueFn(directive);\n}\n\n/**\n * @ngdoc directive\n * @name a\n * @restrict E\n *\n * @description\n * Modifies the default behavior of the html A tag so that the default action is prevented when\n * the href attribute is empty.\n *\n * This change permits the easy creation of action links with the `ngClick` directive\n * without changing the location or causing page reloads, e.g.:\n * `<a href=\"\" ng-click=\"list.addItem()\">Add Item</a>`\n */\nvar htmlAnchorDirective = valueFn({\n  restrict: 'E',\n  compile: function(element, attr) {\n    if (!attr.href && !attr.xlinkHref && !attr.name) {\n      return function(scope, element) {\n        // If the linked element is not an anchor tag anymore, do nothing\n        if (element[0].nodeName.toLowerCase() !== 'a') return;\n\n        // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n        var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n                   'xlink:href' : 'href';\n        element.on('click', function(event) {\n          // if we have no href url, then don't navigate anywhere.\n          if (!element.attr(href)) {\n            event.preventDefault();\n          }\n        });\n      };\n    }\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngHref\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in an href attribute will\n * make the link go to the wrong URL if the user clicks it before\n * Angular has a chance to replace the `{{hash}}` markup with its\n * value. Until Angular replaces the markup the link will be broken\n * and will most likely return a 404 error. The `ngHref` directive\n * solves this problem.\n *\n * The wrong way to write it:\n * ```html\n * <a href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <a ng-href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * @element A\n * @param {template} ngHref any string which can contain `{{}}` markup.\n *\n * @example\n * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes\n * in links and their different behaviors:\n    <example>\n      <file name=\"index.html\">\n        <input ng-model=\"value\" /><br />\n        <a id=\"link-1\" href ng-click=\"value = 1\">link 1</a> (link, don't reload)<br />\n        <a id=\"link-2\" href=\"\" ng-click=\"value = 2\">link 2</a> (link, don't reload)<br />\n        <a id=\"link-3\" ng-href=\"/{{'123'}}\">link 3</a> (link, reload!)<br />\n        <a id=\"link-4\" href=\"\" name=\"xx\" ng-click=\"value = 4\">anchor</a> (link, don't reload)<br />\n        <a id=\"link-5\" name=\"xxx\" ng-click=\"value = 5\">anchor</a> (no link)<br />\n        <a id=\"link-6\" ng-href=\"{{value}}\">link</a> (link, change location)\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should execute ng-click but not reload when href without value', function() {\n          element(by.id('link-1')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('1');\n          expect(element(by.id('link-1')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when href empty string', function() {\n          element(by.id('link-2')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('2');\n          expect(element(by.id('link-2')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click and change url when ng-href specified', function() {\n          expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\\/123$/);\n\n          element(by.id('link-3')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/123$/);\n            });\n          }, 5000, 'page should navigate to /123');\n        });\n\n        xit('should execute ng-click but not reload when href empty string and name specified', function() {\n          element(by.id('link-4')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('4');\n          expect(element(by.id('link-4')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when no href but name specified', function() {\n          element(by.id('link-5')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('5');\n          expect(element(by.id('link-5')).getAttribute('href')).toBe(null);\n        });\n\n        it('should only change url when only ng-href', function() {\n          element(by.model('value')).clear();\n          element(by.model('value')).sendKeys('6');\n          expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\\/6$/);\n\n          element(by.id('link-6')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/6$/);\n            });\n          }, 5000, 'page should navigate to /6');\n        });\n      </file>\n    </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngSrc\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `src` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrc` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img src=\"http://www.gravatar.com/avatar/{{hash}}\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-src=\"http://www.gravatar.com/avatar/{{hash}}\"/>\n * ```\n *\n * @element IMG\n * @param {template} ngSrc any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngSrcset\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrcset` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\"/>\n * ```\n *\n * @element IMG\n * @param {template} ngSrcset any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngDisabled\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:\n * ```html\n * <div ng-init=\"scope = { isDisabled: false }\">\n *  <button disabled=\"{{scope.isDisabled}}\">Disabled</button>\n * </div>\n * ```\n *\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as disabled. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngDisabled` directive solves this problem for the `disabled` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        Click me to toggle: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n        <button ng-model=\"button\" ng-disabled=\"checked\">Button</button>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle button', function() {\n          expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,\n *     then special attribute \"disabled\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngChecked\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as checked. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngChecked` directive solves this problem for the `checked` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        Check me to check both: <input type=\"checkbox\" ng-model=\"master\"><br/>\n        <input id=\"checkSlave\" type=\"checkbox\" ng-checked=\"master\">\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should check both checkBoxes', function() {\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();\n          element(by.model('master')).click();\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,\n *     then special attribute \"checked\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngReadonly\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as readonly. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngReadonly` directive solves this problem for the `readonly` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        Check me to make text readonly: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n        <input type=\"text\" ng-readonly=\"checked\" value=\"I'm Angular\"/>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle readonly attr', function() {\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,\n *     then special attribute \"readonly\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSelected\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as selected. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngSelected` directive solves this problem for the `selected` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        Check me to select: <input type=\"checkbox\" ng-model=\"selected\"><br/>\n        <select>\n          <option>Hello!</option>\n          <option id=\"greet\" ng-selected=\"selected\">Greetings!</option>\n        </select>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should select Greetings!', function() {\n          expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();\n          element(by.model('selected')).click();\n          expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element OPTION\n * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,\n *     then special attribute \"selected\" will be set on the element\n */\n\n/**\n * @ngdoc directive\n * @name ngOpen\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as open. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngOpen` directive solves this problem for the `open` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n     <example>\n       <file name=\"index.html\">\n         Check me check multiple: <input type=\"checkbox\" ng-model=\"open\"><br/>\n         <details id=\"details\" ng-open=\"open\">\n            <summary>Show/Hide me</summary>\n         </details>\n       </file>\n       <file name=\"protractor.js\" type=\"protractor\">\n         it('should toggle open', function() {\n           expect(element(by.id('details')).getAttribute('open')).toBeFalsy();\n           element(by.model('open')).click();\n           expect(element(by.id('details')).getAttribute('open')).toBeTruthy();\n         });\n       </file>\n     </example>\n *\n * @element DETAILS\n * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,\n *     then special attribute \"open\" will be set on the element\n */\n\nvar ngAttributeAliasDirectives = {};\n\n\n// boolean attrs are evaluated\nforEach(BOOLEAN_ATTR, function(propName, attrName) {\n  // binding to multiple is not supported\n  if (propName == \"multiple\") return;\n\n  var normalized = directiveNormalize('ng-' + attrName);\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      restrict: 'A',\n      priority: 100,\n      link: function(scope, element, attr) {\n        scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {\n          attr.$set(attrName, !!value);\n        });\n      }\n    };\n  };\n});\n\n// aliased input attrs are evaluated\nforEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {\n  ngAttributeAliasDirectives[ngAttr] = function() {\n    return {\n      priority: 100,\n      link: function(scope, element, attr) {\n        //special case ngPattern when a literal regular expression value\n        //is used as the expression (this way we don't have to watch anything).\n        if (ngAttr === \"ngPattern\" && attr.ngPattern.charAt(0) == \"/\") {\n          var match = attr.ngPattern.match(REGEX_STRING_REGEXP);\n          if (match) {\n            attr.$set(\"ngPattern\", new RegExp(match[1], match[2]));\n            return;\n          }\n        }\n\n        scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {\n          attr.$set(ngAttr, value);\n        });\n      }\n    };\n  };\n});\n\n// ng-src, ng-srcset, ng-href are interpolated\nforEach(['src', 'srcset', 'href'], function(attrName) {\n  var normalized = directiveNormalize('ng-' + attrName);\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      priority: 99, // it needs to run after the attributes are interpolated\n      link: function(scope, element, attr) {\n        var propName = attrName,\n            name = attrName;\n\n        if (attrName === 'href' &&\n            toString.call(element.prop('href')) === '[object SVGAnimatedString]') {\n          name = 'xlinkHref';\n          attr.$attr[name] = 'xlink:href';\n          propName = null;\n        }\n\n        attr.$observe(normalized, function(value) {\n          if (!value) {\n            if (attrName === 'href') {\n              attr.$set(name, null);\n            }\n            return;\n          }\n\n          attr.$set(name, value);\n\n          // on IE, if \"ng:src\" directive declaration is used and \"src\" attribute doesn't exist\n          // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need\n          // to set the property as well to achieve the desired effect.\n          // we use attr[attrName] value since $set can sanitize the url.\n          if (msie && propName) element.prop(propName, attr[name]);\n        });\n      }\n    };\n  };\n});\n\n/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true\n */\nvar nullFormCtrl = {\n  $addControl: noop,\n  $$renameControl: nullFormRenameControl,\n  $removeControl: noop,\n  $setValidity: noop,\n  $setDirty: noop,\n  $setPristine: noop,\n  $setSubmitted: noop\n},\nSUBMITTED_CLASS = 'ng-submitted';\n\nfunction nullFormRenameControl(control, name) {\n  control.$name = name;\n}\n\n/**\n * @ngdoc type\n * @name form.FormController\n *\n * @property {boolean} $pristine True if user has not interacted with the form yet.\n * @property {boolean} $dirty True if user has already interacted with the form.\n * @property {boolean} $valid True if all of the containing forms and controls are valid.\n * @property {boolean} $invalid True if at least one containing control or form is invalid.\n * @property {boolean} $submitted True if user has submitted the form even if its invalid.\n *\n * @property {Object} $error Is an object hash, containing references to controls or\n *  forms with failing validators, where:\n *\n *  - keys are validation tokens (error names),\n *  - values are arrays of controls or forms that have a failing validator for given error name.\n *\n *  Built-in validation tokens:\n *\n *  - `email`\n *  - `max`\n *  - `maxlength`\n *  - `min`\n *  - `minlength`\n *  - `number`\n *  - `pattern`\n *  - `required`\n *  - `url`\n *  - `date`\n *  - `datetimelocal`\n *  - `time`\n *  - `week`\n *  - `month`\n *\n * @description\n * `FormController` keeps track of all its controls and nested forms as well as the state of them,\n * such as being valid/invalid or dirty/pristine.\n *\n * Each {@link ng.directive:form form} directive creates an instance\n * of `FormController`.\n *\n */\n//asks for $scope to fool the BC controller module\nFormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];\nfunction FormController(element, attrs, $scope, $animate, $interpolate) {\n  var form = this,\n      controls = [];\n\n  var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;\n\n  // init state\n  form.$error = {};\n  form.$$success = {};\n  form.$pending = undefined;\n  form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);\n  form.$dirty = false;\n  form.$pristine = true;\n  form.$valid = true;\n  form.$invalid = false;\n  form.$submitted = false;\n\n  parentForm.$addControl(form);\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$rollbackViewValue\n   *\n   * @description\n   * Rollback all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is typically needed by the reset button of\n   * a form that uses `ng-model-options` to pend updates.\n   */\n  form.$rollbackViewValue = function() {\n    forEach(controls, function(control) {\n      control.$rollbackViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$commitViewValue\n   *\n   * @description\n   * Commit all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  form.$commitViewValue = function() {\n    forEach(controls, function(control) {\n      control.$commitViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$addControl\n   *\n   * @description\n   * Register a control with the form.\n   *\n   * Input elements using ngModelController do this automatically when they are linked.\n   */\n  form.$addControl = function(control) {\n    // Breaking change - before, inputs whose name was \"hasOwnProperty\" were quietly ignored\n    // and not added to the scope.  Now we throw an error.\n    assertNotHasOwnProperty(control.$name, 'input');\n    controls.push(control);\n\n    if (control.$name) {\n      form[control.$name] = control;\n    }\n  };\n\n  // Private API: rename a form control\n  form.$$renameControl = function(control, newName) {\n    var oldName = control.$name;\n\n    if (form[oldName] === control) {\n      delete form[oldName];\n    }\n    form[newName] = control;\n    control.$name = newName;\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$removeControl\n   *\n   * @description\n   * Deregister a control from the form.\n   *\n   * Input elements using ngModelController do this automatically when they are destroyed.\n   */\n  form.$removeControl = function(control) {\n    if (control.$name && form[control.$name] === control) {\n      delete form[control.$name];\n    }\n    forEach(form.$pending, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$error, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$$success, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n\n    arrayRemove(controls, control);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setValidity\n   *\n   * @description\n   * Sets the validity of a form control.\n   *\n   * This method will also propagate to parent forms.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: element,\n    set: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        object[property] = [controller];\n      } else {\n        var index = list.indexOf(controller);\n        if (index === -1) {\n          list.push(controller);\n        }\n      }\n    },\n    unset: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        return;\n      }\n      arrayRemove(list, controller);\n      if (list.length === 0) {\n        delete object[property];\n      }\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setDirty\n   *\n   * @description\n   * Sets the form to a dirty state.\n   *\n   * This method can be called to add the 'ng-dirty' class and set the form to a dirty\n   * state (ng-dirty class). This method will also propagate to parent forms.\n   */\n  form.$setDirty = function() {\n    $animate.removeClass(element, PRISTINE_CLASS);\n    $animate.addClass(element, DIRTY_CLASS);\n    form.$dirty = true;\n    form.$pristine = false;\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setPristine\n   *\n   * @description\n   * Sets the form to its pristine state.\n   *\n   * This method can be called to remove the 'ng-dirty' class and set the form to its pristine\n   * state (ng-pristine class). This method will also propagate to all the controls contained\n   * in this form.\n   *\n   * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after\n   * saving or resetting it.\n   */\n  form.$setPristine = function() {\n    $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);\n    form.$dirty = false;\n    form.$pristine = true;\n    form.$submitted = false;\n    forEach(controls, function(control) {\n      control.$setPristine();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setUntouched\n   *\n   * @description\n   * Sets the form to its untouched state.\n   *\n   * This method can be called to remove the 'ng-touched' class and set the form controls to their\n   * untouched state (ng-untouched class).\n   *\n   * Setting a form controls back to their untouched state is often useful when setting the form\n   * back to its pristine state.\n   */\n  form.$setUntouched = function() {\n    forEach(controls, function(control) {\n      control.$setUntouched();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setSubmitted\n   *\n   * @description\n   * Sets the form to its submitted state.\n   */\n  form.$setSubmitted = function() {\n    $animate.addClass(element, SUBMITTED_CLASS);\n    form.$submitted = true;\n    parentForm.$setSubmitted();\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ngForm\n * @restrict EAC\n *\n * @description\n * Nestable alias of {@link ng.directive:form `form`} directive. HTML\n * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a\n * sub-group of controls needs to be determined.\n *\n * Note: the purpose of `ngForm` is to group controls,\n * but not to be a replacement for the `<form>` tag with all of its capabilities\n * (e.g. posting to the server, ...).\n *\n * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n *\n */\n\n /**\n * @ngdoc directive\n * @name form\n * @restrict E\n *\n * @description\n * Directive that instantiates\n * {@link form.FormController FormController}.\n *\n * If the `name` attribute is specified, the form controller is published onto the current scope under\n * this name.\n *\n * # Alias: {@link ng.directive:ngForm `ngForm`}\n *\n * In Angular forms can be nested. This means that the outer form is valid when all of the child\n * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so\n * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to\n * `<form>` but can be nested.  This allows you to have nested forms, which is very useful when\n * using Angular validation directives in forms that are dynamically generated using the\n * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`\n * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an\n * `ngForm` directive and nest these in an outer `form` element.\n *\n *\n * # CSS classes\n *  - `ng-valid` is set if the form is valid.\n *  - `ng-invalid` is set if the form is invalid.\n *  - `ng-pristine` is set if the form is pristine.\n *  - `ng-dirty` is set if the form is dirty.\n *  - `ng-submitted` is set if the form was submitted.\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n *\n * # Submitting a form and preventing the default action\n *\n * Since the role of forms in client-side Angular applications is different than in classical\n * roundtrip apps, it is desirable for the browser not to translate the form submission into a full\n * page reload that sends the data to the server. Instead some javascript logic should be triggered\n * to handle the form submission in an application-specific way.\n *\n * For this reason, Angular prevents the default action (form submission to the server) unless the\n * `<form>` element has an `action` attribute specified.\n *\n * You can use one of the following two ways to specify what javascript method should be called when\n * a form is submitted:\n *\n * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element\n * - {@link ng.directive:ngClick ngClick} directive on the first\n  *  button or input field of type submit (input[type=submit])\n *\n * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}\n * or {@link ng.directive:ngClick ngClick} directives.\n * This is because of the following form submission rules in the HTML specification:\n *\n * - If a form has only one input field then hitting enter in this field triggers form submit\n * (`ngSubmit`)\n * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter\n * doesn't trigger submit\n * - if a form has one or more input fields and one or more buttons or input[type=submit] then\n * hitting enter in any of the input fields will trigger the click handler on the *first* button or\n * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)\n *\n * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is\n * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * ## Animation Hooks\n *\n * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.\n * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any\n * other validations that are performed within the form. Animations in ngForm are similar to how\n * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well\n * as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style a form element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-form {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-form.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n    <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"formExample\">\n      <file name=\"index.html\">\n       <script>\n         angular.module('formExample', [])\n           .controller('FormController', ['$scope', function($scope) {\n             $scope.userType = 'guest';\n           }]);\n       </script>\n       <style>\n        .my-form {\n          -webkit-transition:all linear 0.5s;\n          transition:all linear 0.5s;\n          background: transparent;\n        }\n        .my-form.ng-invalid {\n          background: red;\n        }\n       </style>\n       <form name=\"myForm\" ng-controller=\"FormController\" class=\"my-form\">\n         userType: <input name=\"input\" ng-model=\"userType\" required>\n         <span class=\"error\" ng-show=\"myForm.input.$error.required\">Required!</span><br>\n         <tt>userType = {{userType}}</tt><br>\n         <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>\n         <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>\n         <tt>myForm.$valid = {{myForm.$valid}}</tt><br>\n         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should initialize to model', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n\n          expect(userType.getText()).toContain('guest');\n          expect(valid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var userInput = element(by.model('userType'));\n\n          userInput.clear();\n          userInput.sendKeys('');\n\n          expect(userType.getText()).toEqual('userType =');\n          expect(valid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n *\n * @param {string=} name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n */\nvar formDirectiveFactory = function(isNgForm) {\n  return ['$timeout', function($timeout) {\n    var formDirective = {\n      name: 'form',\n      restrict: isNgForm ? 'EAC' : 'E',\n      controller: FormController,\n      compile: function ngFormCompile(formElement) {\n        // Setup initial state of the control\n        formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);\n\n        return {\n          pre: function ngFormPreLink(scope, formElement, attr, controller) {\n            // if `action` attr is not present on the form, prevent the default action (submission)\n            if (!('action' in attr)) {\n              // we can't use jq events because if a form is destroyed during submission the default\n              // action is not prevented. see #1238\n              //\n              // IE 9 is not affected because it doesn't fire a submit event and try to do a full\n              // page reload if the form was destroyed by submission of the form via a click handler\n              // on a button in the form. Looks like an IE9 specific bug.\n              var handleFormSubmission = function(event) {\n                scope.$apply(function() {\n                  controller.$commitViewValue();\n                  controller.$setSubmitted();\n                });\n\n                event.preventDefault();\n              };\n\n              addEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n\n              // unregister the preventDefault listener so that we don't not leak memory but in a\n              // way that will achieve the prevention of the default action.\n              formElement.on('$destroy', function() {\n                $timeout(function() {\n                  removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n                }, 0, false);\n              });\n            }\n\n            var parentFormCtrl = controller.$$parentForm,\n                alias = controller.$name;\n\n            if (alias) {\n              setter(scope, null, alias, controller, alias);\n              attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {\n                if (alias === newValue) return;\n                setter(scope, null, alias, undefined, alias);\n                alias = newValue;\n                setter(scope, null, alias, controller, alias);\n                parentFormCtrl.$$renameControl(controller, alias);\n              });\n            }\n            formElement.on('$destroy', function() {\n              parentFormCtrl.$removeControl(controller);\n              if (alias) {\n                setter(scope, null, alias, undefined, alias);\n              }\n              extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards\n            });\n          }\n        };\n      }\n    };\n\n    return formDirective;\n  }];\n};\n\nvar formDirective = formDirectiveFactory();\nvar ngFormDirective = formDirectiveFactory(true);\n\n/* global VALID_CLASS: false,\n  INVALID_CLASS: false,\n  PRISTINE_CLASS: false,\n  DIRTY_CLASS: false,\n  UNTOUCHED_CLASS: false,\n  TOUCHED_CLASS: false,\n  $ngModelMinErr: false,\n*/\n\n// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231\nvar ISO_DATE_REGEXP = /\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)/;\nvar URL_REGEXP = /^(ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?$/;\nvar EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;\nvar NUMBER_REGEXP = /^\\s*(\\-|\\+)?(\\d+|(\\d*(\\.\\d*)))\\s*$/;\nvar DATE_REGEXP = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nvar DATETIMELOCAL_REGEXP = /^(\\d{4})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\nvar WEEK_REGEXP = /^(\\d{4})-W(\\d\\d)$/;\nvar MONTH_REGEXP = /^(\\d{4})-(\\d\\d)$/;\nvar TIME_REGEXP = /^(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\n\nvar inputType = {\n\n  /**\n   * @ngdoc input\n   * @name input[text]\n   *\n   * @description\n   * Standard HTML text input with angular data binding, inherited by most of the `input` elements.\n   *\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Adds `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n   *    This parameter is ignored for input[type=password] controls, which will never trim the\n   *    input.\n   *\n   * @example\n      <example name=\"text-input-directive\" module=\"textInputExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('textInputExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 text: 'guest',\n                 word: /^\\s*\\w*\\s*$/\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           Single word: <input type=\"text\" name=\"input\" ng-model=\"example.text\"\n                               ng-pattern=\"example.word\" required ng-trim=\"false\">\n           <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n             Required!</span>\n           <span class=\"error\" ng-show=\"myForm.input.$error.pattern\">\n             Single word only!</span>\n\n           <tt>text = {{example.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('example.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('guest');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if multi word', function() {\n            input.clear();\n            input.sendKeys('hello world');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'text': textInputType,\n\n    /**\n     * @ngdoc input\n     * @name input[date]\n     *\n     * @description\n     * Input with date validation and transformation. In browsers that do not yet support\n     * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601\n     * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many\n     * modern browsers do not yet support this input type, it is important to provide cues to users on the\n     * expected input format via a placeholder or label.\n     *\n     * The model must always be a Date object, otherwise Angular will throw an error.\n     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n     *\n     * The timezone to be used to read/write the `Date` instance in the model can be defined using\n     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n     *\n     * @param {string} ngModel Assignable angular expression to data-bind to.\n     * @param {string=} name Property name of the form under which the control is published.\n     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n     * valid ISO date string (yyyy-MM-dd).\n     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n     * a valid ISO date string (yyyy-MM-dd).\n     * @param {string=} required Sets `required` validation error key if the value is not entered.\n     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n     *    `required` when you want to data-bind to the `required` attribute.\n     * @param {string=} ngChange Angular expression to be executed when input changes due to user\n     *    interaction with the input element.\n     *\n     * @example\n     <example name=\"date-input-directive\" module=\"dateInputExample\">\n     <file name=\"index.html\">\n       <script>\n          angular.module('dateInputExample', [])\n            .controller('DateController', ['$scope', function($scope) {\n              $scope.example = {\n                value: new Date(2013, 9, 22)\n              };\n            }]);\n       </script>\n       <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n          Pick a date in 2013:\n          <input type=\"date\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n              placeholder=\"yyyy-MM-dd\" min=\"2013-01-01\" max=\"2013-12-31\" required />\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.date\">\n              Not a valid date!</span>\n           <tt>value = {{example.value | date: \"yyyy-MM-dd\"}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n       </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        var value = element(by.binding('example.value | date: \"yyyy-MM-dd\"'));\n        var valid = element(by.binding('myForm.input.$valid'));\n        var input = element(by.model('example.value'));\n\n        // currently protractor/webdriver does not support\n        // sending keys to all known HTML5 input controls\n        // for various browsers (see https://github.com/angular/protractor/issues/562).\n        function setInput(val) {\n          // set the value of the element and force validation.\n          var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n          \"ipt.value = '\" + val + \"';\" +\n          \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n          browser.executeScript(scr);\n        }\n\n        it('should initialize to model', function() {\n          expect(value.getText()).toContain('2013-10-22');\n          expect(valid.getText()).toContain('myForm.input.$valid = true');\n        });\n\n        it('should be invalid if empty', function() {\n          setInput('');\n          expect(value.getText()).toEqual('value =');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n\n        it('should be invalid if over max', function() {\n          setInput('2015-01-01');\n          expect(value.getText()).toContain('');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n     </file>\n     </example>\n     */\n  'date': createDateInputType('date', DATE_REGEXP,\n         createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),\n         'yyyy-MM-dd'),\n\n   /**\n    * @ngdoc input\n    * @name input[datetime-local]\n    *\n    * @description\n    * Input with datetime validation and transformation. In browsers that do not yet support\n    * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"datetimelocal-input-directive\" module=\"dateExample\">\n    <file name=\"index.html\">\n      <script>\n        angular.module('dateExample', [])\n          .controller('DateController', ['$scope', function($scope) {\n            $scope.example = {\n              value: new Date(2010, 11, 28, 14, 57)\n            };\n          }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        Pick a date between in 2013:\n        <input type=\"datetime-local\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"yyyy-MM-ddTHH:mm:ss\" min=\"2001-01-01T00:00:00\" max=\"2013-12-31T00:00:00\" required />\n        <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n        <span class=\"error\" ng-show=\"myForm.input.$error.datetimelocal\">\n            Not a valid date!</span>\n        <tt>value = {{example.value | date: \"yyyy-MM-ddTHH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM-ddTHH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2010-12-28T14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01-01T23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,\n      createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),\n      'yyyy-MM-ddTHH:mm:ss.sss'),\n\n  /**\n   * @ngdoc input\n   * @name input[time]\n   *\n   * @description\n   * Input with time validation and transformation. In browsers that do not yet support\n   * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a\n   * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"time-input-directive\" module=\"timeExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('timeExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(1970, 0, 1, 14, 57, 0)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        Pick a between 8am and 5pm:\n        <input type=\"time\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"HH:mm:ss\" min=\"08:00:00\" max=\"17:00:00\" required />\n        <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n        <span class=\"error\" ng-show=\"myForm.input.$error.time\">\n            Not a valid date!</span>\n        <tt>value = {{example.value | date: \"HH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"HH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'time': createDateInputType('time', TIME_REGEXP,\n      createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),\n     'HH:mm:ss.sss'),\n\n   /**\n    * @ngdoc input\n    * @name input[week]\n    *\n    * @description\n    * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support\n    * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * week format (yyyy-W##), for example: `2013-W02`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO week format (yyyy-W##).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO week format (yyyy-W##).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"week-input-directive\" module=\"weekExample\">\n    <file name=\"index.html\">\n      <script>\n      angular.module('weekExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 0, 3)\n          };\n        }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        Pick a date between in 2013:\n        <input id=\"exampleInput\" type=\"week\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"YYYY-W##\" min=\"2012-W32\" max=\"2013-W52\" required />\n        <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n        <span class=\"error\" ng-show=\"myForm.input.$error.week\">\n            Not a valid date!</span>\n        <tt>value = {{example.value | date: \"yyyy-Www\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-Www\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-W01');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-W01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),\n\n  /**\n   * @ngdoc input\n   * @name input[month]\n   *\n   * @description\n   * Input with month validation and transformation. In browsers that do not yet support\n   * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * month format (yyyy-MM), for example: `2009-01`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   * If the model is not set to the first of the month, the next view to model update will set it\n   * to the first of the month.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be\n   * a valid ISO month format (yyyy-MM).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must\n   * be a valid ISO month format (yyyy-MM).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"month-input-directive\" module=\"monthExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('monthExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 9, 1)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n       Pick a month in 2013:\n       <input id=\"exampleInput\" type=\"month\" name=\"input\" ng-model=\"example.value\"\n          placeholder=\"yyyy-MM\" min=\"2013-01\" max=\"2013-12\" required />\n       <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n          Required!</span>\n       <span class=\"error\" ng-show=\"myForm.input.$error.month\">\n          Not a valid month!</span>\n       <tt>value = {{example.value | date: \"yyyy-MM\"}}</tt><br/>\n       <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n       <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n       <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n       <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-10');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'month': createDateInputType('month', MONTH_REGEXP,\n     createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),\n     'yyyy-MM'),\n\n  /**\n   * @ngdoc input\n   * @name input[number]\n   *\n   * @description\n   * Text input with number validation and transformation. Sets the `number` validation\n   * error if not a valid number.\n   *\n   * The model must always be a number, otherwise Angular will throw an error.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"number-input-directive\" module=\"numberExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('numberExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 value: 12\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           Number: <input type=\"number\" name=\"input\" ng-model=\"example.value\"\n                          min=\"0\" max=\"99\" required>\n           <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n             Required!</span>\n           <span class=\"error\" ng-show=\"myForm.input.$error.number\">\n             Not valid number!</span>\n           <tt>value = {{example.value}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var value = element(by.binding('example.value'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.value'));\n\n          it('should initialize to model', function() {\n            expect(value.getText()).toContain('12');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if over max', function() {\n            input.clear();\n            input.sendKeys('123');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'number': numberInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[url]\n   *\n   * @description\n   * Text input with URL validation. Sets the `url` validation error key if the content is not a\n   * valid URL.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex\n   * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify\n   * the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"url-input-directive\" module=\"urlExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('urlExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.url = {\n                 text: 'http://google.com'\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           URL: <input type=\"url\" name=\"input\" ng-model=\"url.text\" required>\n           <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n             Required!</span>\n           <span class=\"error\" ng-show=\"myForm.input.$error.url\">\n             Not valid url!</span>\n           <tt>text = {{url.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n           <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('url.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('url.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('http://google.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not url', function() {\n            input.clear();\n            input.sendKeys('box');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'url': urlInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[email]\n   *\n   * @description\n   * Text input with email validation. Sets the `email` validation error key if not a valid email\n   * address.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex\n   * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can\n   * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object then this is used directly.\n   *    If the expression is a string then it will be converted to a RegExp after wrapping it in `^` and `$`\n   *    characters. For instance, `\"abc\"` will be converted to `new RegExp('^abc$')`.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"email-input-directive\" module=\"emailExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('emailExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.email = {\n                 text: 'me@example.com'\n               };\n             }]);\n         </script>\n           <form name=\"myForm\" ng-controller=\"ExampleController\">\n             Email: <input type=\"email\" name=\"input\" ng-model=\"email.text\" required>\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.email\">\n               Not valid email!</span>\n             <tt>text = {{email.text}}</tt><br/>\n             <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n             <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n             <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n             <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n             <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>\n           </form>\n         </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('email.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('email.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('me@example.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not email', function() {\n            input.clear();\n            input.sendKeys('xxx');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'email': emailInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[radio]\n   *\n   * @description\n   * HTML radio button.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string} value The value to which the expression should be set when selected.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {string} ngValue Angular expression which sets the value to which the expression should\n   *    be set when selected.\n   *\n   * @example\n      <example name=\"radio-input-directive\" module=\"radioExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('radioExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.color = {\n                 name: 'blue'\n               };\n               $scope.specialValue = {\n                 \"id\": \"12345\",\n                 \"value\": \"green\"\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <input type=\"radio\" ng-model=\"color.name\" value=\"red\">  Red <br/>\n           <input type=\"radio\" ng-model=\"color.name\" ng-value=\"specialValue\"> Green <br/>\n           <input type=\"radio\" ng-model=\"color.name\" value=\"blue\"> Blue <br/>\n           <tt>color = {{color.name | json}}</tt><br/>\n          </form>\n          Note that `ng-value=\"specialValue\"` sets radio item's value to be the value of `$scope.specialValue`.\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var color = element(by.binding('color.name'));\n\n            expect(color.getText()).toContain('blue');\n\n            element.all(by.model('color.name')).get(0).click();\n\n            expect(color.getText()).toContain('red');\n          });\n        </file>\n      </example>\n   */\n  'radio': radioInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[checkbox]\n   *\n   * @description\n   * HTML checkbox.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {expression=} ngTrueValue The value to which the expression should be set when selected.\n   * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"checkbox-input-directive\" module=\"checkboxExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('checkboxExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.checkboxModel = {\n                value1 : true,\n                value2 : 'YES'\n              };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           Value1: <input type=\"checkbox\" ng-model=\"checkboxModel.value1\"> <br/>\n           Value2: <input type=\"checkbox\" ng-model=\"checkboxModel.value2\"\n                          ng-true-value=\"'YES'\" ng-false-value=\"'NO'\"> <br/>\n           <tt>value1 = {{checkboxModel.value1}}</tt><br/>\n           <tt>value2 = {{checkboxModel.value2}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var value1 = element(by.binding('checkboxModel.value1'));\n            var value2 = element(by.binding('checkboxModel.value2'));\n\n            expect(value1.getText()).toContain('true');\n            expect(value2.getText()).toContain('YES');\n\n            element(by.model('checkboxModel.value1')).click();\n            element(by.model('checkboxModel.value2')).click();\n\n            expect(value1.getText()).toContain('false');\n            expect(value2.getText()).toContain('NO');\n          });\n        </file>\n      </example>\n   */\n  'checkbox': checkboxInputType,\n\n  'hidden': noop,\n  'button': noop,\n  'submit': noop,\n  'reset': noop,\n  'file': noop\n};\n\nfunction stringBasedInputType(ctrl) {\n  ctrl.$formatters.push(function(value) {\n    return ctrl.$isEmpty(value) ? value : value.toString();\n  });\n}\n\nfunction textInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n}\n\nfunction baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  var type = lowercase(element[0].type);\n\n  // In composition mode, users are still inputing intermediate text buffer,\n  // hold the listener until composition is done.\n  // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent\n  if (!$sniffer.android) {\n    var composing = false;\n\n    element.on('compositionstart', function(data) {\n      composing = true;\n    });\n\n    element.on('compositionend', function() {\n      composing = false;\n      listener();\n    });\n  }\n\n  var listener = function(ev) {\n    if (timeout) {\n      $browser.defer.cancel(timeout);\n      timeout = null;\n    }\n    if (composing) return;\n    var value = element.val(),\n        event = ev && ev.type;\n\n    // By default we will trim the value\n    // If the attribute ng-trim exists we will avoid trimming\n    // If input type is 'password', the value is never trimmed\n    if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {\n      value = trim(value);\n    }\n\n    // If a control is suffering from bad input (due to native validators), browsers discard its\n    // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the\n    // control's value is the same empty value twice in a row.\n    if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {\n      ctrl.$setViewValue(value, event);\n    }\n  };\n\n  // if the browser does support \"input\" event, we are fine - except on IE9 which doesn't fire the\n  // input event on backspace, delete or cut\n  if ($sniffer.hasEvent('input')) {\n    element.on('input', listener);\n  } else {\n    var timeout;\n\n    var deferListener = function(ev, input, origValue) {\n      if (!timeout) {\n        timeout = $browser.defer(function() {\n          timeout = null;\n          if (!input || input.value !== origValue) {\n            listener(ev);\n          }\n        });\n      }\n    };\n\n    element.on('keydown', function(event) {\n      var key = event.keyCode;\n\n      // ignore\n      //    command            modifiers                   arrows\n      if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;\n\n      deferListener(event, this, this.value);\n    });\n\n    // if user modifies input value using context menu in IE, we need \"paste\" and \"cut\" events to catch it\n    if ($sniffer.hasEvent('paste')) {\n      element.on('paste cut', deferListener);\n    }\n  }\n\n  // if user paste into input using mouse on older browser\n  // or form autocomplete on newer browser, we need \"change\" event to catch it\n  element.on('change', listener);\n\n  ctrl.$render = function() {\n    element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);\n  };\n}\n\nfunction weekParser(isoWeek, existingDate) {\n  if (isDate(isoWeek)) {\n    return isoWeek;\n  }\n\n  if (isString(isoWeek)) {\n    WEEK_REGEXP.lastIndex = 0;\n    var parts = WEEK_REGEXP.exec(isoWeek);\n    if (parts) {\n      var year = +parts[1],\n          week = +parts[2],\n          hours = 0,\n          minutes = 0,\n          seconds = 0,\n          milliseconds = 0,\n          firstThurs = getFirstThursdayOfYear(year),\n          addDays = (week - 1) * 7;\n\n      if (existingDate) {\n        hours = existingDate.getHours();\n        minutes = existingDate.getMinutes();\n        seconds = existingDate.getSeconds();\n        milliseconds = existingDate.getMilliseconds();\n      }\n\n      return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);\n    }\n  }\n\n  return NaN;\n}\n\nfunction createDateParser(regexp, mapping) {\n  return function(iso, date) {\n    var parts, map;\n\n    if (isDate(iso)) {\n      return iso;\n    }\n\n    if (isString(iso)) {\n      // When a date is JSON'ified to wraps itself inside of an extra\n      // set of double quotes. This makes the date parsing code unable\n      // to match the date string and parse it as a date.\n      if (iso.charAt(0) == '\"' && iso.charAt(iso.length - 1) == '\"') {\n        iso = iso.substring(1, iso.length - 1);\n      }\n      if (ISO_DATE_REGEXP.test(iso)) {\n        return new Date(iso);\n      }\n      regexp.lastIndex = 0;\n      parts = regexp.exec(iso);\n\n      if (parts) {\n        parts.shift();\n        if (date) {\n          map = {\n            yyyy: date.getFullYear(),\n            MM: date.getMonth() + 1,\n            dd: date.getDate(),\n            HH: date.getHours(),\n            mm: date.getMinutes(),\n            ss: date.getSeconds(),\n            sss: date.getMilliseconds() / 1000\n          };\n        } else {\n          map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };\n        }\n\n        forEach(parts, function(part, index) {\n          if (index < mapping.length) {\n            map[mapping[index]] = +part;\n          }\n        });\n        return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);\n      }\n    }\n\n    return NaN;\n  };\n}\n\nfunction createDateInputType(type, regexp, parseDate, format) {\n  return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {\n    badInputChecker(scope, element, attr, ctrl);\n    baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n    var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;\n    var previousDate;\n\n    ctrl.$$parserName = type;\n    ctrl.$parsers.push(function(value) {\n      if (ctrl.$isEmpty(value)) return null;\n      if (regexp.test(value)) {\n        // Note: We cannot read ctrl.$modelValue, as there might be a different\n        // parser/formatter in the processing chain so that the model\n        // contains some different data format!\n        var parsedDate = parseDate(value, previousDate);\n        if (timezone === 'UTC') {\n          parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());\n        }\n        return parsedDate;\n      }\n      return undefined;\n    });\n\n    ctrl.$formatters.push(function(value) {\n      if (value && !isDate(value)) {\n        throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);\n      }\n      if (isValidDate(value)) {\n        previousDate = value;\n        if (previousDate && timezone === 'UTC') {\n          var timezoneOffset = 60000 * previousDate.getTimezoneOffset();\n          previousDate = new Date(previousDate.getTime() + timezoneOffset);\n        }\n        return $filter('date')(value, format, timezone);\n      } else {\n        previousDate = null;\n        return '';\n      }\n    });\n\n    if (isDefined(attr.min) || attr.ngMin) {\n      var minVal;\n      ctrl.$validators.min = function(value) {\n        return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;\n      };\n      attr.$observe('min', function(val) {\n        minVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    if (isDefined(attr.max) || attr.ngMax) {\n      var maxVal;\n      ctrl.$validators.max = function(value) {\n        return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;\n      };\n      attr.$observe('max', function(val) {\n        maxVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    function isValidDate(value) {\n      // Invalid Date: getTime() returns NaN\n      return value && !(value.getTime && value.getTime() !== value.getTime());\n    }\n\n    function parseObservedDateValue(val) {\n      return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;\n    }\n  };\n}\n\nfunction badInputChecker(scope, element, attr, ctrl) {\n  var node = element[0];\n  var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);\n  if (nativeValidation) {\n    ctrl.$parsers.push(function(value) {\n      var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};\n      // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):\n      // - also sets validity.badInput (should only be validity.typeMismatch).\n      // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)\n      // - can ignore this case as we can still read out the erroneous email...\n      return validity.badInput && !validity.typeMismatch ? undefined : value;\n    });\n  }\n}\n\nfunction numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  badInputChecker(scope, element, attr, ctrl);\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n  ctrl.$$parserName = 'number';\n  ctrl.$parsers.push(function(value) {\n    if (ctrl.$isEmpty(value))      return null;\n    if (NUMBER_REGEXP.test(value)) return parseFloat(value);\n    return undefined;\n  });\n\n  ctrl.$formatters.push(function(value) {\n    if (!ctrl.$isEmpty(value)) {\n      if (!isNumber(value)) {\n        throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);\n      }\n      value = value.toString();\n    }\n    return value;\n  });\n\n  if (attr.min || attr.ngMin) {\n    var minVal;\n    ctrl.$validators.min = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;\n    };\n\n    attr.$observe('min', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      minVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n\n  if (attr.max || attr.ngMax) {\n    var maxVal;\n    ctrl.$validators.max = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;\n    };\n\n    attr.$observe('max', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      maxVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n}\n\nfunction urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'url';\n  ctrl.$validators.url = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || URL_REGEXP.test(value);\n  };\n}\n\nfunction emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'email';\n  ctrl.$validators.email = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);\n  };\n}\n\nfunction radioInputType(scope, element, attr, ctrl) {\n  // make the name unique, if not defined\n  if (isUndefined(attr.name)) {\n    element.attr('name', nextUid());\n  }\n\n  var listener = function(ev) {\n    if (element[0].checked) {\n      ctrl.$setViewValue(attr.value, ev && ev.type);\n    }\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    var value = attr.value;\n    element[0].checked = (value == ctrl.$viewValue);\n  };\n\n  attr.$observe('value', ctrl.$render);\n}\n\nfunction parseConstantExpr($parse, context, name, expression, fallback) {\n  var parseFn;\n  if (isDefined(expression)) {\n    parseFn = $parse(expression);\n    if (!parseFn.constant) {\n      throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +\n                                   '`{1}`.', name, expression);\n    }\n    return parseFn(context);\n  }\n  return fallback;\n}\n\nfunction checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n  var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);\n  var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);\n\n  var listener = function(ev) {\n    ctrl.$setViewValue(element[0].checked, ev && ev.type);\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    element[0].checked = ctrl.$viewValue;\n  };\n\n  // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`\n  // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert\n  // it to a boolean.\n  ctrl.$isEmpty = function(value) {\n    return value === false;\n  };\n\n  ctrl.$formatters.push(function(value) {\n    return equals(value, trueValue);\n  });\n\n  ctrl.$parsers.push(function(value) {\n    return value ? trueValue : falseValue;\n  });\n}\n\n\n/**\n * @ngdoc directive\n * @name textarea\n * @restrict E\n *\n * @description\n * HTML textarea element control with angular data-binding. The data-binding and validation\n * properties of this element are exactly the same as those of the\n * {@link ng.directive:input input element}.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the\n *    RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for\n *    patterns defined as scope expressions.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n */\n\n\n/**\n * @ngdoc directive\n * @name input\n * @restrict E\n *\n * @description\n * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,\n * input state control, and validation.\n * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Not every feature offered is available for all input types.\n * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.\n * </div>\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {boolean=} ngRequired Sets `required` attribute if set to true\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the\n *    RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for\n *    patterns defined as scope expressions.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n *    This parameter is ignored for input[type=password] controls, which will never trim the\n *    input.\n *\n * @example\n    <example name=\"input-directive\" module=\"inputExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('inputExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.user = {name: 'guest', last: 'visitor'};\n            }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <form name=\"myForm\">\n           User name: <input type=\"text\" name=\"userName\" ng-model=\"user.name\" required>\n           <span class=\"error\" ng-show=\"myForm.userName.$error.required\">\n             Required!</span><br>\n           Last name: <input type=\"text\" name=\"lastName\" ng-model=\"user.last\"\n             ng-minlength=\"3\" ng-maxlength=\"10\">\n           <span class=\"error\" ng-show=\"myForm.lastName.$error.minlength\">\n             Too short!</span>\n           <span class=\"error\" ng-show=\"myForm.lastName.$error.maxlength\">\n             Too long!</span><br>\n         </form>\n         <hr>\n         <tt>user = {{user}}</tt><br/>\n         <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>\n         <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>\n         <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>\n         <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>\n         <tt>myForm.$valid = {{myForm.$valid}}</tt><br>\n         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>\n         <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>\n         <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>\n       </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var user = element(by.exactBinding('user'));\n        var userNameValid = element(by.binding('myForm.userName.$valid'));\n        var lastNameValid = element(by.binding('myForm.lastName.$valid'));\n        var lastNameError = element(by.binding('myForm.lastName.$error'));\n        var formValid = element(by.binding('myForm.$valid'));\n        var userNameInput = element(by.model('user.name'));\n        var userLastInput = element(by.model('user.last'));\n\n        it('should initialize to model', function() {\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty when required', function() {\n          userNameInput.clear();\n          userNameInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('false');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be valid if empty when min length is set', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"\"}');\n          expect(lastNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if less than required min length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('xx');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('minlength');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be invalid if longer than max length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('some ridiculously long name');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('maxlength');\n          expect(formValid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n */\nvar inputDirective = ['$browser', '$sniffer', '$filter', '$parse',\n    function($browser, $sniffer, $filter, $parse) {\n  return {\n    restrict: 'E',\n    require: ['?ngModel'],\n    link: {\n      pre: function(scope, element, attr, ctrls) {\n        if (ctrls[0]) {\n          (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,\n                                                              $browser, $filter, $parse);\n        }\n      }\n    }\n  };\n}];\n\n\n\nvar CONSTANT_VALUE_REGEXP = /^(true|false|\\d+)$/;\n/**\n * @ngdoc directive\n * @name ngValue\n *\n * @description\n * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},\n * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to\n * the bound value.\n *\n * `ngValue` is useful when dynamically generating lists of radio buttons using\n * {@link ngRepeat `ngRepeat`}, as shown below.\n *\n * Likewise, `ngValue` can be used to generate `<option>` elements for\n * the {@link select `select`} element. In that case however, only strings are supported\n * for the `value `attribute, so the resulting `ngModel` will always be a string.\n * Support for `select` models with non-string values is available via `ngOptions`.\n *\n * @element input\n * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute\n *   of the `input` element\n *\n * @example\n    <example name=\"ngValue-directive\" module=\"valueExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('valueExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.names = ['pizza', 'unicorns', 'robots'];\n              $scope.my = { favorite: 'unicorns' };\n            }]);\n       </script>\n        <form ng-controller=\"ExampleController\">\n          <h2>Which is your favorite?</h2>\n            <label ng-repeat=\"name in names\" for=\"{{name}}\">\n              {{name}}\n              <input type=\"radio\"\n                     ng-model=\"my.favorite\"\n                     ng-value=\"name\"\n                     id=\"{{name}}\"\n                     name=\"favorite\">\n            </label>\n          <div>You chose {{my.favorite}}</div>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var favorite = element(by.binding('my.favorite'));\n\n        it('should initialize to model', function() {\n          expect(favorite.getText()).toContain('unicorns');\n        });\n        it('should bind the values to the inputs', function() {\n          element.all(by.model('my.favorite')).get(0).click();\n          expect(favorite.getText()).toContain('pizza');\n        });\n      </file>\n    </example>\n */\nvar ngValueDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    compile: function(tpl, tplAttr) {\n      if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {\n        return function ngValueConstantLink(scope, elm, attr) {\n          attr.$set('value', scope.$eval(attr.ngValue));\n        };\n      } else {\n        return function ngValueLink(scope, elm, attr) {\n          scope.$watch(attr.ngValue, function valueWatchAction(value) {\n            attr.$set('value', value);\n          });\n        };\n      }\n    }\n  };\n};\n\n/**\n * @ngdoc directive\n * @name ngBind\n * @restrict AC\n *\n * @description\n * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element\n * with the value of a given expression, and to update the text content when the value of that\n * expression changes.\n *\n * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like\n * `{{ expression }}` which is similar but less verbose.\n *\n * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily\n * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an\n * element attribute, it makes the bindings invisible to the user while the page is loading.\n *\n * An alternative solution to this problem would be using the\n * {@link ng.directive:ngCloak ngCloak} directive.\n *\n *\n * @element ANY\n * @param {expression} ngBind {@link guide/expression Expression} to evaluate.\n *\n * @example\n * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.name = 'Whirled';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         Enter name: <input type=\"text\" ng-model=\"name\"><br>\n         Hello <span ng-bind=\"name\"></span>!\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var nameInput = element(by.model('name'));\n\n         expect(element(by.binding('name')).getText()).toBe('Whirled');\n         nameInput.clear();\n         nameInput.sendKeys('world');\n         expect(element(by.binding('name')).getText()).toBe('world');\n       });\n     </file>\n   </example>\n */\nvar ngBindDirective = ['$compile', function($compile) {\n  return {\n    restrict: 'AC',\n    compile: function ngBindCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBind);\n        element = element[0];\n        scope.$watch(attr.ngBind, function ngBindWatchAction(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindTemplate\n *\n * @description\n * The `ngBindTemplate` directive specifies that the element\n * text content should be replaced with the interpolation of the template\n * in the `ngBindTemplate` attribute.\n * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`\n * expressions. This directive is needed since some HTML elements\n * (such as TITLE and OPTION) cannot contain SPAN elements.\n *\n * @element ANY\n * @param {string} ngBindTemplate template of form\n *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.\n *\n * @example\n * Try it here: enter text in text box and watch the greeting change.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.salutation = 'Hello';\n             $scope.name = 'World';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n        Salutation: <input type=\"text\" ng-model=\"salutation\"><br>\n        Name: <input type=\"text\" ng-model=\"name\"><br>\n        <pre ng-bind-template=\"{{salutation}} {{name}}!\"></pre>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var salutationElem = element(by.binding('salutation'));\n         var salutationInput = element(by.model('salutation'));\n         var nameInput = element(by.model('name'));\n\n         expect(salutationElem.getText()).toBe('Hello World!');\n\n         salutationInput.clear();\n         salutationInput.sendKeys('Greetings');\n         nameInput.clear();\n         nameInput.sendKeys('user');\n\n         expect(salutationElem.getText()).toBe('Greetings user!');\n       });\n     </file>\n   </example>\n */\nvar ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {\n  return {\n    compile: function ngBindTemplateCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindTemplateLink(scope, element, attr) {\n        var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));\n        $compile.$$addBindingInfo(element, interpolateFn.expressions);\n        element = element[0];\n        attr.$observe('ngBindTemplate', function(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindHtml\n *\n * @description\n * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,\n * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.\n * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link\n * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}\n * in your module's dependencies, you need to include \"angular-sanitize.js\" in your application.\n *\n * You may also bypass sanitization for values you know are safe. To do so, bind to\n * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}.  See the example\n * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.\n *\n * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you\n * will have an exception (instead of an exploit.)\n *\n * @element ANY\n * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.\n *\n * @example\n\n   <example module=\"bindHtmlExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n        <p ng-bind-html=\"myHTML\"></p>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n       angular.module('bindHtmlExample', ['ngSanitize'])\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.myHTML =\n              'I am an <code>HTML</code>string with ' +\n              '<a href=\"#\">links!</a> and other <em>stuff</em>';\n         }]);\n     </file>\n\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind-html', function() {\n         expect(element(by.binding('myHTML')).getText()).toBe(\n             'I am an HTMLstring with links! and other stuff');\n       });\n     </file>\n   </example>\n */\nvar ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {\n  return {\n    restrict: 'A',\n    compile: function ngBindHtmlCompile(tElement, tAttrs) {\n      var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);\n      var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {\n        return (value || '').toString();\n      });\n      $compile.$$addBindingClass(tElement);\n\n      return function ngBindHtmlLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBindHtml);\n\n        scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {\n          // we re-evaluate the expr because we want a TrustedValueHolderType\n          // for $sce, not a string\n          element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');\n        });\n      };\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngChange\n *\n * @description\n * Evaluate the given expression when the user changes the input.\n * The expression is evaluated immediately, unlike the JavaScript onchange event\n * which only triggers at the end of a change (usually, when the user leaves the\n * form element or presses the return key).\n *\n * The `ngChange` expression is only evaluated when a change in the input value causes\n * a new value to be committed to the model.\n *\n * It will not be evaluated:\n * * if the value returned from the `$parsers` transformation pipeline has not changed\n * * if the input has continued to be invalid since the model will stay `null`\n * * if the model is changed programmatically and not by a change to the input value\n *\n *\n * Note, this directive requires `ngModel` to be present.\n *\n * @element input\n * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change\n * in input value.\n *\n * @example\n * <example name=\"ngChange-directive\" module=\"changeExample\">\n *   <file name=\"index.html\">\n *     <script>\n *       angular.module('changeExample', [])\n *         .controller('ExampleController', ['$scope', function($scope) {\n *           $scope.counter = 0;\n *           $scope.change = function() {\n *             $scope.counter++;\n *           };\n *         }]);\n *     </script>\n *     <div ng-controller=\"ExampleController\">\n *       <input type=\"checkbox\" ng-model=\"confirmed\" ng-change=\"change()\" id=\"ng-change-example1\" />\n *       <input type=\"checkbox\" ng-model=\"confirmed\" id=\"ng-change-example2\" />\n *       <label for=\"ng-change-example2\">Confirmed</label><br />\n *       <tt>debug = {{confirmed}}</tt><br/>\n *       <tt>counter = {{counter}}</tt><br/>\n *     </div>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var counter = element(by.binding('counter'));\n *     var debug = element(by.binding('confirmed'));\n *\n *     it('should evaluate the expression if changing from view', function() {\n *       expect(counter.getText()).toContain('0');\n *\n *       element(by.id('ng-change-example1')).click();\n *\n *       expect(counter.getText()).toContain('1');\n *       expect(debug.getText()).toContain('true');\n *     });\n *\n *     it('should not evaluate the expression if changing from model', function() {\n *       element(by.id('ng-change-example2')).click();\n\n *       expect(counter.getText()).toContain('0');\n *       expect(debug.getText()).toContain('true');\n *     });\n *   </file>\n * </example>\n */\nvar ngChangeDirective = valueFn({\n  restrict: 'A',\n  require: 'ngModel',\n  link: function(scope, element, attr, ctrl) {\n    ctrl.$viewChangeListeners.push(function() {\n      scope.$eval(attr.ngChange);\n    });\n  }\n});\n\nfunction classDirective(name, selector) {\n  name = 'ngClass' + name;\n  return ['$animate', function($animate) {\n    return {\n      restrict: 'AC',\n      link: function(scope, element, attr) {\n        var oldVal;\n\n        scope.$watch(attr[name], ngClassWatchAction, true);\n\n        attr.$observe('class', function(value) {\n          ngClassWatchAction(scope.$eval(attr[name]));\n        });\n\n\n        if (name !== 'ngClass') {\n          scope.$watch('$index', function($index, old$index) {\n            // jshint bitwise: false\n            var mod = $index & 1;\n            if (mod !== (old$index & 1)) {\n              var classes = arrayClasses(scope.$eval(attr[name]));\n              mod === selector ?\n                addClasses(classes) :\n                removeClasses(classes);\n            }\n          });\n        }\n\n        function addClasses(classes) {\n          var newClasses = digestClassCounts(classes, 1);\n          attr.$addClass(newClasses);\n        }\n\n        function removeClasses(classes) {\n          var newClasses = digestClassCounts(classes, -1);\n          attr.$removeClass(newClasses);\n        }\n\n        function digestClassCounts(classes, count) {\n          var classCounts = element.data('$classCounts') || {};\n          var classesToUpdate = [];\n          forEach(classes, function(className) {\n            if (count > 0 || classCounts[className]) {\n              classCounts[className] = (classCounts[className] || 0) + count;\n              if (classCounts[className] === +(count > 0)) {\n                classesToUpdate.push(className);\n              }\n            }\n          });\n          element.data('$classCounts', classCounts);\n          return classesToUpdate.join(' ');\n        }\n\n        function updateClasses(oldClasses, newClasses) {\n          var toAdd = arrayDifference(newClasses, oldClasses);\n          var toRemove = arrayDifference(oldClasses, newClasses);\n          toAdd = digestClassCounts(toAdd, 1);\n          toRemove = digestClassCounts(toRemove, -1);\n          if (toAdd && toAdd.length) {\n            $animate.addClass(element, toAdd);\n          }\n          if (toRemove && toRemove.length) {\n            $animate.removeClass(element, toRemove);\n          }\n        }\n\n        function ngClassWatchAction(newVal) {\n          if (selector === true || scope.$index % 2 === selector) {\n            var newClasses = arrayClasses(newVal || []);\n            if (!oldVal) {\n              addClasses(newClasses);\n            } else if (!equals(newVal,oldVal)) {\n              var oldClasses = arrayClasses(oldVal);\n              updateClasses(oldClasses, newClasses);\n            }\n          }\n          oldVal = shallowCopy(newVal);\n        }\n      }\n    };\n\n    function arrayDifference(tokens1, tokens2) {\n      var values = [];\n\n      outer:\n      for (var i = 0; i < tokens1.length; i++) {\n        var token = tokens1[i];\n        for (var j = 0; j < tokens2.length; j++) {\n          if (token == tokens2[j]) continue outer;\n        }\n        values.push(token);\n      }\n      return values;\n    }\n\n    function arrayClasses(classVal) {\n      if (isArray(classVal)) {\n        return classVal;\n      } else if (isString(classVal)) {\n        return classVal.split(' ');\n      } else if (isObject(classVal)) {\n        var classes = [];\n        forEach(classVal, function(v, k) {\n          if (v) {\n            classes = classes.concat(k.split(' '));\n          }\n        });\n        return classes;\n      }\n      return classVal;\n    }\n  }];\n}\n\n/**\n * @ngdoc directive\n * @name ngClass\n * @restrict AC\n *\n * @description\n * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding\n * an expression that represents all classes to be added.\n *\n * The directive operates in three different ways, depending on which of three types the expression\n * evaluates to:\n *\n * 1. If the expression evaluates to a string, the string should be one or more space-delimited class\n * names.\n *\n * 2. If the expression evaluates to an array, each element of the array should be a string that is\n * one or more space-delimited class names.\n *\n * 3. If the expression evaluates to an object, then for each key-value pair of the\n * object with a truthy value the corresponding key is used as a class name.\n *\n * The directive won't add duplicate classes if a particular class was already set.\n *\n * When the expression changes, the previously added classes are removed and only then the\n * new classes are added.\n *\n * @animations\n * **add** - happens just before the class is applied to the elements\n *\n * **remove** - happens just before the class is removed from the element\n *\n * @element ANY\n * @param {expression} ngClass {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class\n *   names, an array, or a map of class names to boolean values. In the case of a map, the\n *   names of the properties whose values are truthy will be added as css classes to the\n *   element.\n *\n * @example Example that demonstrates basic bindings via ngClass directive.\n   <example>\n     <file name=\"index.html\">\n       <p ng-class=\"{strike: deleted, bold: important, red: error}\">Map Syntax Example</p>\n       <input type=\"checkbox\" ng-model=\"deleted\"> deleted (apply \"strike\" class)<br>\n       <input type=\"checkbox\" ng-model=\"important\"> important (apply \"bold\" class)<br>\n       <input type=\"checkbox\" ng-model=\"error\"> error (apply \"red\" class)\n       <hr>\n       <p ng-class=\"style\">Using String Syntax</p>\n       <input type=\"text\" ng-model=\"style\" placeholder=\"Type: bold strike red\">\n       <hr>\n       <p ng-class=\"[style1, style2, style3]\">Using Array Syntax</p>\n       <input ng-model=\"style1\" placeholder=\"Type: bold, strike or red\"><br>\n       <input ng-model=\"style2\" placeholder=\"Type: bold, strike or red\"><br>\n       <input ng-model=\"style3\" placeholder=\"Type: bold, strike or red\"><br>\n     </file>\n     <file name=\"style.css\">\n       .strike {\n         text-decoration: line-through;\n       }\n       .bold {\n           font-weight: bold;\n       }\n       .red {\n           color: red;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var ps = element.all(by.css('p'));\n\n       it('should let you toggle the class', function() {\n\n         expect(ps.first().getAttribute('class')).not.toMatch(/bold/);\n         expect(ps.first().getAttribute('class')).not.toMatch(/red/);\n\n         element(by.model('important')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/bold/);\n\n         element(by.model('error')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/red/);\n       });\n\n       it('should let you toggle string example', function() {\n         expect(ps.get(1).getAttribute('class')).toBe('');\n         element(by.model('style')).clear();\n         element(by.model('style')).sendKeys('red');\n         expect(ps.get(1).getAttribute('class')).toBe('red');\n       });\n\n       it('array example should have 3 classes', function() {\n         expect(ps.last().getAttribute('class')).toBe('');\n         element(by.model('style1')).sendKeys('bold');\n         element(by.model('style2')).sendKeys('strike');\n         element(by.model('style3')).sendKeys('red');\n         expect(ps.last().getAttribute('class')).toBe('bold strike red');\n       });\n     </file>\n   </example>\n\n   ## Animations\n\n   The example below demonstrates how to perform animations using ngClass.\n\n   <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n     <file name=\"index.html\">\n      <input id=\"setbtn\" type=\"button\" value=\"set\" ng-click=\"myVar='my-class'\">\n      <input id=\"clearbtn\" type=\"button\" value=\"clear\" ng-click=\"myVar=''\">\n      <br>\n      <span class=\"base-class\" ng-class=\"myVar\">Sample Text</span>\n     </file>\n     <file name=\"style.css\">\n       .base-class {\n         -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n       }\n\n       .base-class.my-class {\n         color: red;\n         font-size:3em;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class', function() {\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n\n         element(by.id('setbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).\n           toMatch(/my-class/);\n\n         element(by.id('clearbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n       });\n     </file>\n   </example>\n\n\n   ## ngClass and pre-existing CSS3 Transitions/Animations\n   The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.\n   Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder\n   any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure\n   to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and\n   {@link ng.$animate#removeClass $animate.removeClass}.\n */\nvar ngClassDirective = classDirective('', true);\n\n/**\n * @ngdoc directive\n * @name ngClassOdd\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}}\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassOddDirective = classDirective('Odd', 0);\n\n/**\n * @ngdoc directive\n * @name ngClassEven\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The\n *   result of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}} &nbsp; &nbsp; &nbsp;\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassEvenDirective = classDirective('Even', 1);\n\n/**\n * @ngdoc directive\n * @name ngCloak\n * @restrict AC\n *\n * @description\n * The `ngCloak` directive is used to prevent the Angular html template from being briefly\n * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this\n * directive to avoid the undesirable flicker effect caused by the html template display.\n *\n * The directive can be applied to the `<body>` element, but the preferred usage is to apply\n * multiple `ngCloak` directives to small portions of the page to permit progressive rendering\n * of the browser view.\n *\n * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and\n * `angular.min.js`.\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```css\n * [ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {\n *   display: none !important;\n * }\n * ```\n *\n * When this css rule is loaded by the browser, all html elements (including their children) that\n * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive\n * during the compilation of the template it deletes the `ngCloak` element attribute, making\n * the compiled element visible.\n *\n * For the best result, the `angular.js` script must be loaded in the head section of the html\n * document; alternatively, the css rule above must be included in the external stylesheet of the\n * application.\n *\n * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they\n * cannot match the `[ng\\:cloak]` selector. To work around this limitation, you must add the css\n * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.\n *\n * @element ANY\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <div id=\"template1\" ng-cloak>{{ 'hello' }}</div>\n        <div id=\"template2\" ng-cloak class=\"ng-cloak\">{{ 'hello IE7' }}</div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should remove the template directive and css class', function() {\n         expect($('#template1').getAttribute('ng-cloak')).\n           toBeNull();\n         expect($('#template2').getAttribute('ng-cloak')).\n           toBeNull();\n       });\n     </file>\n   </example>\n *\n */\nvar ngCloakDirective = ngDirective({\n  compile: function(element, attr) {\n    attr.$set('ngCloak', undefined);\n    element.removeClass('ng-cloak');\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngController\n *\n * @description\n * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular\n * supports the principles behind the Model-View-Controller design pattern.\n *\n * MVC components in angular:\n *\n * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties\n *   are accessed through bindings.\n * * View — The template (HTML with data bindings) that is rendered into the View.\n * * Controller — The `ngController` directive specifies a Controller class; the class contains business\n *   logic behind the application to decorate the scope with functions and values\n *\n * Note that you can also attach controllers to the DOM by declaring it in a route definition\n * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller\n * again using `ng-controller` in the template itself.  This will cause the controller to be attached\n * and executed twice.\n *\n * @element ANY\n * @scope\n * @priority 500\n * @param {expression} ngController Name of a constructor function registered with the current\n * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}\n * that on the current scope evaluates to a constructor function.\n *\n * The controller instance can be published into a scope property by specifying\n * `ng-controller=\"as propertyName\"`.\n *\n * If the current `$controllerProvider` is configured to use globals (via\n * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may\n * also be the name of a globally accessible constructor function (not recommended).\n *\n * @example\n * Here is a simple form for editing user contact information. Adding, removing, clearing, and\n * greeting are methods declared on the controller (see source tab). These methods can\n * easily be called from the angular markup. Any changes to the data are automatically reflected\n * in the View without the need for a manual update.\n *\n * Two different declaration styles are included below:\n *\n * * one binds methods and properties directly onto the controller using `this`:\n * `ng-controller=\"SettingsController1 as settings\"`\n * * one injects `$scope` into the controller:\n * `ng-controller=\"SettingsController2\"`\n *\n * The second option is more common in the Angular community, and is generally used in boilerplates\n * and in this guide. However, there are advantages to binding properties directly to the controller\n * and avoiding scope.\n *\n * * Using `controller as` makes it obvious which controller you are accessing in the template when\n * multiple controllers apply to an element.\n * * If you are writing your controllers as classes you have easier access to the properties and\n * methods, which will appear on the scope, from inside the controller code.\n * * Since there is always a `.` in the bindings, you don't have to worry about prototypal\n * inheritance masking primitives.\n *\n * This example demonstrates the `controller as` syntax.\n *\n * <example name=\"ngControllerAs\" module=\"controllerAsExample\">\n *   <file name=\"index.html\">\n *    <div id=\"ctrl-as-exmpl\" ng-controller=\"SettingsController1 as settings\">\n *      Name: <input type=\"text\" ng-model=\"settings.name\"/>\n *      [ <a href=\"\" ng-click=\"settings.greet()\">greet</a> ]<br/>\n *      Contact:\n *      <ul>\n *        <li ng-repeat=\"contact in settings.contacts\">\n *          <select ng-model=\"contact.type\">\n *             <option>phone</option>\n *             <option>email</option>\n *          </select>\n *          <input type=\"text\" ng-model=\"contact.value\"/>\n *          [ <a href=\"\" ng-click=\"settings.clearContact(contact)\">clear</a>\n *          | <a href=\"\" ng-click=\"settings.removeContact(contact)\">X</a> ]\n *        </li>\n *        <li>[ <a href=\"\" ng-click=\"settings.addContact()\">add</a> ]</li>\n *     </ul>\n *    </div>\n *   </file>\n *   <file name=\"app.js\">\n *    angular.module('controllerAsExample', [])\n *      .controller('SettingsController1', SettingsController1);\n *\n *    function SettingsController1() {\n *      this.name = \"John Smith\";\n *      this.contacts = [\n *        {type: 'phone', value: '408 555 1212'},\n *        {type: 'email', value: 'john.smith@example.org'} ];\n *    }\n *\n *    SettingsController1.prototype.greet = function() {\n *      alert(this.name);\n *    };\n *\n *    SettingsController1.prototype.addContact = function() {\n *      this.contacts.push({type: 'email', value: 'yourname@example.org'});\n *    };\n *\n *    SettingsController1.prototype.removeContact = function(contactToRemove) {\n *     var index = this.contacts.indexOf(contactToRemove);\n *      this.contacts.splice(index, 1);\n *    };\n *\n *    SettingsController1.prototype.clearContact = function(contact) {\n *      contact.type = 'phone';\n *      contact.value = '';\n *    };\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it('should check controller as', function() {\n *       var container = element(by.id('ctrl-as-exmpl'));\n *         expect(container.element(by.model('settings.name'))\n *           .getAttribute('value')).toBe('John Smith');\n *\n *       var firstRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(0));\n *       var secondRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(1));\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('408 555 1212');\n *\n *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('john.smith@example.org');\n *\n *       firstRepeat.element(by.linkText('clear')).click();\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('');\n *\n *       container.element(by.linkText('add')).click();\n *\n *       expect(container.element(by.repeater('contact in settings.contacts').row(2))\n *           .element(by.model('contact.value'))\n *           .getAttribute('value'))\n *           .toBe('yourname@example.org');\n *     });\n *   </file>\n * </example>\n *\n * This example demonstrates the \"attach to `$scope`\" style of controller.\n *\n * <example name=\"ngController\" module=\"controllerExample\">\n *  <file name=\"index.html\">\n *   <div id=\"ctrl-exmpl\" ng-controller=\"SettingsController2\">\n *     Name: <input type=\"text\" ng-model=\"name\"/>\n *     [ <a href=\"\" ng-click=\"greet()\">greet</a> ]<br/>\n *     Contact:\n *     <ul>\n *       <li ng-repeat=\"contact in contacts\">\n *         <select ng-model=\"contact.type\">\n *            <option>phone</option>\n *            <option>email</option>\n *         </select>\n *         <input type=\"text\" ng-model=\"contact.value\"/>\n *         [ <a href=\"\" ng-click=\"clearContact(contact)\">clear</a>\n *         | <a href=\"\" ng-click=\"removeContact(contact)\">X</a> ]\n *       </li>\n *       <li>[ <a href=\"\" ng-click=\"addContact()\">add</a> ]</li>\n *    </ul>\n *   </div>\n *  </file>\n *  <file name=\"app.js\">\n *   angular.module('controllerExample', [])\n *     .controller('SettingsController2', ['$scope', SettingsController2]);\n *\n *   function SettingsController2($scope) {\n *     $scope.name = \"John Smith\";\n *     $scope.contacts = [\n *       {type:'phone', value:'408 555 1212'},\n *       {type:'email', value:'john.smith@example.org'} ];\n *\n *     $scope.greet = function() {\n *       alert($scope.name);\n *     };\n *\n *     $scope.addContact = function() {\n *       $scope.contacts.push({type:'email', value:'yourname@example.org'});\n *     };\n *\n *     $scope.removeContact = function(contactToRemove) {\n *       var index = $scope.contacts.indexOf(contactToRemove);\n *       $scope.contacts.splice(index, 1);\n *     };\n *\n *     $scope.clearContact = function(contact) {\n *       contact.type = 'phone';\n *       contact.value = '';\n *     };\n *   }\n *  </file>\n *  <file name=\"protractor.js\" type=\"protractor\">\n *    it('should check controller', function() {\n *      var container = element(by.id('ctrl-exmpl'));\n *\n *      expect(container.element(by.model('name'))\n *          .getAttribute('value')).toBe('John Smith');\n *\n *      var firstRepeat =\n *          container.element(by.repeater('contact in contacts').row(0));\n *      var secondRepeat =\n *          container.element(by.repeater('contact in contacts').row(1));\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('408 555 1212');\n *      expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('john.smith@example.org');\n *\n *      firstRepeat.element(by.linkText('clear')).click();\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('');\n *\n *      container.element(by.linkText('add')).click();\n *\n *      expect(container.element(by.repeater('contact in contacts').row(2))\n *          .element(by.model('contact.value'))\n *          .getAttribute('value'))\n *          .toBe('yourname@example.org');\n *    });\n *  </file>\n *</example>\n\n */\nvar ngControllerDirective = [function() {\n  return {\n    restrict: 'A',\n    scope: true,\n    controller: '@',\n    priority: 500\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngCsp\n *\n * @element html\n * @description\n * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.\n *\n * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.\n *\n * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).\n * For Angular to be CSP compatible there are only two things that we need to do differently:\n *\n * - don't use `Function` constructor to generate optimized value getters\n * - don't inject custom stylesheet into the document\n *\n * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`\n * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will\n * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will\n * be raised.\n *\n * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically\n * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).\n * To make those directives work in CSP mode, include the `angular-csp.css` manually.\n *\n * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This\n * autodetection however triggers a CSP error to be logged in the console:\n *\n * ```\n * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of\n * script in the following Content Security Policy directive: \"default-src 'self'\". Note that\n * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.\n * ```\n *\n * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`\n * directive on the root element of the application or on the `angular.js` script tag, whichever\n * appears first in the html document.\n *\n * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*\n *\n * @example\n * This example shows how to apply the `ngCsp` directive to the `html` tag.\n   ```html\n     <!doctype html>\n     <html ng-app ng-csp>\n     ...\n     ...\n     </html>\n   ```\n  * @example\n      // Note: the suffix `.csp` in the example name triggers\n      // csp mode in our http server!\n      <example name=\"example.csp\" module=\"cspExample\" ng-csp=\"true\">\n        <file name=\"index.html\">\n          <div ng-controller=\"MainController as ctrl\">\n            <div>\n              <button ng-click=\"ctrl.inc()\" id=\"inc\">Increment</button>\n              <span id=\"counter\">\n                {{ctrl.counter}}\n              </span>\n            </div>\n\n            <div>\n              <button ng-click=\"ctrl.evil()\" id=\"evil\">Evil</button>\n              <span id=\"evilError\">\n                {{ctrl.evilError}}\n              </span>\n            </div>\n          </div>\n        </file>\n        <file name=\"script.js\">\n           angular.module('cspExample', [])\n             .controller('MainController', function() {\n                this.counter = 0;\n                this.inc = function() {\n                  this.counter++;\n                };\n                this.evil = function() {\n                  // jshint evil:true\n                  try {\n                    eval('1+2');\n                  } catch (e) {\n                    this.evilError = e.message;\n                  }\n                };\n              });\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var util, webdriver;\n\n          var incBtn = element(by.id('inc'));\n          var counter = element(by.id('counter'));\n          var evilBtn = element(by.id('evil'));\n          var evilError = element(by.id('evilError'));\n\n          function getAndClearSevereErrors() {\n            return browser.manage().logs().get('browser').then(function(browserLog) {\n              return browserLog.filter(function(logEntry) {\n                return logEntry.level.value > webdriver.logging.Level.WARNING.value;\n              });\n            });\n          }\n\n          function clearErrors() {\n            getAndClearSevereErrors();\n          }\n\n          function expectNoErrors() {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              expect(filteredLog.length).toEqual(0);\n              if (filteredLog.length) {\n                console.log('browser console errors: ' + util.inspect(filteredLog));\n              }\n            });\n          }\n\n          function expectError(regex) {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              var found = false;\n              filteredLog.forEach(function(log) {\n                if (log.message.match(regex)) {\n                  found = true;\n                }\n              });\n              if (!found) {\n                throw new Error('expected an error that matches ' + regex);\n              }\n            });\n          }\n\n          beforeEach(function() {\n            util = require('util');\n            webdriver = require('protractor/node_modules/selenium-webdriver');\n          });\n\n          // For now, we only test on Chrome,\n          // as Safari does not load the page with Protractor's injected scripts,\n          // and Firefox webdriver always disables content security policy (#6358)\n          if (browser.params.browser !== 'chrome') {\n            return;\n          }\n\n          it('should not report errors when the page is loaded', function() {\n            // clear errors so we are not dependent on previous tests\n            clearErrors();\n            // Need to reload the page as the page is already loaded when\n            // we come here\n            browser.driver.getCurrentUrl().then(function(url) {\n              browser.get(url);\n            });\n            expectNoErrors();\n          });\n\n          it('should evaluate expressions', function() {\n            expect(counter.getText()).toEqual('0');\n            incBtn.click();\n            expect(counter.getText()).toEqual('1');\n            expectNoErrors();\n          });\n\n          it('should throw and report an error when using \"eval\"', function() {\n            evilBtn.click();\n            expect(evilError.getText()).toMatch(/Content Security Policy/);\n            expectError(/Content Security Policy/);\n          });\n        </file>\n      </example>\n  */\n\n// ngCsp is not implemented as a proper directive any more, because we need it be processed while we\n// bootstrap the system (before $parse is instantiated), for this reason we just have\n// the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc\n\n/**\n * @ngdoc directive\n * @name ngClick\n *\n * @description\n * The ngClick directive allows you to specify custom behavior when\n * an element is clicked.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon\n * click. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-click=\"count = count + 1\" ng-init=\"count=0\">\n        Increment\n      </button>\n      <span>\n        count: {{count}}\n      </span>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-click', function() {\n         expect(element(by.binding('count')).getText()).toMatch('0');\n         element(by.css('button')).click();\n         expect(element(by.binding('count')).getText()).toMatch('1');\n       });\n     </file>\n   </example>\n */\n/*\n * A collection of directives that allows creation of custom event handlers that are defined as\n * angular expressions and are compiled and executed within the current scope.\n */\nvar ngEventDirectives = {};\n\n// For events that might fire synchronously during DOM manipulation\n// we need to execute their event handlers asynchronously using $evalAsync,\n// so that they are not executed in an inconsistent state.\nvar forceAsyncEvents = {\n  'blur': true,\n  'focus': true\n};\nforEach(\n  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),\n  function(eventName) {\n    var directiveName = directiveNormalize('ng-' + eventName);\n    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {\n      return {\n        restrict: 'A',\n        compile: function($element, attr) {\n          // We expose the powerful $event object on the scope that provides access to the Window,\n          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better\n          // checks at the cost of speed since event handler expressions are not executed as\n          // frequently as regular change detection.\n          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);\n          return function ngEventHandler(scope, element) {\n            element.on(eventName, function(event) {\n              var callback = function() {\n                fn(scope, {$event:event});\n              };\n              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {\n                scope.$evalAsync(callback);\n              } else {\n                scope.$apply(callback);\n              }\n            });\n          };\n        }\n      };\n    }];\n  }\n);\n\n/**\n * @ngdoc directive\n * @name ngDblclick\n *\n * @description\n * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon\n * a dblclick. (The Event object is available as `$event`)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-dblclick=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on double click)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousedown\n *\n * @description\n * The ngMousedown directive allows you to specify custom behavior on mousedown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon\n * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousedown=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse down)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseup\n *\n * @description\n * Specify custom behavior on mouseup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon\n * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseup=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse up)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngMouseover\n *\n * @description\n * Specify custom behavior on mouseover event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon\n * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseover=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse is over)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseenter\n *\n * @description\n * Specify custom behavior on mouseenter event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon\n * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseenter=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse enters)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseleave\n *\n * @description\n * Specify custom behavior on mouseleave event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon\n * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseleave=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse leaves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousemove\n *\n * @description\n * Specify custom behavior on mousemove event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon\n * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousemove=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse moves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeydown\n *\n * @description\n * Specify custom behavior on keydown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon\n * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keydown=\"count = count + 1\" ng-init=\"count=0\">\n      key down count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeyup\n *\n * @description\n * Specify custom behavior on keyup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon\n * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <p>Typing in the input box below updates the key count</p>\n       <input ng-keyup=\"count = count + 1\" ng-init=\"count=0\"> key up count: {{count}}\n\n       <p>Typing in the input box below updates the keycode</p>\n       <input ng-keyup=\"event=$event\">\n       <p>event keyCode: {{ event.keyCode }}</p>\n       <p>event altKey: {{ event.altKey }}</p>\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeypress\n *\n * @description\n * Specify custom behavior on keypress event.\n *\n * @element ANY\n * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon\n * keypress. ({@link guide/expression#-event- Event object is available as `$event`}\n * and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keypress=\"count = count + 1\" ng-init=\"count=0\">\n      key press count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSubmit\n *\n * @description\n * Enables binding angular expressions to onsubmit events.\n *\n * Additionally it prevents the default action (which for form means sending the request to the\n * server and reloading the current page), but only if the form does not contain `action`,\n * `data-action`, or `x-action` attributes.\n *\n * <div class=\"alert alert-warning\">\n * **Warning:** Be careful not to cause \"double-submission\" by using both the `ngClick` and\n * `ngSubmit` handlers together. See the\n * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}\n * for a detailed discussion of when `ngSubmit` may be triggered.\n * </div>\n *\n * @element form\n * @priority 0\n * @param {expression} ngSubmit {@link guide/expression Expression} to eval.\n * ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example module=\"submitExample\">\n     <file name=\"index.html\">\n      <script>\n        angular.module('submitExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.list = [];\n            $scope.text = 'hello';\n            $scope.submit = function() {\n              if ($scope.text) {\n                $scope.list.push(this.text);\n                $scope.text = '';\n              }\n            };\n          }]);\n      </script>\n      <form ng-submit=\"submit()\" ng-controller=\"ExampleController\">\n        Enter text and hit enter:\n        <input type=\"text\" ng-model=\"text\" name=\"text\" />\n        <input type=\"submit\" id=\"submit\" value=\"Submit\" />\n        <pre>list={{list}}</pre>\n      </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-submit', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n         expect(element(by.model('text')).getAttribute('value')).toBe('');\n       });\n       it('should ignore empty strings', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n        });\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngFocus\n *\n * @description\n * Specify custom behavior on focus event.\n *\n * Note: As the `focus` event is executed synchronously when calling `input.focus()`\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon\n * focus. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngBlur\n *\n * @description\n * Specify custom behavior on blur event.\n *\n * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when\n * an element has lost focus.\n *\n * Note: As the `blur` event is executed synchronously also during DOM manipulations\n * (e.g. removing a focussed input),\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon\n * blur. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngCopy\n *\n * @description\n * Specify custom behavior on copy event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon\n * copy. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-copy=\"copied=true\" ng-init=\"copied=false; value='copy me'\" ng-model=\"value\">\n      copied: {{copied}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngCut\n *\n * @description\n * Specify custom behavior on cut event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon\n * cut. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-cut=\"cut=true\" ng-init=\"cut=false; value='cut me'\" ng-model=\"value\">\n      cut: {{cut}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngPaste\n *\n * @description\n * Specify custom behavior on paste event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon\n * paste. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-paste=\"paste=true\" ng-init=\"paste=false\" placeholder='paste here'>\n      pasted: {{paste}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngIf\n * @restrict A\n *\n * @description\n * The `ngIf` directive removes or recreates a portion of the DOM tree based on an\n * {expression}. If the expression assigned to `ngIf` evaluates to a false\n * value then the element is removed from the DOM, otherwise a clone of the\n * element is reinserted into the DOM.\n *\n * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the\n * element in the DOM rather than changing its visibility via the `display` css property.  A common\n * case when this difference is significant is when using css selectors that rely on an element's\n * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.\n *\n * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope\n * is created when the element is restored.  The scope created within `ngIf` inherits from\n * its parent scope using\n * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).\n * An important implication of this is if `ngModel` is used within `ngIf` to bind to\n * a javascript primitive defined in the parent scope. In this case any modifications made to the\n * variable within the child scope will override (hide) the value in the parent scope.\n *\n * Also, `ngIf` recreates elements using their compiled state. An example of this behavior\n * is if an element's class attribute is directly modified after it's compiled, using something like\n * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element\n * the added class will be lost because the original compiled state is used to regenerate the element.\n *\n * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`\n * and `leave` effects.\n *\n * @animations\n * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container\n * leave - happens just before the `ngIf` contents are removed from the DOM\n *\n * @element ANY\n * @scope\n * @priority 600\n * @param {expression} ngIf If the {@link guide/expression expression} is falsy then\n *     the element is removed from the DOM tree. If it is truthy a copy of the compiled\n *     element is added to the DOM tree.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\" ng-init=\"checked=true\" /><br/>\n      Show when checked:\n      <span ng-if=\"checked\" class=\"animate-if\">\n        This is removed when the checkbox is unchecked.\n      </span>\n    </file>\n    <file name=\"animations.css\">\n      .animate-if {\n        background:white;\n        border:1px solid black;\n        padding:10px;\n      }\n\n      .animate-if.ng-enter, .animate-if.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n      }\n\n      .animate-if.ng-enter,\n      .animate-if.ng-leave.ng-leave-active {\n        opacity:0;\n      }\n\n      .animate-if.ng-leave,\n      .animate-if.ng-enter.ng-enter-active {\n        opacity:1;\n      }\n    </file>\n  </example>\n */\nvar ngIfDirective = ['$animate', function($animate) {\n  return {\n    multiElement: true,\n    transclude: 'element',\n    priority: 600,\n    terminal: true,\n    restrict: 'A',\n    $$tlb: true,\n    link: function($scope, $element, $attr, ctrl, $transclude) {\n        var block, childScope, previousElements;\n        $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {\n\n          if (value) {\n            if (!childScope) {\n              $transclude(function(clone, newScope) {\n                childScope = newScope;\n                clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block = {\n                  clone: clone\n                };\n                $animate.enter(clone, $element.parent(), $element);\n              });\n            }\n          } else {\n            if (previousElements) {\n              previousElements.remove();\n              previousElements = null;\n            }\n            if (childScope) {\n              childScope.$destroy();\n              childScope = null;\n            }\n            if (block) {\n              previousElements = getBlockNodes(block.clone);\n              $animate.leave(previousElements).then(function() {\n                previousElements = null;\n              });\n              block = null;\n            }\n          }\n        });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngInclude\n * @restrict ECA\n *\n * @description\n * Fetches, compiles and includes an external HTML fragment.\n *\n * By default, the template URL is restricted to the same domain and protocol as the\n * application document. This is done by calling {@link $sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols\n * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or\n * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link\n * ng.$sce Strict Contextual Escaping}.\n *\n * In addition, the browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy may further restrict whether the template is successfully loaded.\n * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`\n * access on some browsers.\n *\n * @animations\n * enter - animation is used to bring new content into the browser.\n * leave - animation is used to animate existing content away.\n *\n * The enter and leave animation occur concurrently.\n *\n * @scope\n * @priority 400\n *\n * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,\n *                 make sure you wrap it in **single** quotes, e.g. `src=\"'myPartialTemplate.html'\"`.\n * @param {string=} onload Expression to evaluate when a new partial is loaded.\n *\n * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll\n *                  $anchorScroll} to scroll the viewport after the content is loaded.\n *\n *                  - If the attribute is not set, disable scrolling.\n *                  - If the attribute is set without value, enable scrolling.\n *                  - Otherwise enable scrolling only if the expression evaluates to truthy value.\n *\n * @example\n  <example module=\"includeExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n     <div ng-controller=\"ExampleController\">\n       <select ng-model=\"template\" ng-options=\"t.name for t in templates\">\n        <option value=\"\">(blank)</option>\n       </select>\n       url of the template: <code>{{template.url}}</code>\n       <hr/>\n       <div class=\"slide-animate-container\">\n         <div class=\"slide-animate\" ng-include=\"template.url\"></div>\n       </div>\n     </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('includeExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.templates =\n            [ { name: 'template1.html', url: 'template1.html'},\n              { name: 'template2.html', url: 'template2.html'} ];\n          $scope.template = $scope.templates[0];\n        }]);\n     </file>\n    <file name=\"template1.html\">\n      Content of template1.html\n    </file>\n    <file name=\"template2.html\">\n      Content of template2.html\n    </file>\n    <file name=\"animations.css\">\n      .slide-animate-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .slide-animate {\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter, .slide-animate.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n        display:block;\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter {\n        top:-50px;\n      }\n      .slide-animate.ng-enter.ng-enter-active {\n        top:0;\n      }\n\n      .slide-animate.ng-leave {\n        top:0;\n      }\n      .slide-animate.ng-leave.ng-leave-active {\n        top:50px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var templateSelect = element(by.model('template'));\n      var includeElem = element(by.css('[ng-include]'));\n\n      it('should load template1.html', function() {\n        expect(includeElem.getText()).toMatch(/Content of template1.html/);\n      });\n\n      it('should load template2.html', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          // See https://github.com/angular/protractor/issues/480\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(2).click();\n        expect(includeElem.getText()).toMatch(/Content of template2.html/);\n      });\n\n      it('should change to blank', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(0).click();\n        expect(includeElem.isPresent()).toBe(false);\n      });\n    </file>\n  </example>\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentRequested\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted every time the ngInclude content is requested.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentLoaded\n * @eventType emit on the current ngInclude scope\n * @description\n * Emitted every time the ngInclude content is reloaded.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentError\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\nvar ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',\n                  function($templateRequest,   $anchorScroll,   $animate,   $sce) {\n  return {\n    restrict: 'ECA',\n    priority: 400,\n    terminal: true,\n    transclude: 'element',\n    controller: angular.noop,\n    compile: function(element, attr) {\n      var srcExp = attr.ngInclude || attr.src,\n          onloadExp = attr.onload || '',\n          autoScrollExp = attr.autoscroll;\n\n      return function(scope, $element, $attr, ctrl, $transclude) {\n        var changeCounter = 0,\n            currentScope,\n            previousElement,\n            currentElement;\n\n        var cleanupLastIncludeContent = function() {\n          if (previousElement) {\n            previousElement.remove();\n            previousElement = null;\n          }\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n          if (currentElement) {\n            $animate.leave(currentElement).then(function() {\n              previousElement = null;\n            });\n            previousElement = currentElement;\n            currentElement = null;\n          }\n        };\n\n        scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {\n          var afterAnimation = function() {\n            if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {\n              $anchorScroll();\n            }\n          };\n          var thisChangeId = ++changeCounter;\n\n          if (src) {\n            //set the 2nd param to true to ignore the template request error so that the inner\n            //contents and scope can be cleaned up.\n            $templateRequest(src, true).then(function(response) {\n              if (thisChangeId !== changeCounter) return;\n              var newScope = scope.$new();\n              ctrl.template = response;\n\n              // Note: This will also link all children of ng-include that were contained in the original\n              // html. If that content contains controllers, ... they could pollute/change the scope.\n              // However, using ng-include on an element with additional content does not make sense...\n              // Note: We can't remove them in the cloneAttchFn of $transclude as that\n              // function is called before linking the content, which would apply child\n              // directives to non existing elements.\n              var clone = $transclude(newScope, function(clone) {\n                cleanupLastIncludeContent();\n                $animate.enter(clone, null, $element).then(afterAnimation);\n              });\n\n              currentScope = newScope;\n              currentElement = clone;\n\n              currentScope.$emit('$includeContentLoaded', src);\n              scope.$eval(onloadExp);\n            }, function() {\n              if (thisChangeId === changeCounter) {\n                cleanupLastIncludeContent();\n                scope.$emit('$includeContentError', src);\n              }\n            });\n            scope.$emit('$includeContentRequested', src);\n          } else {\n            cleanupLastIncludeContent();\n            ctrl.template = null;\n          }\n        });\n      };\n    }\n  };\n}];\n\n// This directive is called during the $transclude call of the first `ngInclude` directive.\n// It will replace and compile the content of the element with the loaded template.\n// We need this directive so that the element content is already filled when\n// the link function of another directive on the same element as ngInclude\n// is called.\nvar ngIncludeFillContentDirective = ['$compile',\n  function($compile) {\n    return {\n      restrict: 'ECA',\n      priority: -400,\n      require: 'ngInclude',\n      link: function(scope, $element, $attr, ctrl) {\n        if (/SVG/.test($element[0].toString())) {\n          // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not\n          // support innerHTML, so detect this here and try to generate the contents\n          // specially.\n          $element.empty();\n          $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,\n              function namespaceAdaptedClone(clone) {\n            $element.append(clone);\n          }, {futureParentElement: $element});\n          return;\n        }\n\n        $element.html(ctrl.template);\n        $compile($element.contents())(scope);\n      }\n    };\n  }];\n\n/**\n * @ngdoc directive\n * @name ngInit\n * @restrict AC\n *\n * @description\n * The `ngInit` directive allows you to evaluate an expression in the\n * current scope.\n *\n * <div class=\"alert alert-error\">\n * The only appropriate use of `ngInit` is for aliasing special properties of\n * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you\n * should use {@link guide/controller controllers} rather than `ngInit`\n * to initialize values on a scope.\n * </div>\n * <div class=\"alert alert-warning\">\n * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make\n * sure you have parenthesis for correct precedence:\n * <pre class=\"prettyprint\">\n * `<div ng-init=\"test1 = (data | orderBy:'name')\"></div>`\n * </pre>\n * </div>\n *\n * @priority 450\n *\n * @element ANY\n * @param {expression} ngInit {@link guide/expression Expression} to eval.\n *\n * @example\n   <example module=\"initExample\">\n     <file name=\"index.html\">\n   <script>\n     angular.module('initExample', [])\n       .controller('ExampleController', ['$scope', function($scope) {\n         $scope.list = [['a', 'b'], ['c', 'd']];\n       }]);\n   </script>\n   <div ng-controller=\"ExampleController\">\n     <div ng-repeat=\"innerList in list\" ng-init=\"outerIndex = $index\">\n       <div ng-repeat=\"value in innerList\" ng-init=\"innerIndex = $index\">\n          <span class=\"example-init\">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>\n       </div>\n     </div>\n   </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should alias index positions', function() {\n         var elements = element.all(by.css('.example-init'));\n         expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');\n         expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');\n         expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');\n         expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');\n       });\n     </file>\n   </example>\n */\nvar ngInitDirective = ngDirective({\n  priority: 450,\n  compile: function() {\n    return {\n      pre: function(scope, element, attrs) {\n        scope.$eval(attrs.ngInit);\n      }\n    };\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngList\n *\n * @description\n * Text input that converts between a delimited string and an array of strings. The default\n * delimiter is a comma followed by a space - equivalent to `ng-list=\", \"`. You can specify a custom\n * delimiter as the value of the `ngList` attribute - for example, `ng-list=\" | \"`.\n *\n * The behaviour of the directive is affected by the use of the `ngTrim` attribute.\n * * If `ngTrim` is set to `\"false\"` then whitespace around both the separator and each\n *   list item is respected. This implies that the user of the directive is responsible for\n *   dealing with whitespace but also allows you to use whitespace as a delimiter, such as a\n *   tab or newline character.\n * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected\n *   when joining the list items back together) and whitespace around each list item is stripped\n *   before it is added to the model.\n *\n * ### Example with Validation\n *\n * <example name=\"ngList-directive\" module=\"listExample\">\n *   <file name=\"app.js\">\n *      angular.module('listExample', [])\n *        .controller('ExampleController', ['$scope', function($scope) {\n *          $scope.names = ['morpheus', 'neo', 'trinity'];\n *        }]);\n *   </file>\n *   <file name=\"index.html\">\n *    <form name=\"myForm\" ng-controller=\"ExampleController\">\n *      List: <input name=\"namesInput\" ng-model=\"names\" ng-list required>\n *      <span class=\"error\" ng-show=\"myForm.namesInput.$error.required\">\n *        Required!</span>\n *      <br>\n *      <tt>names = {{names}}</tt><br/>\n *      <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>\n *      <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>\n *      <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n *      <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n *     </form>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var listInput = element(by.model('names'));\n *     var names = element(by.exactBinding('names'));\n *     var valid = element(by.binding('myForm.namesInput.$valid'));\n *     var error = element(by.css('span.error'));\n *\n *     it('should initialize to model', function() {\n *       expect(names.getText()).toContain('[\"morpheus\",\"neo\",\"trinity\"]');\n *       expect(valid.getText()).toContain('true');\n *       expect(error.getCssValue('display')).toBe('none');\n *     });\n *\n *     it('should be invalid if empty', function() {\n *       listInput.clear();\n *       listInput.sendKeys('');\n *\n *       expect(names.getText()).toContain('');\n *       expect(valid.getText()).toContain('false');\n *       expect(error.getCssValue('display')).not.toBe('none');\n *     });\n *   </file>\n * </example>\n *\n * ### Example - splitting on whitespace\n * <example name=\"ngList-directive-newlines\">\n *   <file name=\"index.html\">\n *    <textarea ng-model=\"list\" ng-list=\"&#10;\" ng-trim=\"false\"></textarea>\n *    <pre>{{ list | json }}</pre>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it(\"should split the text by newlines\", function() {\n *       var listInput = element(by.model('list'));\n *       var output = element(by.binding('list | json'));\n *       listInput.sendKeys('abc\\ndef\\nghi');\n *       expect(output.getText()).toContain('[\\n  \"abc\",\\n  \"def\",\\n  \"ghi\"\\n]');\n *     });\n *   </file>\n * </example>\n *\n * @element input\n * @param {string=} ngList optional delimiter that should be used to split the value.\n */\nvar ngListDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    require: 'ngModel',\n    link: function(scope, element, attr, ctrl) {\n      // We want to control whitespace trimming so we use this convoluted approach\n      // to access the ngList attribute, which doesn't pre-trim the attribute\n      var ngList = element.attr(attr.$attr.ngList) || ', ';\n      var trimValues = attr.ngTrim !== 'false';\n      var separator = trimValues ? trim(ngList) : ngList;\n\n      var parse = function(viewValue) {\n        // If the viewValue is invalid (say required but empty) it will be `undefined`\n        if (isUndefined(viewValue)) return;\n\n        var list = [];\n\n        if (viewValue) {\n          forEach(viewValue.split(separator), function(value) {\n            if (value) list.push(trimValues ? trim(value) : value);\n          });\n        }\n\n        return list;\n      };\n\n      ctrl.$parsers.push(parse);\n      ctrl.$formatters.push(function(value) {\n        if (isArray(value)) {\n          return value.join(ngList);\n        }\n\n        return undefined;\n      });\n\n      // Override the standard $isEmpty because an empty array means the input is empty.\n      ctrl.$isEmpty = function(value) {\n        return !value || !value.length;\n      };\n    }\n  };\n};\n\n/* global VALID_CLASS: true,\n  INVALID_CLASS: true,\n  PRISTINE_CLASS: true,\n  DIRTY_CLASS: true,\n  UNTOUCHED_CLASS: true,\n  TOUCHED_CLASS: true,\n*/\n\nvar VALID_CLASS = 'ng-valid',\n    INVALID_CLASS = 'ng-invalid',\n    PRISTINE_CLASS = 'ng-pristine',\n    DIRTY_CLASS = 'ng-dirty',\n    UNTOUCHED_CLASS = 'ng-untouched',\n    TOUCHED_CLASS = 'ng-touched',\n    PENDING_CLASS = 'ng-pending';\n\n\nvar $ngModelMinErr = new minErr('ngModel');\n\n/**\n * @ngdoc type\n * @name ngModel.NgModelController\n *\n * @property {string} $viewValue Actual string value in the view.\n * @property {*} $modelValue The value in the model that the control is bound to.\n * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever\n       the control reads value from the DOM. The functions are called in array order, each passing\n       its return value through to the next. The last return value is forwarded to the\n       {@link ngModel.NgModelController#$validators `$validators`} collection.\n\nParsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue\n`$viewValue`}.\n\nReturning `undefined` from a parser means a parse error occurred. In that case,\nno {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`\nwill be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}\nis set to `true`. The parse error is stored in `ngModel.$error.parse`.\n\n *\n * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever\n       the model value changes. The functions are called in reverse array order, each passing the value through to the\n       next. The last return value is used as the actual DOM value.\n       Used to format / convert values for display in the control.\n * ```js\n * function formatter(value) {\n *   if (value) {\n *     return value.toUpperCase();\n *   }\n * }\n * ngModel.$formatters.push(formatter);\n * ```\n *\n * @property {Object.<string, function>} $validators A collection of validators that are applied\n *      whenever the model value changes. The key value within the object refers to the name of the\n *      validator while the function refers to the validation operation. The validation operation is\n *      provided with the model value as an argument and must return a true or false value depending\n *      on the response of that validation.\n *\n * ```js\n * ngModel.$validators.validCharacters = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *   return /[0-9]+/.test(value) &&\n *          /[a-z]+/.test(value) &&\n *          /[A-Z]+/.test(value) &&\n *          /\\W+/.test(value);\n * };\n * ```\n *\n * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to\n *      perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided\n *      is expected to return a promise when it is run during the model validation process. Once the promise\n *      is delivered then the validation status will be set to true when fulfilled and false when rejected.\n *      When the asynchronous validators are triggered, each of the validators will run in parallel and the model\n *      value will only be updated once all validators have been fulfilled. As long as an asynchronous validator\n *      is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators\n *      will only run once all synchronous validators have passed.\n *\n * Please note that if $http is used then it is important that the server returns a success HTTP response code\n * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.\n *\n * ```js\n * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *\n *   // Lookup user by username\n *   return $http.get('/api/users/' + value).\n *      then(function resolved() {\n *        //username exists, this means validation fails\n *        return $q.reject('exists');\n *      }, function rejected() {\n *        //username does not exist, therefore this validation passes\n *        return true;\n *      });\n * };\n * ```\n *\n * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the\n *     view value has changed. It is called with no arguments, and its return value is ignored.\n *     This can be used in place of additional $watches against the model value.\n *\n * @property {Object} $error An object hash with all failing validator ids as keys.\n * @property {Object} $pending An object hash with all pending validator ids as keys.\n *\n * @property {boolean} $untouched True if control has not lost focus yet.\n * @property {boolean} $touched True if control has lost focus.\n * @property {boolean} $pristine True if user has not interacted with the control yet.\n * @property {boolean} $dirty True if user has already interacted with the control.\n * @property {boolean} $valid True if there is no error.\n * @property {boolean} $invalid True if at least one error on the control.\n * @property {string} $name The name attribute of the control.\n *\n * @description\n *\n * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.\n * The controller contains services for data-binding, validation, CSS updates, and value formatting\n * and parsing. It purposefully does not contain any logic which deals with DOM rendering or\n * listening to DOM events.\n * Such DOM related logic should be provided by other directives which make use of\n * `NgModelController` for data-binding to control elements.\n * Angular provides this DOM logic for most {@link input `input`} elements.\n * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example\n * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.\n *\n * @example\n * ### Custom Control Example\n * This example shows how to use `NgModelController` with a custom control to achieve\n * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)\n * collaborate together to achieve the desired result.\n *\n * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element\n * contents be edited in place by the user.  This will not work on older browsers.\n *\n * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}\n * module to automatically remove \"bad\" content like inline event listener (e.g. `<span onclick=\"...\">`).\n * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks\n * that content using the `$sce` service.\n *\n * <example name=\"NgModelController\" module=\"customControl\" deps=\"angular-sanitize.js\">\n    <file name=\"style.css\">\n      [contenteditable] {\n        border: 1px solid black;\n        background-color: white;\n        min-height: 20px;\n      }\n\n      .ng-invalid {\n        border: 1px solid red;\n      }\n\n    </file>\n    <file name=\"script.js\">\n      angular.module('customControl', ['ngSanitize']).\n        directive('contenteditable', ['$sce', function($sce) {\n          return {\n            restrict: 'A', // only activate on element attribute\n            require: '?ngModel', // get a hold of NgModelController\n            link: function(scope, element, attrs, ngModel) {\n              if (!ngModel) return; // do nothing if no ng-model\n\n              // Specify how UI should be updated\n              ngModel.$render = function() {\n                element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));\n              };\n\n              // Listen for change events to enable binding\n              element.on('blur keyup change', function() {\n                scope.$evalAsync(read);\n              });\n              read(); // initialize\n\n              // Write data to the model\n              function read() {\n                var html = element.html();\n                // When we clear the content editable the browser leaves a <br> behind\n                // If strip-br attribute is provided then we strip this out\n                if ( attrs.stripBr && html == '<br>' ) {\n                  html = '';\n                }\n                ngModel.$setViewValue(html);\n              }\n            }\n          };\n        }]);\n    </file>\n    <file name=\"index.html\">\n      <form name=\"myForm\">\n       <div contenteditable\n            name=\"myWidget\" ng-model=\"userContent\"\n            strip-br=\"true\"\n            required>Change me!</div>\n        <span ng-show=\"myForm.myWidget.$error.required\">Required!</span>\n       <hr>\n       <textarea ng-model=\"userContent\"></textarea>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n    it('should data-bind and become invalid', function() {\n      if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {\n        // SafariDriver can't handle contenteditable\n        // and Firefox driver can't clear contenteditables very well\n        return;\n      }\n      var contentEditable = element(by.css('[contenteditable]'));\n      var content = 'Change me!';\n\n      expect(contentEditable.getText()).toEqual(content);\n\n      contentEditable.clear();\n      contentEditable.sendKeys(protractor.Key.BACK_SPACE);\n      expect(contentEditable.getText()).toEqual('');\n      expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);\n    });\n    </file>\n * </example>\n *\n *\n */\nvar NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',\n    function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {\n  this.$viewValue = Number.NaN;\n  this.$modelValue = Number.NaN;\n  this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.\n  this.$validators = {};\n  this.$asyncValidators = {};\n  this.$parsers = [];\n  this.$formatters = [];\n  this.$viewChangeListeners = [];\n  this.$untouched = true;\n  this.$touched = false;\n  this.$pristine = true;\n  this.$dirty = false;\n  this.$valid = true;\n  this.$invalid = false;\n  this.$error = {}; // keep invalid keys here\n  this.$$success = {}; // keep valid keys here\n  this.$pending = undefined; // keep pending keys here\n  this.$name = $interpolate($attr.name || '', false)($scope);\n\n\n  var parsedNgModel = $parse($attr.ngModel),\n      parsedNgModelAssign = parsedNgModel.assign,\n      ngModelGet = parsedNgModel,\n      ngModelSet = parsedNgModelAssign,\n      pendingDebounce = null,\n      ctrl = this;\n\n  this.$$setOptions = function(options) {\n    ctrl.$options = options;\n    if (options && options.getterSetter) {\n      var invokeModelGetter = $parse($attr.ngModel + '()'),\n          invokeModelSetter = $parse($attr.ngModel + '($$$p)');\n\n      ngModelGet = function($scope) {\n        var modelValue = parsedNgModel($scope);\n        if (isFunction(modelValue)) {\n          modelValue = invokeModelGetter($scope);\n        }\n        return modelValue;\n      };\n      ngModelSet = function($scope, newValue) {\n        if (isFunction(parsedNgModel($scope))) {\n          invokeModelSetter($scope, {$$$p: ctrl.$modelValue});\n        } else {\n          parsedNgModelAssign($scope, ctrl.$modelValue);\n        }\n      };\n    } else if (!parsedNgModel.assign) {\n      throw $ngModelMinErr('nonassign', \"Expression '{0}' is non-assignable. Element: {1}\",\n          $attr.ngModel, startingTag($element));\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$render\n   *\n   * @description\n   * Called when the view needs to be updated. It is expected that the user of the ng-model\n   * directive will implement this method.\n   *\n   * The `$render()` method is invoked in the following situations:\n   *\n   * * `$rollbackViewValue()` is called.  If we are rolling back the view value to the last\n   *   committed value then `$render()` is called to update the input control.\n   * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and\n   *   the `$viewValue` are different to last time.\n   *\n   * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of\n   * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`\n   * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be\n   * invoked if you only change a property on the objects.\n   */\n  this.$render = noop;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$isEmpty\n   *\n   * @description\n   * This is called when we need to determine if the value of an input is empty.\n   *\n   * For instance, the required directive does this to work out if the input has data or not.\n   *\n   * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.\n   *\n   * You can override this for input directives whose concept of being empty is different to the\n   * default. The `checkboxInputType` directive does this because in its case a value of `false`\n   * implies empty.\n   *\n   * @param {*} value The value of the input to check for emptiness.\n   * @returns {boolean} True if `value` is \"empty\".\n   */\n  this.$isEmpty = function(value) {\n    return isUndefined(value) || value === '' || value === null || value !== value;\n  };\n\n  var parentForm = $element.inheritedData('$formController') || nullFormCtrl,\n      currentValidationRunId = 0;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setValidity\n   *\n   * @description\n   * Change the validity state, and notify the form.\n   *\n   * This method can be called within $parsers/$formatters or a custom validation implementation.\n   * However, in most cases it should be sufficient to use the `ngModel.$validators` and\n   * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.\n   *\n   * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned\n   *        to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`\n   *        (for unfulfilled `$asyncValidators`), so that it is available for data-binding.\n   *        The `validationErrorKey` should be in camelCase and will get converted into dash-case\n   *        for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`\n   *        class and can be bound to as  `{{someForm.someControl.$error.myError}}` .\n   * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),\n   *                          or skipped (null). Pending is used for unfulfilled `$asyncValidators`.\n   *                          Skipped is used by Angular when validators do not run because of parse errors and\n   *                          when `$asyncValidators` do not run because any of the `$validators` failed.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: $element,\n    set: function(object, property) {\n      object[property] = true;\n    },\n    unset: function(object, property) {\n      delete object[property];\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setPristine\n   *\n   * @description\n   * Sets the control to its pristine state.\n   *\n   * This method can be called to remove the `ng-dirty` class and set the control to its pristine\n   * state (`ng-pristine` class). A model is considered to be pristine when the control\n   * has not been changed from when first compiled.\n   */\n  this.$setPristine = function() {\n    ctrl.$dirty = false;\n    ctrl.$pristine = true;\n    $animate.removeClass($element, DIRTY_CLASS);\n    $animate.addClass($element, PRISTINE_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setDirty\n   *\n   * @description\n   * Sets the control to its dirty state.\n   *\n   * This method can be called to remove the `ng-pristine` class and set the control to its dirty\n   * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed\n   * from when first compiled.\n   */\n  this.$setDirty = function() {\n    ctrl.$dirty = true;\n    ctrl.$pristine = false;\n    $animate.removeClass($element, PRISTINE_CLASS);\n    $animate.addClass($element, DIRTY_CLASS);\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setUntouched\n   *\n   * @description\n   * Sets the control to its untouched state.\n   *\n   * This method can be called to remove the `ng-touched` class and set the control to its\n   * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched\n   * by default, however this function can be used to restore that state if the model has\n   * already been touched by the user.\n   */\n  this.$setUntouched = function() {\n    ctrl.$touched = false;\n    ctrl.$untouched = true;\n    $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setTouched\n   *\n   * @description\n   * Sets the control to its touched state.\n   *\n   * This method can be called to remove the `ng-untouched` class and set the control to its\n   * touched state (`ng-touched` class). A model is considered to be touched when the user has\n   * first focused the control element and then shifted focus away from the control (blur event).\n   */\n  this.$setTouched = function() {\n    ctrl.$touched = true;\n    ctrl.$untouched = false;\n    $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$rollbackViewValue\n   *\n   * @description\n   * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,\n   * which may be caused by a pending debounced event or because the input is waiting for a some\n   * future event.\n   *\n   * If you have an input that uses `ng-model-options` to set up debounced events or events such\n   * as blur you can have a situation where there is a period when the `$viewValue`\n   * is out of synch with the ngModel's `$modelValue`.\n   *\n   * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`\n   * programmatically before these debounced/future events have resolved/occurred, because Angular's\n   * dirty checking mechanism is not able to tell whether the model has actually changed or not.\n   *\n   * The `$rollbackViewValue()` method should be called before programmatically changing the model of an\n   * input which may have such events pending. This is important in order to make sure that the\n   * input field will be updated with the new model value and any pending operations are cancelled.\n   *\n   * <example name=\"ng-model-cancel-update\" module=\"cancel-update-example\">\n   *   <file name=\"app.js\">\n   *     angular.module('cancel-update-example', [])\n   *\n   *     .controller('CancelUpdateController', ['$scope', function($scope) {\n   *       $scope.resetWithCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myForm.myInput1.$rollbackViewValue();\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *       $scope.resetWithoutCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *     }]);\n   *   </file>\n   *   <file name=\"index.html\">\n   *     <div ng-controller=\"CancelUpdateController\">\n   *       <p>Try typing something in each input.  See that the model only updates when you\n   *          blur off the input.\n   *        </p>\n   *        <p>Now see what happens if you start typing then press the Escape key</p>\n   *\n   *       <form name=\"myForm\" ng-model-options=\"{ updateOn: 'blur' }\">\n   *         <p>With $rollbackViewValue()</p>\n   *         <input name=\"myInput1\" ng-model=\"myValue\" ng-keydown=\"resetWithCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *\n   *         <p>Without $rollbackViewValue()</p>\n   *         <input name=\"myInput2\" ng-model=\"myValue\" ng-keydown=\"resetWithoutCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *       </form>\n   *     </div>\n   *   </file>\n   * </example>\n   */\n  this.$rollbackViewValue = function() {\n    $timeout.cancel(pendingDebounce);\n    ctrl.$viewValue = ctrl.$$lastCommittedViewValue;\n    ctrl.$render();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$validate\n   *\n   * @description\n   * Runs each of the registered validators (first synchronous validators and then\n   * asynchronous validators).\n   * If the validity changes to invalid, the model will be set to `undefined`,\n   * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.\n   * If the validity changes to valid, it will set the model to the last available valid\n   * modelValue, i.e. either the last parsed value or the last value set from the scope.\n   */\n  this.$validate = function() {\n    // ignore $validate before model is initialized\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      return;\n    }\n\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    // Note: we use the $$rawModelValue as $modelValue might have been\n    // set to undefined during a view -> model update that found validation\n    // errors. We can't parse the view here, since that could change\n    // the model although neither viewValue nor the model on the scope changed\n    var modelValue = ctrl.$$rawModelValue;\n\n    // Check if the there's a parse error, so we don't unset it accidentially\n    var parserName = ctrl.$$parserName || 'parse';\n    var parserValid = ctrl.$error[parserName] ? false : undefined;\n\n    var prevValid = ctrl.$valid;\n    var prevModelValue = ctrl.$modelValue;\n\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n\n    ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {\n      // If there was no change in validity, don't update the model\n      // This prevents changing an invalid modelValue to undefined\n      if (!allowInvalid && prevValid !== allValid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n\n        if (ctrl.$modelValue !== prevModelValue) {\n          ctrl.$$writeModelToScope();\n        }\n      }\n    });\n\n  };\n\n  this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {\n    currentValidationRunId++;\n    var localValidationRunId = currentValidationRunId;\n\n    // check parser error\n    if (!processParseErrors(parseValid)) {\n      validationDone(false);\n      return;\n    }\n    if (!processSyncValidators()) {\n      validationDone(false);\n      return;\n    }\n    processAsyncValidators();\n\n    function processParseErrors(parseValid) {\n      var errorKey = ctrl.$$parserName || 'parse';\n      if (parseValid === undefined) {\n        setValidity(errorKey, null);\n      } else {\n        setValidity(errorKey, parseValid);\n        if (!parseValid) {\n          forEach(ctrl.$validators, function(v, name) {\n            setValidity(name, null);\n          });\n          forEach(ctrl.$asyncValidators, function(v, name) {\n            setValidity(name, null);\n          });\n          return false;\n        }\n      }\n      return true;\n    }\n\n    function processSyncValidators() {\n      var syncValidatorsValid = true;\n      forEach(ctrl.$validators, function(validator, name) {\n        var result = validator(modelValue, viewValue);\n        syncValidatorsValid = syncValidatorsValid && result;\n        setValidity(name, result);\n      });\n      if (!syncValidatorsValid) {\n        forEach(ctrl.$asyncValidators, function(v, name) {\n          setValidity(name, null);\n        });\n        return false;\n      }\n      return true;\n    }\n\n    function processAsyncValidators() {\n      var validatorPromises = [];\n      var allValid = true;\n      forEach(ctrl.$asyncValidators, function(validator, name) {\n        var promise = validator(modelValue, viewValue);\n        if (!isPromiseLike(promise)) {\n          throw $ngModelMinErr(\"$asyncValidators\",\n            \"Expected asynchronous validator to return a promise but got '{0}' instead.\", promise);\n        }\n        setValidity(name, undefined);\n        validatorPromises.push(promise.then(function() {\n          setValidity(name, true);\n        }, function(error) {\n          allValid = false;\n          setValidity(name, false);\n        }));\n      });\n      if (!validatorPromises.length) {\n        validationDone(true);\n      } else {\n        $q.all(validatorPromises).then(function() {\n          validationDone(allValid);\n        }, noop);\n      }\n    }\n\n    function setValidity(name, isValid) {\n      if (localValidationRunId === currentValidationRunId) {\n        ctrl.$setValidity(name, isValid);\n      }\n    }\n\n    function validationDone(allValid) {\n      if (localValidationRunId === currentValidationRunId) {\n\n        doneCallback(allValid);\n      }\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$commitViewValue\n   *\n   * @description\n   * Commit a pending update to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  this.$commitViewValue = function() {\n    var viewValue = ctrl.$viewValue;\n\n    $timeout.cancel(pendingDebounce);\n\n    // If the view value has not changed then we should just exit, except in the case where there is\n    // a native validator on the element. In this case the validation state may have changed even though\n    // the viewValue has stayed empty.\n    if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {\n      return;\n    }\n    ctrl.$$lastCommittedViewValue = viewValue;\n\n    // change to dirty\n    if (ctrl.$pristine) {\n      this.$setDirty();\n    }\n    this.$$parseAndValidate();\n  };\n\n  this.$$parseAndValidate = function() {\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    var modelValue = viewValue;\n    var parserValid = isUndefined(modelValue) ? undefined : true;\n\n    if (parserValid) {\n      for (var i = 0; i < ctrl.$parsers.length; i++) {\n        modelValue = ctrl.$parsers[i](modelValue);\n        if (isUndefined(modelValue)) {\n          parserValid = false;\n          break;\n        }\n      }\n    }\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      // ctrl.$modelValue has not been touched yet...\n      ctrl.$modelValue = ngModelGet($scope);\n    }\n    var prevModelValue = ctrl.$modelValue;\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n    ctrl.$$rawModelValue = modelValue;\n\n    if (allowInvalid) {\n      ctrl.$modelValue = modelValue;\n      writeToModelIfNeeded();\n    }\n\n    // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.\n    // This can happen if e.g. $setViewValue is called from inside a parser\n    ctrl.$$runValidators(parserValid, modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {\n      if (!allowInvalid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n        writeToModelIfNeeded();\n      }\n    });\n\n    function writeToModelIfNeeded() {\n      if (ctrl.$modelValue !== prevModelValue) {\n        ctrl.$$writeModelToScope();\n      }\n    }\n  };\n\n  this.$$writeModelToScope = function() {\n    ngModelSet($scope, ctrl.$modelValue);\n    forEach(ctrl.$viewChangeListeners, function(listener) {\n      try {\n        listener();\n      } catch (e) {\n        $exceptionHandler(e);\n      }\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setViewValue\n   *\n   * @description\n   * Update the view value.\n   *\n   * This method should be called when an input directive want to change the view value; typically,\n   * this is done from within a DOM event handler.\n   *\n   * For example {@link ng.directive:input input} calls it when the value of the input changes and\n   * {@link ng.directive:select select} calls it when an option is selected.\n   *\n   * If the new `value` is an object (rather than a string or a number), we should make a copy of the\n   * object before passing it to `$setViewValue`.  This is because `ngModel` does not perform a deep\n   * watch of objects, it only looks for a change of identity. If you only change the property of\n   * the object then ngModel will not realise that the object has changed and will not invoke the\n   * `$parsers` and `$validators` pipelines.\n   *\n   * For this reason, you should not change properties of the copy once it has been passed to\n   * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.\n   *\n   * When this method is called, the new `value` will be staged for committing through the `$parsers`\n   * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged\n   * value sent directly for processing, finally to be applied to `$modelValue` and then the\n   * **expression** specified in the `ng-model` attribute.\n   *\n   * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.\n   *\n   * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`\n   * and the `default` trigger is not listed, all those actions will remain pending until one of the\n   * `updateOn` events is triggered on the DOM element.\n   * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}\n   * directive is used with a custom debounce for this particular event.\n   *\n   * Note that calling this function does not trigger a `$digest`.\n   *\n   * @param {string} value Value from the view.\n   * @param {string} trigger Event that triggered the update.\n   */\n  this.$setViewValue = function(value, trigger) {\n    ctrl.$viewValue = value;\n    if (!ctrl.$options || ctrl.$options.updateOnDefault) {\n      ctrl.$$debounceViewValueCommit(trigger);\n    }\n  };\n\n  this.$$debounceViewValueCommit = function(trigger) {\n    var debounceDelay = 0,\n        options = ctrl.$options,\n        debounce;\n\n    if (options && isDefined(options.debounce)) {\n      debounce = options.debounce;\n      if (isNumber(debounce)) {\n        debounceDelay = debounce;\n      } else if (isNumber(debounce[trigger])) {\n        debounceDelay = debounce[trigger];\n      } else if (isNumber(debounce['default'])) {\n        debounceDelay = debounce['default'];\n      }\n    }\n\n    $timeout.cancel(pendingDebounce);\n    if (debounceDelay) {\n      pendingDebounce = $timeout(function() {\n        ctrl.$commitViewValue();\n      }, debounceDelay);\n    } else if ($rootScope.$$phase) {\n      ctrl.$commitViewValue();\n    } else {\n      $scope.$apply(function() {\n        ctrl.$commitViewValue();\n      });\n    }\n  };\n\n  // model -> value\n  // Note: we cannot use a normal scope.$watch as we want to detect the following:\n  // 1. scope value is 'a'\n  // 2. user enters 'b'\n  // 3. ng-change kicks in and reverts scope value to 'a'\n  //    -> scope value did not change since the last digest as\n  //       ng-change executes in apply phase\n  // 4. view should be changed back to 'a'\n  $scope.$watch(function ngModelWatch() {\n    var modelValue = ngModelGet($scope);\n\n    // if scope model value and ngModel value are out of sync\n    // TODO(perf): why not move this to the action fn?\n    if (modelValue !== ctrl.$modelValue) {\n      ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;\n\n      var formatters = ctrl.$formatters,\n          idx = formatters.length;\n\n      var viewValue = modelValue;\n      while (idx--) {\n        viewValue = formatters[idx](viewValue);\n      }\n      if (ctrl.$viewValue !== viewValue) {\n        ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;\n        ctrl.$render();\n\n        ctrl.$$runValidators(undefined, modelValue, viewValue, noop);\n      }\n    }\n\n    return modelValue;\n  });\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngModel\n *\n * @element input\n * @priority 1\n *\n * @description\n * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a\n * property on the scope using {@link ngModel.NgModelController NgModelController},\n * which is created and exposed by this directive.\n *\n * `ngModel` is responsible for:\n *\n * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`\n *   require.\n * - Providing validation behavior (i.e. required, number, email, url).\n * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).\n * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.\n * - Registering the control with its parent {@link ng.directive:form form}.\n *\n * Note: `ngModel` will try to bind to the property given by evaluating the expression on the\n * current scope. If the property doesn't already exist on this scope, it will be created\n * implicitly and added to the scope.\n *\n * For best practices on using `ngModel`, see:\n *\n *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)\n *\n * For basic examples, how to use `ngModel`, see:\n *\n *  - {@link ng.directive:input input}\n *    - {@link input[text] text}\n *    - {@link input[checkbox] checkbox}\n *    - {@link input[radio] radio}\n *    - {@link input[number] number}\n *    - {@link input[email] email}\n *    - {@link input[url] url}\n *    - {@link input[date] date}\n *    - {@link input[datetime-local] datetime-local}\n *    - {@link input[time] time}\n *    - {@link input[month] month}\n *    - {@link input[week] week}\n *  - {@link ng.directive:select select}\n *  - {@link ng.directive:textarea textarea}\n *\n * # CSS classes\n * The following CSS classes are added and removed on the associated input/select/textarea element\n * depending on the validity of the model.\n *\n *  - `ng-valid`: the model is valid\n *  - `ng-invalid`: the model is invalid\n *  - `ng-valid-[key]`: for each valid key added by `$setValidity`\n *  - `ng-invalid-[key]`: for each invalid key added by `$setValidity`\n *  - `ng-pristine`: the control hasn't been interacted with yet\n *  - `ng-dirty`: the control has been interacted with\n *  - `ng-touched`: the control has been blurred\n *  - `ng-untouched`: the control hasn't been blurred\n *  - `ng-pending`: any `$asyncValidators` are unfulfilled\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n * ## Animation Hooks\n *\n * Animations within models are triggered when any of the associated CSS classes are added and removed\n * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,\n * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.\n * The animations that are triggered within ngModel are similar to how they work in ngClass and\n * animations can be hooked into using CSS transitions, keyframes as well as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style an input element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-input {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-input.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n * <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"inputExample\">\n     <file name=\"index.html\">\n       <script>\n        angular.module('inputExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.val = '1';\n          }]);\n       </script>\n       <style>\n         .my-input {\n           -webkit-transition:all linear 0.5s;\n           transition:all linear 0.5s;\n           background: transparent;\n         }\n         .my-input.ng-invalid {\n           color:white;\n           background: red;\n         }\n       </style>\n       Update input to see transitions when valid/invalid.\n       Integer is a valid value.\n       <form name=\"testForm\" ng-controller=\"ExampleController\">\n         <input ng-model=\"val\" ng-pattern=\"/^\\d+$/\" name=\"anim\" class=\"my-input\" />\n       </form>\n     </file>\n * </example>\n *\n * ## Binding to a getter/setter\n *\n * Sometimes it's helpful to bind `ngModel` to a getter/setter function.  A getter/setter is a\n * function that returns a representation of the model when called with zero arguments, and sets\n * the internal state of a model when called with an argument. It's sometimes useful to use this\n * for models that have an internal representation that's different than what the model exposes\n * to the view.\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more\n * frequently than other parts of your code.\n * </div>\n *\n * You use this behavior by adding `ng-model-options=\"{ getterSetter: true }\"` to an element that\n * has `ng-model` attached to it. You can also add `ng-model-options=\"{ getterSetter: true }\"` to\n * a `<form>`, which will enable this behavior for all `<input>`s within it. See\n * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.\n *\n * The following example shows how to use `ngModel` with a getter/setter:\n *\n * @example\n * <example name=\"ngModel-getter-setter\" module=\"getterSetterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <form name=\"userForm\">\n           Name:\n           <input type=\"text\" name=\"userName\"\n                  ng-model=\"user.name\"\n                  ng-model-options=\"{ getterSetter: true }\" />\n         </form>\n         <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n       </div>\n     </file>\n     <file name=\"app.js\">\n       angular.module('getterSetterExample', [])\n         .controller('ExampleController', ['$scope', function($scope) {\n           var _name = 'Brian';\n           $scope.user = {\n             name: function(newName) {\n               if (angular.isDefined(newName)) {\n                 _name = newName;\n               }\n               return _name;\n             }\n           };\n         }]);\n     </file>\n * </example>\n */\nvar ngModelDirective = ['$rootScope', function($rootScope) {\n  return {\n    restrict: 'A',\n    require: ['ngModel', '^?form', '^?ngModelOptions'],\n    controller: NgModelController,\n    // Prelink needs to run before any input directive\n    // so that we can set the NgModelOptions in NgModelController\n    // before anyone else uses it.\n    priority: 1,\n    compile: function ngModelCompile(element) {\n      // Setup initial state of the control\n      element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);\n\n      return {\n        pre: function ngModelPreLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0],\n              formCtrl = ctrls[1] || nullFormCtrl;\n\n          modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);\n\n          // notify others, especially parent forms\n          formCtrl.$addControl(modelCtrl);\n\n          attr.$observe('name', function(newValue) {\n            if (modelCtrl.$name !== newValue) {\n              formCtrl.$$renameControl(modelCtrl, newValue);\n            }\n          });\n\n          scope.$on('$destroy', function() {\n            formCtrl.$removeControl(modelCtrl);\n          });\n        },\n        post: function ngModelPostLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0];\n          if (modelCtrl.$options && modelCtrl.$options.updateOn) {\n            element.on(modelCtrl.$options.updateOn, function(ev) {\n              modelCtrl.$$debounceViewValueCommit(ev && ev.type);\n            });\n          }\n\n          element.on('blur', function(ev) {\n            if (modelCtrl.$touched) return;\n\n            if ($rootScope.$$phase) {\n              scope.$evalAsync(modelCtrl.$setTouched);\n            } else {\n              scope.$apply(modelCtrl.$setTouched);\n            }\n          });\n        }\n      };\n    }\n  };\n}];\n\nvar DEFAULT_REGEXP = /(\\s+|^)default(\\s+|$)/;\n\n/**\n * @ngdoc directive\n * @name ngModelOptions\n *\n * @description\n * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of\n * events that will trigger a model update and/or a debouncing delay so that the actual update only\n * takes place when a timer expires; this timer will be reset after another change takes place.\n *\n * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might\n * be different than the value in the actual model. This means that if you update the model you\n * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in\n * order to make sure it is synchronized with the model and that any debounced action is canceled.\n *\n * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}\n * method is by making sure the input is placed inside a form that has a `name` attribute. This is\n * important because `form` controllers are published to the related scope under the name in their\n * `name` attribute.\n *\n * Any pending changes will take place immediately when an enclosing form is submitted via the\n * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * `ngModelOptions` has an effect on the element it's declared on and its descendants.\n *\n * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:\n *   - `updateOn`: string specifying which event should the input be bound to. You can set several\n *     events using an space delimited list. There is a special event called `default` that\n *     matches the default events belonging of the control.\n *   - `debounce`: integer value which contains the debounce model update value in milliseconds. A\n *     value of 0 triggers an immediate update. If an object is supplied instead, you can specify a\n *     custom value for each event. For example:\n *     `ng-model-options=\"{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }\"`\n *   - `allowInvalid`: boolean value which indicates that the model can be set with values that did\n *     not validate correctly instead of the default behavior of setting the model to undefined.\n *   - `getterSetter`: boolean value which determines whether or not to treat functions bound to\n       `ngModel` as getters/setters.\n *   - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for\n *     `<input type=\"date\">`, `<input type=\"time\">`, ... . Right now, the only supported value is `'UTC'`,\n *     otherwise the default timezone of the browser will be used.\n *\n * @example\n\n  The following example shows how to override immediate updates. Changes on the inputs within the\n  form will update the model only when the control loses focus (blur event). If `escape` key is\n  pressed while the input field is focused, the value is reset to the value in the current model.\n\n  <example name=\"ngModelOptions-directive-blur\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          Name:\n          <input type=\"text\" name=\"userName\"\n                 ng-model=\"user.name\"\n                 ng-model-options=\"{ updateOn: 'blur' }\"\n                 ng-keyup=\"cancel($event)\" /><br />\n\n          Other data:\n          <input type=\"text\" ng-model=\"user.data\" /><br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say', data: '' };\n\n          $scope.cancel = function(e) {\n            if (e.keyCode == 27) {\n              $scope.userForm.userName.$rollbackViewValue();\n            }\n          };\n        }]);\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var model = element(by.binding('user.name'));\n      var input = element(by.model('user.name'));\n      var other = element(by.model('user.data'));\n\n      it('should allow custom events', function() {\n        input.sendKeys(' hello');\n        input.click();\n        expect(model.getText()).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say hello');\n      });\n\n      it('should $rollbackViewValue when model changes', function() {\n        input.sendKeys(' hello');\n        expect(input.getAttribute('value')).toEqual('say hello');\n        input.sendKeys(protractor.Key.ESCAPE);\n        expect(input.getAttribute('value')).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say');\n      });\n    </file>\n  </example>\n\n  This one shows how to debounce model changes. Model will be updated only 1 sec after last change.\n  If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.\n\n  <example name=\"ngModelOptions-directive-debounce\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          Name:\n          <input type=\"text\" name=\"userName\"\n                 ng-model=\"user.name\"\n                 ng-model-options=\"{ debounce: 1000 }\" />\n          <button ng-click=\"userForm.userName.$rollbackViewValue(); user.name=''\">Clear</button><br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say' };\n        }]);\n    </file>\n  </example>\n\n  This one shows how to bind to getter/setters:\n\n  <example name=\"ngModelOptions-directive-getter-setter\" module=\"getterSetterExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          Name:\n          <input type=\"text\" name=\"userName\"\n                 ng-model=\"user.name\"\n                 ng-model-options=\"{ getterSetter: true }\" />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('getterSetterExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          var _name = 'Brian';\n          $scope.user = {\n            name: function(newName) {\n              return angular.isDefined(newName) ? (_name = newName) : _name;\n            }\n          };\n        }]);\n    </file>\n  </example>\n */\nvar ngModelOptionsDirective = function() {\n  return {\n    restrict: 'A',\n    controller: ['$scope', '$attrs', function($scope, $attrs) {\n      var that = this;\n      this.$options = $scope.$eval($attrs.ngModelOptions);\n      // Allow adding/overriding bound events\n      if (this.$options.updateOn !== undefined) {\n        this.$options.updateOnDefault = false;\n        // extract \"default\" pseudo-event from list of events that can trigger a model update\n        this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {\n          that.$options.updateOnDefault = true;\n          return ' ';\n        }));\n      } else {\n        this.$options.updateOnDefault = true;\n      }\n    }]\n  };\n};\n\n\n\n// helper methods\nfunction addSetValidityMethod(context) {\n  var ctrl = context.ctrl,\n      $element = context.$element,\n      classCache = {},\n      set = context.set,\n      unset = context.unset,\n      parentForm = context.parentForm,\n      $animate = context.$animate;\n\n  classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));\n\n  ctrl.$setValidity = setValidity;\n\n  function setValidity(validationErrorKey, state, controller) {\n    if (state === undefined) {\n      createAndSet('$pending', validationErrorKey, controller);\n    } else {\n      unsetAndCleanup('$pending', validationErrorKey, controller);\n    }\n    if (!isBoolean(state)) {\n      unset(ctrl.$error, validationErrorKey, controller);\n      unset(ctrl.$$success, validationErrorKey, controller);\n    } else {\n      if (state) {\n        unset(ctrl.$error, validationErrorKey, controller);\n        set(ctrl.$$success, validationErrorKey, controller);\n      } else {\n        set(ctrl.$error, validationErrorKey, controller);\n        unset(ctrl.$$success, validationErrorKey, controller);\n      }\n    }\n    if (ctrl.$pending) {\n      cachedToggleClass(PENDING_CLASS, true);\n      ctrl.$valid = ctrl.$invalid = undefined;\n      toggleValidationCss('', null);\n    } else {\n      cachedToggleClass(PENDING_CLASS, false);\n      ctrl.$valid = isObjectEmpty(ctrl.$error);\n      ctrl.$invalid = !ctrl.$valid;\n      toggleValidationCss('', ctrl.$valid);\n    }\n\n    // re-read the state as the set/unset methods could have\n    // combined state in ctrl.$error[validationError] (used for forms),\n    // where setting/unsetting only increments/decrements the value,\n    // and does not replace it.\n    var combinedState;\n    if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {\n      combinedState = undefined;\n    } else if (ctrl.$error[validationErrorKey]) {\n      combinedState = false;\n    } else if (ctrl.$$success[validationErrorKey]) {\n      combinedState = true;\n    } else {\n      combinedState = null;\n    }\n\n    toggleValidationCss(validationErrorKey, combinedState);\n    parentForm.$setValidity(validationErrorKey, combinedState, ctrl);\n  }\n\n  function createAndSet(name, value, controller) {\n    if (!ctrl[name]) {\n      ctrl[name] = {};\n    }\n    set(ctrl[name], value, controller);\n  }\n\n  function unsetAndCleanup(name, value, controller) {\n    if (ctrl[name]) {\n      unset(ctrl[name], value, controller);\n    }\n    if (isObjectEmpty(ctrl[name])) {\n      ctrl[name] = undefined;\n    }\n  }\n\n  function cachedToggleClass(className, switchValue) {\n    if (switchValue && !classCache[className]) {\n      $animate.addClass($element, className);\n      classCache[className] = true;\n    } else if (!switchValue && classCache[className]) {\n      $animate.removeClass($element, className);\n      classCache[className] = false;\n    }\n  }\n\n  function toggleValidationCss(validationErrorKey, isValid) {\n    validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';\n\n    cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);\n    cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);\n  }\n}\n\nfunction isObjectEmpty(obj) {\n  if (obj) {\n    for (var prop in obj) {\n      return false;\n    }\n  }\n  return true;\n}\n\n/**\n * @ngdoc directive\n * @name ngNonBindable\n * @restrict AC\n * @priority 1000\n *\n * @description\n * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current\n * DOM element. This is useful if the element contains what appears to be Angular directives and\n * bindings but which should be ignored by Angular. This could be the case if you have a site that\n * displays snippets of code, for instance.\n *\n * @element ANY\n *\n * @example\n * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,\n * but the one wrapped in `ngNonBindable` is left alone.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <div>Normal: {{1 + 2}}</div>\n        <div ng-non-bindable>Ignored: {{1 + 2}}</div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-non-bindable', function() {\n         expect(element(by.binding('1 + 2')).getText()).toContain('3');\n         expect(element.all(by.css('div')).last().getText()).toMatch(/1 \\+ 2/);\n       });\n      </file>\n    </example>\n */\nvar ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });\n\n/**\n * @ngdoc directive\n * @name ngPluralize\n * @restrict EA\n *\n * @description\n * `ngPluralize` is a directive that displays messages according to en-US localization rules.\n * These rules are bundled with angular.js, but can be overridden\n * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive\n * by specifying the mappings between\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * and the strings to be displayed.\n *\n * # Plural categories and explicit number rules\n * There are two\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * in Angular's default en-US locale: \"one\" and \"other\".\n *\n * While a plural category may match many numbers (for example, in en-US locale, \"other\" can match\n * any number that is not 1), an explicit number rule can only match one number. For example, the\n * explicit number rule for \"3\" matches the number 3. There are examples of plural categories\n * and explicit number rules throughout the rest of this documentation.\n *\n * # Configuring ngPluralize\n * You configure ngPluralize by providing 2 attributes: `count` and `when`.\n * You can also provide an optional attribute, `offset`.\n *\n * The value of the `count` attribute can be either a string or an {@link guide/expression\n * Angular expression}; these are evaluated on the current scope for its bound value.\n *\n * The `when` attribute specifies the mappings between plural categories and the actual\n * string to be displayed. The value of the attribute should be a JSON object.\n *\n * The following example shows how to configure ngPluralize:\n *\n * ```html\n * <ng-pluralize count=\"personCount\"\n                 when=\"{'0': 'Nobody is viewing.',\n *                      'one': '1 person is viewing.',\n *                      'other': '{} people are viewing.'}\">\n * </ng-pluralize>\n *```\n *\n * In the example, `\"0: Nobody is viewing.\"` is an explicit number rule. If you did not\n * specify this rule, 0 would be matched to the \"other\" category and \"0 people are viewing\"\n * would be shown instead of \"Nobody is viewing\". You can specify an explicit number rule for\n * other numbers, for example 12, so that instead of showing \"12 people are viewing\", you can\n * show \"a dozen people are viewing\".\n *\n * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted\n * into pluralized strings. In the previous example, Angular will replace `{}` with\n * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder\n * for <span ng-non-bindable>{{numberExpression}}</span>.\n *\n * # Configuring ngPluralize with offset\n * The `offset` attribute allows further customization of pluralized text, which can result in\n * a better user experience. For example, instead of the message \"4 people are viewing this document\",\n * you might display \"John, Kate and 2 others are viewing this document\".\n * The offset attribute allows you to offset a number by any desired value.\n * Let's take a look at an example:\n *\n * ```html\n * <ng-pluralize count=\"personCount\" offset=2\n *               when=\"{'0': 'Nobody is viewing.',\n *                      '1': '{{person1}} is viewing.',\n *                      '2': '{{person1}} and {{person2}} are viewing.',\n *                      'one': '{{person1}}, {{person2}} and one other person are viewing.',\n *                      'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n * </ng-pluralize>\n * ```\n *\n * Notice that we are still using two plural categories(one, other), but we added\n * three explicit number rules 0, 1 and 2.\n * When one person, perhaps John, views the document, \"John is viewing\" will be shown.\n * When three people view the document, no explicit number rule is found, so\n * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.\n * In this case, plural category 'one' is matched and \"John, Mary and one other person are viewing\"\n * is shown.\n *\n * Note that when you specify offsets, you must provide explicit number rules for\n * numbers from 0 up to and including the offset. If you use an offset of 3, for example,\n * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for\n * plural categories \"one\" and \"other\".\n *\n * @param {string|expression} count The variable to be bound to.\n * @param {string} when The mapping between plural category to its corresponding strings.\n * @param {number=} offset Offset to deduct from the total number.\n *\n * @example\n    <example module=\"pluralizeExample\">\n      <file name=\"index.html\">\n        <script>\n          angular.module('pluralizeExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.person1 = 'Igor';\n              $scope.person2 = 'Misko';\n              $scope.personCount = 1;\n            }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          Person 1:<input type=\"text\" ng-model=\"person1\" value=\"Igor\" /><br/>\n          Person 2:<input type=\"text\" ng-model=\"person2\" value=\"Misko\" /><br/>\n          Number of People:<input type=\"text\" ng-model=\"personCount\" value=\"1\" /><br/>\n\n          <!--- Example with simple pluralization rules for en locale --->\n          Without Offset:\n          <ng-pluralize count=\"personCount\"\n                        when=\"{'0': 'Nobody is viewing.',\n                               'one': '1 person is viewing.',\n                               'other': '{} people are viewing.'}\">\n          </ng-pluralize><br>\n\n          <!--- Example with offset --->\n          With Offset(2):\n          <ng-pluralize count=\"personCount\" offset=2\n                        when=\"{'0': 'Nobody is viewing.',\n                               '1': '{{person1}} is viewing.',\n                               '2': '{{person1}} and {{person2}} are viewing.',\n                               'one': '{{person1}}, {{person2}} and one other person are viewing.',\n                               'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n          </ng-pluralize>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should show correct pluralized string', function() {\n          var withoutOffset = element.all(by.css('ng-pluralize')).get(0);\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var countInput = element(by.model('personCount'));\n\n          expect(withoutOffset.getText()).toEqual('1 person is viewing.');\n          expect(withOffset.getText()).toEqual('Igor is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('0');\n\n          expect(withoutOffset.getText()).toEqual('Nobody is viewing.');\n          expect(withOffset.getText()).toEqual('Nobody is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('2');\n\n          expect(withoutOffset.getText()).toEqual('2 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('3');\n\n          expect(withoutOffset.getText()).toEqual('3 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('4');\n\n          expect(withoutOffset.getText()).toEqual('4 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');\n        });\n        it('should show data-bound names', function() {\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var personCount = element(by.model('personCount'));\n          var person1 = element(by.model('person1'));\n          var person2 = element(by.model('person2'));\n          personCount.clear();\n          personCount.sendKeys('4');\n          person1.clear();\n          person1.sendKeys('Di');\n          person2.clear();\n          person2.sendKeys('Vojta');\n          expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');\n        });\n      </file>\n    </example>\n */\nvar ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {\n  var BRACE = /{}/g,\n      IS_WHEN = /^when(Minus)?(.+)$/;\n\n  return {\n    restrict: 'EA',\n    link: function(scope, element, attr) {\n      var numberExp = attr.count,\n          whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs\n          offset = attr.offset || 0,\n          whens = scope.$eval(whenExp) || {},\n          whensExpFns = {},\n          startSymbol = $interpolate.startSymbol(),\n          endSymbol = $interpolate.endSymbol(),\n          braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,\n          watchRemover = angular.noop,\n          lastCount;\n\n      forEach(attr, function(expression, attributeName) {\n        var tmpMatch = IS_WHEN.exec(attributeName);\n        if (tmpMatch) {\n          var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);\n          whens[whenKey] = element.attr(attr.$attr[attributeName]);\n        }\n      });\n      forEach(whens, function(expression, key) {\n        whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));\n\n      });\n\n      scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {\n        var count = parseFloat(newVal);\n        var countIsNaN = isNaN(count);\n\n        if (!countIsNaN && !(count in whens)) {\n          // If an explicit number rule such as 1, 2, 3... is defined, just use it.\n          // Otherwise, check it against pluralization rules in $locale service.\n          count = $locale.pluralCat(count - offset);\n        }\n\n        // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.\n        // In JS `NaN !== NaN`, so we have to exlicitly check.\n        if ((count !== lastCount) && !(countIsNaN && isNaN(lastCount))) {\n          watchRemover();\n          watchRemover = scope.$watch(whensExpFns[count], updateElementText);\n          lastCount = count;\n        }\n      });\n\n      function updateElementText(newText) {\n        element.text(newText || '');\n      }\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngRepeat\n *\n * @description\n * The `ngRepeat` directive instantiates a template once per item from a collection. Each template\n * instance gets its own scope, where the given loop variable is set to the current collection item,\n * and `$index` is set to the item index or key.\n *\n * Special properties are exposed on the local scope of each template instance, including:\n *\n * | Variable  | Type            | Details                                                                     |\n * |-----------|-----------------|-----------------------------------------------------------------------------|\n * | `$index`  | {@type number}  | iterator offset of the repeated element (0..length-1)                       |\n * | `$first`  | {@type boolean} | true if the repeated element is first in the iterator.                      |\n * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |\n * | `$last`   | {@type boolean} | true if the repeated element is last in the iterator.                       |\n * | `$even`   | {@type boolean} | true if the iterator position `$index` is even (otherwise false).           |\n * | `$odd`    | {@type boolean} | true if the iterator position `$index` is odd (otherwise false).            |\n *\n * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.\n * This may be useful when, for instance, nesting ngRepeats.\n *\n * # Iterating over object properties\n *\n * It is possible to get `ngRepeat` to iterate over the properties of an object using the following\n * syntax:\n *\n * ```js\n * <div ng-repeat=\"(key, value) in myObj\"> ... </div>\n * ```\n *\n * You need to be aware that the JavaScript specification does not define what order\n * it will return the keys for an object. In order to have a guaranteed deterministic order\n * for the keys, Angular versions up to and including 1.3 **sort the keys alphabetically**.\n *\n * If this is not desired, the recommended workaround is to convert your object into an array\n * that is sorted into the order that you prefer before providing it to `ngRepeat`.  You could\n * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)\n * or implement a `$watch` on the object yourself.\n *\n * In version 1.4 we will remove the sorting, since it seems that browsers generally follow the\n * strategy of providing keys in the order in which they were defined, although there are exceptions\n * when keys are deleted and reinstated.\n *\n *\n * # Special repeat start and end points\n * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending\n * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.\n * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)\n * up to and including the ending HTML tag where **ng-repeat-end** is placed.\n *\n * The example below makes use of this feature:\n * ```html\n *   <header ng-repeat-start=\"item in items\">\n *     Header {{ item }}\n *   </header>\n *   <div class=\"body\">\n *     Body {{ item }}\n *   </div>\n *   <footer ng-repeat-end>\n *     Footer {{ item }}\n *   </footer>\n * ```\n *\n * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:\n * ```html\n *   <header>\n *     Header A\n *   </header>\n *   <div class=\"body\">\n *     Body A\n *   </div>\n *   <footer>\n *     Footer A\n *   </footer>\n *   <header>\n *     Header B\n *   </header>\n *   <div class=\"body\">\n *     Body B\n *   </div>\n *   <footer>\n *     Footer B\n *   </footer>\n * ```\n *\n * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such\n * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).\n *\n * @animations\n * **.enter** - when a new item is added to the list or when an item is revealed after a filter\n *\n * **.leave** - when an item is removed from the list or when an item is filtered out\n *\n * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered\n *\n * @element ANY\n * @scope\n * @priority 1000\n * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These\n *   formats are currently supported:\n *\n *   * `variable in expression` – where variable is the user defined loop variable and `expression`\n *     is a scope expression giving the collection to enumerate.\n *\n *     For example: `album in artist.albums`.\n *\n *   * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,\n *     and `expression` is the scope expression giving the collection to enumerate.\n *\n *     For example: `(name, age) in {'adam':10, 'amalie':12}`.\n *\n *   * `variable in expression track by tracking_expression` – You can also provide an optional tracking function\n *     which can be used to associate the objects in the collection with the DOM elements. If no tracking function\n *     is specified the ng-repeat associates elements by identity in the collection. It is an error to have\n *     more than one tracking function to resolve to the same key. (This would mean that two distinct objects are\n *     mapped to the same DOM element, which is not possible.)  Filters should be applied to the expression,\n *     before specifying a tracking expression.\n *\n *     For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements\n *     will be associated by item identity in the array.\n *\n *     For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique\n *     `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements\n *     with the corresponding item in the array by identity. Moving the same object in array would move the DOM\n *     element in the same way in the DOM.\n *\n *     For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this\n *     case the object identity does not matter. Two objects are considered equivalent as long as their `id`\n *     property is same.\n *\n *     For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter\n *     to items in conjunction with a tracking expression.\n *\n *   * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the\n *     intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message\n *     when a filter is active on the repeater, but the filtered result set is empty.\n *\n *     For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after\n *     the items have been processed through the filter.\n *\n * @example\n * This example initializes the scope to a list of names and\n * then uses `ngRepeat` to display every person:\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-init=\"friends = [\n        {name:'John', age:25, gender:'boy'},\n        {name:'Jessie', age:30, gender:'girl'},\n        {name:'Johanna', age:28, gender:'girl'},\n        {name:'Joy', age:15, gender:'girl'},\n        {name:'Mary', age:28, gender:'girl'},\n        {name:'Peter', age:95, gender:'boy'},\n        {name:'Sebastian', age:50, gender:'boy'},\n        {name:'Erika', age:27, gender:'girl'},\n        {name:'Patrick', age:40, gender:'boy'},\n        {name:'Samantha', age:60, gender:'girl'}\n      ]\">\n        I have {{friends.length}} friends. They are:\n        <input type=\"search\" ng-model=\"q\" placeholder=\"filter friends...\" />\n        <ul class=\"example-animate-container\">\n          <li class=\"animate-repeat\" ng-repeat=\"friend in friends | filter:q as results\">\n            [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.\n          </li>\n          <li class=\"animate-repeat\" ng-if=\"results.length == 0\">\n            <strong>No results found...</strong>\n          </li>\n        </ul>\n      </div>\n    </file>\n    <file name=\"animations.css\">\n      .example-animate-container {\n        background:white;\n        border:1px solid black;\n        list-style:none;\n        margin:0;\n        padding:0 10px;\n      }\n\n      .animate-repeat {\n        line-height:40px;\n        list-style:none;\n        box-sizing:border-box;\n      }\n\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter,\n      .animate-repeat.ng-leave {\n        -webkit-transition:all linear 0.5s;\n        transition:all linear 0.5s;\n      }\n\n      .animate-repeat.ng-leave.ng-leave-active,\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter {\n        opacity:0;\n        max-height:0;\n      }\n\n      .animate-repeat.ng-leave,\n      .animate-repeat.ng-move.ng-move-active,\n      .animate-repeat.ng-enter.ng-enter-active {\n        opacity:1;\n        max-height:40px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var friends = element.all(by.repeater('friend in friends'));\n\n      it('should render initial data set', function() {\n        expect(friends.count()).toBe(10);\n        expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');\n        expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');\n        expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');\n        expect(element(by.binding('friends.length')).getText())\n            .toMatch(\"I have 10 friends. They are:\");\n      });\n\n       it('should update repeater when filter predicate changes', function() {\n         expect(friends.count()).toBe(10);\n\n         element(by.model('q')).sendKeys('ma');\n\n         expect(friends.count()).toBe(2);\n         expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');\n         expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');\n       });\n      </file>\n    </example>\n */\nvar ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {\n  var NG_REMOVED = '$$NG_REMOVED';\n  var ngRepeatMinErr = minErr('ngRepeat');\n\n  var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {\n    // TODO(perf): generate setters to shave off ~40ms or 1-1.5%\n    scope[valueIdentifier] = value;\n    if (keyIdentifier) scope[keyIdentifier] = key;\n    scope.$index = index;\n    scope.$first = (index === 0);\n    scope.$last = (index === (arrayLength - 1));\n    scope.$middle = !(scope.$first || scope.$last);\n    // jshint bitwise: false\n    scope.$odd = !(scope.$even = (index&1) === 0);\n    // jshint bitwise: true\n  };\n\n  var getBlockStart = function(block) {\n    return block.clone[0];\n  };\n\n  var getBlockEnd = function(block) {\n    return block.clone[block.clone.length - 1];\n  };\n\n\n  return {\n    restrict: 'A',\n    multiElement: true,\n    transclude: 'element',\n    priority: 1000,\n    terminal: true,\n    $$tlb: true,\n    compile: function ngRepeatCompile($element, $attr) {\n      var expression = $attr.ngRepeat;\n      var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');\n\n      var match = expression.match(/^\\s*([\\s\\S]+?)\\s+in\\s+([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+track\\s+by\\s+([\\s\\S]+?))?\\s*$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iexp', \"Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.\",\n            expression);\n      }\n\n      var lhs = match[1];\n      var rhs = match[2];\n      var aliasAs = match[3];\n      var trackByExp = match[4];\n\n      match = lhs.match(/^(?:(\\s*[\\$\\w]+)|\\(\\s*([\\$\\w]+)\\s*,\\s*([\\$\\w]+)\\s*\\))$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iidexp', \"'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.\",\n            lhs);\n      }\n      var valueIdentifier = match[3] || match[1];\n      var keyIdentifier = match[2];\n\n      if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||\n          /^(null|undefined|this|\\$index|\\$first|\\$middle|\\$last|\\$even|\\$odd|\\$parent|\\$root|\\$id)$/.test(aliasAs))) {\n        throw ngRepeatMinErr('badident', \"alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.\",\n          aliasAs);\n      }\n\n      var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;\n      var hashFnLocals = {$id: hashKey};\n\n      if (trackByExp) {\n        trackByExpGetter = $parse(trackByExp);\n      } else {\n        trackByIdArrayFn = function(key, value) {\n          return hashKey(value);\n        };\n        trackByIdObjFn = function(key) {\n          return key;\n        };\n      }\n\n      return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {\n\n        if (trackByExpGetter) {\n          trackByIdExpFn = function(key, value, index) {\n            // assign key, value, and $index to the locals so that they can be used in hash functions\n            if (keyIdentifier) hashFnLocals[keyIdentifier] = key;\n            hashFnLocals[valueIdentifier] = value;\n            hashFnLocals.$index = index;\n            return trackByExpGetter($scope, hashFnLocals);\n          };\n        }\n\n        // Store a list of elements from previous run. This is a hash where key is the item from the\n        // iterator, and the value is objects with following properties.\n        //   - scope: bound scope\n        //   - element: previous element.\n        //   - index: position\n        //\n        // We are using no-proto object so that we don't need to guard against inherited props via\n        // hasOwnProperty.\n        var lastBlockMap = createMap();\n\n        //watch props\n        $scope.$watchCollection(rhs, function ngRepeatAction(collection) {\n          var index, length,\n              previousNode = $element[0],     // node that cloned nodes should be inserted after\n                                              // initialized to the comment node anchor\n              nextNode,\n              // Same as lastBlockMap but it has the current state. It will become the\n              // lastBlockMap on the next iteration.\n              nextBlockMap = createMap(),\n              collectionLength,\n              key, value, // key/value of iteration\n              trackById,\n              trackByIdFn,\n              collectionKeys,\n              block,       // last object information {scope, element, id}\n              nextBlockOrder,\n              elementsToRemove;\n\n          if (aliasAs) {\n            $scope[aliasAs] = collection;\n          }\n\n          if (isArrayLike(collection)) {\n            collectionKeys = collection;\n            trackByIdFn = trackByIdExpFn || trackByIdArrayFn;\n          } else {\n            trackByIdFn = trackByIdExpFn || trackByIdObjFn;\n            // if object, extract keys, sort them and use to determine order of iteration over obj props\n            collectionKeys = [];\n            for (var itemKey in collection) {\n              if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {\n                collectionKeys.push(itemKey);\n              }\n            }\n            collectionKeys.sort();\n          }\n\n          collectionLength = collectionKeys.length;\n          nextBlockOrder = new Array(collectionLength);\n\n          // locate existing items\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            trackById = trackByIdFn(key, value, index);\n            if (lastBlockMap[trackById]) {\n              // found previously seen block\n              block = lastBlockMap[trackById];\n              delete lastBlockMap[trackById];\n              nextBlockMap[trackById] = block;\n              nextBlockOrder[index] = block;\n            } else if (nextBlockMap[trackById]) {\n              // if collision detected. restore lastBlockMap and throw an error\n              forEach(nextBlockOrder, function(block) {\n                if (block && block.scope) lastBlockMap[block.id] = block;\n              });\n              throw ngRepeatMinErr('dupes',\n                  \"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}\",\n                  expression, trackById, value);\n            } else {\n              // new never before seen block\n              nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};\n              nextBlockMap[trackById] = true;\n            }\n          }\n\n          // remove leftover items\n          for (var blockKey in lastBlockMap) {\n            block = lastBlockMap[blockKey];\n            elementsToRemove = getBlockNodes(block.clone);\n            $animate.leave(elementsToRemove);\n            if (elementsToRemove[0].parentNode) {\n              // if the element was not removed yet because of pending animation, mark it as deleted\n              // so that we can ignore it later\n              for (index = 0, length = elementsToRemove.length; index < length; index++) {\n                elementsToRemove[index][NG_REMOVED] = true;\n              }\n            }\n            block.scope.$destroy();\n          }\n\n          // we are not using forEach for perf reasons (trying to avoid #call)\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            block = nextBlockOrder[index];\n\n            if (block.scope) {\n              // if we have already seen this object, then we need to reuse the\n              // associated scope/element\n\n              nextNode = previousNode;\n\n              // skip nodes that are already pending removal via leave animation\n              do {\n                nextNode = nextNode.nextSibling;\n              } while (nextNode && nextNode[NG_REMOVED]);\n\n              if (getBlockStart(block) != nextNode) {\n                // existing item which got moved\n                $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));\n              }\n              previousNode = getBlockEnd(block);\n              updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n            } else {\n              // new item which we don't know about\n              $transclude(function ngRepeatTransclude(clone, scope) {\n                block.scope = scope;\n                // http://jsperf.com/clone-vs-createcomment\n                var endNode = ngRepeatEndComment.cloneNode(false);\n                clone[clone.length++] = endNode;\n\n                // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?\n                $animate.enter(clone, null, jqLite(previousNode));\n                previousNode = endNode;\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block.clone = clone;\n                nextBlockMap[block.id] = block;\n                updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n              });\n            }\n          }\n          lastBlockMap = nextBlockMap;\n        });\n      };\n    }\n  };\n}];\n\nvar NG_HIDE_CLASS = 'ng-hide';\nvar NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';\n/**\n * @ngdoc directive\n * @name ngShow\n *\n * @description\n * The `ngShow` directive shows or hides the given HTML element based on the expression\n * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding\n * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is visible) -->\n * <div ng-show=\"myValue\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is hidden) -->\n * <div ng-show=\"myValue\" class=\"ng-hide\"></div>\n * ```\n *\n * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope\n * with extra animation classes that can be added.\n *\n * ```css\n * .ng-hide:not(.ng-hide-animate) {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngShow`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass except that\n * you must also include the !important flag to override the display property\n * so that you can perform an animation when the element is hidden during the time of the animation.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   /&#42; this is required as of 1.3x to properly\n *      apply all styling in a show/hide animation &#42;/\n *   transition: 0s linear all;\n * }\n *\n * .my-element.ng-hide-add-active,\n * .my-element.ng-hide-remove-active {\n *   /&#42; the transition is defined in the active class &#42;/\n *   transition: 1s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible\n * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden\n *\n * @element ANY\n * @param {expression} ngShow If the {@link guide/expression expression} is truthy\n *     then the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-show\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-show\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-show {\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-show.ng-hide-add.ng-hide-add-active,\n      .animate-show.ng-hide-remove.ng-hide-remove-active {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n      }\n\n      .animate-show.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngShowDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngShow, function ngShowWatchAction(value) {\n        // we're adding a temporary, animation-specific class for ng-hide since this way\n        // we can control when the element is actually displayed on screen without having\n        // to have a global/greedy CSS selector that breaks when other animations are run.\n        // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845\n        $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngHide\n *\n * @description\n * The `ngHide` directive shows or hides the given HTML element based on the expression\n * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding\n * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is hidden) -->\n * <div ng-hide=\"myValue\" class=\"ng-hide\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is visible) -->\n * <div ng-hide=\"myValue\"></div>\n * ```\n *\n * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class in CSS:\n *\n * ```css\n * .ng-hide {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngHide`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`\n * CSS class is added and removed for you instead of your own CSS class.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   transition: 0.5s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden\n * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible\n *\n * @element ANY\n * @param {expression} ngHide If the {@link guide/expression expression} is truthy then\n *     the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-hide\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-hide\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-hide {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-hide.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngHideDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngHide, function ngHideWatchAction(value) {\n        // The comment inside of the ngShowDirective explains why we add and\n        // remove a temporary class for the show/hide animation\n        $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngStyle\n * @restrict AC\n *\n * @description\n * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.\n *\n * @element ANY\n * @param {expression} ngStyle\n *\n * {@link guide/expression Expression} which evals to an\n * object whose keys are CSS style names and values are corresponding values for those CSS\n * keys.\n *\n * Since some CSS style names are not valid keys for an object, they must be quoted.\n * See the 'background-color' style in the example below.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <input type=\"button\" value=\"set color\" ng-click=\"myStyle={color:'red'}\">\n        <input type=\"button\" value=\"set background\" ng-click=\"myStyle={'background-color':'blue'}\">\n        <input type=\"button\" value=\"clear\" ng-click=\"myStyle={}\">\n        <br/>\n        <span ng-style=\"myStyle\">Sample Text</span>\n        <pre>myStyle={{myStyle}}</pre>\n     </file>\n     <file name=\"style.css\">\n       span {\n         color: black;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var colorSpan = element(by.css('span'));\n\n       it('should check ng-style', function() {\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n         element(by.css('input[value=\\'set color\\']')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');\n         element(by.css('input[value=clear]')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n       });\n     </file>\n   </example>\n */\nvar ngStyleDirective = ngDirective(function(scope, element, attr) {\n  scope.$watchCollection(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {\n    if (oldStyles && (newStyles !== oldStyles)) {\n      forEach(oldStyles, function(val, style) { element.css(style, '');});\n    }\n    if (newStyles) element.css(newStyles);\n  });\n});\n\n/**\n * @ngdoc directive\n * @name ngSwitch\n * @restrict EA\n *\n * @description\n * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.\n * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location\n * as specified in the template.\n *\n * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it\n * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element\n * matches the value obtained from the evaluated expression. In other words, you define a container element\n * (where you place the directive), place an expression on the **`on=\"...\"` attribute**\n * (or the **`ng-switch=\"...\"` attribute**), define any inner elements inside of the directive and place\n * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on\n * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default\n * attribute is displayed.\n *\n * <div class=\"alert alert-info\">\n * Be aware that the attribute values to match against cannot be expressions. They are interpreted\n * as literal string values to match against.\n * For example, **`ng-switch-when=\"someVal\"`** will match against the string `\"someVal\"` not against the\n * value of the expression `$scope.someVal`.\n * </div>\n\n * @animations\n * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container\n * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM\n *\n * @usage\n *\n * ```\n * <ANY ng-switch=\"expression\">\n *   <ANY ng-switch-when=\"matchValue1\">...</ANY>\n *   <ANY ng-switch-when=\"matchValue2\">...</ANY>\n *   <ANY ng-switch-default>...</ANY>\n * </ANY>\n * ```\n *\n *\n * @scope\n * @priority 1200\n * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.\n * On child elements add:\n *\n * * `ngSwitchWhen`: the case statement to match against. If match then this\n *   case will be displayed. If the same match appears multiple times, all the\n *   elements will be displayed.\n * * `ngSwitchDefault`: the default case when no other case match. If there\n *   are multiple default cases, all of them will be displayed when no other\n *   case match.\n *\n *\n * @example\n  <example module=\"switchExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <select ng-model=\"selection\" ng-options=\"item for item in items\">\n        </select>\n        <tt>selection={{selection}}</tt>\n        <hr/>\n        <div class=\"animate-switch-container\"\n          ng-switch on=\"selection\">\n            <div class=\"animate-switch\" ng-switch-when=\"settings\">Settings Div</div>\n            <div class=\"animate-switch\" ng-switch-when=\"home\">Home Span</div>\n            <div class=\"animate-switch\" ng-switch-default>default</div>\n        </div>\n      </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('switchExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.items = ['settings', 'home', 'other'];\n          $scope.selection = $scope.items[0];\n        }]);\n    </file>\n    <file name=\"animations.css\">\n      .animate-switch-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .animate-switch {\n        padding:10px;\n      }\n\n      .animate-switch.ng-animate {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n      }\n\n      .animate-switch.ng-leave.ng-leave-active,\n      .animate-switch.ng-enter {\n        top:-50px;\n      }\n      .animate-switch.ng-leave,\n      .animate-switch.ng-enter.ng-enter-active {\n        top:0;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var switchElem = element(by.css('[ng-switch]'));\n      var select = element(by.model('selection'));\n\n      it('should start in settings', function() {\n        expect(switchElem.getText()).toMatch(/Settings Div/);\n      });\n      it('should change to home', function() {\n        select.all(by.css('option')).get(1).click();\n        expect(switchElem.getText()).toMatch(/Home Span/);\n      });\n      it('should select default', function() {\n        select.all(by.css('option')).get(2).click();\n        expect(switchElem.getText()).toMatch(/default/);\n      });\n    </file>\n  </example>\n */\nvar ngSwitchDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'EA',\n    require: 'ngSwitch',\n\n    // asks for $scope to fool the BC controller module\n    controller: ['$scope', function ngSwitchController() {\n     this.cases = {};\n    }],\n    link: function(scope, element, attr, ngSwitchController) {\n      var watchExpr = attr.ngSwitch || attr.on,\n          selectedTranscludes = [],\n          selectedElements = [],\n          previousLeaveAnimations = [],\n          selectedScopes = [];\n\n      var spliceFactory = function(array, index) {\n          return function() { array.splice(index, 1); };\n      };\n\n      scope.$watch(watchExpr, function ngSwitchWatchAction(value) {\n        var i, ii;\n        for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {\n          $animate.cancel(previousLeaveAnimations[i]);\n        }\n        previousLeaveAnimations.length = 0;\n\n        for (i = 0, ii = selectedScopes.length; i < ii; ++i) {\n          var selected = getBlockNodes(selectedElements[i].clone);\n          selectedScopes[i].$destroy();\n          var promise = previousLeaveAnimations[i] = $animate.leave(selected);\n          promise.then(spliceFactory(previousLeaveAnimations, i));\n        }\n\n        selectedElements.length = 0;\n        selectedScopes.length = 0;\n\n        if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {\n          forEach(selectedTranscludes, function(selectedTransclude) {\n            selectedTransclude.transclude(function(caseElement, selectedScope) {\n              selectedScopes.push(selectedScope);\n              var anchor = selectedTransclude.element;\n              caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');\n              var block = { clone: caseElement };\n\n              selectedElements.push(block);\n              $animate.enter(caseElement, anchor.parent(), anchor);\n            });\n          });\n        }\n      });\n    }\n  };\n}];\n\nvar ngSwitchWhenDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attrs, ctrl, $transclude) {\n    ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);\n    ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });\n  }\n});\n\nvar ngSwitchDefaultDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attr, ctrl, $transclude) {\n    ctrl.cases['?'] = (ctrl.cases['?'] || []);\n    ctrl.cases['?'].push({ transclude: $transclude, element: element });\n   }\n});\n\n/**\n * @ngdoc directive\n * @name ngTransclude\n * @restrict EAC\n *\n * @description\n * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.\n *\n * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.\n *\n * @element ANY\n *\n * @example\n   <example module=\"transcludeExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('transcludeExample', [])\n          .directive('pane', function(){\n             return {\n               restrict: 'E',\n               transclude: true,\n               scope: { title:'@' },\n               template: '<div style=\"border: 1px solid black;\">' +\n                           '<div style=\"background-color: gray\">{{title}}</div>' +\n                           '<ng-transclude></ng-transclude>' +\n                         '</div>'\n             };\n         })\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.title = 'Lorem Ipsum';\n           $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';\n         }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input ng-model=\"title\"> <br/>\n         <textarea ng-model=\"text\"></textarea> <br/>\n         <pane title=\"{{title}}\">{{text}}</pane>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        it('should have transcluded', function() {\n          var titleElement = element(by.model('title'));\n          titleElement.clear();\n          titleElement.sendKeys('TITLE');\n          var textElement = element(by.model('text'));\n          textElement.clear();\n          textElement.sendKeys('TEXT');\n          expect(element(by.binding('title')).getText()).toEqual('TITLE');\n          expect(element(by.binding('text')).getText()).toEqual('TEXT');\n        });\n     </file>\n   </example>\n *\n */\nvar ngTranscludeDirective = ngDirective({\n  restrict: 'EAC',\n  link: function($scope, $element, $attrs, controller, $transclude) {\n    if (!$transclude) {\n      throw minErr('ngTransclude')('orphan',\n       'Illegal use of ngTransclude directive in the template! ' +\n       'No parent directive that requires a transclusion found. ' +\n       'Element: {0}',\n       startingTag($element));\n    }\n\n    $transclude(function(clone) {\n      $element.empty();\n      $element.append(clone);\n    });\n  }\n});\n\n/**\n * @ngdoc directive\n * @name script\n * @restrict E\n *\n * @description\n * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the\n * template can be used by {@link ng.directive:ngInclude `ngInclude`},\n * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the\n * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be\n * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.\n *\n * @param {string} type Must be set to `'text/ng-template'`.\n * @param {string} id Cache name of the template.\n *\n * @example\n  <example>\n    <file name=\"index.html\">\n      <script type=\"text/ng-template\" id=\"/tpl.html\">\n        Content of the template.\n      </script>\n\n      <a ng-click=\"currentTpl='/tpl.html'\" id=\"tpl-link\">Load inlined template</a>\n      <div id=\"tpl-content\" ng-include src=\"currentTpl\"></div>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      it('should load template defined inside script tag', function() {\n        element(by.css('#tpl-link')).click();\n        expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);\n      });\n    </file>\n  </example>\n */\nvar scriptDirective = ['$templateCache', function($templateCache) {\n  return {\n    restrict: 'E',\n    terminal: true,\n    compile: function(element, attr) {\n      if (attr.type == 'text/ng-template') {\n        var templateUrl = attr.id,\n            text = element[0].text;\n\n        $templateCache.put(templateUrl, text);\n      }\n    }\n  };\n}];\n\nvar ngOptionsMinErr = minErr('ngOptions');\n/**\n * @ngdoc directive\n * @name select\n * @restrict E\n *\n * @description\n * HTML `SELECT` element with angular data-binding.\n *\n * # `ngOptions`\n *\n * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`\n * elements for the `<select>` element using the array or object obtained by evaluating the\n * `ngOptions` comprehension expression.\n *\n * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a\n * similar result. However, `ngOptions` provides some benefits such as reducing memory and\n * increasing speed by not creating a new scope for each repeated instance, as well as providing\n * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the\n * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound\n *  to a non-string value. This is because an option element can only be bound to string values at\n * present.\n *\n * When an item in the `<select>` menu is selected, the array element or object property\n * represented by the selected option will be bound to the model identified by the `ngModel`\n * directive.\n *\n * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can\n * be nested into the `<select>` element. This element will then represent the `null` or \"not selected\"\n * option. See example below for demonstration.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** `ngModel` compares by reference, not value. This is important when binding to an\n * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).\n * </div>\n *\n * ## `select` **`as`**\n *\n * Using `select` **`as`** will bind the result of the `select` expression to the model, but\n * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)\n * or property name (for object data sources) of the value within the collection. If a **`track by`** expression\n * is used, the result of that expression will be set as the value of the `option` and `select` elements.\n *\n *\n * ### `select` **`as`** and **`track by`**\n *\n * <div class=\"alert alert-warning\">\n * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.\n * </div>\n *\n * Consider the following example:\n *\n * ```html\n * <select ng-options=\"item.subItem as item.label for item in values track by item.id\" ng-model=\"selected\">\n * ```\n *\n * ```js\n * $scope.values = [{\n *   id: 1,\n *   label: 'aLabel',\n *   subItem: { name: 'aSubItem' }\n * }, {\n *   id: 2,\n *   label: 'bLabel',\n *   subItem: { name: 'bSubItem' }\n * }];\n *\n * $scope.selected = { name: 'aSubItem' };\n * ```\n *\n * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element\n * of the data source (to `item` in this example). To calculate whether an element is selected, we do the\n * following:\n *\n * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`\n * 2. Apply **`track by`** to the already selected value in `ngModel`.\n *    In the example: this is not possible as **`track by`** refers to `item.id`, but the selected\n *    value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to\n *    a wrong object, the selected element can't be found, `<select>` is always reset to the \"not\n *    selected\" option.\n *\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required The control is considered valid only if value is entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {comprehension_expression=} ngOptions in one of the following forms:\n *\n *   * for array data sources:\n *     * `label` **`for`** `value` **`in`** `array`\n *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`\n *     * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`\n *        (for including a filter with `track by`)\n *   * for object data sources:\n *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`group by`** `group`\n *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`\n *\n * Where:\n *\n *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.\n *   * `value`: local variable which will refer to each item in the `array` or each property value\n *      of `object` during iteration.\n *   * `key`: local variable which will refer to a property name in `object` during iteration.\n *   * `label`: The result of this expression will be the label for `<option>` element. The\n *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).\n *   * `select`: The result of this expression will be bound to the model of the parent `<select>`\n *      element. If not specified, `select` expression will default to `value`.\n *   * `group`: The result of this expression will be used to group options using the `<optgroup>`\n *      DOM element.\n *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be\n *      used to identify the objects in the array. The `trackexpr` will most likely refer to the\n *     `value` variable (e.g. `value.propertyName`). With this the selection is preserved\n *      even when the options are recreated (e.g. reloaded from the server).\n *\n * @example\n    <example module=\"selectExample\">\n      <file name=\"index.html\">\n        <script>\n        angular.module('selectExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.colors = [\n              {name:'black', shade:'dark'},\n              {name:'white', shade:'light'},\n              {name:'red', shade:'dark'},\n              {name:'blue', shade:'dark'},\n              {name:'yellow', shade:'light'}\n            ];\n            $scope.myColor = $scope.colors[2]; // red\n          }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          <ul>\n            <li ng-repeat=\"color in colors\">\n              Name: <input ng-model=\"color.name\">\n              [<a href ng-click=\"colors.splice($index, 1)\">X</a>]\n            </li>\n            <li>\n              [<a href ng-click=\"colors.push({})\">add</a>]\n            </li>\n          </ul>\n          <hr/>\n          Color (null not allowed):\n          <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\"></select><br>\n\n          Color (null allowed):\n          <span  class=\"nullable\">\n            <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\">\n              <option value=\"\">-- choose color --</option>\n            </select>\n          </span><br/>\n\n          Color grouped by shade:\n          <select ng-model=\"myColor\" ng-options=\"color.name group by color.shade for color in colors\">\n          </select><br/>\n\n\n          Select <a href ng-click=\"myColor = { name:'not in list', shade: 'other' }\">bogus</a>.<br>\n          <hr/>\n          Currently selected: {{ {selected_color:myColor} }}\n          <div style=\"border:solid 1px black; height:20px\"\n               ng-style=\"{'background-color':myColor.name}\">\n          </div>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n         it('should check ng-options', function() {\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');\n           element.all(by.model('myColor')).first().click();\n           element.all(by.css('select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');\n           element(by.css('.nullable select[ng-model=\"myColor\"]')).click();\n           element.all(by.css('.nullable select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');\n         });\n      </file>\n    </example>\n */\n\nvar ngOptionsDirective = valueFn({\n  restrict: 'A',\n  terminal: true\n});\n\n// jshint maxlen: false\nvar selectDirective = ['$compile', '$parse', function($compile,   $parse) {\n                         //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888\n  var NG_OPTIONS_REGEXP = /^\\s*([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+group\\s+by\\s+([\\s\\S]+?))?\\s+for\\s+(?:([\\$\\w][\\$\\w]*)|(?:\\(\\s*([\\$\\w][\\$\\w]*)\\s*,\\s*([\\$\\w][\\$\\w]*)\\s*\\)))\\s+in\\s+([\\s\\S]+?)(?:\\s+track\\s+by\\s+([\\s\\S]+?))?$/,\n      nullModelCtrl = {$setViewValue: noop};\n// jshint maxlen: 100\n\n  return {\n    restrict: 'E',\n    require: ['select', '?ngModel'],\n    controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {\n      var self = this,\n          optionsMap = {},\n          ngModelCtrl = nullModelCtrl,\n          nullOption,\n          unknownOption;\n\n\n      self.databound = $attrs.ngModel;\n\n\n      self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {\n        ngModelCtrl = ngModelCtrl_;\n        nullOption = nullOption_;\n        unknownOption = unknownOption_;\n      };\n\n\n      self.addOption = function(value, element) {\n        assertNotHasOwnProperty(value, '\"option value\"');\n        optionsMap[value] = true;\n\n        if (ngModelCtrl.$viewValue == value) {\n          $element.val(value);\n          if (unknownOption.parent()) unknownOption.remove();\n        }\n        // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459\n        // Adding an <option selected=\"selected\"> element to a <select required=\"required\"> should\n        // automatically select the new element\n        if (element && element[0].hasAttribute('selected')) {\n          element[0].selected = true;\n        }\n      };\n\n\n      self.removeOption = function(value) {\n        if (this.hasOption(value)) {\n          delete optionsMap[value];\n          if (ngModelCtrl.$viewValue === value) {\n            this.renderUnknownOption(value);\n          }\n        }\n      };\n\n\n      self.renderUnknownOption = function(val) {\n        var unknownVal = '? ' + hashKey(val) + ' ?';\n        unknownOption.val(unknownVal);\n        $element.prepend(unknownOption);\n        $element.val(unknownVal);\n        unknownOption.prop('selected', true); // needed for IE\n      };\n\n\n      self.hasOption = function(value) {\n        return optionsMap.hasOwnProperty(value);\n      };\n\n      $scope.$on('$destroy', function() {\n        // disable unknown option so that we don't do work when the whole select is being destroyed\n        self.renderUnknownOption = noop;\n      });\n    }],\n\n    link: function(scope, element, attr, ctrls) {\n      // if ngModel is not defined, we don't need to do anything\n      if (!ctrls[1]) return;\n\n      var selectCtrl = ctrls[0],\n          ngModelCtrl = ctrls[1],\n          multiple = attr.multiple,\n          optionsExp = attr.ngOptions,\n          nullOption = false, // if false, user will not be able to select it (used by ngOptions)\n          emptyOption,\n          renderScheduled = false,\n          // we can't just jqLite('<option>') since jqLite is not smart enough\n          // to create it in <select> and IE barfs otherwise.\n          optionTemplate = jqLite(document.createElement('option')),\n          optGroupTemplate =jqLite(document.createElement('optgroup')),\n          unknownOption = optionTemplate.clone();\n\n      // find \"null\" option\n      for (var i = 0, children = element.children(), ii = children.length; i < ii; i++) {\n        if (children[i].value === '') {\n          emptyOption = nullOption = children.eq(i);\n          break;\n        }\n      }\n\n      selectCtrl.init(ngModelCtrl, nullOption, unknownOption);\n\n      // required validator\n      if (multiple) {\n        ngModelCtrl.$isEmpty = function(value) {\n          return !value || value.length === 0;\n        };\n      }\n\n      if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);\n      else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);\n      else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);\n\n\n      ////////////////////////////\n\n\n\n      function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {\n        ngModelCtrl.$render = function() {\n          var viewValue = ngModelCtrl.$viewValue;\n\n          if (selectCtrl.hasOption(viewValue)) {\n            if (unknownOption.parent()) unknownOption.remove();\n            selectElement.val(viewValue);\n            if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy\n          } else {\n            if (isUndefined(viewValue) && emptyOption) {\n              selectElement.val('');\n            } else {\n              selectCtrl.renderUnknownOption(viewValue);\n            }\n          }\n        };\n\n        selectElement.on('change', function() {\n          scope.$apply(function() {\n            if (unknownOption.parent()) unknownOption.remove();\n            ngModelCtrl.$setViewValue(selectElement.val());\n          });\n        });\n      }\n\n      function setupAsMultiple(scope, selectElement, ctrl) {\n        var lastView;\n        ctrl.$render = function() {\n          var items = new HashMap(ctrl.$viewValue);\n          forEach(selectElement.find('option'), function(option) {\n            option.selected = isDefined(items.get(option.value));\n          });\n        };\n\n        // we have to do it on each watch since ngModel watches reference, but\n        // we need to work of an array, so we need to see if anything was inserted/removed\n        scope.$watch(function selectMultipleWatch() {\n          if (!equals(lastView, ctrl.$viewValue)) {\n            lastView = shallowCopy(ctrl.$viewValue);\n            ctrl.$render();\n          }\n        });\n\n        selectElement.on('change', function() {\n          scope.$apply(function() {\n            var array = [];\n            forEach(selectElement.find('option'), function(option) {\n              if (option.selected) {\n                array.push(option.value);\n              }\n            });\n            ctrl.$setViewValue(array);\n          });\n        });\n      }\n\n      function setupAsOptions(scope, selectElement, ctrl) {\n        var match;\n\n        if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {\n          throw ngOptionsMinErr('iexp',\n            \"Expected expression in form of \" +\n            \"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'\" +\n            \" but got '{0}'. Element: {1}\",\n            optionsExp, startingTag(selectElement));\n        }\n\n        var displayFn = $parse(match[2] || match[1]),\n            valueName = match[4] || match[6],\n            selectAs = / as /.test(match[0]) && match[1],\n            selectAsFn = selectAs ? $parse(selectAs) : null,\n            keyName = match[5],\n            groupByFn = $parse(match[3] || ''),\n            valueFn = $parse(match[2] ? match[1] : valueName),\n            valuesFn = $parse(match[7]),\n            track = match[8],\n            trackFn = track ? $parse(match[8]) : null,\n            trackKeysCache = {},\n            // This is an array of array of existing option groups in DOM.\n            // We try to reuse these if possible\n            // - optionGroupsCache[0] is the options with no option group\n            // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element\n            optionGroupsCache = [[{element: selectElement, label:''}]],\n            //re-usable object to represent option's locals\n            locals = {};\n\n        if (nullOption) {\n          // compile the element since there might be bindings in it\n          $compile(nullOption)(scope);\n\n          // remove the class, which is added automatically because we recompile the element and it\n          // becomes the compilation root\n          nullOption.removeClass('ng-scope');\n\n          // we need to remove it before calling selectElement.empty() because otherwise IE will\n          // remove the label from the element. wtf?\n          nullOption.remove();\n        }\n\n        // clear contents, we'll add what's needed based on the model\n        selectElement.empty();\n\n        selectElement.on('change', selectionChanged);\n\n        ctrl.$render = render;\n\n        scope.$watchCollection(valuesFn, scheduleRendering);\n        scope.$watchCollection(getLabels, scheduleRendering);\n\n        if (multiple) {\n          scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);\n        }\n\n        // ------------------------------------------------------------------ //\n\n        function callExpression(exprFn, key, value) {\n          locals[valueName] = value;\n          if (keyName) locals[keyName] = key;\n          return exprFn(scope, locals);\n        }\n\n        function selectionChanged() {\n          scope.$apply(function() {\n            var collection = valuesFn(scope) || [];\n            var viewValue;\n            if (multiple) {\n              viewValue = [];\n              forEach(selectElement.val(), function(selectedKey) {\n                  selectedKey = trackFn ? trackKeysCache[selectedKey] : selectedKey;\n                viewValue.push(getViewValue(selectedKey, collection[selectedKey]));\n              });\n            } else {\n              var selectedKey = trackFn ? trackKeysCache[selectElement.val()] : selectElement.val();\n              viewValue = getViewValue(selectedKey, collection[selectedKey]);\n            }\n            ctrl.$setViewValue(viewValue);\n            render();\n          });\n        }\n\n        function getViewValue(key, value) {\n          if (key === '?') {\n            return undefined;\n          } else if (key === '') {\n            return null;\n          } else {\n            var viewValueFn = selectAsFn ? selectAsFn : valueFn;\n            return callExpression(viewValueFn, key, value);\n          }\n        }\n\n        function getLabels() {\n          var values = valuesFn(scope);\n          var toDisplay;\n          if (values && isArray(values)) {\n            toDisplay = new Array(values.length);\n            for (var i = 0, ii = values.length; i < ii; i++) {\n              toDisplay[i] = callExpression(displayFn, i, values[i]);\n            }\n            return toDisplay;\n          } else if (values) {\n            // TODO: Add a test for this case\n            toDisplay = {};\n            for (var prop in values) {\n              if (values.hasOwnProperty(prop)) {\n                toDisplay[prop] = callExpression(displayFn, prop, values[prop]);\n              }\n            }\n          }\n          return toDisplay;\n        }\n\n        function createIsSelectedFn(viewValue) {\n          var selectedSet;\n          if (multiple) {\n            if (trackFn && isArray(viewValue)) {\n\n              selectedSet = new HashMap([]);\n              for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {\n                // tracking by key\n                selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);\n              }\n            } else {\n              selectedSet = new HashMap(viewValue);\n            }\n          } else if (trackFn) {\n            viewValue = callExpression(trackFn, null, viewValue);\n          }\n\n          return function isSelected(key, value) {\n            var compareValueFn;\n            if (trackFn) {\n              compareValueFn = trackFn;\n            } else if (selectAsFn) {\n              compareValueFn = selectAsFn;\n            } else {\n              compareValueFn = valueFn;\n            }\n\n            if (multiple) {\n              return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));\n            } else {\n              return viewValue === callExpression(compareValueFn, key, value);\n            }\n          };\n        }\n\n        function scheduleRendering() {\n          if (!renderScheduled) {\n            scope.$$postDigest(render);\n            renderScheduled = true;\n          }\n        }\n\n        /**\n         * A new labelMap is created with each render.\n         * This function is called for each existing option with added=false,\n         * and each new option with added=true.\n         * - Labels that are passed to this method twice,\n         * (once with added=true and once with added=false) will end up with a value of 0, and\n         * will cause no change to happen to the corresponding option.\n         * - Labels that are passed to this method only once with added=false will end up with a\n         * value of -1 and will eventually be passed to selectCtrl.removeOption()\n         * - Labels that are passed to this method only once with added=true will end up with a\n         * value of 1 and will eventually be passed to selectCtrl.addOption()\n        */\n        function updateLabelMap(labelMap, label, added) {\n          labelMap[label] = labelMap[label] || 0;\n          labelMap[label] += (added ? 1 : -1);\n        }\n\n        function render() {\n          renderScheduled = false;\n\n          // Temporary location for the option groups before we render them\n          var optionGroups = {'':[]},\n              optionGroupNames = [''],\n              optionGroupName,\n              optionGroup,\n              option,\n              existingParent, existingOptions, existingOption,\n              viewValue = ctrl.$viewValue,\n              values = valuesFn(scope) || [],\n              keys = keyName ? sortedKeys(values) : values,\n              key,\n              value,\n              groupLength, length,\n              groupIndex, index,\n              labelMap = {},\n              selected,\n              isSelected = createIsSelectedFn(viewValue),\n              anySelected = false,\n              lastElement,\n              element,\n              label,\n              optionId;\n\n          trackKeysCache = {};\n\n          // We now build up the list of options we need (we merge later)\n          for (index = 0; length = keys.length, index < length; index++) {\n            key = index;\n            if (keyName) {\n              key = keys[index];\n              if (key.charAt(0) === '$') continue;\n            }\n            value = values[key];\n\n            optionGroupName = callExpression(groupByFn, key, value) || '';\n            if (!(optionGroup = optionGroups[optionGroupName])) {\n              optionGroup = optionGroups[optionGroupName] = [];\n              optionGroupNames.push(optionGroupName);\n            }\n\n            selected = isSelected(key, value);\n            anySelected = anySelected || selected;\n\n            label = callExpression(displayFn, key, value); // what will be seen by the user\n\n            // doing displayFn(scope, locals) || '' overwrites zero values\n            label = isDefined(label) ? label : '';\n            optionId = trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index);\n            if (trackFn) {\n              trackKeysCache[optionId] = key;\n            }\n\n            optionGroup.push({\n              // either the index into array or key from object\n              id: optionId,\n              label: label,\n              selected: selected                   // determine if we should be selected\n            });\n          }\n          if (!multiple) {\n            if (nullOption || viewValue === null) {\n              // insert null option if we have a placeholder, or the model is null\n              optionGroups[''].unshift({id:'', label:'', selected:!anySelected});\n            } else if (!anySelected) {\n              // option could not be found, we have to insert the undefined item\n              optionGroups[''].unshift({id:'?', label:'', selected:true});\n            }\n          }\n\n          // Now we need to update the list of DOM nodes to match the optionGroups we computed above\n          for (groupIndex = 0, groupLength = optionGroupNames.length;\n               groupIndex < groupLength;\n               groupIndex++) {\n            // current option group name or '' if no group\n            optionGroupName = optionGroupNames[groupIndex];\n\n            // list of options for that group. (first item has the parent)\n            optionGroup = optionGroups[optionGroupName];\n\n            if (optionGroupsCache.length <= groupIndex) {\n              // we need to grow the optionGroups\n              existingParent = {\n                element: optGroupTemplate.clone().attr('label', optionGroupName),\n                label: optionGroup.label\n              };\n              existingOptions = [existingParent];\n              optionGroupsCache.push(existingOptions);\n              selectElement.append(existingParent.element);\n            } else {\n              existingOptions = optionGroupsCache[groupIndex];\n              existingParent = existingOptions[0];  // either SELECT (no group) or OPTGROUP element\n\n              // update the OPTGROUP label if not the same.\n              if (existingParent.label != optionGroupName) {\n                existingParent.element.attr('label', existingParent.label = optionGroupName);\n              }\n            }\n\n            lastElement = null;  // start at the beginning\n            for (index = 0, length = optionGroup.length; index < length; index++) {\n              option = optionGroup[index];\n              if ((existingOption = existingOptions[index + 1])) {\n                // reuse elements\n                lastElement = existingOption.element;\n                if (existingOption.label !== option.label) {\n                  updateLabelMap(labelMap, existingOption.label, false);\n                  updateLabelMap(labelMap, option.label, true);\n                  lastElement.text(existingOption.label = option.label);\n                  lastElement.prop('label', existingOption.label);\n                }\n                if (existingOption.id !== option.id) {\n                  lastElement.val(existingOption.id = option.id);\n                }\n                // lastElement.prop('selected') provided by jQuery has side-effects\n                if (lastElement[0].selected !== option.selected) {\n                  lastElement.prop('selected', (existingOption.selected = option.selected));\n                  if (msie) {\n                    // See #7692\n                    // The selected item wouldn't visually update on IE without this.\n                    // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well\n                    lastElement.prop('selected', existingOption.selected);\n                  }\n                }\n              } else {\n                // grow elements\n\n                // if it's a null option\n                if (option.id === '' && nullOption) {\n                  // put back the pre-compiled element\n                  element = nullOption;\n                } else {\n                  // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but\n                  // in this version of jQuery on some browser the .text() returns a string\n                  // rather then the element.\n                  (element = optionTemplate.clone())\n                      .val(option.id)\n                      .prop('selected', option.selected)\n                      .attr('selected', option.selected)\n                      .prop('label', option.label)\n                      .text(option.label);\n                }\n\n                existingOptions.push(existingOption = {\n                    element: element,\n                    label: option.label,\n                    id: option.id,\n                    selected: option.selected\n                });\n                updateLabelMap(labelMap, option.label, true);\n                if (lastElement) {\n                  lastElement.after(element);\n                } else {\n                  existingParent.element.append(element);\n                }\n                lastElement = element;\n              }\n            }\n            // remove any excessive OPTIONs in a group\n            index++; // increment since the existingOptions[0] is parent element not OPTION\n            while (existingOptions.length > index) {\n              option = existingOptions.pop();\n              updateLabelMap(labelMap, option.label, false);\n              option.element.remove();\n            }\n          }\n          // remove any excessive OPTGROUPs from select\n          while (optionGroupsCache.length > groupIndex) {\n            // remove all the labels in the option group\n            optionGroup = optionGroupsCache.pop();\n            for (index = 1; index < optionGroup.length; ++index) {\n              updateLabelMap(labelMap, optionGroup[index].label, false);\n            }\n            optionGroup[0].element.remove();\n          }\n          forEach(labelMap, function(count, label) {\n            if (count > 0) {\n              selectCtrl.addOption(label);\n            } else if (count < 0) {\n              selectCtrl.removeOption(label);\n            }\n          });\n        }\n      }\n    }\n  };\n}];\n\nvar optionDirective = ['$interpolate', function($interpolate) {\n  var nullSelectCtrl = {\n    addOption: noop,\n    removeOption: noop\n  };\n\n  return {\n    restrict: 'E',\n    priority: 100,\n    compile: function(element, attr) {\n      if (isUndefined(attr.value)) {\n        var interpolateFn = $interpolate(element.text(), true);\n        if (!interpolateFn) {\n          attr.$set('value', element.text());\n        }\n      }\n\n      return function(scope, element, attr) {\n        var selectCtrlName = '$selectController',\n            parent = element.parent(),\n            selectCtrl = parent.data(selectCtrlName) ||\n              parent.parent().data(selectCtrlName); // in case we are in optgroup\n\n        if (!selectCtrl || !selectCtrl.databound) {\n          selectCtrl = nullSelectCtrl;\n        }\n\n        if (interpolateFn) {\n          scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {\n            attr.$set('value', newVal);\n            if (oldVal !== newVal) {\n              selectCtrl.removeOption(oldVal);\n            }\n            selectCtrl.addOption(newVal, element);\n          });\n        } else {\n          selectCtrl.addOption(attr.value, element);\n        }\n\n        element.on('$destroy', function() {\n          selectCtrl.removeOption(attr.value);\n        });\n      };\n    }\n  };\n}];\n\nvar styleDirective = valueFn({\n  restrict: 'E',\n  terminal: false\n});\n\nvar requiredDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n      attr.required = true; // force truthy in case we are on non input element\n\n      ctrl.$validators.required = function(modelValue, viewValue) {\n        return !attr.required || !ctrl.$isEmpty(viewValue);\n      };\n\n      attr.$observe('required', function() {\n        ctrl.$validate();\n      });\n    }\n  };\n};\n\n\nvar patternDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var regexp, patternExp = attr.ngPattern || attr.pattern;\n      attr.$observe('pattern', function(regex) {\n        if (isString(regex) && regex.length > 0) {\n          regex = new RegExp('^' + regex + '$');\n        }\n\n        if (regex && !regex.test) {\n          throw minErr('ngPattern')('noregexp',\n            'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,\n            regex, startingTag(elm));\n        }\n\n        regexp = regex || undefined;\n        ctrl.$validate();\n      });\n\n      ctrl.$validators.pattern = function(value) {\n        return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);\n      };\n    }\n  };\n};\n\n\nvar maxlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var maxlength = -1;\n      attr.$observe('maxlength', function(value) {\n        var intVal = int(value);\n        maxlength = isNaN(intVal) ? -1 : intVal;\n        ctrl.$validate();\n      });\n      ctrl.$validators.maxlength = function(modelValue, viewValue) {\n        return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);\n      };\n    }\n  };\n};\n\nvar minlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var minlength = 0;\n      attr.$observe('minlength', function(value) {\n        minlength = int(value) || 0;\n        ctrl.$validate();\n      });\n      ctrl.$validators.minlength = function(modelValue, viewValue) {\n        return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;\n      };\n    }\n  };\n};\n\n  if (window.angular.bootstrap) {\n    //AngularJS is already loaded, so we can return here...\n    console.log('WARNING: Tried to load angular more than once.');\n    return;\n  }\n\n  //try to bind to jquery now so that one can write jqLite(document).ready()\n  //but we will rebind on bootstrap again.\n  bindJQuery();\n\n  publishExternalAPI(angular);\n\n  jqLite(document).ready(function() {\n    angularInit(document, bootstrap);\n  });\n\n})(window, document);\n\n!window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type=\"text/css\">@charset \"UTF-8\";[ng\\\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\\\:form{display:block;}</style>');\n\n/*!\n * ionic.bundle.js is a concatenation of:\n * ionic.js, angular.js, angular-animate.js,\n * angular-sanitize.js, angular-ui-router.js,\n * and ionic-angular.js\n */\n\n/**\n * @license AngularJS v1.3.13\n * (c) 2010-2014 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* jshint maxlen: false */\n\n/**\n * @ngdoc module\n * @name ngAnimate\n * @description\n *\n * The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.\n *\n * <div doc-module-components=\"ngAnimate\"></div>\n *\n * # Usage\n *\n * To see animations in action, all that is required is to define the appropriate CSS classes\n * or to register a JavaScript animation via the `myModule.animation()` function. The directives that support animation automatically are:\n * `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation\n * by using the `$animate` service.\n *\n * Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:\n *\n * | Directive                                                                                                | Supported Animations                                                     |\n * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|\n * | {@link ng.directive:ngRepeat#animations ngRepeat}                                                        | enter, leave and move                                                    |\n * | {@link ngRoute.directive:ngView#animations ngView}                                                       | enter and leave                                                          |\n * | {@link ng.directive:ngInclude#animations ngInclude}                                                      | enter and leave                                                          |\n * | {@link ng.directive:ngSwitch#animations ngSwitch}                                                        | enter and leave                                                          |\n * | {@link ng.directive:ngIf#animations ngIf}                                                                | enter and leave                                                          |\n * | {@link ng.directive:ngClass#animations ngClass}                                                          | add and remove (the CSS class(es) present)                               |\n * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide}            | add and remove (the ng-hide class value)                                 |\n * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel}    | add and remove (dirty, pristine, valid, invalid & all other validations) |\n * | {@link module:ngMessages#animations ngMessages}                                                          | add and remove (ng-active & ng-inactive)                                 |\n * | {@link module:ngMessages#animations ngMessage}                                                           | enter and leave                                                          |\n *\n * You can find out more information about animations upon visiting each directive page.\n *\n * Below is an example of how to apply animations to a directive that supports animation hooks:\n *\n * ```html\n * <style type=\"text/css\">\n * .slide.ng-enter, .slide.ng-leave {\n *   -webkit-transition:0.5s linear all;\n *   transition:0.5s linear all;\n * }\n *\n * .slide.ng-enter { }        /&#42; starting animations for enter &#42;/\n * .slide.ng-enter.ng-enter-active { } /&#42; terminal animations for enter &#42;/\n * .slide.ng-leave { }        /&#42; starting animations for leave &#42;/\n * .slide.ng-leave.ng-leave-active { } /&#42; terminal animations for leave &#42;/\n * </style>\n *\n * <!--\n * the animate service will automatically add .ng-enter and .ng-leave to the element\n * to trigger the CSS transition/animations\n * -->\n * <ANY class=\"slide\" ng-include=\"...\"></ANY>\n * ```\n *\n * Keep in mind that, by default, if an animation is running, any child elements cannot be animated\n * until the parent element's animation has completed. This blocking feature can be overridden by\n * placing the `ng-animate-children` attribute on a parent container tag.\n *\n * ```html\n * <div class=\"slide-animation\" ng-if=\"on\" ng-animate-children>\n *   <div class=\"fade-animation\" ng-if=\"on\">\n *     <div class=\"explode-animation\" ng-if=\"on\">\n *        ...\n *     </div>\n *   </div>\n * </div>\n * ```\n *\n * When the `on` expression value changes and an animation is triggered then each of the elements within\n * will all animate without the block being applied to child elements.\n *\n * ## Are animations run when the application starts?\n * No they are not. When an application is bootstrapped Angular will disable animations from running to avoid\n * a frenzy of animations from being triggered as soon as the browser has rendered the screen. For this to work,\n * Angular will wait for two digest cycles until enabling animations. From there on, any animation-triggering\n * layout changes in the application will trigger animations as normal.\n *\n * In addition, upon bootstrap, if the routing system or any directives or load remote data (via $http) then Angular\n * will automatically extend the wait time to enable animations once **all** of the outbound HTTP requests\n * are complete.\n *\n * ## CSS-defined Animations\n * The animate service will automatically apply two CSS classes to the animated element and these two CSS classes\n * are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported\n * and can be used to play along with this naming structure.\n *\n * The following code below demonstrates how to perform animations using **CSS transitions** with Angular:\n *\n * ```html\n * <style type=\"text/css\">\n * /&#42;\n *  The animate class is apart of the element and the ng-enter class\n *  is attached to the element once the enter animation event is triggered\n * &#42;/\n * .reveal-animation.ng-enter {\n *  -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/\n *  transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/\n *\n *  /&#42; The animation preparation code &#42;/\n *  opacity: 0;\n * }\n *\n * /&#42;\n *  Keep in mind that you want to combine both CSS\n *  classes together to avoid any CSS-specificity\n *  conflicts\n * &#42;/\n * .reveal-animation.ng-enter.ng-enter-active {\n *  /&#42; The animation code itself &#42;/\n *  opacity: 1;\n * }\n * </style>\n *\n * <div class=\"view-container\">\n *   <div ng-view class=\"reveal-animation\"></div>\n * </div>\n * ```\n *\n * The following code below demonstrates how to perform animations using **CSS animations** with Angular:\n *\n * ```html\n * <style type=\"text/css\">\n * .reveal-animation.ng-enter {\n *   -webkit-animation: enter_sequence 1s linear; /&#42; Safari/Chrome &#42;/\n *   animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/\n * }\n * @-webkit-keyframes enter_sequence {\n *   from { opacity:0; }\n *   to { opacity:1; }\n * }\n * @keyframes enter_sequence {\n *   from { opacity:0; }\n *   to { opacity:1; }\n * }\n * </style>\n *\n * <div class=\"view-container\">\n *   <div ng-view class=\"reveal-animation\"></div>\n * </div>\n * ```\n *\n * Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.\n *\n * Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add\n * the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically\n * detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be\n * removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end\n * immediately resulting in a DOM element that is at its final state. This final state is when the DOM element\n * has no CSS transition/animation classes applied to it.\n *\n * ### Structural transition animations\n *\n * Structural transitions (such as enter, leave and move) will always apply a `0s none` transition\n * value to force the browser into rendering the styles defined in the setup (`.ng-enter`, `.ng-leave`\n * or `.ng-move`) class. This means that any active transition animations operating on the element\n * will be cut off to make way for the enter, leave or move animation.\n *\n * ### Class-based transition animations\n *\n * Class-based transitions refer to transition animations that are triggered when a CSS class is\n * added to or removed from the element (via `$animate.addClass`, `$animate.removeClass`,\n * `$animate.setClass`, or by directives such as `ngClass`, `ngModel` and `form`).\n * They are different when compared to structural animations since they **do not cancel existing\n * animations** nor do they **block successive transitions** from rendering on the same element.\n * This distinction allows for **multiple class-based transitions** to be performed on the same element.\n *\n * In addition to ngAnimate supporting the default (natural) functionality of class-based transition\n * animations, ngAnimate also decorates the element with starting and ending CSS classes to aid the\n * developer in further styling the element throughout the transition animation. Earlier versions\n * of ngAnimate may have caused natural CSS transitions to break and not render properly due to\n * $animate temporarily blocking transitions using `0s none` in order to allow the setup CSS class\n * (the `-add` or `-remove` class) to be applied without triggering an animation. However, as of\n * **version 1.3**, this workaround has been removed with ngAnimate and all non-ngAnimate CSS\n * class transitions are compatible with ngAnimate.\n *\n * There is, however, one special case when dealing with class-based transitions in ngAnimate.\n * When rendering class-based transitions that make use of the setup and active CSS classes\n * (e.g. `.fade-add` and `.fade-add-active` for when `.fade` is added) be sure to define\n * the transition value **on the active CSS class** and not the setup class.\n *\n * ```css\n * .fade-add {\n *   /&#42; remember to place a 0s transition here\n *      to ensure that the styles are applied instantly\n *      even if the element already has a transition style &#42;/\n *   transition:0s linear all;\n *\n *   /&#42; starting CSS styles &#42;/\n *   opacity:1;\n * }\n * .fade-add.fade-add-active {\n *   /&#42; this will be the length of the animation &#42;/\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * The setup CSS class (in this case `.fade-add`) also has a transition style property, however, it\n * has a duration of zero. This may not be required, however, incase the browser is unable to render\n * the styling present in this CSS class instantly then it could be that the browser is attempting\n * to perform an unnecessary transition.\n *\n * This workaround, however, does not apply to  standard class-based transitions that are rendered\n * when a CSS class containing a transition is applied to an element:\n *\n * ```css\n * /&#42; this works as expected &#42;/\n * .fade {\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * Please keep this in mind when coding the CSS markup that will be used within class-based transitions.\n * Also, try not to mix the two class-based animation flavors together since the CSS code may become\n * overly complex.\n *\n *\n * ### Preventing Collisions With Third Party Libraries\n *\n * Some third-party frameworks place animation duration defaults across many element or className\n * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which\n * is expecting actual animations on these elements and has to wait for their completion.\n *\n * You can prevent this unwanted behavior by using a prefix on all your animation classes:\n *\n * ```css\n * /&#42; prefixed with animate- &#42;/\n * .animate-fade-add.animate-fade-add-active {\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * You then configure `$animate` to enforce this prefix:\n *\n * ```js\n * $animateProvider.classNameFilter(/animate-/);\n * ```\n * </div>\n *\n * ### CSS Staggering Animations\n * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a\n * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be\n * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for\n * the animation. The style property expected within the stagger class can either be a **transition-delay** or an\n * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).\n *\n * ```css\n * .my-animation.ng-enter {\n *   /&#42; standard transition code &#42;/\n *   -webkit-transition: 1s linear all;\n *   transition: 1s linear all;\n *   opacity:0;\n * }\n * .my-animation.ng-enter-stagger {\n *   /&#42; this will have a 100ms delay between each successive leave animation &#42;/\n *   -webkit-transition-delay: 0.1s;\n *   transition-delay: 0.1s;\n *\n *   /&#42; in case the stagger doesn't work then these two values\n *    must be set to 0 to avoid an accidental CSS inheritance &#42;/\n *   -webkit-transition-duration: 0s;\n *   transition-duration: 0s;\n * }\n * .my-animation.ng-enter.ng-enter-active {\n *   /&#42; standard transition styles &#42;/\n *   opacity:1;\n * }\n * ```\n *\n * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations\n * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this\n * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation\n * will also be reset if more than 10ms has passed after the last animation has been fired.\n *\n * The following code will issue the **ng-leave-stagger** event on the element provided:\n *\n * ```js\n * var kids = parent.children();\n *\n * $animate.leave(kids[0]); //stagger index=0\n * $animate.leave(kids[1]); //stagger index=1\n * $animate.leave(kids[2]); //stagger index=2\n * $animate.leave(kids[3]); //stagger index=3\n * $animate.leave(kids[4]); //stagger index=4\n *\n * $timeout(function() {\n *   //stagger has reset itself\n *   $animate.leave(kids[5]); //stagger index=0\n *   $animate.leave(kids[6]); //stagger index=1\n * }, 100, false);\n * ```\n *\n * Stagger animations are currently only supported within CSS-defined animations.\n *\n * ## JavaScript-defined Animations\n * In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not\n * yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.\n *\n * ```js\n * //!annotate=\"YourApp\" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.\n * var ngModule = angular.module('YourApp', ['ngAnimate']);\n * ngModule.animation('.my-crazy-animation', function() {\n *   return {\n *     enter: function(element, done) {\n *       //run the animation here and call done when the animation is complete\n *       return function(cancelled) {\n *         //this (optional) function will be called when the animation\n *         //completes or when the animation is cancelled (the cancelled\n *         //flag will be set to true if cancelled).\n *       };\n *     },\n *     leave: function(element, done) { },\n *     move: function(element, done) { },\n *\n *     //animation that can be triggered before the class is added\n *     beforeAddClass: function(element, className, done) { },\n *\n *     //animation that can be triggered after the class is added\n *     addClass: function(element, className, done) { },\n *\n *     //animation that can be triggered before the class is removed\n *     beforeRemoveClass: function(element, className, done) { },\n *\n *     //animation that can be triggered after the class is removed\n *     removeClass: function(element, className, done) { }\n *   };\n * });\n * ```\n *\n * JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run\n * a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits\n * the element's CSS class attribute value and then run the matching animation event function (if found).\n * In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will\n * be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).\n *\n * Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned.\n * As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run,\n * and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation\n * or transition code that is defined via a stylesheet).\n *\n *\n * ### Applying Directive-specific Styles to an Animation\n * In some cases a directive or service may want to provide `$animate` with extra details that the animation will\n * include into its animation. Let's say for example we wanted to render an animation that animates an element\n * towards the mouse coordinates as to where the user clicked last. By collecting the X/Y coordinates of the click\n * (via the event parameter) we can set the `top` and `left` styles into an object and pass that into our function\n * call to `$animate.addClass`.\n *\n * ```js\n * canvas.on('click', function(e) {\n *   $animate.addClass(element, 'on', {\n *     to: {\n *       left : e.client.x + 'px',\n *       top : e.client.y + 'px'\n *     }\n *   }):\n * });\n * ```\n *\n * Now when the animation runs, and a transition or keyframe animation is picked up, then the animation itself will\n * also include and transition the styling of the `left` and `top` properties into its running animation. If we want\n * to provide some starting animation values then we can do so by placing the starting animations styles into an object\n * called `from` in the same object as the `to` animations.\n *\n * ```js\n * canvas.on('click', function(e) {\n *   $animate.addClass(element, 'on', {\n *     from: {\n *        position: 'absolute',\n *        left: '0px',\n *        top: '0px'\n *     },\n *     to: {\n *       left : e.client.x + 'px',\n *       top : e.client.y + 'px'\n *     }\n *   }):\n * });\n * ```\n *\n * Once the animation is complete or cancelled then the union of both the before and after styles are applied to the\n * element. If `ngAnimate` is not present then the styles will be applied immediately.\n *\n */\n\nangular.module('ngAnimate', ['ng'])\n\n  /**\n   * @ngdoc provider\n   * @name $animateProvider\n   * @description\n   *\n   * The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module.\n   * When an animation is triggered, the $animate service will query the $animate service to find any animations that match\n   * the provided name value.\n   *\n   * Requires the {@link ngAnimate `ngAnimate`} module to be installed.\n   *\n   * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.\n   *\n   */\n  .directive('ngAnimateChildren', function() {\n    var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';\n    return function(scope, element, attrs) {\n      var val = attrs.ngAnimateChildren;\n      if (angular.isString(val) && val.length === 0) { //empty attribute\n        element.data(NG_ANIMATE_CHILDREN, true);\n      } else {\n        scope.$watch(val, function(value) {\n          element.data(NG_ANIMATE_CHILDREN, !!value);\n        });\n      }\n    };\n  })\n\n  //this private service is only used within CSS-enabled animations\n  //IE8 + IE9 do not support rAF natively, but that is fine since they\n  //also don't support transitions and keyframes which means that the code\n  //below will never be used by the two browsers.\n  .factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) {\n    var bod = $document[0].body;\n    return function(fn) {\n      //the returned function acts as the cancellation function\n      return $$rAF(function() {\n        //the line below will force the browser to perform a repaint\n        //so that all the animated elements within the animation frame\n        //will be properly updated and drawn on screen. This is\n        //required to perform multi-class CSS based animations with\n        //Firefox. DO NOT REMOVE THIS LINE.\n        var a = bod.offsetWidth + 1;\n        fn();\n      });\n    };\n  }])\n\n  .config(['$provide', '$animateProvider', function($provide, $animateProvider) {\n    var noop = angular.noop;\n    var forEach = angular.forEach;\n    var selectors = $animateProvider.$$selectors;\n    var isArray = angular.isArray;\n    var isString = angular.isString;\n    var isObject = angular.isObject;\n\n    var ELEMENT_NODE = 1;\n    var NG_ANIMATE_STATE = '$$ngAnimateState';\n    var NG_ANIMATE_CHILDREN = '$$ngAnimateChildren';\n    var NG_ANIMATE_CLASS_NAME = 'ng-animate';\n    var rootAnimateState = {running: true};\n\n    function extractElementNode(element) {\n      for (var i = 0; i < element.length; i++) {\n        var elm = element[i];\n        if (elm.nodeType == ELEMENT_NODE) {\n          return elm;\n        }\n      }\n    }\n\n    function prepareElement(element) {\n      return element && angular.element(element);\n    }\n\n    function stripCommentsFromElement(element) {\n      return angular.element(extractElementNode(element));\n    }\n\n    function isMatchingElement(elm1, elm2) {\n      return extractElementNode(elm1) == extractElementNode(elm2);\n    }\n    var $$jqLite;\n    $provide.decorator('$animate',\n        ['$delegate', '$$q', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document', '$templateRequest', '$$jqLite',\n function($delegate,   $$q,   $injector,   $sniffer,   $rootElement,   $$asyncCallback,   $rootScope,   $document,   $templateRequest,   $$$jqLite) {\n\n      $$jqLite = $$$jqLite;\n      $rootElement.data(NG_ANIMATE_STATE, rootAnimateState);\n\n      // Wait until all directive and route-related templates are downloaded and\n      // compiled. The $templateRequest.totalPendingRequests variable keeps track of\n      // all of the remote templates being currently downloaded. If there are no\n      // templates currently downloading then the watcher will still fire anyway.\n      var deregisterWatch = $rootScope.$watch(\n        function() { return $templateRequest.totalPendingRequests; },\n        function(val, oldVal) {\n          if (val !== 0) return;\n          deregisterWatch();\n\n          // Now that all templates have been downloaded, $animate will wait until\n          // the post digest queue is empty before enabling animations. By having two\n          // calls to $postDigest calls we can ensure that the flag is enabled at the\n          // very end of the post digest queue. Since all of the animations in $animate\n          // use $postDigest, it's important that the code below executes at the end.\n          // This basically means that the page is fully downloaded and compiled before\n          // any animations are triggered.\n          $rootScope.$$postDigest(function() {\n            $rootScope.$$postDigest(function() {\n              rootAnimateState.running = false;\n            });\n          });\n        }\n      );\n\n      var globalAnimationCounter = 0;\n      var classNameFilter = $animateProvider.classNameFilter();\n      var isAnimatableClassName = !classNameFilter\n              ? function() { return true; }\n              : function(className) {\n                return classNameFilter.test(className);\n              };\n\n      function classBasedAnimationsBlocked(element, setter) {\n        var data = element.data(NG_ANIMATE_STATE) || {};\n        if (setter) {\n          data.running = true;\n          data.structural = true;\n          element.data(NG_ANIMATE_STATE, data);\n        }\n        return data.disabled || (data.running && data.structural);\n      }\n\n      function runAnimationPostDigest(fn) {\n        var cancelFn, defer = $$q.defer();\n        defer.promise.$$cancelFn = function() {\n          cancelFn && cancelFn();\n        };\n        $rootScope.$$postDigest(function() {\n          cancelFn = fn(function() {\n            defer.resolve();\n          });\n        });\n        return defer.promise;\n      }\n\n      function parseAnimateOptions(options) {\n        // some plugin code may still be passing in the callback\n        // function as the last param for the $animate methods so\n        // it's best to only allow string or array values for now\n        if (isObject(options)) {\n          if (options.tempClasses && isString(options.tempClasses)) {\n            options.tempClasses = options.tempClasses.split(/\\s+/);\n          }\n          return options;\n        }\n      }\n\n      function resolveElementClasses(element, cache, runningAnimations) {\n        runningAnimations = runningAnimations || {};\n\n        var lookup = {};\n        forEach(runningAnimations, function(data, selector) {\n          forEach(selector.split(' '), function(s) {\n            lookup[s]=data;\n          });\n        });\n\n        var hasClasses = Object.create(null);\n        forEach((element.attr('class') || '').split(/\\s+/), function(className) {\n          hasClasses[className] = true;\n        });\n\n        var toAdd = [], toRemove = [];\n        forEach((cache && cache.classes) || [], function(status, className) {\n          var hasClass = hasClasses[className];\n          var matchingAnimation = lookup[className] || {};\n\n          // When addClass and removeClass is called then $animate will check to\n          // see if addClass and removeClass cancel each other out. When there are\n          // more calls to removeClass than addClass then the count falls below 0\n          // and then the removeClass animation will be allowed. Otherwise if the\n          // count is above 0 then that means an addClass animation will commence.\n          // Once an animation is allowed then the code will also check to see if\n          // there exists any on-going animation that is already adding or remvoing\n          // the matching CSS class.\n          if (status === false) {\n            //does it have the class or will it have the class\n            if (hasClass || matchingAnimation.event == 'addClass') {\n              toRemove.push(className);\n            }\n          } else if (status === true) {\n            //is the class missing or will it be removed?\n            if (!hasClass || matchingAnimation.event == 'removeClass') {\n              toAdd.push(className);\n            }\n          }\n        });\n\n        return (toAdd.length + toRemove.length) > 0 && [toAdd.join(' '), toRemove.join(' ')];\n      }\n\n      function lookup(name) {\n        if (name) {\n          var matches = [],\n              flagMap = {},\n              classes = name.substr(1).split('.');\n\n          //the empty string value is the default animation\n          //operation which performs CSS transition and keyframe\n          //animations sniffing. This is always included for each\n          //element animation procedure if the browser supports\n          //transitions and/or keyframe animations. The default\n          //animation is added to the top of the list to prevent\n          //any previous animations from affecting the element styling\n          //prior to the element being animated.\n          if ($sniffer.transitions || $sniffer.animations) {\n            matches.push($injector.get(selectors['']));\n          }\n\n          for (var i=0; i < classes.length; i++) {\n            var klass = classes[i],\n                selectorFactoryName = selectors[klass];\n            if (selectorFactoryName && !flagMap[klass]) {\n              matches.push($injector.get(selectorFactoryName));\n              flagMap[klass] = true;\n            }\n          }\n          return matches;\n        }\n      }\n\n      function animationRunner(element, animationEvent, className, options) {\n        //transcluded directives may sometimes fire an animation using only comment nodes\n        //best to catch this early on to prevent any animation operations from occurring\n        var node = element[0];\n        if (!node) {\n          return;\n        }\n\n        if (options) {\n          options.to = options.to || {};\n          options.from = options.from || {};\n        }\n\n        var classNameAdd;\n        var classNameRemove;\n        if (isArray(className)) {\n          classNameAdd = className[0];\n          classNameRemove = className[1];\n          if (!classNameAdd) {\n            className = classNameRemove;\n            animationEvent = 'removeClass';\n          } else if (!classNameRemove) {\n            className = classNameAdd;\n            animationEvent = 'addClass';\n          } else {\n            className = classNameAdd + ' ' + classNameRemove;\n          }\n        }\n\n        var isSetClassOperation = animationEvent == 'setClass';\n        var isClassBased = isSetClassOperation\n                           || animationEvent == 'addClass'\n                           || animationEvent == 'removeClass'\n                           || animationEvent == 'animate';\n\n        var currentClassName = element.attr('class');\n        var classes = currentClassName + ' ' + className;\n        if (!isAnimatableClassName(classes)) {\n          return;\n        }\n\n        var beforeComplete = noop,\n            beforeCancel = [],\n            before = [],\n            afterComplete = noop,\n            afterCancel = [],\n            after = [];\n\n        var animationLookup = (' ' + classes).replace(/\\s+/g,'.');\n        forEach(lookup(animationLookup), function(animationFactory) {\n          var created = registerAnimation(animationFactory, animationEvent);\n          if (!created && isSetClassOperation) {\n            registerAnimation(animationFactory, 'addClass');\n            registerAnimation(animationFactory, 'removeClass');\n          }\n        });\n\n        function registerAnimation(animationFactory, event) {\n          var afterFn = animationFactory[event];\n          var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)];\n          if (afterFn || beforeFn) {\n            if (event == 'leave') {\n              beforeFn = afterFn;\n              //when set as null then animation knows to skip this phase\n              afterFn = null;\n            }\n            after.push({\n              event: event, fn: afterFn\n            });\n            before.push({\n              event: event, fn: beforeFn\n            });\n            return true;\n          }\n        }\n\n        function run(fns, cancellations, allCompleteFn) {\n          var animations = [];\n          forEach(fns, function(animation) {\n            animation.fn && animations.push(animation);\n          });\n\n          var count = 0;\n          function afterAnimationComplete(index) {\n            if (cancellations) {\n              (cancellations[index] || noop)();\n              if (++count < animations.length) return;\n              cancellations = null;\n            }\n            allCompleteFn();\n          }\n\n          //The code below adds directly to the array in order to work with\n          //both sync and async animations. Sync animations are when the done()\n          //operation is called right away. DO NOT REFACTOR!\n          forEach(animations, function(animation, index) {\n            var progress = function() {\n              afterAnimationComplete(index);\n            };\n            switch (animation.event) {\n              case 'setClass':\n                cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress, options));\n                break;\n              case 'animate':\n                cancellations.push(animation.fn(element, className, options.from, options.to, progress));\n                break;\n              case 'addClass':\n                cancellations.push(animation.fn(element, classNameAdd || className,     progress, options));\n                break;\n              case 'removeClass':\n                cancellations.push(animation.fn(element, classNameRemove || className,  progress, options));\n                break;\n              default:\n                cancellations.push(animation.fn(element, progress, options));\n                break;\n            }\n          });\n\n          if (cancellations && cancellations.length === 0) {\n            allCompleteFn();\n          }\n        }\n\n        return {\n          node: node,\n          event: animationEvent,\n          className: className,\n          isClassBased: isClassBased,\n          isSetClassOperation: isSetClassOperation,\n          applyStyles: function() {\n            if (options) {\n              element.css(angular.extend(options.from || {}, options.to || {}));\n            }\n          },\n          before: function(allCompleteFn) {\n            beforeComplete = allCompleteFn;\n            run(before, beforeCancel, function() {\n              beforeComplete = noop;\n              allCompleteFn();\n            });\n          },\n          after: function(allCompleteFn) {\n            afterComplete = allCompleteFn;\n            run(after, afterCancel, function() {\n              afterComplete = noop;\n              allCompleteFn();\n            });\n          },\n          cancel: function() {\n            if (beforeCancel) {\n              forEach(beforeCancel, function(cancelFn) {\n                (cancelFn || noop)(true);\n              });\n              beforeComplete(true);\n            }\n            if (afterCancel) {\n              forEach(afterCancel, function(cancelFn) {\n                (cancelFn || noop)(true);\n              });\n              afterComplete(true);\n            }\n          }\n        };\n      }\n\n      /**\n       * @ngdoc service\n       * @name $animate\n       * @kind object\n       *\n       * @description\n       * The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations.\n       * When any of these operations are run, the $animate service\n       * will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object)\n       * as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.\n       *\n       * The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives\n       * will work out of the box without any extra configuration.\n       *\n       * Requires the {@link ngAnimate `ngAnimate`} module to be installed.\n       *\n       * Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.\n       * ## Callback Promises\n       * With AngularJS 1.3, each of the animation methods, on the `$animate` service, return a promise when called. The\n       * promise itself is then resolved once the animation has completed itself, has been cancelled or has been\n       * skipped due to animations being disabled. (Note that even if the animation is cancelled it will still\n       * call the resolve function of the animation.)\n       *\n       * ```js\n       * $animate.enter(element, container).then(function() {\n       *   //...this is called once the animation is complete...\n       * });\n       * ```\n       *\n       * Also note that, due to the nature of the callback promise, if any Angular-specific code (like changing the scope,\n       * location of the page, etc...) is executed within the callback promise then be sure to wrap the code using\n       * `$scope.$apply(...)`;\n       *\n       * ```js\n       * $animate.leave(element).then(function() {\n       *   $scope.$apply(function() {\n       *     $location.path('/new-page');\n       *   });\n       * });\n       * ```\n       *\n       * An animation can also be cancelled by calling the `$animate.cancel(promise)` method with the provided\n       * promise that was returned when the animation was started.\n       *\n       * ```js\n       * var promise = $animate.addClass(element, 'super-long-animation');\n       * promise.then(function() {\n       *   //this will still be called even if cancelled\n       * });\n       *\n       * element.on('click', function() {\n       *   //tooo lazy to wait for the animation to end\n       *   $animate.cancel(promise);\n       * });\n       * ```\n       *\n       * (Keep in mind that the promise cancellation is unique to `$animate` since promises in\n       * general cannot be cancelled.)\n       *\n       */\n      return {\n        /**\n         * @ngdoc method\n         * @name $animate#animate\n         * @kind function\n         *\n         * @description\n         * Performs an inline animation on the element which applies the provided `to` and `from` CSS styles to the element.\n         * If any detected CSS transition, keyframe or JavaScript matches the provided `className` value then the animation\n         * will take on the provided styles. For example, if a transition animation is set for the given className then the\n         * provided `from` and `to` styles will be applied alongside the given transition. If a JavaScript animation is\n         * detected then the provided styles will be given in as function paramters.\n         *\n         * ```js\n         * ngModule.animation('.my-inline-animation', function() {\n         *   return {\n         *     animate : function(element, className, from, to, done) {\n         *       //styles\n         *     }\n         *   }\n         * });\n         * ```\n         *\n         * Below is a breakdown of each step that occurs during the `animate` animation:\n         *\n         * | Animation Step                                                                                                        | What the element class attribute looks like                  |\n         * |-----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------|\n         * | 1. `$animate.animate(...)` is called                                                                                  | `class=\"my-animation\"`                                       |\n         * | 2. `$animate` waits for the next digest to start the animation                                                        | `class=\"my-animation ng-animate\"`                            |\n         * | 3. `$animate` runs the JavaScript-defined animations detected on the element                                          | `class=\"my-animation ng-animate\"`                            |\n         * | 4. the `className` class value is added to the element                                                                | `class=\"my-animation ng-animate className\"`                  |\n         * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay                         | `class=\"my-animation ng-animate className\"`                  |\n         * | 6. `$animate` blocks all CSS transitions on the element to ensure the `.className` class styling is applied right away| `class=\"my-animation ng-animate className\"`                  |\n         * | 7. `$animate` applies the provided collection of `from` CSS styles to the element                                     | `class=\"my-animation ng-animate className\"`                  |\n         * | 8. `$animate` waits for a single animation frame (this performs a reflow)                                             | `class=\"my-animation ng-animate className\"`                  |\n         * | 9. `$animate` removes the CSS transition block placed on the element                                                  | `class=\"my-animation ng-animate className\"`                  |\n         * | 10. the `className-active` class is added (this triggers the CSS transition/animation)                                | `class=\"my-animation ng-animate className className-active\"` |\n         * | 11. `$animate` applies the collection of `to` CSS styles to the element which are then handled by the transition      | `class=\"my-animation ng-animate className className-active\"` |\n         * | 12. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate className className-active\"` |\n         * | 13. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                       |\n         * | 14. The returned promise is resolved.                                                                                 | `class=\"my-animation\"`                                       |\n         *\n         * @param {DOMElement} element the element that will be the focus of the enter animation\n         * @param {object} from a collection of CSS styles that will be applied to the element at the start of the animation\n         * @param {object} to a collection of CSS styles that the element will animate towards\n         * @param {string=} className an optional CSS class that will be added to the element for the duration of the animation (the default class is `ng-inline-animate`)\n         * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        animate: function(element, from, to, className, options) {\n          className = className || 'ng-inline-animate';\n          options = parseAnimateOptions(options) || {};\n          options.from = to ? from : null;\n          options.to   = to ? to : from;\n\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('animate', className, stripCommentsFromElement(element), null, null, noop, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#enter\n         * @kind function\n         *\n         * @description\n         * Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once\n         * the animation is started, the following CSS classes will be present on the element for the duration of the animation:\n         *\n         * Below is a breakdown of each step that occurs during enter animation:\n         *\n         * | Animation Step                                                                                                        | What the element class attribute looks like                |\n         * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|\n         * | 1. `$animate.enter(...)` is called                                                                                    | `class=\"my-animation\"`                                     |\n         * | 2. element is inserted into the `parentElement` element or beside the `afterElement` element                          | `class=\"my-animation\"`                                     |\n         * | 3. `$animate` waits for the next digest to start the animation                                                        | `class=\"my-animation ng-animate\"`                          |\n         * | 4. `$animate` runs the JavaScript-defined animations detected on the element                                          | `class=\"my-animation ng-animate\"`                          |\n         * | 5. the `.ng-enter` class is added to the element                                                                      | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                         | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 7. `$animate` blocks all CSS transitions on the element to ensure the `.ng-enter` class styling is applied right away | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 8. `$animate` waits for a single animation frame (this performs a reflow)                                             | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 9. `$animate` removes the CSS transition block placed on the element                                                  | `class=\"my-animation ng-animate ng-enter\"`                 |\n         * | 10. the `.ng-enter-active` class is added (this triggers the CSS transition/animation)                                | `class=\"my-animation ng-animate ng-enter ng-enter-active\"` |\n         * | 11. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate ng-enter ng-enter-active\"` |\n         * | 12. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                     |\n         * | 13. The returned promise is resolved.                                                                                 | `class=\"my-animation\"`                                     |\n         *\n         * @param {DOMElement} element the element that will be the focus of the enter animation\n         * @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation\n         * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation\n         * @param {object=} options an optional collection of options that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        enter: function(element, parentElement, afterElement, options) {\n          options = parseAnimateOptions(options);\n          element = angular.element(element);\n          parentElement = prepareElement(parentElement);\n          afterElement = prepareElement(afterElement);\n\n          classBasedAnimationsBlocked(element, true);\n          $delegate.enter(element, parentElement, afterElement);\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('enter', 'ng-enter', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#leave\n         * @kind function\n         *\n         * @description\n         * Runs the leave animation operation and, upon completion, removes the element from the DOM. Once\n         * the animation is started, the following CSS classes will be added for the duration of the animation:\n         *\n         * Below is a breakdown of each step that occurs during leave animation:\n         *\n         * | Animation Step                                                                                                        | What the element class attribute looks like                |\n         * |-----------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------|\n         * | 1. `$animate.leave(...)` is called                                                                                    | `class=\"my-animation\"`                                     |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                                          | `class=\"my-animation ng-animate\"`                          |\n         * | 3. `$animate` waits for the next digest to start the animation                                                        | `class=\"my-animation ng-animate\"`                          |\n         * | 4. the `.ng-leave` class is added to the element                                                                      | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 5. `$animate` scans the element styles to get the CSS transition/animation duration and delay                         | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 6. `$animate` blocks all CSS transitions on the element to ensure the `.ng-leave` class styling is applied right away | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 7. `$animate` waits for a single animation frame (this performs a reflow)                                             | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 8. `$animate` removes the CSS transition block placed on the element                                                  | `class=\"my-animation ng-animate ng-leave\"`                 |\n         * | 9. the `.ng-leave-active` class is added (this triggers the CSS transition/animation)                                 | `class=\"my-animation ng-animate ng-leave ng-leave-active\"` |\n         * | 10. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate ng-leave ng-leave-active\"` |\n         * | 11. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                     |\n         * | 12. The element is removed from the DOM                                                                               | ...                                                        |\n         * | 13. The returned promise is resolved.                                                                                 | ...                                                        |\n         *\n         * @param {DOMElement} element the element that will be the focus of the leave animation\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        leave: function(element, options) {\n          options = parseAnimateOptions(options);\n          element = angular.element(element);\n\n          cancelChildAnimations(element);\n          classBasedAnimationsBlocked(element, true);\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() {\n              $delegate.leave(element);\n            }, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#move\n         * @kind function\n         *\n         * @description\n         * Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or\n         * add the element directly after the afterElement element if present. Then the move animation will be run. Once\n         * the animation is started, the following CSS classes will be added for the duration of the animation:\n         *\n         * Below is a breakdown of each step that occurs during move animation:\n         *\n         * | Animation Step                                                                                                       | What the element class attribute looks like              |\n         * |----------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|\n         * | 1. `$animate.move(...)` is called                                                                                    | `class=\"my-animation\"`                                   |\n         * | 2. element is moved into the parentElement element or beside the afterElement element                                | `class=\"my-animation\"`                                   |\n         * | 3. `$animate` waits for the next digest to start the animation                                                       | `class=\"my-animation ng-animate\"`                        |\n         * | 4. `$animate` runs the JavaScript-defined animations detected on the element                                         | `class=\"my-animation ng-animate\"`                        |\n         * | 5. the `.ng-move` class is added to the element                                                                      | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                        | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 7. `$animate` blocks all CSS transitions on the element to ensure the `.ng-move` class styling is applied right away | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 8. `$animate` waits for a single animation frame (this performs a reflow)                                            | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 9. `$animate` removes the CSS transition block placed on the element                                                 | `class=\"my-animation ng-animate ng-move\"`                |\n         * | 10. the `.ng-move-active` class is added (this triggers the CSS transition/animation)                                | `class=\"my-animation ng-animate ng-move ng-move-active\"` |\n         * | 11. `$animate` waits for the animation to complete (via events and timeout)                                          | `class=\"my-animation ng-animate ng-move ng-move-active\"` |\n         * | 12. The animation ends and all generated CSS classes are removed from the element                                    | `class=\"my-animation\"`                                   |\n         * | 13. The returned promise is resolved.                                                                                | `class=\"my-animation\"`                                   |\n         *\n         * @param {DOMElement} element the element that will be the focus of the move animation\n         * @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation\n         * @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        move: function(element, parentElement, afterElement, options) {\n          options = parseAnimateOptions(options);\n          element = angular.element(element);\n          parentElement = prepareElement(parentElement);\n          afterElement = prepareElement(afterElement);\n\n          cancelChildAnimations(element);\n          classBasedAnimationsBlocked(element, true);\n          $delegate.move(element, parentElement, afterElement);\n          return runAnimationPostDigest(function(done) {\n            return performAnimation('move', 'ng-move', stripCommentsFromElement(element), parentElement, afterElement, noop, options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#addClass\n         *\n         * @description\n         * Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class.\n         * Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide\n         * the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions\n         * or keyframes are defined on the -add-active or base CSS class).\n         *\n         * Below is a breakdown of each step that occurs during addClass animation:\n         *\n         * | Animation Step                                                                                         | What the element class attribute looks like                        |\n         * |--------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|\n         * | 1. `$animate.addClass(element, 'super')` is called                                                     | `class=\"my-animation\"`                                             |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                           | `class=\"my-animation ng-animate\"`                                  |\n         * | 3. the `.super-add` class is added to the element                                                      | `class=\"my-animation ng-animate super-add\"`                        |\n         * | 4. `$animate` waits for a single animation frame (this performs a reflow)                              | `class=\"my-animation ng-animate super-add\"`                        |\n         * | 5. the `.super` and `.super-add-active` classes are added (this triggers the CSS transition/animation) | `class=\"my-animation ng-animate super super-add super-add-active\"` |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay          | `class=\"my-animation ng-animate super super-add super-add-active\"` |\n         * | 7. `$animate` waits for the animation to complete (via events and timeout)                             | `class=\"my-animation ng-animate super super-add super-add-active\"` |\n         * | 8. The animation ends and all generated CSS classes are removed from the element                       | `class=\"my-animation super\"`                                       |\n         * | 9. The super class is kept on the element                                                              | `class=\"my-animation super\"`                                       |\n         * | 10. The returned promise is resolved.                                                                  | `class=\"my-animation super\"`                                       |\n         *\n         * @param {DOMElement} element the element that will be animated\n         * @param {string} className the CSS class that will be added to the element and then animated\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        addClass: function(element, className, options) {\n          return this.setClass(element, className, [], options);\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#removeClass\n         *\n         * @description\n         * Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value\n         * from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in\n         * order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if\n         * no CSS transitions or keyframes are defined on the -remove or base CSS classes).\n         *\n         * Below is a breakdown of each step that occurs during removeClass animation:\n         *\n         * | Animation Step                                                                                                       | What the element class attribute looks like                        |\n         * |----------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------|\n         * | 1. `$animate.removeClass(element, 'super')` is called                                                                | `class=\"my-animation super\"`                                       |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                                         | `class=\"my-animation super ng-animate\"`                            |\n         * | 3. the `.super-remove` class is added to the element                                                                 | `class=\"my-animation super ng-animate super-remove\"`               |\n         * | 4. `$animate` waits for a single animation frame (this performs a reflow)                                            | `class=\"my-animation super ng-animate super-remove\"`               |\n         * | 5. the `.super-remove-active` classes are added and `.super` is removed (this triggers the CSS transition/animation) | `class=\"my-animation ng-animate super-remove super-remove-active\"` |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                        | `class=\"my-animation ng-animate super-remove super-remove-active\"` |\n         * | 7. `$animate` waits for the animation to complete (via events and timeout)                                           | `class=\"my-animation ng-animate super-remove super-remove-active\"` |\n         * | 8. The animation ends and all generated CSS classes are removed from the element                                     | `class=\"my-animation\"`                                             |\n         * | 9. The returned promise is resolved.                                                                                 | `class=\"my-animation\"`                                             |\n         *\n         *\n         * @param {DOMElement} element the element that will be animated\n         * @param {string} className the CSS class that will be animated and then removed from the element\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n        */\n        removeClass: function(element, className, options) {\n          return this.setClass(element, [], className, options);\n        },\n\n        /**\n         *\n         * @ngdoc method\n         * @name $animate#setClass\n         *\n         * @description Adds and/or removes the given CSS classes to and from the element.\n         * Once complete, the `done()` callback will be fired (if provided).\n         *\n         * | Animation Step                                                                                                                               | What the element class attribute looks like                                            |\n         * |----------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|\n         * | 1. `$animate.setClass(element, 'on', 'off')` is called                                                                                       | `class=\"my-animation off\"`                                                             |\n         * | 2. `$animate` runs the JavaScript-defined animations detected on the element                                                                 | `class=\"my-animation ng-animate off\"`                                                  |\n         * | 3. the `.on-add` and `.off-remove` classes are added to the element                                                                          | `class=\"my-animation ng-animate on-add off-remove off\"`                                |\n         * | 4. `$animate` waits for a single animation frame (this performs a reflow)                                                                    | `class=\"my-animation ng-animate on-add off-remove off\"`                                |\n         * | 5. the `.on`, `.on-add-active` and `.off-remove-active` classes are added and `.off` is removed (this triggers the CSS transition/animation) | `class=\"my-animation ng-animate on on-add on-add-active off-remove off-remove-active\"` |\n         * | 6. `$animate` scans the element styles to get the CSS transition/animation duration and delay                                                | `class=\"my-animation ng-animate on on-add on-add-active off-remove off-remove-active\"` |\n         * | 7. `$animate` waits for the animation to complete (via events and timeout)                                                                   | `class=\"my-animation ng-animate on on-add on-add-active off-remove off-remove-active\"` |\n         * | 8. The animation ends and all generated CSS classes are removed from the element                                                             | `class=\"my-animation on\"`                                                              |\n         * | 9. The returned promise is resolved.                                                                                                         | `class=\"my-animation on\"`                                                              |\n         *\n         * @param {DOMElement} element the element which will have its CSS classes changed\n         *   removed from it\n         * @param {string} add the CSS classes which will be added to the element\n         * @param {string} remove the CSS class which will be removed from the element\n         *   CSS classes have been set on the element\n         * @param {object=} options an optional collection of styles that will be picked up by the CSS transition/animation\n         * @return {Promise} the animation callback promise\n         */\n        setClass: function(element, add, remove, options) {\n          options = parseAnimateOptions(options);\n\n          var STORAGE_KEY = '$$animateClasses';\n          element = angular.element(element);\n          element = stripCommentsFromElement(element);\n\n          if (classBasedAnimationsBlocked(element)) {\n            return $delegate.$$setClassImmediately(element, add, remove, options);\n          }\n\n          // we're using a combined array for both the add and remove\n          // operations since the ORDER OF addClass and removeClass matters\n          var classes, cache = element.data(STORAGE_KEY);\n          var hasCache = !!cache;\n          if (!cache) {\n            cache = {};\n            cache.classes = {};\n          }\n          classes = cache.classes;\n\n          add = isArray(add) ? add : add.split(' ');\n          forEach(add, function(c) {\n            if (c && c.length) {\n              classes[c] = true;\n            }\n          });\n\n          remove = isArray(remove) ? remove : remove.split(' ');\n          forEach(remove, function(c) {\n            if (c && c.length) {\n              classes[c] = false;\n            }\n          });\n\n          if (hasCache) {\n            if (options && cache.options) {\n              cache.options = angular.extend(cache.options || {}, options);\n            }\n\n            //the digest cycle will combine all the animations into one function\n            return cache.promise;\n          } else {\n            element.data(STORAGE_KEY, cache = {\n              classes: classes,\n              options: options\n            });\n          }\n\n          return cache.promise = runAnimationPostDigest(function(done) {\n            var parentElement = element.parent();\n            var elementNode = extractElementNode(element);\n            var parentNode = elementNode.parentNode;\n            // TODO(matsko): move this code into the animationsDisabled() function once #8092 is fixed\n            if (!parentNode || parentNode['$$NG_REMOVED'] || elementNode['$$NG_REMOVED']) {\n              done();\n              return;\n            }\n\n            var cache = element.data(STORAGE_KEY);\n            element.removeData(STORAGE_KEY);\n\n            var state = element.data(NG_ANIMATE_STATE) || {};\n            var classes = resolveElementClasses(element, cache, state.active);\n            return !classes\n              ? done()\n              : performAnimation('setClass', classes, element, parentElement, null, function() {\n                  if (classes[0]) $delegate.$$addClassImmediately(element, classes[0]);\n                  if (classes[1]) $delegate.$$removeClassImmediately(element, classes[1]);\n                }, cache.options, done);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#cancel\n         * @kind function\n         *\n         * @param {Promise} animationPromise The animation promise that is returned when an animation is started.\n         *\n         * @description\n         * Cancels the provided animation.\n        */\n        cancel: function(promise) {\n          promise.$$cancelFn();\n        },\n\n        /**\n         * @ngdoc method\n         * @name $animate#enabled\n         * @kind function\n         *\n         * @param {boolean=} value If provided then set the animation on or off.\n         * @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation\n         * @return {boolean} Current animation state.\n         *\n         * @description\n         * Globally enables/disables animations.\n         *\n        */\n        enabled: function(value, element) {\n          switch (arguments.length) {\n            case 2:\n              if (value) {\n                cleanup(element);\n              } else {\n                var data = element.data(NG_ANIMATE_STATE) || {};\n                data.disabled = true;\n                element.data(NG_ANIMATE_STATE, data);\n              }\n            break;\n\n            case 1:\n              rootAnimateState.disabled = !value;\n            break;\n\n            default:\n              value = !rootAnimateState.disabled;\n            break;\n          }\n          return !!value;\n         }\n      };\n\n      /*\n        all animations call this shared animation triggering function internally.\n        The animationEvent variable refers to the JavaScript animation event that will be triggered\n        and the className value is the name of the animation that will be applied within the\n        CSS code. Element, `parentElement` and `afterElement` are provided DOM elements for the animation\n        and the onComplete callback will be fired once the animation is fully complete.\n      */\n      function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, options, doneCallback) {\n        var noopCancel = noop;\n        var runner = animationRunner(element, animationEvent, className, options);\n        if (!runner) {\n          fireDOMOperation();\n          fireBeforeCallbackAsync();\n          fireAfterCallbackAsync();\n          closeAnimation();\n          return noopCancel;\n        }\n\n        animationEvent = runner.event;\n        className = runner.className;\n        var elementEvents = angular.element._data(runner.node);\n        elementEvents = elementEvents && elementEvents.events;\n\n        if (!parentElement) {\n          parentElement = afterElement ? afterElement.parent() : element.parent();\n        }\n\n        //skip the animation if animations are disabled, a parent is already being animated,\n        //the element is not currently attached to the document body or then completely close\n        //the animation if any matching animations are not found at all.\n        //NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found.\n        if (animationsDisabled(element, parentElement)) {\n          fireDOMOperation();\n          fireBeforeCallbackAsync();\n          fireAfterCallbackAsync();\n          closeAnimation();\n          return noopCancel;\n        }\n\n        var ngAnimateState  = element.data(NG_ANIMATE_STATE) || {};\n        var runningAnimations     = ngAnimateState.active || {};\n        var totalActiveAnimations = ngAnimateState.totalActive || 0;\n        var lastAnimation         = ngAnimateState.last;\n        var skipAnimation = false;\n\n        if (totalActiveAnimations > 0) {\n          var animationsToCancel = [];\n          if (!runner.isClassBased) {\n            if (animationEvent == 'leave' && runningAnimations['ng-leave']) {\n              skipAnimation = true;\n            } else {\n              //cancel all animations when a structural animation takes place\n              for (var klass in runningAnimations) {\n                animationsToCancel.push(runningAnimations[klass]);\n              }\n              ngAnimateState = {};\n              cleanup(element, true);\n            }\n          } else if (lastAnimation.event == 'setClass') {\n            animationsToCancel.push(lastAnimation);\n            cleanup(element, className);\n          } else if (runningAnimations[className]) {\n            var current = runningAnimations[className];\n            if (current.event == animationEvent) {\n              skipAnimation = true;\n            } else {\n              animationsToCancel.push(current);\n              cleanup(element, className);\n            }\n          }\n\n          if (animationsToCancel.length > 0) {\n            forEach(animationsToCancel, function(operation) {\n              operation.cancel();\n            });\n          }\n        }\n\n        if (runner.isClassBased\n            && !runner.isSetClassOperation\n            && animationEvent != 'animate'\n            && !skipAnimation) {\n          skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR\n        }\n\n        if (skipAnimation) {\n          fireDOMOperation();\n          fireBeforeCallbackAsync();\n          fireAfterCallbackAsync();\n          fireDoneCallbackAsync();\n          return noopCancel;\n        }\n\n        runningAnimations     = ngAnimateState.active || {};\n        totalActiveAnimations = ngAnimateState.totalActive || 0;\n\n        if (animationEvent == 'leave') {\n          //there's no need to ever remove the listener since the element\n          //will be removed (destroyed) after the leave animation ends or\n          //is cancelled midway\n          element.one('$destroy', function(e) {\n            var element = angular.element(this);\n            var state = element.data(NG_ANIMATE_STATE);\n            if (state) {\n              var activeLeaveAnimation = state.active['ng-leave'];\n              if (activeLeaveAnimation) {\n                activeLeaveAnimation.cancel();\n                cleanup(element, 'ng-leave');\n              }\n            }\n          });\n        }\n\n        //the ng-animate class does nothing, but it's here to allow for\n        //parent animations to find and cancel child animations when needed\n        $$jqLite.addClass(element, NG_ANIMATE_CLASS_NAME);\n        if (options && options.tempClasses) {\n          forEach(options.tempClasses, function(className) {\n            $$jqLite.addClass(element, className);\n          });\n        }\n\n        var localAnimationCount = globalAnimationCounter++;\n        totalActiveAnimations++;\n        runningAnimations[className] = runner;\n\n        element.data(NG_ANIMATE_STATE, {\n          last: runner,\n          active: runningAnimations,\n          index: localAnimationCount,\n          totalActive: totalActiveAnimations\n        });\n\n        //first we run the before animations and when all of those are complete\n        //then we perform the DOM operation and run the next set of animations\n        fireBeforeCallbackAsync();\n        runner.before(function(cancelled) {\n          var data = element.data(NG_ANIMATE_STATE);\n          cancelled = cancelled ||\n                        !data || !data.active[className] ||\n                        (runner.isClassBased && data.active[className].event != animationEvent);\n\n          fireDOMOperation();\n          if (cancelled === true) {\n            closeAnimation();\n          } else {\n            fireAfterCallbackAsync();\n            runner.after(closeAnimation);\n          }\n        });\n\n        return runner.cancel;\n\n        function fireDOMCallback(animationPhase) {\n          var eventName = '$animate:' + animationPhase;\n          if (elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) {\n            $$asyncCallback(function() {\n              element.triggerHandler(eventName, {\n                event: animationEvent,\n                className: className\n              });\n            });\n          }\n        }\n\n        function fireBeforeCallbackAsync() {\n          fireDOMCallback('before');\n        }\n\n        function fireAfterCallbackAsync() {\n          fireDOMCallback('after');\n        }\n\n        function fireDoneCallbackAsync() {\n          fireDOMCallback('close');\n          doneCallback();\n        }\n\n        //it is less complicated to use a flag than managing and canceling\n        //timeouts containing multiple callbacks.\n        function fireDOMOperation() {\n          if (!fireDOMOperation.hasBeenRun) {\n            fireDOMOperation.hasBeenRun = true;\n            domOperation();\n          }\n        }\n\n        function closeAnimation() {\n          if (!closeAnimation.hasBeenRun) {\n            if (runner) { //the runner doesn't exist if it fails to instantiate\n              runner.applyStyles();\n            }\n\n            closeAnimation.hasBeenRun = true;\n            if (options && options.tempClasses) {\n              forEach(options.tempClasses, function(className) {\n                $$jqLite.removeClass(element, className);\n              });\n            }\n\n            var data = element.data(NG_ANIMATE_STATE);\n            if (data) {\n\n              /* only structural animations wait for reflow before removing an\n                 animation, but class-based animations don't. An example of this\n                 failing would be when a parent HTML tag has a ng-class attribute\n                 causing ALL directives below to skip animations during the digest */\n              if (runner && runner.isClassBased) {\n                cleanup(element, className);\n              } else {\n                $$asyncCallback(function() {\n                  var data = element.data(NG_ANIMATE_STATE) || {};\n                  if (localAnimationCount == data.index) {\n                    cleanup(element, className, animationEvent);\n                  }\n                });\n                element.data(NG_ANIMATE_STATE, data);\n              }\n            }\n            fireDoneCallbackAsync();\n          }\n        }\n      }\n\n      function cancelChildAnimations(element) {\n        var node = extractElementNode(element);\n        if (node) {\n          var nodes = angular.isFunction(node.getElementsByClassName) ?\n            node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) :\n            node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME);\n          forEach(nodes, function(element) {\n            element = angular.element(element);\n            var data = element.data(NG_ANIMATE_STATE);\n            if (data && data.active) {\n              forEach(data.active, function(runner) {\n                runner.cancel();\n              });\n            }\n          });\n        }\n      }\n\n      function cleanup(element, className) {\n        if (isMatchingElement(element, $rootElement)) {\n          if (!rootAnimateState.disabled) {\n            rootAnimateState.running = false;\n            rootAnimateState.structural = false;\n          }\n        } else if (className) {\n          var data = element.data(NG_ANIMATE_STATE) || {};\n\n          var removeAnimations = className === true;\n          if (!removeAnimations && data.active && data.active[className]) {\n            data.totalActive--;\n            delete data.active[className];\n          }\n\n          if (removeAnimations || !data.totalActive) {\n            $$jqLite.removeClass(element, NG_ANIMATE_CLASS_NAME);\n            element.removeData(NG_ANIMATE_STATE);\n          }\n        }\n      }\n\n      function animationsDisabled(element, parentElement) {\n        if (rootAnimateState.disabled) {\n          return true;\n        }\n\n        if (isMatchingElement(element, $rootElement)) {\n          return rootAnimateState.running;\n        }\n\n        var allowChildAnimations, parentRunningAnimation, hasParent;\n        do {\n          //the element did not reach the root element which means that it\n          //is not apart of the DOM. Therefore there is no reason to do\n          //any animations on it\n          if (parentElement.length === 0) break;\n\n          var isRoot = isMatchingElement(parentElement, $rootElement);\n          var state = isRoot ? rootAnimateState : (parentElement.data(NG_ANIMATE_STATE) || {});\n          if (state.disabled) {\n            return true;\n          }\n\n          //no matter what, for an animation to work it must reach the root element\n          //this implies that the element is attached to the DOM when the animation is run\n          if (isRoot) {\n            hasParent = true;\n          }\n\n          //once a flag is found that is strictly false then everything before\n          //it will be discarded and all child animations will be restricted\n          if (allowChildAnimations !== false) {\n            var animateChildrenFlag = parentElement.data(NG_ANIMATE_CHILDREN);\n            if (angular.isDefined(animateChildrenFlag)) {\n              allowChildAnimations = animateChildrenFlag;\n            }\n          }\n\n          parentRunningAnimation = parentRunningAnimation ||\n                                   state.running ||\n                                   (state.last && !state.last.isClassBased);\n        }\n        while (parentElement = parentElement.parent());\n\n        return !hasParent || (!allowChildAnimations && parentRunningAnimation);\n      }\n    }]);\n\n    $animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow',\n                           function($window,   $sniffer,   $timeout,   $$animateReflow) {\n      // Detect proper transitionend/animationend event names.\n      var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;\n\n      // If unprefixed events are not supported but webkit-prefixed are, use the latter.\n      // Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.\n      // Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`\n      // but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.\n      // Register both events in case `window.onanimationend` is not supported because of that,\n      // do the same for `transitionend` as Safari is likely to exhibit similar behavior.\n      // Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit\n      // therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition\n      if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {\n        CSS_PREFIX = '-webkit-';\n        TRANSITION_PROP = 'WebkitTransition';\n        TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';\n      } else {\n        TRANSITION_PROP = 'transition';\n        TRANSITIONEND_EVENT = 'transitionend';\n      }\n\n      if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {\n        CSS_PREFIX = '-webkit-';\n        ANIMATION_PROP = 'WebkitAnimation';\n        ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';\n      } else {\n        ANIMATION_PROP = 'animation';\n        ANIMATIONEND_EVENT = 'animationend';\n      }\n\n      var DURATION_KEY = 'Duration';\n      var PROPERTY_KEY = 'Property';\n      var DELAY_KEY = 'Delay';\n      var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';\n      var ANIMATION_PLAYSTATE_KEY = 'PlayState';\n      var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey';\n      var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data';\n      var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;\n      var CLOSING_TIME_BUFFER = 1.5;\n      var ONE_SECOND = 1000;\n\n      var lookupCache = {};\n      var parentCounter = 0;\n      var animationReflowQueue = [];\n      var cancelAnimationReflow;\n      function clearCacheAfterReflow() {\n        if (!cancelAnimationReflow) {\n          cancelAnimationReflow = $$animateReflow(function() {\n            animationReflowQueue = [];\n            cancelAnimationReflow = null;\n            lookupCache = {};\n          });\n        }\n      }\n\n      function afterReflow(element, callback) {\n        if (cancelAnimationReflow) {\n          cancelAnimationReflow();\n        }\n        animationReflowQueue.push(callback);\n        cancelAnimationReflow = $$animateReflow(function() {\n          forEach(animationReflowQueue, function(fn) {\n            fn();\n          });\n\n          animationReflowQueue = [];\n          cancelAnimationReflow = null;\n          lookupCache = {};\n        });\n      }\n\n      var closingTimer = null;\n      var closingTimestamp = 0;\n      var animationElementQueue = [];\n      function animationCloseHandler(element, totalTime) {\n        var node = extractElementNode(element);\n        element = angular.element(node);\n\n        //this item will be garbage collected by the closing\n        //animation timeout\n        animationElementQueue.push(element);\n\n        //but it may not need to cancel out the existing timeout\n        //if the timestamp is less than the previous one\n        var futureTimestamp = Date.now() + totalTime;\n        if (futureTimestamp <= closingTimestamp) {\n          return;\n        }\n\n        $timeout.cancel(closingTimer);\n\n        closingTimestamp = futureTimestamp;\n        closingTimer = $timeout(function() {\n          closeAllAnimations(animationElementQueue);\n          animationElementQueue = [];\n        }, totalTime, false);\n      }\n\n      function closeAllAnimations(elements) {\n        forEach(elements, function(element) {\n          var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);\n          if (elementData) {\n            forEach(elementData.closeAnimationFns, function(fn) {\n              fn();\n            });\n          }\n        });\n      }\n\n      function getElementAnimationDetails(element, cacheKey) {\n        var data = cacheKey ? lookupCache[cacheKey] : null;\n        if (!data) {\n          var transitionDuration = 0;\n          var transitionDelay = 0;\n          var animationDuration = 0;\n          var animationDelay = 0;\n\n          //we want all the styles defined before and after\n          forEach(element, function(element) {\n            if (element.nodeType == ELEMENT_NODE) {\n              var elementStyles = $window.getComputedStyle(element) || {};\n\n              var transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY];\n              transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration);\n\n              var transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY];\n              transitionDelay  = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay);\n\n              var animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY];\n              animationDelay   = Math.max(parseMaxTime(elementStyles[ANIMATION_PROP + DELAY_KEY]), animationDelay);\n\n              var aDuration  = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]);\n\n              if (aDuration > 0) {\n                aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1;\n              }\n              animationDuration = Math.max(aDuration, animationDuration);\n            }\n          });\n          data = {\n            total: 0,\n            transitionDelay: transitionDelay,\n            transitionDuration: transitionDuration,\n            animationDelay: animationDelay,\n            animationDuration: animationDuration\n          };\n          if (cacheKey) {\n            lookupCache[cacheKey] = data;\n          }\n        }\n        return data;\n      }\n\n      function parseMaxTime(str) {\n        var maxValue = 0;\n        var values = isString(str) ?\n          str.split(/\\s*,\\s*/) :\n          [];\n        forEach(values, function(value) {\n          maxValue = Math.max(parseFloat(value) || 0, maxValue);\n        });\n        return maxValue;\n      }\n\n      function getCacheKey(element) {\n        var parentElement = element.parent();\n        var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY);\n        if (!parentID) {\n          parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter);\n          parentID = parentCounter;\n        }\n        return parentID + '-' + extractElementNode(element).getAttribute('class');\n      }\n\n      function animateSetup(animationEvent, element, className, styles) {\n        var structural = ['ng-enter','ng-leave','ng-move'].indexOf(className) >= 0;\n\n        var cacheKey = getCacheKey(element);\n        var eventCacheKey = cacheKey + ' ' + className;\n        var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0;\n\n        var stagger = {};\n        if (itemIndex > 0) {\n          var staggerClassName = className + '-stagger';\n          var staggerCacheKey = cacheKey + ' ' + staggerClassName;\n          var applyClasses = !lookupCache[staggerCacheKey];\n\n          applyClasses && $$jqLite.addClass(element, staggerClassName);\n\n          stagger = getElementAnimationDetails(element, staggerCacheKey);\n\n          applyClasses && $$jqLite.removeClass(element, staggerClassName);\n        }\n\n        $$jqLite.addClass(element, className);\n\n        var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {};\n        var timings = getElementAnimationDetails(element, eventCacheKey);\n        var transitionDuration = timings.transitionDuration;\n        var animationDuration = timings.animationDuration;\n\n        if (structural && transitionDuration === 0 && animationDuration === 0) {\n          $$jqLite.removeClass(element, className);\n          return false;\n        }\n\n        var blockTransition = styles || (structural && transitionDuration > 0);\n        var blockAnimation = animationDuration > 0 &&\n                             stagger.animationDelay > 0 &&\n                             stagger.animationDuration === 0;\n\n        var closeAnimationFns = formerData.closeAnimationFns || [];\n        element.data(NG_ANIMATE_CSS_DATA_KEY, {\n          stagger: stagger,\n          cacheKey: eventCacheKey,\n          running: formerData.running || 0,\n          itemIndex: itemIndex,\n          blockTransition: blockTransition,\n          closeAnimationFns: closeAnimationFns\n        });\n\n        var node = extractElementNode(element);\n\n        if (blockTransition) {\n          blockTransitions(node, true);\n          if (styles) {\n            element.css(styles);\n          }\n        }\n\n        if (blockAnimation) {\n          blockAnimations(node, true);\n        }\n\n        return true;\n      }\n\n      function animateRun(animationEvent, element, className, activeAnimationComplete, styles) {\n        var node = extractElementNode(element);\n        var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);\n        if (node.getAttribute('class').indexOf(className) == -1 || !elementData) {\n          activeAnimationComplete();\n          return;\n        }\n\n        var activeClassName = '';\n        var pendingClassName = '';\n        forEach(className.split(' '), function(klass, i) {\n          var prefix = (i > 0 ? ' ' : '') + klass;\n          activeClassName += prefix + '-active';\n          pendingClassName += prefix + '-pending';\n        });\n\n        var style = '';\n        var appliedStyles = [];\n        var itemIndex = elementData.itemIndex;\n        var stagger = elementData.stagger;\n        var staggerTime = 0;\n        if (itemIndex > 0) {\n          var transitionStaggerDelay = 0;\n          if (stagger.transitionDelay > 0 && stagger.transitionDuration === 0) {\n            transitionStaggerDelay = stagger.transitionDelay * itemIndex;\n          }\n\n          var animationStaggerDelay = 0;\n          if (stagger.animationDelay > 0 && stagger.animationDuration === 0) {\n            animationStaggerDelay = stagger.animationDelay * itemIndex;\n            appliedStyles.push(CSS_PREFIX + 'animation-play-state');\n          }\n\n          staggerTime = Math.round(Math.max(transitionStaggerDelay, animationStaggerDelay) * 100) / 100;\n        }\n\n        if (!staggerTime) {\n          $$jqLite.addClass(element, activeClassName);\n          if (elementData.blockTransition) {\n            blockTransitions(node, false);\n          }\n        }\n\n        var eventCacheKey = elementData.cacheKey + ' ' + activeClassName;\n        var timings = getElementAnimationDetails(element, eventCacheKey);\n        var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration);\n        if (maxDuration === 0) {\n          $$jqLite.removeClass(element, activeClassName);\n          animateClose(element, className);\n          activeAnimationComplete();\n          return;\n        }\n\n        if (!staggerTime && styles && Object.keys(styles).length > 0) {\n          if (!timings.transitionDuration) {\n            element.css('transition', timings.animationDuration + 's linear all');\n            appliedStyles.push('transition');\n          }\n          element.css(styles);\n        }\n\n        var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay);\n        var maxDelayTime = maxDelay * ONE_SECOND;\n\n        if (appliedStyles.length > 0) {\n          //the element being animated may sometimes contain comment nodes in\n          //the jqLite object, so we're safe to use a single variable to house\n          //the styles since there is always only one element being animated\n          var oldStyle = node.getAttribute('style') || '';\n          if (oldStyle.charAt(oldStyle.length - 1) !== ';') {\n            oldStyle += ';';\n          }\n          node.setAttribute('style', oldStyle + ' ' + style);\n        }\n\n        var startTime = Date.now();\n        var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT;\n        var animationTime     = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER;\n        var totalTime         = (staggerTime + animationTime) * ONE_SECOND;\n\n        var staggerTimeout;\n        if (staggerTime > 0) {\n          $$jqLite.addClass(element, pendingClassName);\n          staggerTimeout = $timeout(function() {\n            staggerTimeout = null;\n\n            if (timings.transitionDuration > 0) {\n              blockTransitions(node, false);\n            }\n            if (timings.animationDuration > 0) {\n              blockAnimations(node, false);\n            }\n\n            $$jqLite.addClass(element, activeClassName);\n            $$jqLite.removeClass(element, pendingClassName);\n\n            if (styles) {\n              if (timings.transitionDuration === 0) {\n                element.css('transition', timings.animationDuration + 's linear all');\n              }\n              element.css(styles);\n              appliedStyles.push('transition');\n            }\n          }, staggerTime * ONE_SECOND, false);\n        }\n\n        element.on(css3AnimationEvents, onAnimationProgress);\n        elementData.closeAnimationFns.push(function() {\n          onEnd();\n          activeAnimationComplete();\n        });\n\n        elementData.running++;\n        animationCloseHandler(element, totalTime);\n        return onEnd;\n\n        // This will automatically be called by $animate so\n        // there is no need to attach this internally to the\n        // timeout done method.\n        function onEnd() {\n          element.off(css3AnimationEvents, onAnimationProgress);\n          $$jqLite.removeClass(element, activeClassName);\n          $$jqLite.removeClass(element, pendingClassName);\n          if (staggerTimeout) {\n            $timeout.cancel(staggerTimeout);\n          }\n          animateClose(element, className);\n          var node = extractElementNode(element);\n          for (var i in appliedStyles) {\n            node.style.removeProperty(appliedStyles[i]);\n          }\n        }\n\n        function onAnimationProgress(event) {\n          event.stopPropagation();\n          var ev = event.originalEvent || event;\n          var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();\n\n          /* Firefox (or possibly just Gecko) likes to not round values up\n           * when a ms measurement is used for the animation */\n          var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));\n\n          /* $manualTimeStamp is a mocked timeStamp value which is set\n           * within browserTrigger(). This is only here so that tests can\n           * mock animations properly. Real events fallback to event.timeStamp,\n           * or, if they don't, then a timeStamp is automatically created for them.\n           * We're checking to see if the timeStamp surpasses the expected delay,\n           * but we're using elapsedTime instead of the timeStamp on the 2nd\n           * pre-condition since animations sometimes close off early */\n          if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {\n            activeAnimationComplete();\n          }\n        }\n      }\n\n      function blockTransitions(node, bool) {\n        node.style[TRANSITION_PROP + PROPERTY_KEY] = bool ? 'none' : '';\n      }\n\n      function blockAnimations(node, bool) {\n        node.style[ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY] = bool ? 'paused' : '';\n      }\n\n      function animateBefore(animationEvent, element, className, styles) {\n        if (animateSetup(animationEvent, element, className, styles)) {\n          return function(cancelled) {\n            cancelled && animateClose(element, className);\n          };\n        }\n      }\n\n      function animateAfter(animationEvent, element, className, afterAnimationComplete, styles) {\n        if (element.data(NG_ANIMATE_CSS_DATA_KEY)) {\n          return animateRun(animationEvent, element, className, afterAnimationComplete, styles);\n        } else {\n          animateClose(element, className);\n          afterAnimationComplete();\n        }\n      }\n\n      function animate(animationEvent, element, className, animationComplete, options) {\n        //If the animateSetup function doesn't bother returning a\n        //cancellation function then it means that there is no animation\n        //to perform at all\n        var preReflowCancellation = animateBefore(animationEvent, element, className, options.from);\n        if (!preReflowCancellation) {\n          clearCacheAfterReflow();\n          animationComplete();\n          return;\n        }\n\n        //There are two cancellation functions: one is before the first\n        //reflow animation and the second is during the active state\n        //animation. The first function will take care of removing the\n        //data from the element which will not make the 2nd animation\n        //happen in the first place\n        var cancel = preReflowCancellation;\n        afterReflow(element, function() {\n          //once the reflow is complete then we point cancel to\n          //the new cancellation function which will remove all of the\n          //animation properties from the active animation\n          cancel = animateAfter(animationEvent, element, className, animationComplete, options.to);\n        });\n\n        return function(cancelled) {\n          (cancel || noop)(cancelled);\n        };\n      }\n\n      function animateClose(element, className) {\n        $$jqLite.removeClass(element, className);\n        var data = element.data(NG_ANIMATE_CSS_DATA_KEY);\n        if (data) {\n          if (data.running) {\n            data.running--;\n          }\n          if (!data.running || data.running === 0) {\n            element.removeData(NG_ANIMATE_CSS_DATA_KEY);\n          }\n        }\n      }\n\n      return {\n        animate: function(element, className, from, to, animationCompleted, options) {\n          options = options || {};\n          options.from = from;\n          options.to = to;\n          return animate('animate', element, className, animationCompleted, options);\n        },\n\n        enter: function(element, animationCompleted, options) {\n          options = options || {};\n          return animate('enter', element, 'ng-enter', animationCompleted, options);\n        },\n\n        leave: function(element, animationCompleted, options) {\n          options = options || {};\n          return animate('leave', element, 'ng-leave', animationCompleted, options);\n        },\n\n        move: function(element, animationCompleted, options) {\n          options = options || {};\n          return animate('move', element, 'ng-move', animationCompleted, options);\n        },\n\n        beforeSetClass: function(element, add, remove, animationCompleted, options) {\n          options = options || {};\n          var className = suffixClasses(remove, '-remove') + ' ' +\n                          suffixClasses(add, '-add');\n          var cancellationMethod = animateBefore('setClass', element, className, options.from);\n          if (cancellationMethod) {\n            afterReflow(element, animationCompleted);\n            return cancellationMethod;\n          }\n          clearCacheAfterReflow();\n          animationCompleted();\n        },\n\n        beforeAddClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), options.from);\n          if (cancellationMethod) {\n            afterReflow(element, animationCompleted);\n            return cancellationMethod;\n          }\n          clearCacheAfterReflow();\n          animationCompleted();\n        },\n\n        beforeRemoveClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), options.from);\n          if (cancellationMethod) {\n            afterReflow(element, animationCompleted);\n            return cancellationMethod;\n          }\n          clearCacheAfterReflow();\n          animationCompleted();\n        },\n\n        setClass: function(element, add, remove, animationCompleted, options) {\n          options = options || {};\n          remove = suffixClasses(remove, '-remove');\n          add = suffixClasses(add, '-add');\n          var className = remove + ' ' + add;\n          return animateAfter('setClass', element, className, animationCompleted, options.to);\n        },\n\n        addClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted, options.to);\n        },\n\n        removeClass: function(element, className, animationCompleted, options) {\n          options = options || {};\n          return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted, options.to);\n        }\n      };\n\n      function suffixClasses(classes, suffix) {\n        var className = '';\n        classes = isArray(classes) ? classes : classes.split(/\\s+/);\n        forEach(classes, function(klass, i) {\n          if (klass && klass.length > 0) {\n            className += (i > 0 ? ' ' : '') + klass + suffix;\n          }\n        });\n        return className;\n      }\n    }]);\n  }]);\n\n\n})(window, window.angular);\n\n/*!\n * ionic.bundle.js is a concatenation of:\n * ionic.js, angular.js, angular-animate.js,\n * angular-sanitize.js, angular-ui-router.js,\n * and ionic-angular.js\n */\n\n/**\n * @license AngularJS v1.3.13\n * (c) 2010-2014 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\nvar $sanitizeMinErr = angular.$$minErr('$sanitize');\n\n/**\n * @ngdoc module\n * @name ngSanitize\n * @description\n *\n * # ngSanitize\n *\n * The `ngSanitize` module provides functionality to sanitize HTML.\n *\n *\n * <div doc-module-components=\"ngSanitize\"></div>\n *\n * See {@link ngSanitize.$sanitize `$sanitize`} for usage.\n */\n\n/*\n * HTML Parser By Misko Hevery (misko@hevery.com)\n * based on:  HTML Parser By John Resig (ejohn.org)\n * Original code by Erik Arvidsson, Mozilla Public License\n * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js\n *\n * // Use like so:\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n */\n\n\n/**\n * @ngdoc service\n * @name $sanitize\n * @kind function\n *\n * @description\n *   The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are\n *   then serialized back to properly escaped html string. This means that no unsafe input can make\n *   it into the returned string, however, since our parser is more strict than a typical browser\n *   parser, it's possible that some obscure input, which would be recognized as valid HTML by a\n *   browser, won't make it through the sanitizer. The input may also contain SVG markup.\n *   The whitelist is configured using the functions `aHrefSanitizationWhitelist` and\n *   `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.\n *\n * @param {string} html HTML input.\n * @returns {string} Sanitized HTML.\n *\n * @example\n   <example module=\"sanitizeExample\" deps=\"angular-sanitize.js\">\n   <file name=\"index.html\">\n     <script>\n         angular.module('sanitizeExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {\n             $scope.snippet =\n               '<p style=\"color:blue\">an html\\n' +\n               '<em onmouseover=\"this.textContent=\\'PWN3D!\\'\">click here</em>\\n' +\n               'snippet</p>';\n             $scope.deliberatelyTrustDangerousSnippet = function() {\n               return $sce.trustAsHtml($scope.snippet);\n             };\n           }]);\n     </script>\n     <div ng-controller=\"ExampleController\">\n        Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Directive</td>\n           <td>How</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"bind-html-with-sanitize\">\n           <td>ng-bind-html</td>\n           <td>Automatically uses $sanitize</td>\n           <td><pre>&lt;div ng-bind-html=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind-html=\"snippet\"></div></td>\n         </tr>\n         <tr id=\"bind-html-with-trust\">\n           <td>ng-bind-html</td>\n           <td>Bypass $sanitize by explicitly trusting the dangerous value</td>\n           <td>\n           <pre>&lt;div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"&gt;\n&lt;/div&gt;</pre>\n           </td>\n           <td><div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"></div></td>\n         </tr>\n         <tr id=\"bind-default\">\n           <td>ng-bind</td>\n           <td>Automatically escapes</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n       </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should sanitize the html snippet by default', function() {\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('<p>an html\\n<em>click here</em>\\nsnippet</p>');\n     });\n\n     it('should inline raw snippet if bound to a trusted value', function() {\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).\n         toBe(\"<p style=\\\"color:blue\\\">an html\\n\" +\n              \"<em onmouseover=\\\"this.textContent='PWN3D!'\\\">click here</em>\\n\" +\n              \"snippet</p>\");\n     });\n\n     it('should escape snippet without any filter', function() {\n       expect(element(by.css('#bind-default div')).getInnerHtml()).\n         toBe(\"&lt;p style=\\\"color:blue\\\"&gt;an html\\n\" +\n              \"&lt;em onmouseover=\\\"this.textContent='PWN3D!'\\\"&gt;click here&lt;/em&gt;\\n\" +\n              \"snippet&lt;/p&gt;\");\n     });\n\n     it('should update', function() {\n       element(by.model('snippet')).clear();\n       element(by.model('snippet')).sendKeys('new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('new <b>text</b>');\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(\n         'new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(\n         \"new &lt;b onclick=\\\"alert(1)\\\"&gt;text&lt;/b&gt;\");\n     });\n   </file>\n   </example>\n */\nfunction $SanitizeProvider() {\n  this.$get = ['$$sanitizeUri', function($$sanitizeUri) {\n    return function(html) {\n      var buf = [];\n      htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {\n        return !/^unsafe/.test($$sanitizeUri(uri, isImage));\n      }));\n      return buf.join('');\n    };\n  }];\n}\n\nfunction sanitizeText(chars) {\n  var buf = [];\n  var writer = htmlSanitizeWriter(buf, angular.noop);\n  writer.chars(chars);\n  return buf.join('');\n}\n\n\n// Regular Expressions for parsing tags and attributes\nvar START_TAG_REGEXP =\n       /^<((?:[a-zA-Z])[\\w:-]*)((?:\\s+[\\w:-]+(?:\\s*=\\s*(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?)*)\\s*(\\/?)\\s*(>?)/,\n  END_TAG_REGEXP = /^<\\/\\s*([\\w:-]+)[^>]*>/,\n  ATTR_REGEXP = /([\\w:-]+)(?:\\s*=\\s*(?:(?:\"((?:[^\"])*)\")|(?:'((?:[^'])*)')|([^>\\s]+)))?/g,\n  BEGIN_TAG_REGEXP = /^</,\n  BEGING_END_TAGE_REGEXP = /^<\\//,\n  COMMENT_REGEXP = /<!--(.*?)-->/g,\n  DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,\n  CDATA_REGEXP = /<!\\[CDATA\\[(.*?)]]>/g,\n  SURROGATE_PAIR_REGEXP = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g,\n  // Match everything outside of normal chars and \" (quote character)\n  NON_ALPHANUMERIC_REGEXP = /([^\\#-~| |!])/g;\n\n\n// Good source of info about elements and attributes\n// http://dev.w3.org/html5/spec/Overview.html#semantics\n// http://simon.html5.org/html-elements\n\n// Safe Void Elements - HTML5\n// http://dev.w3.org/html5/spec/Overview.html#void-elements\nvar voidElements = makeMap(\"area,br,col,hr,img,wbr\");\n\n// Elements that you can, intentionally, leave open (and which close themselves)\n// http://dev.w3.org/html5/spec/Overview.html#optional-tags\nvar optionalEndTagBlockElements = makeMap(\"colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr\"),\n    optionalEndTagInlineElements = makeMap(\"rp,rt\"),\n    optionalEndTagElements = angular.extend({},\n                                            optionalEndTagInlineElements,\n                                            optionalEndTagBlockElements);\n\n// Safe Block Elements - HTML5\nvar blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap(\"address,article,\" +\n        \"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,\" +\n        \"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul\"));\n\n// Inline Elements - HTML5\nvar inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap(\"a,abbr,acronym,b,\" +\n        \"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,\" +\n        \"samp,small,span,strike,strong,sub,sup,time,tt,u,var\"));\n\n// SVG Elements\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements\nvar svgElements = makeMap(\"animate,animateColor,animateMotion,animateTransform,circle,defs,\" +\n        \"desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,hkern,image,linearGradient,\" +\n        \"line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,radialGradient,rect,set,\" +\n        \"stop,svg,switch,text,title,tspan,use\");\n\n// Special Elements (can contain anything)\nvar specialElements = makeMap(\"script,style\");\n\nvar validElements = angular.extend({},\n                                   voidElements,\n                                   blockElements,\n                                   inlineElements,\n                                   optionalEndTagElements,\n                                   svgElements);\n\n//Attributes that have href and hence need to be sanitized\nvar uriAttrs = makeMap(\"background,cite,href,longdesc,src,usemap,xlink:href\");\n\nvar htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +\n    'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +\n    'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +\n    'scope,scrolling,shape,size,span,start,summary,target,title,type,' +\n    'valign,value,vspace,width');\n\n// SVG attributes (without \"id\" and \"name\" attributes)\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes\nvar svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +\n    'attributeName,attributeType,baseProfile,bbox,begin,by,calcMode,cap-height,class,color,' +\n    'color-rendering,content,cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,' +\n    'font-size,font-stretch,font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,' +\n    'gradientUnits,hanging,height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,' +\n    'keySplines,keyTimes,lang,marker-end,marker-mid,marker-start,markerHeight,markerUnits,' +\n    'markerWidth,mathematical,max,min,offset,opacity,orient,origin,overline-position,' +\n    'overline-thickness,panose-1,path,pathLength,points,preserveAspectRatio,r,refX,refY,' +\n    'repeatCount,repeatDur,requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,' +\n    'stemv,stop-color,stop-opacity,strikethrough-position,strikethrough-thickness,stroke,' +\n    'stroke-dasharray,stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,' +\n    'stroke-opacity,stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,' +\n    'underline-position,underline-thickness,unicode,unicode-range,units-per-em,values,version,' +\n    'viewBox,visibility,width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,' +\n    'xlink:show,xlink:title,xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,' +\n    'zoomAndPan');\n\nvar validAttrs = angular.extend({},\n                                uriAttrs,\n                                svgAttrs,\n                                htmlAttrs);\n\nfunction makeMap(str) {\n  var obj = {}, items = str.split(','), i;\n  for (i = 0; i < items.length; i++) obj[items[i]] = true;\n  return obj;\n}\n\n\n/**\n * @example\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n * @param {string} html string\n * @param {object} handler\n */\nfunction htmlParser(html, handler) {\n  if (typeof html !== 'string') {\n    if (html === null || typeof html === 'undefined') {\n      html = '';\n    } else {\n      html = '' + html;\n    }\n  }\n  var index, chars, match, stack = [], last = html, text;\n  stack.last = function() { return stack[stack.length - 1]; };\n\n  while (html) {\n    text = '';\n    chars = true;\n\n    // Make sure we're not in a script or style element\n    if (!stack.last() || !specialElements[stack.last()]) {\n\n      // Comment\n      if (html.indexOf(\"<!--\") === 0) {\n        // comments containing -- are not allowed unless they terminate the comment\n        index = html.indexOf(\"--\", 4);\n\n        if (index >= 0 && html.lastIndexOf(\"-->\", index) === index) {\n          if (handler.comment) handler.comment(html.substring(4, index));\n          html = html.substring(index + 3);\n          chars = false;\n        }\n      // DOCTYPE\n      } else if (DOCTYPE_REGEXP.test(html)) {\n        match = html.match(DOCTYPE_REGEXP);\n\n        if (match) {\n          html = html.replace(match[0], '');\n          chars = false;\n        }\n      // end tag\n      } else if (BEGING_END_TAGE_REGEXP.test(html)) {\n        match = html.match(END_TAG_REGEXP);\n\n        if (match) {\n          html = html.substring(match[0].length);\n          match[0].replace(END_TAG_REGEXP, parseEndTag);\n          chars = false;\n        }\n\n      // start tag\n      } else if (BEGIN_TAG_REGEXP.test(html)) {\n        match = html.match(START_TAG_REGEXP);\n\n        if (match) {\n          // We only have a valid start-tag if there is a '>'.\n          if (match[4]) {\n            html = html.substring(match[0].length);\n            match[0].replace(START_TAG_REGEXP, parseStartTag);\n          }\n          chars = false;\n        } else {\n          // no ending tag found --- this piece should be encoded as an entity.\n          text += '<';\n          html = html.substring(1);\n        }\n      }\n\n      if (chars) {\n        index = html.indexOf(\"<\");\n\n        text += index < 0 ? html : html.substring(0, index);\n        html = index < 0 ? \"\" : html.substring(index);\n\n        if (handler.chars) handler.chars(decodeEntities(text));\n      }\n\n    } else {\n      // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\\W\\w].\n      html = html.replace(new RegExp(\"([\\\\W\\\\w]*)<\\\\s*\\\\/\\\\s*\" + stack.last() + \"[^>]*>\", 'i'),\n        function(all, text) {\n          text = text.replace(COMMENT_REGEXP, \"$1\").replace(CDATA_REGEXP, \"$1\");\n\n          if (handler.chars) handler.chars(decodeEntities(text));\n\n          return \"\";\n      });\n\n      parseEndTag(\"\", stack.last());\n    }\n\n    if (html == last) {\n      throw $sanitizeMinErr('badparse', \"The sanitizer was unable to parse the following block \" +\n                                        \"of html: {0}\", html);\n    }\n    last = html;\n  }\n\n  // Clean up any remaining tags\n  parseEndTag();\n\n  function parseStartTag(tag, tagName, rest, unary) {\n    tagName = angular.lowercase(tagName);\n    if (blockElements[tagName]) {\n      while (stack.last() && inlineElements[stack.last()]) {\n        parseEndTag(\"\", stack.last());\n      }\n    }\n\n    if (optionalEndTagElements[tagName] && stack.last() == tagName) {\n      parseEndTag(\"\", tagName);\n    }\n\n    unary = voidElements[tagName] || !!unary;\n\n    if (!unary)\n      stack.push(tagName);\n\n    var attrs = {};\n\n    rest.replace(ATTR_REGEXP,\n      function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {\n        var value = doubleQuotedValue\n          || singleQuotedValue\n          || unquotedValue\n          || '';\n\n        attrs[name] = decodeEntities(value);\n    });\n    if (handler.start) handler.start(tagName, attrs, unary);\n  }\n\n  function parseEndTag(tag, tagName) {\n    var pos = 0, i;\n    tagName = angular.lowercase(tagName);\n    if (tagName)\n      // Find the closest opened tag of the same type\n      for (pos = stack.length - 1; pos >= 0; pos--)\n        if (stack[pos] == tagName)\n          break;\n\n    if (pos >= 0) {\n      // Close all the open elements, up the stack\n      for (i = stack.length - 1; i >= pos; i--)\n        if (handler.end) handler.end(stack[i]);\n\n      // Remove the open elements from the stack\n      stack.length = pos;\n    }\n  }\n}\n\nvar hiddenPre=document.createElement(\"pre\");\nvar spaceRe = /^(\\s*)([\\s\\S]*?)(\\s*)$/;\n/**\n * decodes all entities into regular string\n * @param value\n * @returns {string} A string with decoded entities.\n */\nfunction decodeEntities(value) {\n  if (!value) { return ''; }\n\n  // Note: IE8 does not preserve spaces at the start/end of innerHTML\n  // so we must capture them and reattach them afterward\n  var parts = spaceRe.exec(value);\n  var spaceBefore = parts[1];\n  var spaceAfter = parts[3];\n  var content = parts[2];\n  if (content) {\n    hiddenPre.innerHTML=content.replace(/</g,\"&lt;\");\n    // innerText depends on styling as it doesn't display hidden elements.\n    // Therefore, it's better to use textContent not to cause unnecessary\n    // reflows. However, IE<9 don't support textContent so the innerText\n    // fallback is necessary.\n    content = 'textContent' in hiddenPre ?\n      hiddenPre.textContent : hiddenPre.innerText;\n  }\n  return spaceBefore + content + spaceAfter;\n}\n\n/**\n * Escapes all potentially dangerous characters, so that the\n * resulting string can be safely inserted into attribute or\n * element text.\n * @param value\n * @returns {string} escaped text\n */\nfunction encodeEntities(value) {\n  return value.\n    replace(/&/g, '&amp;').\n    replace(SURROGATE_PAIR_REGEXP, function(value) {\n      var hi = value.charCodeAt(0);\n      var low = value.charCodeAt(1);\n      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';\n    }).\n    replace(NON_ALPHANUMERIC_REGEXP, function(value) {\n      return '&#' + value.charCodeAt(0) + ';';\n    }).\n    replace(/</g, '&lt;').\n    replace(/>/g, '&gt;');\n}\n\n/**\n * create an HTML/XML writer which writes to buffer\n * @param {Array} buf use buf.jain('') to get out sanitized html string\n * @returns {object} in the form of {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * }\n */\nfunction htmlSanitizeWriter(buf, uriValidator) {\n  var ignore = false;\n  var out = angular.bind(buf, buf.push);\n  return {\n    start: function(tag, attrs, unary) {\n      tag = angular.lowercase(tag);\n      if (!ignore && specialElements[tag]) {\n        ignore = tag;\n      }\n      if (!ignore && validElements[tag] === true) {\n        out('<');\n        out(tag);\n        angular.forEach(attrs, function(value, key) {\n          var lkey=angular.lowercase(key);\n          var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');\n          if (validAttrs[lkey] === true &&\n            (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {\n            out(' ');\n            out(key);\n            out('=\"');\n            out(encodeEntities(value));\n            out('\"');\n          }\n        });\n        out(unary ? '/>' : '>');\n      }\n    },\n    end: function(tag) {\n        tag = angular.lowercase(tag);\n        if (!ignore && validElements[tag] === true) {\n          out('</');\n          out(tag);\n          out('>');\n        }\n        if (tag == ignore) {\n          ignore = false;\n        }\n      },\n    chars: function(chars) {\n        if (!ignore) {\n          out(encodeEntities(chars));\n        }\n      }\n  };\n}\n\n\n// define ngSanitize module and register $sanitize service\nangular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);\n\n/* global sanitizeText: false */\n\n/**\n * @ngdoc filter\n * @name linky\n * @kind function\n *\n * @description\n * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and\n * plain email address links.\n *\n * Requires the {@link ngSanitize `ngSanitize`} module to be installed.\n *\n * @param {string} text Input text.\n * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.\n * @returns {string} Html-linkified text.\n *\n * @usage\n   <span ng-bind-html=\"linky_expression | linky\"></span>\n *\n * @example\n   <example module=\"linkyExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('linkyExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.snippet =\n               'Pretty text with some links:\\n'+\n               'http://angularjs.org/,\\n'+\n               'mailto:us@somewhere.org,\\n'+\n               'another@somewhere.org,\\n'+\n               'and one more: ftp://127.0.0.1/.';\n             $scope.snippetWithTarget = 'http://angularjs.org/';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n       Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Filter</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"linky-filter\">\n           <td>linky filter</td>\n           <td>\n             <pre>&lt;div ng-bind-html=\"snippet | linky\"&gt;<br>&lt;/div&gt;</pre>\n           </td>\n           <td>\n             <div ng-bind-html=\"snippet | linky\"></div>\n           </td>\n         </tr>\n         <tr id=\"linky-target\">\n          <td>linky target</td>\n          <td>\n            <pre>&lt;div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"&gt;<br>&lt;/div&gt;</pre>\n          </td>\n          <td>\n            <div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"></div>\n          </td>\n         </tr>\n         <tr id=\"escaped-html\">\n           <td>no filter</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should linkify the snippet with urls', function() {\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);\n       });\n\n       it('should not linkify snippet without the linky filter', function() {\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);\n       });\n\n       it('should update', function() {\n         element(by.model('snippet')).clear();\n         element(by.model('snippet')).sendKeys('new http://link.');\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('new http://link.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())\n             .toBe('new http://link.');\n       });\n\n       it('should work with the target property', function() {\n        expect(element(by.id('linky-target')).\n            element(by.binding(\"snippetWithTarget | linky:'_blank'\")).getText()).\n            toBe('http://angularjs.org/');\n        expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');\n       });\n     </file>\n   </example>\n */\nangular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {\n  var LINKY_URL_REGEXP =\n        /((ftp|https?):\\/\\/|(www\\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\\S*[^\\s.;,(){}<>\"”’]/,\n      MAILTO_REGEXP = /^mailto:/;\n\n  return function(text, target) {\n    if (!text) return text;\n    var match;\n    var raw = text;\n    var html = [];\n    var url;\n    var i;\n    while ((match = raw.match(LINKY_URL_REGEXP))) {\n      // We can not end in these as they are sometimes found at the end of the sentence\n      url = match[0];\n      // if we did not match ftp/http/www/mailto then assume mailto\n      if (!match[2] && !match[4]) {\n        url = (match[3] ? 'http://' : 'mailto:') + url;\n      }\n      i = match.index;\n      addText(raw.substr(0, i));\n      addLink(url, match[0].replace(MAILTO_REGEXP, ''));\n      raw = raw.substring(i + match[0].length);\n    }\n    addText(raw);\n    return $sanitize(html.join(''));\n\n    function addText(text) {\n      if (!text) {\n        return;\n      }\n      html.push(sanitizeText(text));\n    }\n\n    function addLink(url, text) {\n      html.push('<a ');\n      if (angular.isDefined(target)) {\n        html.push('target=\"',\n                  target,\n                  '\" ');\n      }\n      html.push('href=\"',\n                url.replace(/\"/g, '&quot;'),\n                '\">');\n      addText(text);\n      html.push('</a>');\n    }\n  };\n}]);\n\n\n})(window, window.angular);\n\n/*!\n * ionic.bundle.js is a concatenation of:\n * ionic.js, angular.js, angular-animate.js,\n * angular-sanitize.js, angular-ui-router.js,\n * and ionic-angular.js\n */\n\n/**\n * State-based routing for AngularJS\n * @version v0.2.13\n * @link http://angular-ui.github.com/\n * @license MIT License, http://www.opensource.org/licenses/MIT\n */\n\n/* commonjs package manager support (eg componentjs) */\nif (typeof module !== \"undefined\" && typeof exports !== \"undefined\" && module.exports === exports){\n  module.exports = 'ui.router';\n}\n\n(function (window, angular, undefined) {\n/*jshint globalstrict:true*/\n/*global angular:false*/\n'use strict';\n\nvar isDefined = angular.isDefined,\n    isFunction = angular.isFunction,\n    isString = angular.isString,\n    isObject = angular.isObject,\n    isArray = angular.isArray,\n    forEach = angular.forEach,\n    extend = angular.extend,\n    copy = angular.copy;\n\nfunction inherit(parent, extra) {\n  return extend(new (extend(function() {}, { prototype: parent }))(), extra);\n}\n\nfunction merge(dst) {\n  forEach(arguments, function(obj) {\n    if (obj !== dst) {\n      forEach(obj, function(value, key) {\n        if (!dst.hasOwnProperty(key)) dst[key] = value;\n      });\n    }\n  });\n  return dst;\n}\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nfunction ancestors(first, second) {\n  var path = [];\n\n  for (var n in first.path) {\n    if (first.path[n] !== second.path[n]) break;\n    path.push(first.path[n]);\n  }\n  return path;\n}\n\n/**\n * IE8-safe wrapper for `Object.keys()`.\n *\n * @param {Object} object A JavaScript object.\n * @return {Array} Returns the keys of the object as an array.\n */\nfunction objectKeys(object) {\n  if (Object.keys) {\n    return Object.keys(object);\n  }\n  var result = [];\n\n  angular.forEach(object, function(val, key) {\n    result.push(key);\n  });\n  return result;\n}\n\n/**\n * IE8-safe wrapper for `Array.prototype.indexOf()`.\n *\n * @param {Array} array A JavaScript array.\n * @param {*} value A value to search the array for.\n * @return {Number} Returns the array index value of `value`, or `-1` if not present.\n */\nfunction indexOf(array, value) {\n  if (Array.prototype.indexOf) {\n    return array.indexOf(value, Number(arguments[2]) || 0);\n  }\n  var len = array.length >>> 0, from = Number(arguments[2]) || 0;\n  from = (from < 0) ? Math.ceil(from) : Math.floor(from);\n\n  if (from < 0) from += len;\n\n  for (; from < len; from++) {\n    if (from in array && array[from] === value) return from;\n  }\n  return -1;\n}\n\n/**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} currentParams The value of the current state parameters ($stateParams).\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\nfunction inheritParams(currentParams, newParams, $current, $to) {\n  var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];\n\n  for (var i in parents) {\n    if (!parents[i].params) continue;\n    parentParams = objectKeys(parents[i].params);\n    if (!parentParams.length) continue;\n\n    for (var j in parentParams) {\n      if (indexOf(inheritList, parentParams[j]) >= 0) continue;\n      inheritList.push(parentParams[j]);\n      inherited[parentParams[j]] = currentParams[parentParams[j]];\n    }\n  }\n  return extend({}, inherited, newParams);\n}\n\n/**\n * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.\n *\n * @param {Object} a The first object.\n * @param {Object} b The second object.\n * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,\n *                     it defaults to the list of keys in `a`.\n * @return {Boolean} Returns `true` if the keys match, otherwise `false`.\n */\nfunction equalForKeys(a, b, keys) {\n  if (!keys) {\n    keys = [];\n    for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility\n  }\n\n  for (var i=0; i<keys.length; i++) {\n    var k = keys[i];\n    if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized\n  }\n  return true;\n}\n\n/**\n * Returns the subset of an object, based on a list of keys.\n *\n * @param {Array} keys\n * @param {Object} values\n * @return {Boolean} Returns a subset of `values`.\n */\nfunction filterByKeys(keys, values) {\n  var filtered = {};\n\n  forEach(keys, function (name) {\n    filtered[name] = values[name];\n  });\n  return filtered;\n}\n\n// like _.indexBy\n// when you know that your index values will be unique, or you want last-one-in to win\nfunction indexBy(array, propName) {\n  var result = {};\n  forEach(array, function(item) {\n    result[item[propName]] = item;\n  });\n  return result;\n}\n\n// extracted from underscore.js\n// Return a copy of the object only containing the whitelisted properties.\nfunction pick(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  forEach(keys, function(key) {\n    if (key in obj) copy[key] = obj[key];\n  });\n  return copy;\n}\n\n// extracted from underscore.js\n// Return a copy of the object omitting the blacklisted properties.\nfunction omit(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  for (var key in obj) {\n    if (indexOf(keys, key) == -1) copy[key] = obj[key];\n  }\n  return copy;\n}\n\nfunction pluck(collection, key) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = isFunction(key) ? key(val) : val[key];\n  });\n  return result;\n}\n\nfunction filter(collection, callback) {\n  var array = isArray(collection);\n  var result = array ? [] : {};\n  forEach(collection, function(val, i) {\n    if (callback(val, i)) {\n      result[array ? result.length : i] = val;\n    }\n  });\n  return result;\n}\n\nfunction map(collection, callback) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = callback(val, i);\n  });\n  return result;\n}\n\n/**\n * @ngdoc overview\n * @name ui.router.util\n *\n * @description\n * # ui.router.util sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n *\n */\nangular.module('ui.router.util', ['ng']);\n\n/**\n * @ngdoc overview\n * @name ui.router.router\n * \n * @requires ui.router.util\n *\n * @description\n * # ui.router.router sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n */\nangular.module('ui.router.router', ['ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router.state\n * \n * @requires ui.router.router\n * @requires ui.router.util\n *\n * @description\n * # ui.router.state sub-module\n *\n * This module is a dependency of the main ui.router module. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n * \n */\nangular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router\n *\n * @requires ui.router.state\n *\n * @description\n * # ui.router\n * \n * ## The main module for ui.router \n * There are several sub-modules included with the ui.router module, however only this module is needed\n * as a dependency within your angular app. The other modules are for organization purposes. \n *\n * The modules are:\n * * ui.router - the main \"umbrella\" module\n * * ui.router.router - \n * \n * *You'll need to include **only** this module as the dependency within your angular app.*\n * \n * <pre>\n * <!doctype html>\n * <html ng-app=\"myApp\">\n * <head>\n *   <script src=\"js/angular.js\"></script>\n *   <!-- Include the ui-router script -->\n *   <script src=\"js/angular-ui-router.min.js\"></script>\n *   <script>\n *     // ...and add 'ui.router' as a dependency\n *     var myApp = angular.module('myApp', ['ui.router']);\n *   </script>\n * </head>\n * <body>\n * </body>\n * </html>\n * </pre>\n */\nangular.module('ui.router', ['ui.router.state']);\n\nangular.module('ui.router.compat', ['ui.router']);\n\n/**\n * @ngdoc object\n * @name ui.router.util.$resolve\n *\n * @requires $q\n * @requires $injector\n *\n * @description\n * Manages resolution of (acyclic) graphs of promises.\n */\n$Resolve.$inject = ['$q', '$injector'];\nfunction $Resolve(  $q,    $injector) {\n  \n  var VISIT_IN_PROGRESS = 1,\n      VISIT_DONE = 2,\n      NOTHING = {},\n      NO_DEPENDENCIES = [],\n      NO_LOCALS = NOTHING,\n      NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });\n  \n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#study\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Studies a set of invocables that are likely to be used multiple times.\n   * <pre>\n   * $resolve.study(invocables)(locals, parent, self)\n   * </pre>\n   * is equivalent to\n   * <pre>\n   * $resolve.resolve(invocables, locals, parent, self)\n   * </pre>\n   * but the former is more efficient (in fact `resolve` just calls `study` \n   * internally).\n   *\n   * @param {object} invocables Invocable objects\n   * @return {function} a function to pass in locals, parent and self\n   */\n  this.study = function (invocables) {\n    if (!isObject(invocables)) throw new Error(\"'invocables' must be an object\");\n    var invocableKeys = objectKeys(invocables || {});\n    \n    // Perform a topological sort of invocables to build an ordered plan\n    var plan = [], cycle = [], visited = {};\n    function visit(value, key) {\n      if (visited[key] === VISIT_DONE) return;\n      \n      cycle.push(key);\n      if (visited[key] === VISIT_IN_PROGRESS) {\n        cycle.splice(0, indexOf(cycle, key));\n        throw new Error(\"Cyclic dependency: \" + cycle.join(\" -> \"));\n      }\n      visited[key] = VISIT_IN_PROGRESS;\n      \n      if (isString(value)) {\n        plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);\n      } else {\n        var params = $injector.annotate(value);\n        forEach(params, function (param) {\n          if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);\n        });\n        plan.push(key, value, params);\n      }\n      \n      cycle.pop();\n      visited[key] = VISIT_DONE;\n    }\n    forEach(invocables, visit);\n    invocables = cycle = visited = null; // plan is all that's required\n    \n    function isResolve(value) {\n      return isObject(value) && value.then && value.$$promises;\n    }\n    \n    return function (locals, parent, self) {\n      if (isResolve(locals) && self === undefined) {\n        self = parent; parent = locals; locals = null;\n      }\n      if (!locals) locals = NO_LOCALS;\n      else if (!isObject(locals)) {\n        throw new Error(\"'locals' must be an object\");\n      }       \n      if (!parent) parent = NO_PARENT;\n      else if (!isResolve(parent)) {\n        throw new Error(\"'parent' must be a promise returned by $resolve.resolve()\");\n      }\n      \n      // To complete the overall resolution, we have to wait for the parent\n      // promise and for the promise for each invokable in our plan.\n      var resolution = $q.defer(),\n          result = resolution.promise,\n          promises = result.$$promises = {},\n          values = extend({}, locals),\n          wait = 1 + plan.length/3,\n          merged = false;\n          \n      function done() {\n        // Merge parent values we haven't got yet and publish our own $$values\n        if (!--wait) {\n          if (!merged) merge(values, parent.$$values); \n          result.$$values = values;\n          result.$$promises = result.$$promises || true; // keep for isResolve()\n          delete result.$$inheritedValues;\n          resolution.resolve(values);\n        }\n      }\n      \n      function fail(reason) {\n        result.$$failure = reason;\n        resolution.reject(reason);\n      }\n\n      // Short-circuit if parent has already failed\n      if (isDefined(parent.$$failure)) {\n        fail(parent.$$failure);\n        return result;\n      }\n      \n      if (parent.$$inheritedValues) {\n        merge(values, omit(parent.$$inheritedValues, invocableKeys));\n      }\n\n      // Merge parent values if the parent has already resolved, or merge\n      // parent promises and wait if the parent resolve is still in progress.\n      extend(promises, parent.$$promises);\n      if (parent.$$values) {\n        merged = merge(values, omit(parent.$$values, invocableKeys));\n        result.$$inheritedValues = omit(parent.$$values, invocableKeys);\n        done();\n      } else {\n        if (parent.$$inheritedValues) {\n          result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);\n        }        \n        parent.then(done, fail);\n      }\n      \n      // Process each invocable in the plan, but ignore any where a local of the same name exists.\n      for (var i=0, ii=plan.length; i<ii; i+=3) {\n        if (locals.hasOwnProperty(plan[i])) done();\n        else invoke(plan[i], plan[i+1], plan[i+2]);\n      }\n      \n      function invoke(key, invocable, params) {\n        // Create a deferred for this invocation. Failures will propagate to the resolution as well.\n        var invocation = $q.defer(), waitParams = 0;\n        function onfailure(reason) {\n          invocation.reject(reason);\n          fail(reason);\n        }\n        // Wait for any parameter that we have a promise for (either from parent or from this\n        // resolve; in that case study() will have made sure it's ordered before us in the plan).\n        forEach(params, function (dep) {\n          if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {\n            waitParams++;\n            promises[dep].then(function (result) {\n              values[dep] = result;\n              if (!(--waitParams)) proceed();\n            }, onfailure);\n          }\n        });\n        if (!waitParams) proceed();\n        function proceed() {\n          if (isDefined(result.$$failure)) return;\n          try {\n            invocation.resolve($injector.invoke(invocable, self, values));\n            invocation.promise.then(function (result) {\n              values[key] = result;\n              done();\n            }, onfailure);\n          } catch (e) {\n            onfailure(e);\n          }\n        }\n        // Publish promise synchronously; invocations further down in the plan may depend on it.\n        promises[key] = invocation.promise;\n      }\n      \n      return result;\n    };\n  };\n  \n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#resolve\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Resolves a set of invocables. An invocable is a function to be invoked via \n   * `$injector.invoke()`, and can have an arbitrary number of dependencies. \n   * An invocable can either return a value directly,\n   * or a `$q` promise. If a promise is returned it will be resolved and the \n   * resulting value will be used instead. Dependencies of invocables are resolved \n   * (in this order of precedence)\n   *\n   * - from the specified `locals`\n   * - from another invocable that is part of this `$resolve` call\n   * - from an invocable that is inherited from a `parent` call to `$resolve` \n   *   (or recursively\n   * - from any ancestor `$resolve` of that parent).\n   *\n   * The return value of `$resolve` is a promise for an object that contains \n   * (in this order of precedence)\n   *\n   * - any `locals` (if specified)\n   * - the resolved return values of all injectables\n   * - any values inherited from a `parent` call to `$resolve` (if specified)\n   *\n   * The promise will resolve after the `parent` promise (if any) and all promises \n   * returned by injectables have been resolved. If any invocable \n   * (or `$injector.invoke`) throws an exception, or if a promise returned by an \n   * invocable is rejected, the `$resolve` promise is immediately rejected with the \n   * same error. A rejection of a `parent` promise (if specified) will likewise be \n   * propagated immediately. Once the `$resolve` promise has been rejected, no \n   * further invocables will be called.\n   * \n   * Cyclic dependencies between invocables are not permitted and will caues `$resolve`\n   * to throw an error. As a special case, an injectable can depend on a parameter \n   * with the same name as the injectable, which will be fulfilled from the `parent` \n   * injectable of the same name. This allows inherited values to be decorated. \n   * Note that in this case any other injectable in the same `$resolve` with the same\n   * dependency would see the decorated value, not the inherited value.\n   *\n   * Note that missing dependencies -- unlike cyclic dependencies -- will cause an \n   * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous) \n   * exception.\n   *\n   * Invocables are invoked eagerly as soon as all dependencies are available. \n   * This is true even for dependencies inherited from a `parent` call to `$resolve`.\n   *\n   * As a special case, an invocable can be a string, in which case it is taken to \n   * be a service name to be passed to `$injector.get()`. This is supported primarily \n   * for backwards-compatibility with the `resolve` property of `$routeProvider` \n   * routes.\n   *\n   * @param {object} invocables functions to invoke or \n   * `$injector` services to fetch.\n   * @param {object} locals  values to make available to the injectables\n   * @param {object} parent  a promise returned by another call to `$resolve`.\n   * @param {object} self  the `this` for the invoked methods\n   * @return {object} Promise for an object that contains the resolved return value\n   * of all invocables, as well as any inherited and local values.\n   */\n  this.resolve = function (invocables, locals, parent, self) {\n    return this.study(invocables)(locals, parent, self);\n  };\n}\n\nangular.module('ui.router.util').service('$resolve', $Resolve);\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$templateFactory\n *\n * @requires $http\n * @requires $templateCache\n * @requires $injector\n *\n * @description\n * Service. Manages loading of templates.\n */\n$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];\nfunction $TemplateFactory(  $http,   $templateCache,   $injector) {\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromConfig\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a configuration object. \n   *\n   * @param {object} config Configuration object for which to load a template. \n   * The following properties are search in the specified order, and the first one \n   * that is defined is used to create the template:\n   *\n   * @param {string|object} config.template html string template or function to \n   * load via {@link ui.router.util.$templateFactory#fromString fromString}.\n   * @param {string|object} config.templateUrl url to load or a function returning \n   * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.\n   * @param {Function} config.templateProvider function to invoke via \n   * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.\n   * @param {object} params  Parameters to pass to the template function.\n   * @param {object} locals Locals to pass to `invoke` if the template is loaded \n   * via a `templateProvider`. Defaults to `{ params: params }`.\n   *\n   * @return {string|object}  The template html as a string, or a promise for \n   * that string,or `null` if no template is configured.\n   */\n  this.fromConfig = function (config, params, locals) {\n    return (\n      isDefined(config.template) ? this.fromString(config.template, params) :\n      isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :\n      isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :\n      null\n    );\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromString\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a string or a function returning a string.\n   *\n   * @param {string|object} template html template as a string or function that \n   * returns an html template as a string.\n   * @param {object} params Parameters to pass to the template function.\n   *\n   * @return {string|object} The template html as a string, or a promise for that \n   * string.\n   */\n  this.fromString = function (template, params) {\n    return isFunction(template) ? template(params) : template;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromUrl\n   * @methodOf ui.router.util.$templateFactory\n   * \n   * @description\n   * Loads a template from the a URL via `$http` and `$templateCache`.\n   *\n   * @param {string|Function} url url of the template to load, or a function \n   * that returns a url.\n   * @param {Object} params Parameters to pass to the url function.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromUrl = function (url, params) {\n    if (isFunction(url)) url = url(params);\n    if (url == null) return null;\n    else return $http\n        .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})\n        .then(function(response) { return response.data; });\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromProvider\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template by invoking an injectable provider function.\n   *\n   * @param {Function} provider Function to invoke via `$injector.invoke`\n   * @param {Object} params Parameters for the template.\n   * @param {Object} locals Locals to pass to `invoke`. Defaults to \n   * `{ params: params }`.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromProvider = function (provider, params, locals) {\n    return $injector.invoke(provider, null, locals || { params: params });\n  };\n}\n\nangular.module('ui.router.util').service('$templateFactory', $TemplateFactory);\n\nvar $$UMFP; // reference to $UrlMatcherFactoryProvider\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:UrlMatcher\n *\n * @description\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list\n * of search parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.\n * \n * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace\n * syntax, which optionally allows a regular expression for the parameter to be specified:\n *\n * * `':'` name - colon placeholder\n * * `'*'` name - catch-all placeholder\n * * `'{' name '}'` - curly placeholder\n * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the\n *   regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters). For colon \n * placeholders or curly placeholders without an explicit regexp, a path parameter matches any\n * number of characters other than '/'. For catch-all placeholders the path parameter matches\n * any number of characters.\n * \n * Examples:\n * \n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n *   trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n *   '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n *   parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n *   path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n *   in the built-in  `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n * @param {string} pattern  The pattern to compile into a matcher.\n * @param {Object} config  A configuration object hash:\n * @param {Object=} parentMatcher Used to concatenate the pattern/config onto\n *   an existing UrlMatcher\n *\n * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n *\n * @property {string} prefix  A static prefix of this pattern. The matcher guarantees that any\n *   URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns\n *   non-null) will start with this prefix.\n *\n * @property {string} source  The pattern that was passed into the constructor\n *\n * @property {string} sourcePath  The path portion of the source property\n *\n * @property {string} sourceSearch  The search portion of the source property\n *\n * @property {string} regex  The constructed regex that will be used to match against the url when \n *   it is time to determine which url will match.\n *\n * @returns {Object}  New `UrlMatcher` object\n */\nfunction UrlMatcher(pattern, config, parentMatcher) {\n  config = extend({ params: {} }, isObject(config) ? config : {});\n\n  // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n  //   '*' name\n  //   ':' name\n  //   '{' name '}'\n  //   '{' name ':' regexp '}'\n  // The regular expression is somewhat complicated due to the need to allow curly braces\n  // inside the regular expression. The placeholder regexp breaks down as follows:\n  //    ([:*])([\\w\\[\\]]+)              - classic placeholder ($1 / $2) (search version has - for snake-case)\n  //    \\{([\\w\\[\\]]+)(?:\\:( ... ))?\\}  - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n  //    (?: ... | ... | ... )+         - the regexp consists of any number of atoms, an atom being either\n  //    [^{}\\\\]+                       - anything other than curly braces or backslash\n  //    \\\\.                            - a backslash escape\n  //    \\{(?:[^{}\\\\]+|\\\\.)*\\}          - a matched set of curly braces containing other atoms\n  var placeholder       = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      searchPlaceholder = /([:]?)([\\w\\[\\]-]+)|\\{([\\w\\[\\]-]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      compiled = '^', last = 0, m,\n      segments = this.segments = [],\n      parentParams = parentMatcher ? parentMatcher.params : {},\n      params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),\n      paramNames = [];\n\n  function addParameter(id, type, config, location) {\n    paramNames.push(id);\n    if (parentParams[id]) return parentParams[id];\n    if (!/^\\w+(-+\\w+)*(?:\\[\\])?$/.test(id)) throw new Error(\"Invalid parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    if (params[id]) throw new Error(\"Duplicate parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    params[id] = new $$UMFP.Param(id, type, config, location);\n    return params[id];\n  }\n\n  function quoteRegExp(string, pattern, squash) {\n    var surroundPattern = ['',''], result = string.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, \"\\\\$&\");\n    if (!pattern) return result;\n    switch(squash) {\n      case false: surroundPattern = ['(', ')'];   break;\n      case true:  surroundPattern = ['?(', ')?']; break;\n      default:    surroundPattern = ['(' + squash + \"|\", ')?'];  break;\n    }\n    return result + surroundPattern[0] + pattern + surroundPattern[1];\n  }\n\n  this.source = pattern;\n\n  // Split into static segments separated by path parameter placeholders.\n  // The number of segments is always 1 more than the number of parameters.\n  function matchDetails(m, isSearch) {\n    var id, regexp, segment, type, cfg, arrayMode;\n    id          = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null\n    cfg         = config.params[id];\n    segment     = pattern.substring(last, m.index);\n    regexp      = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);\n    type        = $$UMFP.type(regexp || \"string\") || inherit($$UMFP.type(\"string\"), { pattern: new RegExp(regexp) });\n    return {\n      id: id, regexp: regexp, segment: segment, type: type, cfg: cfg\n    };\n  }\n\n  var p, param, segment;\n  while ((m = placeholder.exec(pattern))) {\n    p = matchDetails(m, false);\n    if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n    param = addParameter(p.id, p.type, p.cfg, \"path\");\n    compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash);\n    segments.push(p.segment);\n    last = placeholder.lastIndex;\n  }\n  segment = pattern.substring(last);\n\n  // Find any search parameter names and remove them from the last segment\n  var i = segment.indexOf('?');\n\n  if (i >= 0) {\n    var search = this.sourceSearch = segment.substring(i);\n    segment = segment.substring(0, i);\n    this.sourcePath = pattern.substring(0, last + i);\n\n    if (search.length > 0) {\n      last = 0;\n      while ((m = searchPlaceholder.exec(search))) {\n        p = matchDetails(m, true);\n        param = addParameter(p.id, p.type, p.cfg, \"search\");\n        last = placeholder.lastIndex;\n        // check if ?&\n      }\n    }\n  } else {\n    this.sourcePath = pattern;\n    this.sourceSearch = '';\n  }\n\n  compiled += quoteRegExp(segment) + (config.strict === false ? '\\/?' : '') + '$';\n  segments.push(segment);\n\n  this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);\n  this.prefix = segments[0];\n  this.$$paramNames = paramNames;\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#concat\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns a new matcher for a pattern constructed by appending the path part and adding the\n * search parameters of the specified pattern to this pattern. The current pattern is not\n * modified. This can be understood as creating a pattern for URLs that are relative to (or\n * suffixes of) the current pattern.\n *\n * @example\n * The following two matchers are equivalent:\n * <pre>\n * new UrlMatcher('/user/{id}?q').concat('/details?date');\n * new UrlMatcher('/user/{id}/details?q&date');\n * </pre>\n *\n * @param {string} pattern  The pattern to append.\n * @param {Object} config  An object hash of the configuration for the matcher.\n * @returns {UrlMatcher}  A matcher for the concatenated pattern.\n */\nUrlMatcher.prototype.concat = function (pattern, config) {\n  // Because order of search parameters is irrelevant, we can add our own search\n  // parameters to the end of the new pattern. Parse the new pattern by itself\n  // and then join the bits together, but it's much easier to do this on a string level.\n  var defaultConfig = {\n    caseInsensitive: $$UMFP.caseInsensitive(),\n    strict: $$UMFP.strictMode(),\n    squash: $$UMFP.defaultSquashPolicy()\n  };\n  return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);\n};\n\nUrlMatcher.prototype.toString = function () {\n  return this.source;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#exec\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Tests the specified path against this matcher, and returns an object containing the captured\n * parameter values, or null if the path does not match. The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `searchParams`. This means that search parameters are always treated\n * as optional.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n *   x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * </pre>\n *\n * @param {string} path  The URL path to match, e.g. `$location.path()`.\n * @param {Object} searchParams  URL search parameters, e.g. `$location.search()`.\n * @returns {Object}  The captured parameter values.\n */\nUrlMatcher.prototype.exec = function (path, searchParams) {\n  var m = this.regexp.exec(path);\n  if (!m) return null;\n  searchParams = searchParams || {};\n\n  var paramNames = this.parameters(), nTotal = paramNames.length,\n    nPath = this.segments.length - 1,\n    values = {}, i, j, cfg, paramName;\n\n  if (nPath !== m.length - 1) throw new Error(\"Unbalanced capture group in route '\" + this.source + \"'\");\n\n  function decodePathArray(string) {\n    function reverseString(str) { return str.split(\"\").reverse().join(\"\"); }\n    function unquoteDashes(str) { return str.replace(/\\\\-/, \"-\"); }\n\n    var split = reverseString(string).split(/-(?!\\\\)/);\n    var allReversed = map(split, reverseString);\n    return map(allReversed, unquoteDashes).reverse();\n  }\n\n  for (i = 0; i < nPath; i++) {\n    paramName = paramNames[i];\n    var param = this.params[paramName];\n    var paramVal = m[i+1];\n    // if the param value matches a pre-replace pair, replace the value before decoding.\n    for (j = 0; j < param.replace; j++) {\n      if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;\n    }\n    if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);\n    values[paramName] = param.value(paramVal);\n  }\n  for (/**/; i < nTotal; i++) {\n    paramName = paramNames[i];\n    values[paramName] = this.params[paramName].value(searchParams[paramName]);\n  }\n\n  return values;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#parameters\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns the names of all path and search parameters of this pattern in an unspecified order.\n * \n * @returns {Array.<string>}  An array of parameter names. Must be treated as read-only. If the\n *    pattern has no parameters, an empty array is returned.\n */\nUrlMatcher.prototype.parameters = function (param) {\n  if (!isDefined(param)) return this.$$paramNames;\n  return this.params[param] || null;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#validate\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param {Object} params The object hash of parameters to validate.\n * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.\n */\nUrlMatcher.prototype.validates = function (params) {\n  return this.params.$$validates(params);\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#format\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters. Null values for path parameters are\n * treated as empty strings.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * </pre>\n *\n * @param {Object} values  the values to substitute for the parameters in this pattern.\n * @returns {string}  the formatted URL (path and optionally search part).\n */\nUrlMatcher.prototype.format = function (values) {\n  values = values || {};\n  var segments = this.segments, params = this.parameters(), paramset = this.params;\n  if (!this.validates(values)) return null;\n\n  var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];\n\n  function encodeDashes(str) { // Replace dashes with encoded \"\\-\"\n    return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });\n  }\n\n  for (i = 0; i < nTotal; i++) {\n    var isPathParam = i < nPath;\n    var name = params[i], param = paramset[name], value = param.value(values[name]);\n    var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);\n    var squash = isDefaultValue ? param.squash : false;\n    var encoded = param.type.encode(value);\n\n    if (isPathParam) {\n      var nextSegment = segments[i + 1];\n      if (squash === false) {\n        if (encoded != null) {\n          if (isArray(encoded)) {\n            result += map(encoded, encodeDashes).join(\"-\");\n          } else {\n            result += encodeURIComponent(encoded);\n          }\n        }\n        result += nextSegment;\n      } else if (squash === true) {\n        var capture = result.match(/\\/$/) ? /\\/?(.*)/ : /(.*)/;\n        result += nextSegment.match(capture)[1];\n      } else if (isString(squash)) {\n        result += squash + nextSegment;\n      }\n    } else {\n      if (encoded == null || (isDefaultValue && squash !== false)) continue;\n      if (!isArray(encoded)) encoded = [ encoded ];\n      encoded = map(encoded, encodeURIComponent).join('&' + name + '=');\n      result += (search ? '&' : '?') + (name + '=' + encoded);\n      search = true;\n    }\n  }\n\n  return result;\n};\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:Type\n *\n * @description\n * Implements an interface to define custom parameter types that can be decoded from and encoded to\n * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}\n * objects when matching or formatting URLs, or comparing or validating parameter values.\n *\n * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more\n * information on registering custom types.\n *\n * @param {Object} config  A configuration object which contains the custom type definition.  The object's\n *        properties will override the default methods and/or pattern in `Type`'s public interface.\n * @example\n * <pre>\n * {\n *   decode: function(val) { return parseInt(val, 10); },\n *   encode: function(val) { return val && val.toString(); },\n *   equals: function(a, b) { return this.is(a) && a === b; },\n *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },\n *   pattern: /\\d+/\n * }\n * </pre>\n *\n * @property {RegExp} pattern The regular expression pattern used to match values of this type when\n *           coming from a substring of a URL.\n *\n * @returns {Object}  Returns a new `Type` object.\n */\nfunction Type(config) {\n  extend(this, config);\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#is\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Detects whether a value is of a particular type. Accepts a native (decoded) value\n * and determines whether it matches the current `Type` object.\n *\n * @param {*} val  The value to check.\n * @param {string} key  Optional. If the type check is happening in the context of a specific\n *        {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the\n *        parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.\n * @returns {Boolean}  Returns `true` if the value matches the type, otherwise `false`.\n */\nType.prototype.is = function(val, key) {\n  return true;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#encode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the\n * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it\n * only needs to be a representation of `val` that has been coerced to a string.\n *\n * @param {*} val  The value to encode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {string}  Returns a string representation of `val` that can be encoded in a URL.\n */\nType.prototype.encode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#decode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Converts a parameter value (from URL string or transition param) to a custom/native value.\n *\n * @param {string} val  The URL parameter value to decode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {*}  Returns a custom representation of the URL parameter value.\n */\nType.prototype.decode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#equals\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Determines whether two decoded values are equivalent.\n *\n * @param {*} a  A value to compare against.\n * @param {*} b  A value to compare against.\n * @returns {Boolean}  Returns `true` if the values are equivalent/equal, otherwise `false`.\n */\nType.prototype.equals = function(a, b) {\n  return a == b;\n};\n\nType.prototype.$subPattern = function() {\n  var sub = this.pattern.toString();\n  return sub.substr(1, sub.length - 2);\n};\n\nType.prototype.pattern = /.*/;\n\nType.prototype.toString = function() { return \"{Type:\" + this.name + \"}\"; };\n\n/*\n * Wraps an existing custom Type as an array of Type, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\nType.prototype.$asArray = function(mode, isSearch) {\n  if (!mode) return this;\n  if (mode === \"auto\" && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n  return new ArrayType(this, mode);\n\n  function ArrayType(type, mode) {\n    function bindTo(type, callbackName) {\n      return function() {\n        return type[callbackName].apply(type, arguments);\n      };\n    }\n\n    // Wrap non-array value as array\n    function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }\n    // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n    function arrayUnwrap(val) {\n      switch(val.length) {\n        case 0: return undefined;\n        case 1: return mode === \"auto\" ? val[0] : val;\n        default: return val;\n      }\n    }\n    function falsey(val) { return !val; }\n\n    // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n    function arrayHandler(callback, allTruthyMode) {\n      return function handleArray(val) {\n        val = arrayWrap(val);\n        var result = map(val, callback);\n        if (allTruthyMode === true)\n          return filter(result, falsey).length === 0;\n        return arrayUnwrap(result);\n      };\n    }\n\n    // Wraps type (.equals) functions to operate on each value of an array\n    function arrayEqualsHandler(callback) {\n      return function handleArray(val1, val2) {\n        var left = arrayWrap(val1), right = arrayWrap(val2);\n        if (left.length !== right.length) return false;\n        for (var i = 0; i < left.length; i++) {\n          if (!callback(left[i], right[i])) return false;\n        }\n        return true;\n      };\n    }\n\n    this.encode = arrayHandler(bindTo(type, 'encode'));\n    this.decode = arrayHandler(bindTo(type, 'decode'));\n    this.is     = arrayHandler(bindTo(type, 'is'), true);\n    this.equals = arrayEqualsHandler(bindTo(type, 'equals'));\n    this.pattern = type.pattern;\n    this.$arrayMode = mode;\n  }\n};\n\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$urlMatcherFactory\n *\n * @description\n * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory\n * is also available to providers under the name `$urlMatcherFactoryProvider`.\n */\nfunction $UrlMatcherFactory() {\n  $$UMFP = this;\n\n  var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;\n\n  function valToString(val) { return val != null ? val.toString().replace(/\\//g, \"%2F\") : val; }\n  function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, \"/\") : val; }\n//  TODO: in 1.0, make string .is() return false if value is undefined by default.\n//  function regexpMatches(val) { /*jshint validthis:true */ return isDefined(val) && this.pattern.test(val); }\n  function regexpMatches(val) { /*jshint validthis:true */ return this.pattern.test(val); }\n\n  var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {\n    string: {\n      encode: valToString,\n      decode: valFromString,\n      is: regexpMatches,\n      pattern: /[^/]*/\n    },\n    int: {\n      encode: valToString,\n      decode: function(val) { return parseInt(val, 10); },\n      is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },\n      pattern: /\\d+/\n    },\n    bool: {\n      encode: function(val) { return val ? 1 : 0; },\n      decode: function(val) { return parseInt(val, 10) !== 0; },\n      is: function(val) { return val === true || val === false; },\n      pattern: /0|1/\n    },\n    date: {\n      encode: function (val) {\n        if (!this.is(val))\n          return undefined;\n        return [ val.getFullYear(),\n          ('0' + (val.getMonth() + 1)).slice(-2),\n          ('0' + val.getDate()).slice(-2)\n        ].join(\"-\");\n      },\n      decode: function (val) {\n        if (this.is(val)) return val;\n        var match = this.capture.exec(val);\n        return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n      },\n      is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },\n      equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },\n      pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n      capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/\n    },\n    json: {\n      encode: angular.toJson,\n      decode: angular.fromJson,\n      is: angular.isObject,\n      equals: angular.equals,\n      pattern: /[^/]*/\n    },\n    any: { // does not encode/decode\n      encode: angular.identity,\n      decode: angular.identity,\n      is: angular.identity,\n      equals: angular.equals,\n      pattern: /.*/\n    }\n  };\n\n  function getDefaultConfig() {\n    return {\n      strict: isStrictMode,\n      caseInsensitive: isCaseInsensitive\n    };\n  }\n\n  function isInjectable(value) {\n    return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));\n  }\n\n  /**\n   * [Internal] Get the default value of a parameter, which may be an injectable function.\n   */\n  $UrlMatcherFactory.$$getDefaultValue = function(config) {\n    if (!isInjectable(config.value)) return config.value;\n    if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n    return injector.invoke(config.value);\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#caseInsensitive\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URL matching should be case sensitive (the default behavior), or not.\n   *\n   * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;\n   * @returns {boolean} the current value of caseInsensitive\n   */\n  this.caseInsensitive = function(value) {\n    if (isDefined(value))\n      isCaseInsensitive = value;\n    return isCaseInsensitive;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#strictMode\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URLs should match trailing slashes, or not (the default behavior).\n   *\n   * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.\n   * @returns {boolean} the current value of strictMode\n   */\n  this.strictMode = function(value) {\n    if (isDefined(value))\n      isStrictMode = value;\n    return isStrictMode;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Sets the default behavior when generating or matching URLs with default parameter values.\n   *\n   * @param {string} value A string that defines the default parameter URL squashing behavior.\n   *    `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL\n   *    `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the\n   *             parameter is surrounded by slashes, squash (remove) one slash from the URL\n   *    any other string, e.g. \"~\": When generating an href with a default parameter value, squash (remove)\n   *             the parameter value from the URL and replace it with this string.\n   */\n  this.defaultSquashPolicy = function(value) {\n    if (!isDefined(value)) return defaultSquashPolicy;\n    if (value !== true && value !== false && !isString(value))\n      throw new Error(\"Invalid squash policy: \" + value + \". Valid policies: false, true, arbitrary-string\");\n    defaultSquashPolicy = value;\n    return value;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#compile\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.\n   *\n   * @param {string} pattern  The URL pattern.\n   * @param {Object} config  The config object hash.\n   * @returns {UrlMatcher}  The UrlMatcher.\n   */\n  this.compile = function (pattern, config) {\n    return new UrlMatcher(pattern, extend(getDefaultConfig(), config));\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#isMatcher\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Returns true if the specified object is a `UrlMatcher`, or false otherwise.\n   *\n   * @param {Object} object  The object to perform the type check against.\n   * @returns {Boolean}  Returns `true` if the object matches the `UrlMatcher` interface, by\n   *          implementing all the same methods.\n   */\n  this.isMatcher = function (o) {\n    if (!isObject(o)) return false;\n    var result = true;\n\n    forEach(UrlMatcher.prototype, function(val, name) {\n      if (isFunction(val)) {\n        result = result && (isDefined(o[name]) && isFunction(o[name]));\n      }\n    });\n    return result;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#type\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to\n   * generate URLs with typed parameters.\n   *\n   * @param {string} name  The type name.\n   * @param {Object|Function} definition   The type definition. See\n   *        {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   * @param {Object|Function} definitionFn (optional) A function that is injected before the app\n   *        runtime starts.  The result of this function is merged into the existing `definition`.\n   *        See {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   *\n   * @returns {Object}  Returns `$urlMatcherFactoryProvider`.\n   *\n   * @example\n   * This is a simple example of a custom type that encodes and decodes items from an\n   * array, using the array index as the URL-encoded value:\n   *\n   * <pre>\n   * var list = ['John', 'Paul', 'George', 'Ringo'];\n   *\n   * $urlMatcherFactoryProvider.type('listItem', {\n   *   encode: function(item) {\n   *     // Represent the list item in the URL using its corresponding index\n   *     return list.indexOf(item);\n   *   },\n   *   decode: function(item) {\n   *     // Look up the list item by index\n   *     return list[parseInt(item, 10)];\n   *   },\n   *   is: function(item) {\n   *     // Ensure the item is valid by checking to see that it appears\n   *     // in the list\n   *     return list.indexOf(item) > -1;\n   *   }\n   * });\n   *\n   * $stateProvider.state('list', {\n   *   url: \"/list/{item:listItem}\",\n   *   controller: function($scope, $stateParams) {\n   *     console.log($stateParams.item);\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * // Changes URL to '/list/3', logs \"Ringo\" to the console\n   * $state.go('list', { item: \"Ringo\" });\n   * </pre>\n   *\n   * This is a more complex example of a type that relies on dependency injection to\n   * interact with services, and uses the parameter name from the URL to infer how to\n   * handle encoding and decoding parameter values:\n   *\n   * <pre>\n   * // Defines a custom type that gets a value from a service,\n   * // where each service gets different types of values from\n   * // a backend API:\n   * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {\n   *\n   *   // Matches up services to URL parameter names\n   *   var services = {\n   *     user: Users,\n   *     post: Posts\n   *   };\n   *\n   *   return {\n   *     encode: function(object) {\n   *       // Represent the object in the URL using its unique ID\n   *       return object.id;\n   *     },\n   *     decode: function(value, key) {\n   *       // Look up the object by ID, using the parameter\n   *       // name (key) to call the correct service\n   *       return services[key].findById(value);\n   *     },\n   *     is: function(object, key) {\n   *       // Check that object is a valid dbObject\n   *       return angular.isObject(object) && object.id && services[key];\n   *     }\n   *     equals: function(a, b) {\n   *       // Check the equality of decoded objects by comparing\n   *       // their unique IDs\n   *       return a.id === b.id;\n   *     }\n   *   };\n   * });\n   *\n   * // In a config() block, you can then attach URLs with\n   * // type-annotated parameters:\n   * $stateProvider.state('users', {\n   *   url: \"/users\",\n   *   // ...\n   * }).state('users.item', {\n   *   url: \"/{user:dbObject}\",\n   *   controller: function($scope, $stateParams) {\n   *     // $stateParams.user will now be an object returned from\n   *     // the Users service\n   *   },\n   *   // ...\n   * });\n   * </pre>\n   */\n  this.type = function (name, definition, definitionFn) {\n    if (!isDefined(definition)) return $types[name];\n    if ($types.hasOwnProperty(name)) throw new Error(\"A type named '\" + name + \"' has already been defined.\");\n\n    $types[name] = new Type(extend({ name: name }, definition));\n    if (definitionFn) {\n      typeQueue.push({ name: name, def: definitionFn });\n      if (!enqueue) flushTypeQueue();\n    }\n    return this;\n  };\n\n  // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s\n  function flushTypeQueue() {\n    while(typeQueue.length) {\n      var type = typeQueue.shift();\n      if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n      angular.extend($types[type.name], injector.invoke(type.def));\n    }\n  }\n\n  // Register default types. Store them in the prototype of $types.\n  forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });\n  $types = inherit($types, {});\n\n  /* No need to document $get, since it returns this */\n  this.$get = ['$injector', function ($injector) {\n    injector = $injector;\n    enqueue = false;\n    flushTypeQueue();\n\n    forEach(defaultTypes, function(type, name) {\n      if (!$types[name]) $types[name] = new Type(type);\n    });\n    return this;\n  }];\n\n  this.Param = function Param(id, type, config, location) {\n    var self = this;\n    config = unwrapShorthand(config);\n    type = getType(config, type, location);\n    var arrayMode = getArrayMode();\n    type = arrayMode ? type.$asArray(arrayMode, location === \"search\") : type;\n    if (type.name === \"string\" && !arrayMode && location === \"path\" && config.value === undefined)\n      config.value = \"\"; // for 0.2.x; in 0.3.0+ do not automatically default to \"\"\n    var isOptional = config.value !== undefined;\n    var squash = getSquashPolicy(config, isOptional);\n    var replace = getReplace(config, arrayMode, isOptional, squash);\n\n    function unwrapShorthand(config) {\n      var keys = isObject(config) ? objectKeys(config) : [];\n      var isShorthand = indexOf(keys, \"value\") === -1 && indexOf(keys, \"type\") === -1 &&\n                        indexOf(keys, \"squash\") === -1 && indexOf(keys, \"array\") === -1;\n      if (isShorthand) config = { value: config };\n      config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };\n      return config;\n    }\n\n    function getType(config, urlType, location) {\n      if (config.type && urlType) throw new Error(\"Param '\"+id+\"' has two type configurations.\");\n      if (urlType) return urlType;\n      if (!config.type) return (location === \"config\" ? $types.any : $types.string);\n      return config.type instanceof Type ? config.type : new Type(config.type);\n    }\n\n    // array config: param name (param[]) overrides default settings.  explicit config overrides param name.\n    function getArrayMode() {\n      var arrayDefaults = { array: (location === \"search\" ? \"auto\" : false) };\n      var arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n      return extend(arrayDefaults, arrayParamNomenclature, config).array;\n    }\n\n    /**\n     * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n     */\n    function getSquashPolicy(config, isOptional) {\n      var squash = config.squash;\n      if (!isOptional || squash === false) return false;\n      if (!isDefined(squash) || squash == null) return defaultSquashPolicy;\n      if (squash === true || isString(squash)) return squash;\n      throw new Error(\"Invalid squash policy: '\" + squash + \"'. Valid policies: false, true, or arbitrary string\");\n    }\n\n    function getReplace(config, arrayMode, isOptional, squash) {\n      var replace, configuredKeys, defaultPolicy = [\n        { from: \"\",   to: (isOptional || arrayMode ? undefined : \"\") },\n        { from: null, to: (isOptional || arrayMode ? undefined : \"\") }\n      ];\n      replace = isArray(config.replace) ? config.replace : [];\n      if (isString(squash))\n        replace.push({ from: squash, to: undefined });\n      configuredKeys = map(replace, function(item) { return item.from; } );\n      return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);\n    }\n\n    /**\n     * [Internal] Get the default value of a parameter, which may be an injectable function.\n     */\n    function $$getDefaultValue() {\n      if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n      return injector.invoke(config.$$fn);\n    }\n\n    /**\n     * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n     * default value, which may be the result of an injectable function.\n     */\n    function $value(value) {\n      function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }\n      function $replace(value) {\n        var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });\n        return replacement.length ? replacement[0] : value;\n      }\n      value = $replace(value);\n      return isDefined(value) ? self.type.decode(value) : $$getDefaultValue();\n    }\n\n    function toString() { return \"{Param:\" + id + \" \" + type + \" squash: '\" + squash + \"' optional: \" + isOptional + \"}\"; }\n\n    extend(this, {\n      id: id,\n      type: type,\n      location: location,\n      array: arrayMode,\n      squash: squash,\n      replace: replace,\n      isOptional: isOptional,\n      value: $value,\n      dynamic: undefined,\n      config: config,\n      toString: toString\n    });\n  };\n\n  function ParamSet(params) {\n    extend(this, params || {});\n  }\n\n  ParamSet.prototype = {\n    $$new: function() {\n      return inherit(this, extend(new ParamSet(), { $$parent: this}));\n    },\n    $$keys: function () {\n      var keys = [], chain = [], parent = this,\n        ignore = objectKeys(ParamSet.prototype);\n      while (parent) { chain.push(parent); parent = parent.$$parent; }\n      chain.reverse();\n      forEach(chain, function(paramset) {\n        forEach(objectKeys(paramset), function(key) {\n            if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);\n        });\n      });\n      return keys;\n    },\n    $$values: function(paramValues) {\n      var values = {}, self = this;\n      forEach(self.$$keys(), function(key) {\n        values[key] = self[key].value(paramValues && paramValues[key]);\n      });\n      return values;\n    },\n    $$equals: function(paramValues1, paramValues2) {\n      var equal = true, self = this;\n      forEach(self.$$keys(), function(key) {\n        var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];\n        if (!self[key].type.equals(left, right)) equal = false;\n      });\n      return equal;\n    },\n    $$validates: function $$validate(paramValues) {\n      var result = true, isOptional, val, param, self = this;\n\n      forEach(this.$$keys(), function(key) {\n        param = self[key];\n        val = paramValues[key];\n        isOptional = !val && param.isOptional;\n        result = result && (isOptional || !!param.type.is(val));\n      });\n      return result;\n    },\n    $$parent: undefined\n  };\n\n  this.ParamSet = ParamSet;\n}\n\n// Register as a provider so it's available to other providers\nangular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);\nangular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);\n\n/**\n * @ngdoc object\n * @name ui.router.router.$urlRouterProvider\n *\n * @requires ui.router.util.$urlMatcherFactoryProvider\n * @requires $locationProvider\n *\n * @description\n * `$urlRouterProvider` has the responsibility of watching `$location`. \n * When `$location` changes it runs through a list of rules one by one until a \n * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify \n * a url in a state configuration. All urls are compiled into a UrlMatcher object.\n *\n * There are several methods on `$urlRouterProvider` that make it useful to use directly\n * in your module config.\n */\n$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];\nfunction $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {\n  var rules = [], otherwise = null, interceptDeferred = false, listener;\n\n  // Returns a string that is a prefix of all strings matching the RegExp\n  function regExpPrefix(re) {\n    var prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\n    return (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\n  }\n\n  // Interpolates matched values into a String.replace()-style pattern\n  function interpolate(pattern, match) {\n    return pattern.replace(/\\$(\\$|\\d{1,2})/, function (m, what) {\n      return match[what === '$' ? 0 : Number(what)];\n    });\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#rule\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines rules that are used by `$urlRouterProvider` to find matches for\n   * specific URLs.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // Here's an example of how you might allow case insensitive urls\n   *   $urlRouterProvider.rule(function ($injector, $location) {\n   *     var path = $location.path(),\n   *         normalized = path.toLowerCase();\n   *\n   *     if (path !== normalized) {\n   *       return normalized;\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {object} rule Handler function that takes `$injector` and `$location`\n   * services as arguments. You can use them to return a valid path as a string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.rule = function (rule) {\n    if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    rules.push(rule);\n    return this;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouterProvider#otherwise\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines a path that is used when an invalid route is requested.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // if the path doesn't match any of the urls you configured\n   *   // otherwise will take care of routing the user to the\n   *   // specified url\n   *   $urlRouterProvider.otherwise('/index');\n   *\n   *   // Example of using function rule as param\n   *   $urlRouterProvider.otherwise(function ($injector, $location) {\n   *     return '/a/valid/url';\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} rule The url path you want to redirect to or a function \n   * rule that returns the url path. The function version is passed two params: \n   * `$injector` and `$location` services, and must return a url string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.otherwise = function (rule) {\n    if (isString(rule)) {\n      var redirect = rule;\n      rule = function () { return redirect; };\n    }\n    else if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    otherwise = rule;\n    return this;\n  };\n\n\n  function handleIfMatch($injector, handler, match) {\n    if (!match) return false;\n    var result = $injector.invoke(handler, handler, { $match: match });\n    return isDefined(result) ? result : true;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#when\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Registers a handler for a given url matching. if handle is a string, it is\n   * treated as a redirect, and is interpolated according to the syntax of match\n   * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n   *\n   * If the handler is a function, it is injectable. It gets invoked if `$location`\n   * matches. You have the option of inject the match object as `$match`.\n   *\n   * The handler can return\n   *\n   * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n   *   will continue trying to find another one that matches.\n   * - **string** which is treated as a redirect and passed to `$location.url()`\n   * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n   *     if ($state.$current.navigable !== state ||\n   *         !equalForKeys($match, $stateParams) {\n   *      $state.transitionTo(state, $match, false);\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} what The incoming path that you want to redirect.\n   * @param {string|object} handler The path you want to redirect your user to.\n   */\n  this.when = function (what, handler) {\n    var redirect, handlerIsString = isString(handler);\n    if (isString(what)) what = $urlMatcherFactory.compile(what);\n\n    if (!handlerIsString && !isFunction(handler) && !isArray(handler))\n      throw new Error(\"invalid 'handler' in when()\");\n\n    var strategies = {\n      matcher: function (what, handler) {\n        if (handlerIsString) {\n          redirect = $urlMatcherFactory.compile(handler);\n          handler = ['$match', function ($match) { return redirect.format($match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));\n        }, {\n          prefix: isString(what.prefix) ? what.prefix : ''\n        });\n      },\n      regex: function (what, handler) {\n        if (what.global || what.sticky) throw new Error(\"when() RegExp must not be global or sticky\");\n\n        if (handlerIsString) {\n          redirect = handler;\n          handler = ['$match', function ($match) { return interpolate(redirect, $match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path()));\n        }, {\n          prefix: regExpPrefix(what)\n        });\n      }\n    };\n\n    var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };\n\n    for (var n in check) {\n      if (check[n]) return this.rule(strategies[n](what, handler));\n    }\n\n    throw new Error(\"invalid 'what' in when()\");\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#deferIntercept\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Disables (or enables) deferring location change interception.\n   *\n   * If you wish to customize the behavior of syncing the URL (for example, if you wish to\n   * defer a transition but maintain the current URL), call this method at configuration time.\n   * Then, at run time, call `$urlRouter.listen()` after you have configured your own\n   * `$locationChangeSuccess` event handler.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *\n   *   // Prevent $urlRouter from automatically intercepting URL changes;\n   *   // this allows you to configure custom behavior in between\n   *   // location changes and route synchronization:\n   *   $urlRouterProvider.deferIntercept();\n   *\n   * }).run(function ($rootScope, $urlRouter, UserService) {\n   *\n   *   $rootScope.$on('$locationChangeSuccess', function(e) {\n   *     // UserService is an example service for managing user state\n   *     if (UserService.isLoggedIn()) return;\n   *\n   *     // Prevent $urlRouter's default handler from firing\n   *     e.preventDefault();\n   *\n   *     UserService.handleLogin().then(function() {\n   *       // Once the user has logged in, sync the current URL\n   *       // to the router:\n   *       $urlRouter.sync();\n   *     });\n   *   });\n   *\n   *   // Configures $urlRouter's listener *after* your custom listener\n   *   $urlRouter.listen();\n   * });\n   * </pre>\n   *\n   * @param {boolean} defer Indicates whether to defer location change interception. Passing\n            no parameter is equivalent to `true`.\n   */\n  this.deferIntercept = function (defer) {\n    if (defer === undefined) defer = true;\n    interceptDeferred = defer;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouter\n   *\n   * @requires $location\n   * @requires $rootScope\n   * @requires $injector\n   * @requires $browser\n   *\n   * @description\n   *\n   */\n  this.$get = $get;\n  $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];\n  function $get(   $location,   $rootScope,   $injector,   $browser) {\n\n    var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;\n\n    function appendBasePath(url, isHtml5, absolute) {\n      if (baseHref === '/') return url;\n      if (isHtml5) return baseHref.slice(0, -1) + url;\n      if (absolute) return baseHref.slice(1) + url;\n      return url;\n    }\n\n    // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree\n    function update(evt) {\n      if (evt && evt.defaultPrevented) return;\n      var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;\n      lastPushedUrl = undefined;\n      if (ignoreUpdate) return true;\n\n      function check(rule) {\n        var handled = rule($injector, $location);\n\n        if (!handled) return false;\n        if (isString(handled)) $location.replace().url(handled);\n        return true;\n      }\n      var n = rules.length, i;\n\n      for (i = 0; i < n; i++) {\n        if (check(rules[i])) return;\n      }\n      // always check otherwise last to allow dynamic updates to the set of rules\n      if (otherwise) check(otherwise);\n    }\n\n    function listen() {\n      listener = listener || $rootScope.$on('$locationChangeSuccess', update);\n      return listener;\n    }\n\n    if (!interceptDeferred) listen();\n\n    return {\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#sync\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.\n       * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,\n       * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed\n       * with the transition by calling `$urlRouter.sync()`.\n       *\n       * @example\n       * <pre>\n       * angular.module('app', ['ui.router'])\n       *   .run(function($rootScope, $urlRouter) {\n       *     $rootScope.$on('$locationChangeSuccess', function(evt) {\n       *       // Halt state change from even starting\n       *       evt.preventDefault();\n       *       // Perform custom logic\n       *       var meetsRequirement = ...\n       *       // Continue with the update and state transition if logic allows\n       *       if (meetsRequirement) $urlRouter.sync();\n       *     });\n       * });\n       * </pre>\n       */\n      sync: function() {\n        update();\n      },\n\n      listen: function() {\n        return listen();\n      },\n\n      update: function(read) {\n        if (read) {\n          location = $location.url();\n          return;\n        }\n        if ($location.url() === location) return;\n\n        $location.url(location);\n        $location.replace();\n      },\n\n      push: function(urlMatcher, params, options) {\n        $location.url(urlMatcher.format(params || {}));\n        lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;\n        if (options && options.replace) $location.replace();\n      },\n\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#href\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * A URL generation method that returns the compiled URL for a given\n       * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.\n       *\n       * @example\n       * <pre>\n       * $bob = $urlRouter.href(new UrlMatcher(\"/about/:person\"), {\n       *   person: \"bob\"\n       * });\n       * // $bob == \"/about/bob\";\n       * </pre>\n       *\n       * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.\n       * @param {object=} params An object of parameter values to fill the matcher's required parameters.\n       * @param {object=} options Options object. The options are:\n       *\n       * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n       *\n       * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n       */\n      href: function(urlMatcher, params, options) {\n        if (!urlMatcher.validates(params)) return null;\n\n        var isHtml5 = $locationProvider.html5Mode();\n        if (angular.isObject(isHtml5)) {\n          isHtml5 = isHtml5.enabled;\n        }\n        \n        var url = urlMatcher.format(params);\n        options = options || {};\n\n        if (!isHtml5 && url !== null) {\n          url = \"#\" + $locationProvider.hashPrefix() + url;\n        }\n        url = appendBasePath(url, isHtml5, options.absolute);\n\n        if (!options.absolute || !url) {\n          return url;\n        }\n\n        var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();\n        port = (port === 80 || port === 443 ? '' : ':' + port);\n\n        return [$location.protocol(), '://', $location.host(), port, slash, url].join('');\n      }\n    };\n  }\n}\n\nangular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$stateProvider\n *\n * @requires ui.router.router.$urlRouterProvider\n * @requires ui.router.util.$urlMatcherFactoryProvider\n *\n * @description\n * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\n$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];\nfunction $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {\n\n  var root, states = {}, $state, queue = {}, abstractKey = 'abstract';\n\n  // Builds state properties from definition passed to registerState()\n  var stateBuilder = {\n\n    // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.\n    // state.children = [];\n    // if (parent) parent.children.push(state);\n    parent: function(state) {\n      if (isDefined(state.parent) && state.parent) return findState(state.parent);\n      // regex matches any valid composite state name\n      // would match \"contact.list\" but not \"contacts\"\n      var compositeName = /^(.+)\\.[^.]+$/.exec(state.name);\n      return compositeName ? findState(compositeName[1]) : root;\n    },\n\n    // inherit 'data' from parent and override by own values (if any)\n    data: function(state) {\n      if (state.parent && state.parent.data) {\n        state.data = state.self.data = extend({}, state.parent.data, state.data);\n      }\n      return state.data;\n    },\n\n    // Build a URLMatcher if necessary, either via a relative or absolute URL\n    url: function(state) {\n      var url = state.url, config = { params: state.params || {} };\n\n      if (isString(url)) {\n        if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);\n        return (state.parent.navigable || root).url.concat(url, config);\n      }\n\n      if (!url || $urlMatcherFactory.isMatcher(url)) return url;\n      throw new Error(\"Invalid url '\" + url + \"' in state '\" + state + \"'\");\n    },\n\n    // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n    navigable: function(state) {\n      return state.url ? state : (state.parent ? state.parent.navigable : null);\n    },\n\n    // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params\n    ownParams: function(state) {\n      var params = state.url && state.url.params || new $$UMFP.ParamSet();\n      forEach(state.params || {}, function(config, id) {\n        if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, \"config\");\n      });\n      return params;\n    },\n\n    // Derive parameters for this state and ensure they're a super-set of parent's parameters\n    params: function(state) {\n      return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();\n    },\n\n    // If there is no explicit multi-view configuration, make one up so we don't have\n    // to handle both cases in the view directive later. Note that having an explicit\n    // 'views' property will mean the default unnamed view properties are ignored. This\n    // is also a good time to resolve view names to absolute names, so everything is a\n    // straight lookup at link time.\n    views: function(state) {\n      var views = {};\n\n      forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {\n        if (name.indexOf('@') < 0) name += '@' + state.parent.name;\n        views[name] = view;\n      });\n      return views;\n    },\n\n    // Keep a full path from the root down to this state as this is needed for state activation.\n    path: function(state) {\n      return state.parent ? state.parent.path.concat(state) : []; // exclude root from path\n    },\n\n    // Speed up $state.contains() as it's used a lot\n    includes: function(state) {\n      var includes = state.parent ? extend({}, state.parent.includes) : {};\n      includes[state.name] = true;\n      return includes;\n    },\n\n    $delegates: {}\n  };\n\n  function isRelative(stateName) {\n    return stateName.indexOf(\".\") === 0 || stateName.indexOf(\"^\") === 0;\n  }\n\n  function findState(stateOrName, base) {\n    if (!stateOrName) return undefined;\n\n    var isStr = isString(stateOrName),\n        name  = isStr ? stateOrName : stateOrName.name,\n        path  = isRelative(name);\n\n    if (path) {\n      if (!base) throw new Error(\"No reference point given for path '\"  + name + \"'\");\n      base = findState(base);\n      \n      var rel = name.split(\".\"), i = 0, pathLength = rel.length, current = base;\n\n      for (; i < pathLength; i++) {\n        if (rel[i] === \"\" && i === 0) {\n          current = base;\n          continue;\n        }\n        if (rel[i] === \"^\") {\n          if (!current.parent) throw new Error(\"Path '\" + name + \"' not valid for state '\" + base.name + \"'\");\n          current = current.parent;\n          continue;\n        }\n        break;\n      }\n      rel = rel.slice(i).join(\".\");\n      name = current.name + (current.name && rel ? \".\" : \"\") + rel;\n    }\n    var state = states[name];\n\n    if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n      return state;\n    }\n    return undefined;\n  }\n\n  function queueState(parentName, state) {\n    if (!queue[parentName]) {\n      queue[parentName] = [];\n    }\n    queue[parentName].push(state);\n  }\n\n  function flushQueuedChildren(parentName) {\n    var queued = queue[parentName] || [];\n    while(queued.length) {\n      registerState(queued.shift());\n    }\n  }\n\n  function registerState(state) {\n    // Wrap a new object around the state so we can store our private details easily.\n    state = inherit(state, {\n      self: state,\n      resolve: state.resolve || {},\n      toString: function() { return this.name; }\n    });\n\n    var name = state.name;\n    if (!isString(name) || name.indexOf('@') >= 0) throw new Error(\"State must have a valid name\");\n    if (states.hasOwnProperty(name)) throw new Error(\"State '\" + name + \"'' is already defined\");\n\n    // Get parent name\n    var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))\n        : (isString(state.parent)) ? state.parent\n        : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name\n        : '';\n\n    // If parent is not registered yet, add state to queue and register later\n    if (parentName && !states[parentName]) {\n      return queueState(parentName, state.self);\n    }\n\n    for (var key in stateBuilder) {\n      if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);\n    }\n    states[name] = state;\n\n    // Register the state in the global state list and with $urlRouter if necessary.\n    if (!state[abstractKey] && state.url) {\n      $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {\n        if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {\n          $state.transitionTo(state, $match, { inherit: true, location: false });\n        }\n      }]);\n    }\n\n    // Register any queued children\n    flushQueuedChildren(name);\n\n    return state;\n  }\n\n  // Checks text to see if it looks like a glob.\n  function isGlob (text) {\n    return text.indexOf('*') > -1;\n  }\n\n  // Returns true if glob matches current $state name.\n  function doesStateMatchGlob (glob) {\n    var globSegments = glob.split('.'),\n        segments = $state.$current.name.split('.');\n\n    //match greedy starts\n    if (globSegments[0] === '**') {\n       segments = segments.slice(indexOf(segments, globSegments[1]));\n       segments.unshift('**');\n    }\n    //match greedy ends\n    if (globSegments[globSegments.length - 1] === '**') {\n       segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);\n       segments.push('**');\n    }\n\n    if (globSegments.length != segments.length) {\n      return false;\n    }\n\n    //match single stars\n    for (var i = 0, l = globSegments.length; i < l; i++) {\n      if (globSegments[i] === '*') {\n        segments[i] = '*';\n      }\n    }\n\n    return segments.join('') === globSegments.join('');\n  }\n\n\n  // Implicit root state that is always active\n  root = registerState({\n    name: '',\n    url: '^',\n    views: null,\n    'abstract': true\n  });\n  root.navigable = null;\n\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#decorator\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Allows you to extend (carefully) or override (at your own peril) the \n   * `stateBuilder` object used internally by `$stateProvider`. This can be used \n   * to add custom functionality to ui-router, for example inferring templateUrl \n   * based on the state name.\n   *\n   * When passing only a name, it returns the current (original or decorated) builder\n   * function that matches `name`.\n   *\n   * The builder functions that can be decorated are listed below. Though not all\n   * necessarily have a good use case for decoration, that is up to you to decide.\n   *\n   * In addition, users can attach custom decorators, which will generate new \n   * properties within the state's internal definition. There is currently no clear \n   * use-case for this beyond accessing internal states (i.e. $state.$current), \n   * however, expect this to become increasingly relevant as we introduce additional \n   * meta-programming features.\n   *\n   * **Warning**: Decorators should not be interdependent because the order of \n   * execution of the builder functions in non-deterministic. Builder functions \n   * should only be dependent on the state definition object and super function.\n   *\n   *\n   * Existing builder functions and current return values:\n   *\n   * - **parent** `{object}` - returns the parent state object.\n   * - **data** `{object}` - returns state data, including any inherited data that is not\n   *   overridden by own values (if any).\n   * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n   *   or `null`.\n   * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is \n   *   navigable).\n   * - **params** `{object}` - returns an array of state params that are ensured to \n   *   be a super-set of parent's params.\n   * - **views** `{object}` - returns a views object where each key is an absolute view \n   *   name (i.e. \"viewName@stateName\") and each value is the config object \n   *   (template, controller) for the view. Even when you don't use the views object \n   *   explicitly on a state config, one is still created for you internally.\n   *   So by decorating this builder function you have access to decorating template \n   *   and controller properties.\n   * - **ownParams** `{object}` - returns an array of params that belong to the state, \n   *   not including any params defined by ancestor states.\n   * - **path** `{string}` - returns the full path from the root down to this state. \n   *   Needed for state activation.\n   * - **includes** `{object}` - returns an object that includes every state that \n   *   would pass a `$state.includes()` test.\n   *\n   * @example\n   * <pre>\n   * // Override the internal 'views' builder with a function that takes the state\n   * // definition, and a reference to the internal function being overridden:\n   * $stateProvider.decorator('views', function (state, parent) {\n   *   var result = {},\n   *       views = parent(state);\n   *\n   *   angular.forEach(views, function (config, name) {\n   *     var autoName = (state.name + '.' + name).replace('.', '/');\n   *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n   *     result[name] = config;\n   *   });\n   *   return result;\n   * });\n   *\n   * $stateProvider.state('home', {\n   *   views: {\n   *     'contact.list': { controller: 'ListController' },\n   *     'contact.item': { controller: 'ItemController' }\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * $state.go('home');\n   * // Auto-populates list and item views with /partials/home/contact/list.html,\n   * // and /partials/home/contact/item.html, respectively.\n   * </pre>\n   *\n   * @param {string} name The name of the builder function to decorate. \n   * @param {object} func A function that is responsible for decorating the original \n   * builder function. The function receives two parameters:\n   *\n   *   - `{object}` - state - The state config object.\n   *   - `{object}` - super - The original builder function.\n   *\n   * @return {object} $stateProvider - $stateProvider instance\n   */\n  this.decorator = decorator;\n  function decorator(name, func) {\n    /*jshint validthis: true */\n    if (isString(name) && !isDefined(func)) {\n      return stateBuilder[name];\n    }\n    if (!isFunction(func) || !isString(name)) {\n      return this;\n    }\n    if (stateBuilder[name] && !stateBuilder.$delegates[name]) {\n      stateBuilder.$delegates[name] = stateBuilder[name];\n    }\n    stateBuilder[name] = func;\n    return this;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#state\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Registers a state configuration under a given state name. The stateConfig object\n   * has the following acceptable properties.\n   *\n   * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n   * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n   * @param {object} stateConfig State configuration object.\n   * @param {string|function=} stateConfig.template\n   * <a id='template'></a>\n   *   html template as a string or a function that returns\n   *   an html template as a string which should be used by the uiView directives. This property \n   *   takes precedence over templateUrl.\n   *   \n   *   If `template` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by\n   *     applying the current state\n   *\n   * <pre>template:\n   *   \"<h1>inline template definition</h1>\" +\n   *   \"<div ui-view></div>\"</pre>\n   * <pre>template: function(params) {\n   *       return \"<h1>generated template</h1>\"; }</pre>\n   * </div>\n   *\n   * @param {string|function=} stateConfig.templateUrl\n   * <a id='templateUrl'></a>\n   *\n   *   path or function that returns a path to an html\n   *   template that should be used by uiView.\n   *   \n   *   If `templateUrl` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by \n   *     applying the current state\n   *\n   * <pre>templateUrl: \"home.html\"</pre>\n   * <pre>templateUrl: function(params) {\n   *     return myTemplates[params.pageId]; }</pre>\n   *\n   * @param {function=} stateConfig.templateProvider\n   * <a id='templateProvider'></a>\n   *    Provider function that returns HTML content string.\n   * <pre> templateProvider:\n   *       function(MyTemplateService, params) {\n   *         return MyTemplateService.getTemplate(params.pageId);\n   *       }</pre>\n   *\n   * @param {string|function=} stateConfig.controller\n   * <a id='controller'></a>\n   *\n   *  Controller fn that should be associated with newly\n   *   related scope or the name of a registered controller if passed as a string.\n   *   Optionally, the ControllerAs may be declared here.\n   * <pre>controller: \"MyRegisteredController\"</pre>\n   * <pre>controller:\n   *     \"MyRegisteredController as fooCtrl\"}</pre>\n   * <pre>controller: function($scope, MyService) {\n   *     $scope.data = MyService.getData(); }</pre>\n   *\n   * @param {function=} stateConfig.controllerProvider\n   * <a id='controllerProvider'></a>\n   *\n   * Injectable provider function that returns the actual controller or string.\n   * <pre>controllerProvider:\n   *   function(MyResolveData) {\n   *     if (MyResolveData.foo)\n   *       return \"FooCtrl\"\n   *     else if (MyResolveData.bar)\n   *       return \"BarCtrl\";\n   *     else return function($scope) {\n   *       $scope.baz = \"Qux\";\n   *     }\n   *   }</pre>\n   *\n   * @param {string=} stateConfig.controllerAs\n   * <a id='controllerAs'></a>\n   * \n   * A controller alias name. If present the controller will be\n   *   published to scope under the controllerAs name.\n   * <pre>controllerAs: \"myCtrl\"</pre>\n   *\n   * @param {object=} stateConfig.resolve\n   * <a id='resolve'></a>\n   *\n   * An optional map&lt;string, function&gt; of dependencies which\n   *   should be injected into the controller. If any of these dependencies are promises, \n   *   the router will wait for them all to be resolved before the controller is instantiated.\n   *   If all the promises are resolved successfully, the $stateChangeSuccess event is fired\n   *   and the values of the resolved promises are injected into any controllers that reference them.\n   *   If any  of the promises are rejected the $stateChangeError event is fired.\n   *\n   *   The map object is:\n   *   \n   *   - key - {string}: name of dependency to be injected into controller\n   *   - factory - {string|function}: If string then it is alias for service. Otherwise if function, \n   *     it is injected and return value it treated as dependency. If result is a promise, it is \n   *     resolved before its value is injected into controller.\n   *\n   * <pre>resolve: {\n   *     myResolve1:\n   *       function($http, $stateParams) {\n   *         return $http.get(\"/api/foos/\"+stateParams.fooID);\n   *       }\n   *     }</pre>\n   *\n   * @param {string=} stateConfig.url\n   * <a id='url'></a>\n   *\n   *   A url fragment with optional parameters. When a state is navigated or\n   *   transitioned to, the `$stateParams` service will be populated with any \n   *   parameters that were passed.\n   *\n   * examples:\n   * <pre>url: \"/home\"\n   * url: \"/users/:userid\"\n   * url: \"/books/{bookid:[a-zA-Z_-]}\"\n   * url: \"/books/{categoryid:int}\"\n   * url: \"/books/{publishername:string}/{categoryid:int}\"\n   * url: \"/messages?before&after\"\n   * url: \"/messages?{before:date}&{after:date}\"</pre>\n   * url: \"/messages/:mailboxid?{before:date}&{after:date}\"\n   *\n   * @param {object=} stateConfig.views\n   * <a id='views'></a>\n   * an optional map&lt;string, object&gt; which defined multiple views, or targets views\n   * manually/explicitly.\n   *\n   * Examples:\n   *\n   * Targets three named `ui-view`s in the parent state's template\n   * <pre>views: {\n   *     header: {\n   *       controller: \"headerCtrl\",\n   *       templateUrl: \"header.html\"\n   *     }, body: {\n   *       controller: \"bodyCtrl\",\n   *       templateUrl: \"body.html\"\n   *     }, footer: {\n   *       controller: \"footCtrl\",\n   *       templateUrl: \"footer.html\"\n   *     }\n   *   }</pre>\n   *\n   * Targets named `ui-view=\"header\"` from grandparent state 'top''s template, and named `ui-view=\"body\" from parent state's template.\n   * <pre>views: {\n   *     'header@top': {\n   *       controller: \"msgHeaderCtrl\",\n   *       templateUrl: \"msgHeader.html\"\n   *     }, 'body': {\n   *       controller: \"messagesCtrl\",\n   *       templateUrl: \"messages.html\"\n   *     }\n   *   }</pre>\n   *\n   * @param {boolean=} [stateConfig.abstract=false]\n   * <a id='abstract'></a>\n   * An abstract state will never be directly activated,\n   *   but can provide inherited properties to its common children states.\n   * <pre>abstract: true</pre>\n   *\n   * @param {function=} stateConfig.onEnter\n   * <a id='onEnter'></a>\n   *\n   * Callback function for when a state is entered. Good way\n   *   to trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onEnter: function(MyService, $stateParams) {\n   *     MyService.foo($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {function=} stateConfig.onExit\n   * <a id='onExit'></a>\n   *\n   * Callback function for when a state is exited. Good way to\n   *   trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onExit: function(MyService, $stateParams) {\n   *     MyService.cleanup($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {boolean=} [stateConfig.reloadOnSearch=true]\n   * <a id='reloadOnSearch'></a>\n   *\n   * If `false`, will not retrigger the same state\n   *   just because a search/query parameter has changed (via $location.search() or $location.hash()). \n   *   Useful for when you'd like to modify $location.search() without triggering a reload.\n   * <pre>reloadOnSearch: false</pre>\n   *\n   * @param {object=} stateConfig.data\n   * <a id='data'></a>\n   *\n   * Arbitrary data object, useful for custom configuration.  The parent state's `data` is\n   *   prototypally inherited.  In other words, adding a data property to a state adds it to\n   *   the entire subtree via prototypal inheritance.\n   *\n   * <pre>data: {\n   *     requiredRole: 'foo'\n   * } </pre>\n   *\n   * @param {object=} stateConfig.params\n   * <a id='params'></a>\n   *\n   * A map which optionally configures parameters declared in the `url`, or\n   *   defines additional non-url parameters.  For each parameter being\n   *   configured, add a configuration object keyed to the name of the parameter.\n   *\n   *   Each parameter configuration object may contain the following properties:\n   *\n   *   - ** value ** - {object|function=}: specifies the default value for this\n   *     parameter.  This implicitly sets this parameter as optional.\n   *\n   *     When UI-Router routes to a state and no value is\n   *     specified for this parameter in the URL or transition, the\n   *     default value will be used instead.  If `value` is a function,\n   *     it will be injected and invoked, and the return value used.\n   *\n   *     *Note*: `undefined` is treated as \"no default value\" while `null`\n   *     is treated as \"the default value is `null`\".\n   *\n   *     *Shorthand*: If you only need to configure the default value of the\n   *     parameter, you may use a shorthand syntax.   In the **`params`**\n   *     map, instead mapping the param name to a full parameter configuration\n   *     object, simply set map it to the default parameter value, e.g.:\n   *\n   * <pre>// define a parameter's default value\n   * params: {\n   *     param1: { value: \"defaultValue\" }\n   * }\n   * // shorthand default values\n   * params: {\n   *     param1: \"defaultValue\",\n   *     param2: \"param2Default\"\n   * }</pre>\n   *\n   *   - ** array ** - {boolean=}: *(default: false)* If true, the param value will be\n   *     treated as an array of values.  If you specified a Type, the value will be\n   *     treated as an array of the specified Type.  Note: query parameter values\n   *     default to a special `\"auto\"` mode.\n   *\n   *     For query parameters in `\"auto\"` mode, if multiple  values for a single parameter\n   *     are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values\n   *     are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`).  However, if\n   *     only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single\n   *     value (e.g.: `{ foo: '1' }`).\n   *\n   * <pre>params: {\n   *     param1: { array: true }\n   * }</pre>\n   *\n   *   - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when\n   *     the current parameter value is the same as the default value. If `squash` is not set, it uses the\n   *     configured default squash policy.\n   *     (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})\n   *\n   *   There are three squash settings:\n   *\n   *     - false: The parameter's default value is not squashed.  It is encoded and included in the URL\n   *     - true: The parameter's default value is omitted from the URL.  If the parameter is preceeded and followed\n   *       by slashes in the state's `url` declaration, then one of those slashes are omitted.\n   *       This can allow for cleaner looking URLs.\n   *     - `\"<arbitrary string>\"`: The parameter's default value is replaced with an arbitrary placeholder of  your choice.\n   *\n   * <pre>params: {\n   *     param1: {\n   *       value: \"defaultId\",\n   *       squash: true\n   * } }\n   * // squash \"defaultValue\" to \"~\"\n   * params: {\n   *     param1: {\n   *       value: \"defaultValue\",\n   *       squash: \"~\"\n   * } }\n   * </pre>\n   *\n   *\n   * @example\n   * <pre>\n   * // Some state name examples\n   *\n   * // stateName can be a single top-level name (must be unique).\n   * $stateProvider.state(\"home\", {});\n   *\n   * // Or it can be a nested state name. This state is a child of the\n   * // above \"home\" state.\n   * $stateProvider.state(\"home.newest\", {});\n   *\n   * // Nest states as deeply as needed.\n   * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n   *\n   * // state() returns $stateProvider, so you can chain state declarations.\n   * $stateProvider\n   *   .state(\"home\", {})\n   *   .state(\"about\", {})\n   *   .state(\"contacts\", {});\n   * </pre>\n   *\n   */\n  this.state = state;\n  function state(name, definition) {\n    /*jshint validthis: true */\n    if (isObject(name)) definition = name;\n    else definition.name = name;\n    registerState(definition);\n    return this;\n  }\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$state\n   *\n   * @requires $rootScope\n   * @requires $q\n   * @requires ui.router.state.$view\n   * @requires $injector\n   * @requires ui.router.util.$resolve\n   * @requires ui.router.state.$stateParams\n   * @requires ui.router.router.$urlRouter\n   *\n   * @property {object} params A param object, e.g. {sectionId: section.id)}, that \n   * you'd like to test against the current active state.\n   * @property {object} current A reference to the state's config object. However \n   * you passed it in. Useful for accessing custom data.\n   * @property {object} transition Currently pending transition. A promise that'll \n   * resolve or reject.\n   *\n   * @description\n   * `$state` service is responsible for representing states as well as transitioning\n   * between them. It also provides interfaces to ask for current state or even states\n   * you're coming from.\n   */\n  this.$get = $get;\n  $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];\n  function $get(   $rootScope,   $q,   $view,   $injector,   $resolve,   $stateParams,   $urlRouter,   $location,   $urlMatcherFactory) {\n\n    var TransitionSuperseded = $q.reject(new Error('transition superseded'));\n    var TransitionPrevented = $q.reject(new Error('transition prevented'));\n    var TransitionAborted = $q.reject(new Error('transition aborted'));\n    var TransitionFailed = $q.reject(new Error('transition failed'));\n\n    // Handles the case where a state which is the target of a transition is not found, and the user\n    // can optionally retry or defer the transition\n    function handleRedirect(redirect, state, params, options) {\n      /**\n       * @ngdoc event\n       * @name ui.router.state.$state#$stateNotFound\n       * @eventOf ui.router.state.$state\n       * @eventType broadcast on root scope\n       * @description\n       * Fired when a requested state **cannot be found** using the provided state name during transition.\n       * The event is broadcast allowing any handlers a single chance to deal with the error (usually by\n       * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,\n       * you can see its three properties in the example. You can use `event.preventDefault()` to abort the\n       * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.\n       *\n       * @param {Object} event Event object.\n       * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.\n       * @param {State} fromState Current state object.\n       * @param {Object} fromParams Current state params.\n       *\n       * @example\n       *\n       * <pre>\n       * // somewhere, assume lazy.state has not been defined\n       * $state.go(\"lazy.state\", {a:1, b:2}, {inherit:false});\n       *\n       * // somewhere else\n       * $scope.$on('$stateNotFound',\n       * function(event, unfoundState, fromState, fromParams){\n       *     console.log(unfoundState.to); // \"lazy.state\"\n       *     console.log(unfoundState.toParams); // {a:1, b:2}\n       *     console.log(unfoundState.options); // {inherit:false} + default options\n       * })\n       * </pre>\n       */\n      var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);\n\n      if (evt.defaultPrevented) {\n        $urlRouter.update();\n        return TransitionAborted;\n      }\n\n      if (!evt.retry) {\n        return null;\n      }\n\n      // Allow the handler to return a promise to defer state lookup retry\n      if (options.$retry) {\n        $urlRouter.update();\n        return TransitionFailed;\n      }\n      var retryTransition = $state.transition = $q.when(evt.retry);\n\n      retryTransition.then(function() {\n        if (retryTransition !== $state.transition) return TransitionSuperseded;\n        redirect.options.$retry = true;\n        return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);\n      }, function() {\n        return TransitionAborted;\n      });\n      $urlRouter.update();\n\n      return retryTransition;\n    }\n\n    root.locals = { resolve: null, globals: { $stateParams: {} } };\n\n    $state = {\n      params: {},\n      current: root.self,\n      $current: root,\n      transition: null\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#reload\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method that force reloads the current state. All resolves are re-resolved, events are not re-fired, \n     * and controllers reinstantiated (bug with controllers reinstantiating right now, fixing soon).\n     *\n     * @example\n     * <pre>\n     * var app angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.reload = function(){\n     *     $state.reload();\n     *   }\n     * });\n     * </pre>\n     *\n     * `reload()` is just an alias for:\n     * <pre>\n     * $state.transitionTo($state.current, $stateParams, { \n     *   reload: true, inherit: false, notify: true\n     * });\n     * </pre>\n     *\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.reload = function reload() {\n      return $state.transitionTo($state.current, $stateParams, { reload: true, inherit: false, notify: true });\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#go\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Convenience method for transitioning to a new state. `$state.go` calls \n     * `$state.transitionTo` internally but automatically sets options to \n     * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. \n     * This allows you to easily use an absolute or relative to path and specify \n     * only the parameters you'd like to update (while letting unspecified parameters \n     * inherit from the currently active ancestor states).\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.go('contact.detail');\n     *   };\n     * });\n     * </pre>\n     * <img src='../ngdoc_assets/StateGoExamples.png'/>\n     *\n     * @param {string} to Absolute state name or relative state path. Some examples:\n     *\n     * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n     * - `$state.go('^')` - will go to a parent state\n     * - `$state.go('^.sibling')` - will go to a sibling state\n     * - `$state.go('.child.grandchild')` - will go to grandchild state\n     *\n     * @param {object=} params A map of the parameters that will be sent to the state, \n     * will populate $stateParams. Any parameters that are not specified will be inherited from currently \n     * defined parameters. This allows, for example, going to a sibling state that shares parameters\n     * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.\n     * transitioning to a sibling will get you the parameters for all parents, transitioning to a child\n     * will get you all current parameters, etc.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *\n     * @returns {promise} A promise representing the state of the new transition.\n     *\n     * Possible success values:\n     *\n     * - $state.current\n     *\n     * <br/>Possible rejection values:\n     *\n     * - 'transition superseded' - when a newer transition has been started after this one\n     * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener\n     * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or\n     *   when a `$stateNotFound` `event.retry` promise errors.\n     * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.\n     * - *resolve error* - when an error has occurred with a `resolve`\n     *\n     */\n    $state.go = function go(to, params, options) {\n      return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#transitionTo\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}\n     * uses `transitionTo` internally. `$state.go` is recommended in most situations.\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.transitionTo('contact.detail');\n     *   };\n     * });\n     * </pre>\n     *\n     * @param {string} to State name.\n     * @param {object=} toParams A map of the parameters that will be sent to the state,\n     * will populate $stateParams.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.transitionTo = function transitionTo(to, toParams, options) {\n      toParams = toParams || {};\n      options = extend({\n        location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false\n      }, options || {});\n\n      var from = $state.$current, fromParams = $state.params, fromPath = from.path;\n      var evt, toState = findState(to, options.relative);\n\n      if (!isDefined(toState)) {\n        var redirect = { to: to, toParams: toParams, options: options };\n        var redirectResult = handleRedirect(redirect, from.self, fromParams, options);\n\n        if (redirectResult) {\n          return redirectResult;\n        }\n\n        // Always retry once if the $stateNotFound was not prevented\n        // (handles either redirect changed or state lazy-definition)\n        to = redirect.to;\n        toParams = redirect.toParams;\n        options = redirect.options;\n        toState = findState(to, options.relative);\n\n        if (!isDefined(toState)) {\n          if (!options.relative) throw new Error(\"No such state '\" + to + \"'\");\n          throw new Error(\"Could not resolve '\" + to + \"' from state '\" + options.relative + \"'\");\n        }\n      }\n      if (toState[abstractKey]) throw new Error(\"Cannot transition to abstract state '\" + to + \"'\");\n      if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);\n      if (!toState.params.$$validates(toParams)) return TransitionFailed;\n\n      toParams = toState.params.$$values(toParams);\n      to = toState;\n\n      var toPath = to.path;\n\n      // Starting from the root of the path, keep all levels that haven't changed\n      var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];\n\n      if (!options.reload) {\n        while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {\n          locals = toLocals[keep] = state.locals;\n          keep++;\n          state = toPath[keep];\n        }\n      }\n\n      // If we're going to the same state and all locals are kept, we've got nothing to do.\n      // But clear 'transition', as we still want to cancel any other pending transitions.\n      // TODO: We may not want to bump 'transition' if we're called from a location change\n      // that we've initiated ourselves, because we might accidentally abort a legitimate\n      // transition initiated from code?\n      if (shouldTriggerReload(to, from, locals, options)) {\n        if (to.self.reloadOnSearch !== false) $urlRouter.update();\n        $state.transition = null;\n        return $q.when($state.current);\n      }\n\n      // Filter parameters before we pass them to event handlers etc.\n      toParams = filterByKeys(to.params.$$keys(), toParams || {});\n\n      // Broadcast start event and cancel the transition if requested\n      if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeStart\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when the state transition **begins**. You can use `event.preventDefault()`\n         * to prevent the transition from happening and then the transition promise will be\n         * rejected with a `'transition prevented'` value.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         *\n         * @example\n         *\n         * <pre>\n         * $rootScope.$on('$stateChangeStart',\n         * function(event, toState, toParams, fromState, fromParams){\n         *     event.preventDefault();\n         *     // transitionTo() promise will be rejected with\n         *     // a 'transition prevented' error\n         * })\n         * </pre>\n         */\n        if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {\n          $urlRouter.update();\n          return TransitionPrevented;\n        }\n      }\n\n      // Resolve locals for the remaining states, but don't update any global state just\n      // yet -- if anything fails to resolve the current state needs to remain untouched.\n      // We also set up an inheritance chain for the locals here. This allows the view directive\n      // to quickly look up the correct definition for each view in the current state. Even\n      // though we create the locals object itself outside resolveState(), it is initially\n      // empty and gets filled asynchronously. We need to keep track of the promise for the\n      // (fully resolved) current locals, and pass this down the chain.\n      var resolved = $q.when(locals);\n\n      for (var l = keep; l < toPath.length; l++, state = toPath[l]) {\n        locals = toLocals[l] = inherit(locals);\n        resolved = resolveState(state, toParams, state === to, resolved, locals, options);\n      }\n\n      // Once everything is resolved, we are ready to perform the actual transition\n      // and return a promise for the new state. We also keep track of what the\n      // current promise is, so that we can detect overlapping transitions and\n      // keep only the outcome of the last transition.\n      var transition = $state.transition = resolved.then(function () {\n        var l, entering, exiting;\n\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Exit 'from' states not kept\n        for (l = fromPath.length - 1; l >= keep; l--) {\n          exiting = fromPath[l];\n          if (exiting.self.onExit) {\n            $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);\n          }\n          exiting.locals = null;\n        }\n\n        // Enter 'to' states not kept\n        for (l = keep; l < toPath.length; l++) {\n          entering = toPath[l];\n          entering.locals = toLocals[l];\n          if (entering.self.onEnter) {\n            $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);\n          }\n        }\n\n        // Run it again, to catch any transitions in callbacks\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Update globals in $state\n        $state.$current = to;\n        $state.current = to.self;\n        $state.params = toParams;\n        copy($state.params, $stateParams);\n        $state.transition = null;\n\n        if (options.location && to.navigable) {\n          $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {\n            $$avoidResync: true, replace: options.location === 'replace'\n          });\n        }\n\n        if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeSuccess\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired once the state transition is **complete**.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         */\n          $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);\n        }\n        $urlRouter.update(true);\n\n        return $state.current;\n      }, function (error) {\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        $state.transition = null;\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeError\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when an **error occurs** during transition. It's important to note that if you\n         * have any errors in your resolve functions (javascript errors, non-existent services, etc)\n         * they will not throw traditionally. You must listen for this $stateChangeError event to\n         * catch **ALL** errors.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         * @param {Error} error The resolve error object.\n         */\n        evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);\n\n        if (!evt.defaultPrevented) {\n            $urlRouter.update();\n        }\n\n        return $q.reject(error);\n      });\n\n      return transition;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#is\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Similar to {@link ui.router.state.$state#methods_includes $state.includes},\n     * but only checks for the full state name. If params is supplied then it will be\n     * tested for strict equality against the current active params object, so all params\n     * must match with none missing and no extras.\n     *\n     * @example\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // absolute name\n     * $state.is('contact.details.item'); // returns true\n     * $state.is(contactDetailItemStateObject); // returns true\n     *\n     * // relative name (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.is('.item')}\">Item</div>\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like\n     * to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object} -  If `stateOrName` is a relative state name and `options.relative` is set, .is will\n     * test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it is the state.\n     */\n    $state.is = function is(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) { return undefined; }\n      if ($state.$current !== state) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#includes\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method to determine if the current active state is equal to or is the child of the\n     * state stateName. If any params are passed then they will be tested for a match as well.\n     * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n     *\n     * @example\n     * Partial and relative names\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // Using partial names\n     * $state.includes(\"contacts\"); // returns true\n     * $state.includes(\"contacts.details\"); // returns true\n     * $state.includes(\"contacts.details.item\"); // returns true\n     * $state.includes(\"contacts.list\"); // returns false\n     * $state.includes(\"about\"); // returns false\n     *\n     * // Using relative names (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.includes('.item')}\">Item</div>\n     * </pre>\n     *\n     * Basic globbing patterns\n     * <pre>\n     * $state.$current.name = 'contacts.details.item.url';\n     *\n     * $state.includes(\"*.details.*.*\"); // returns true\n     * $state.includes(\"*.details.**\"); // returns true\n     * $state.includes(\"**.item.**\"); // returns true\n     * $state.includes(\"*.details.item.url\"); // returns true\n     * $state.includes(\"*.details.*.url\"); // returns true\n     * $state.includes(\"*.details.*\"); // returns false\n     * $state.includes(\"item.**\"); // returns false\n     * </pre>\n     *\n     * @param {string} stateOrName A partial name, relative name, or glob pattern\n     * to be searched for within the current state name.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`,\n     * that you'd like to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object=} -  If `stateOrName` is a relative state reference and `options.relative` is set,\n     * .includes will test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it does include the state\n     */\n    $state.includes = function includes(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      if (isString(stateOrName) && isGlob(stateOrName)) {\n        if (!doesStateMatchGlob(stateOrName)) {\n          return false;\n        }\n        stateOrName = $state.$current.name;\n      }\n\n      var state = findState(stateOrName, options.relative);\n      if (!isDefined(state)) { return undefined; }\n      if (!isDefined($state.$current.includes[state.name])) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;\n    };\n\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#href\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A url generation method that returns the compiled url for the given state populated with the given params.\n     *\n     * @example\n     * <pre>\n     * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.\n     * @param {object=} params An object of parameter values to fill the state's required parameters.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`lossy`** - {boolean=true} -  If true, and if there is no url associated with the state provided in the\n     *    first parameter, then the constructed href url will be built from the first navigable ancestor (aka\n     *    ancestor with a valid url).\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n     * \n     * @returns {string} compiled state url\n     */\n    $state.href = function href(stateOrName, params, options) {\n      options = extend({\n        lossy:    true,\n        inherit:  true,\n        absolute: false,\n        relative: $state.$current\n      }, options || {});\n\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) return null;\n      if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);\n      \n      var nav = (state && options.lossy) ? state.navigable : state;\n\n      if (!nav || nav.url === undefined || nav.url === null) {\n        return null;\n      }\n      return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys(), params || {}), {\n        absolute: options.absolute\n      });\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#get\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Returns the state configuration object for any specific state or all states.\n     *\n     * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for\n     * the requested state. If not provided, returns an array of ALL state configs.\n     * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.\n     * @returns {Object|Array} State configuration object or array of all objects.\n     */\n    $state.get = function (stateOrName, context) {\n      if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });\n      var state = findState(stateOrName, context || $state.$current);\n      return (state && state.self) ? state.self : null;\n    };\n\n    function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {\n      // Make a restricted $stateParams with only the parameters that apply to this state if\n      // necessary. In addition to being available to the controller and onEnter/onExit callbacks,\n      // we also need $stateParams to be available for any $injector calls we make during the\n      // dependency resolution process.\n      var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);\n      var locals = { $stateParams: $stateParams };\n\n      // Resolve 'global' dependencies for the state, i.e. those not specific to a view.\n      // We're also including $stateParams in this; that way the parameters are restricted\n      // to the set that should be visible to the state, and are independent of when we update\n      // the global $state and $stateParams values.\n      dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);\n      var promises = [dst.resolve.then(function (globals) {\n        dst.globals = globals;\n      })];\n      if (inherited) promises.push(inherited);\n\n      // Resolve template and dependencies for all views.\n      forEach(state.views, function (view, name) {\n        var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});\n        injectables.$template = [ function () {\n          return $view.load(name, { view: view, locals: locals, params: $stateParams, notify: options.notify }) || '';\n        }];\n\n        promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {\n          // References to the controller (only instantiated at link time)\n          if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {\n            var injectLocals = angular.extend({}, injectables, locals);\n            result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);\n          } else {\n            result.$$controller = view.controller;\n          }\n          // Provide access to the state itself for internal use\n          result.$$state = state;\n          result.$$controllerAs = view.controllerAs;\n          dst[name] = result;\n        }));\n      });\n\n      // Wait for all the promises and then return the activation object\n      return $q.all(promises).then(function (values) {\n        return dst;\n      });\n    }\n\n    return $state;\n  }\n\n  function shouldTriggerReload(to, from, locals, options) {\n    if (to === from && ((locals === from.locals && !options.reload) || (to.self.reloadOnSearch === false))) {\n      return true;\n    }\n  }\n}\n\nangular.module('ui.router.state')\n  .value('$stateParams', {})\n  .provider('$state', $StateProvider);\n\n\n$ViewProvider.$inject = [];\nfunction $ViewProvider() {\n\n  this.$get = $get;\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$view\n   *\n   * @requires ui.router.util.$templateFactory\n   * @requires $rootScope\n   *\n   * @description\n   *\n   */\n  $get.$inject = ['$rootScope', '$templateFactory'];\n  function $get(   $rootScope,   $templateFactory) {\n    return {\n      // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })\n      /**\n       * @ngdoc function\n       * @name ui.router.state.$view#load\n       * @methodOf ui.router.state.$view\n       *\n       * @description\n       *\n       * @param {string} name name\n       * @param {object} options option object.\n       */\n      load: function load(name, options) {\n        var result, defaults = {\n          template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}\n        };\n        options = extend(defaults, options);\n\n        if (options.view) {\n          result = $templateFactory.fromConfig(options.view, options.params, options.locals);\n        }\n        if (result && options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$viewContentLoading\n         * @eventOf ui.router.state.$view\n         * @eventType broadcast on root scope\n         * @description\n         *\n         * Fired once the view **begins loading**, *before* the DOM is rendered.\n         *\n         * @param {Object} event Event object.\n         * @param {Object} viewConfig The view config properties (template, controller, etc).\n         *\n         * @example\n         *\n         * <pre>\n         * $scope.$on('$viewContentLoading',\n         * function(event, viewConfig){\n         *     // Access to all the view config properties.\n         *     // and one special property 'targetView'\n         *     // viewConfig.targetView\n         * });\n         * </pre>\n         */\n          $rootScope.$broadcast('$viewContentLoading', options);\n        }\n        return result;\n      }\n    };\n  }\n}\n\nangular.module('ui.router.state').provider('$view', $ViewProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$uiViewScrollProvider\n *\n * @description\n * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.\n */\nfunction $ViewScrollProvider() {\n\n  var useAnchorScroll = false;\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll\n   * @methodOf ui.router.state.$uiViewScrollProvider\n   *\n   * @description\n   * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for\n   * scrolling based on the url anchor.\n   */\n  this.useAnchorScroll = function () {\n    useAnchorScroll = true;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$uiViewScroll\n   *\n   * @requires $anchorScroll\n   * @requires $timeout\n   *\n   * @description\n   * When called with a jqLite element, it scrolls the element into view (after a\n   * `$timeout` so the DOM has time to refresh).\n   *\n   * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,\n   * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.\n   */\n  this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {\n    if (useAnchorScroll) {\n      return $anchorScroll;\n    }\n\n    return function ($element) {\n      $timeout(function () {\n        $element[0].scrollIntoView();\n      }, 0, false);\n    };\n  }];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-view\n *\n * @requires ui.router.state.$state\n * @requires $compile\n * @requires $controller\n * @requires $injector\n * @requires ui.router.state.$uiViewScroll\n * @requires $document\n *\n * @restrict ECA\n *\n * @description\n * The ui-view directive tells $state where to place your templates.\n *\n * @param {string=} name A view name. The name should be unique amongst the other views in the\n * same state. You can have views of the same name that live in different states.\n *\n * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window\n * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll\n * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you\n * scroll ui-view elements into view when they are populated during a state activation.\n *\n * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*\n *\n * @param {string=} onload Expression to evaluate whenever the view updates.\n * \n * @example\n * A view can be unnamed or named. \n * <pre>\n * <!-- Unnamed -->\n * <div ui-view></div> \n * \n * <!-- Named -->\n * <div ui-view=\"viewName\"></div>\n * </pre>\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a \n * single view and it is unnamed then you can populate it like so:\n * <pre>\n * <div ui-view></div> \n * $stateProvider.state(\"home\", {\n *   template: \"<h1>HELLO!</h1>\"\n * })\n * </pre>\n * \n * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}\n * config property, by name, in this case an empty name:\n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * But typically you'll only use the views property if you name your view or have more than one view \n * in the same template. There's not really a compelling reason to name a view if its the only one, \n * but you could if you wanted, like so:\n * <pre>\n * <div ui-view=\"main\"></div>\n * </pre> \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"main\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * Really though, you'll use views to set up multiple views:\n * <pre>\n * <div ui-view></div>\n * <div ui-view=\"chart\"></div> \n * <div ui-view=\"data\"></div> \n * </pre>\n * \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     },\n *     \"chart\": {\n *       template: \"<chart_thing/>\"\n *     },\n *     \"data\": {\n *       template: \"<data_thing/>\"\n *     }\n *   }    \n * })\n * </pre>\n *\n * Examples for `autoscroll`:\n *\n * <pre>\n * <!-- If autoscroll present with no expression,\n *      then scroll ui-view into view -->\n * <ui-view autoscroll/>\n *\n * <!-- If autoscroll present with valid expression,\n *      then scroll ui-view into view if expression evaluates to true -->\n * <ui-view autoscroll='true'/>\n * <ui-view autoscroll='false'/>\n * <ui-view autoscroll='scopeVariable'/>\n * </pre>\n */\n$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];\nfunction $ViewDirective(   $state,   $injector,   $uiViewScroll,   $interpolate) {\n\n  function getService() {\n    return ($injector.has) ? function(service) {\n      return $injector.has(service) ? $injector.get(service) : null;\n    } : function(service) {\n      try {\n        return $injector.get(service);\n      } catch (e) {\n        return null;\n      }\n    };\n  }\n\n  var service = getService(),\n      $animator = service('$animator'),\n      $animate = service('$animate');\n\n  // Returns a set of DOM manipulation functions based on which Angular version\n  // it should use\n  function getRenderer(attrs, scope) {\n    var statics = function() {\n      return {\n        enter: function (element, target, cb) { target.after(element); cb(); },\n        leave: function (element, cb) { element.remove(); cb(); }\n      };\n    };\n\n    if ($animate) {\n      return {\n        enter: function(element, target, cb) {\n          var promise = $animate.enter(element, null, target, cb);\n          if (promise && promise.then) promise.then(cb);\n        },\n        leave: function(element, cb) {\n          var promise = $animate.leave(element, cb);\n          if (promise && promise.then) promise.then(cb);\n        }\n      };\n    }\n\n    if ($animator) {\n      var animate = $animator && $animator(scope, attrs);\n\n      return {\n        enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },\n        leave: function(element, cb) { animate.leave(element); cb(); }\n      };\n    }\n\n    return statics();\n  }\n\n  var directive = {\n    restrict: 'ECA',\n    terminal: true,\n    priority: 400,\n    transclude: 'element',\n    compile: function (tElement, tAttrs, $transclude) {\n      return function (scope, $element, attrs) {\n        var previousEl, currentEl, currentScope, latestLocals,\n            onloadExp     = attrs.onload || '',\n            autoScrollExp = attrs.autoscroll,\n            renderer      = getRenderer(attrs, scope);\n\n        scope.$on('$stateChangeSuccess', function() {\n          updateView(false);\n        });\n        scope.$on('$viewContentLoading', function() {\n          updateView(false);\n        });\n\n        updateView(true);\n\n        function cleanupLastView() {\n          if (previousEl) {\n            previousEl.remove();\n            previousEl = null;\n          }\n\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n\n          if (currentEl) {\n            renderer.leave(currentEl, function() {\n              previousEl = null;\n            });\n\n            previousEl = currentEl;\n            currentEl = null;\n          }\n        }\n\n        function updateView(firstTime) {\n          var newScope,\n              name            = getUiViewName(scope, attrs, $element, $interpolate),\n              previousLocals  = name && $state.$current && $state.$current.locals[name];\n\n          if (!firstTime && previousLocals === latestLocals) return; // nothing to do\n          newScope = scope.$new();\n          latestLocals = $state.$current.locals[name];\n\n          var clone = $transclude(newScope, function(clone) {\n            renderer.enter(clone, $element, function onUiViewEnter() {\n              if(currentScope) {\n                currentScope.$emit('$viewContentAnimationEnded');\n              }\n\n              if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {\n                $uiViewScroll(clone);\n              }\n            });\n            cleanupLastView();\n          });\n\n          currentEl = clone;\n          currentScope = newScope;\n          /**\n           * @ngdoc event\n           * @name ui.router.state.directive:ui-view#$viewContentLoaded\n           * @eventOf ui.router.state.directive:ui-view\n           * @eventType emits on ui-view directive scope\n           * @description           *\n           * Fired once the view is **loaded**, *after* the DOM is rendered.\n           *\n           * @param {Object} event Event object.\n           */\n          currentScope.$emit('$viewContentLoaded');\n          currentScope.$eval(onloadExp);\n        }\n      };\n    }\n  };\n\n  return directive;\n}\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];\nfunction $ViewDirectiveFill (  $compile,   $controller,   $state,   $interpolate) {\n  return {\n    restrict: 'ECA',\n    priority: -400,\n    compile: function (tElement) {\n      var initial = tElement.html();\n      return function (scope, $element, attrs) {\n        var current = $state.$current,\n            name = getUiViewName(scope, attrs, $element, $interpolate),\n            locals  = current && current.locals[name];\n\n        if (! locals) {\n          return;\n        }\n\n        $element.data('$uiView', { name: name, state: locals.$$state });\n        $element.html(locals.$template ? locals.$template : initial);\n\n        var link = $compile($element.contents());\n\n        if (locals.$$controller) {\n          locals.$scope = scope;\n          var controller = $controller(locals.$$controller, locals);\n          if (locals.$$controllerAs) {\n            scope[locals.$$controllerAs] = controller;\n          }\n          $element.data('$ngControllerController', controller);\n          $element.children().data('$ngControllerController', controller);\n        }\n\n        link(scope);\n      };\n    }\n  };\n}\n\n/**\n * Shared ui-view code for both directives:\n * Given scope, element, and its attributes, return the view's name\n */\nfunction getUiViewName(scope, attrs, element, $interpolate) {\n  var name = $interpolate(attrs.uiView || attrs.name || '')(scope);\n  var inherited = element.inheritedData('$uiView');\n  return name.indexOf('@') >= 0 ?  name :  (name + '@' + (inherited ? inherited.state.name : ''));\n}\n\nangular.module('ui.router.state').directive('uiView', $ViewDirective);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n\nfunction parseStateRef(ref, current) {\n  var preparsed = ref.match(/^\\s*({[^}]*})\\s*$/), parsed;\n  if (preparsed) ref = current + '(' + preparsed[1] + ')';\n  parsed = ref.replace(/\\n/g, \" \").match(/^([^(]+?)\\s*(\\((.*)\\))?$/);\n  if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n  return { state: parsed[1], paramExpr: parsed[3] || null };\n}\n\nfunction stateContext(el) {\n  var stateData = el.parent().inheritedData('$uiView');\n\n  if (stateData && stateData.state && stateData.state.name) {\n    return stateData.state;\n  }\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref\n *\n * @requires ui.router.state.$state\n * @requires $timeout\n *\n * @restrict A\n *\n * @description\n * A directive that binds a link (`<a>` tag) to a state. If the state has an associated \n * URL, the directive will automatically generate & update the `href` attribute via \n * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking \n * the link will trigger a state transition with optional parameters. \n *\n * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be \n * handled natively by the browser.\n *\n * You can also use relative state paths within ui-sref, just like the relative \n * paths passed to `$state.go()`. You just need to be aware that the path is relative\n * to the state that the link lives in, in other words the state that loaded the \n * template containing the link.\n *\n * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}\n * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,\n * and `reload`.\n *\n * @example\n * Here's an example of how you'd use ui-sref and how it would compile. If you have the \n * following template:\n * <pre>\n * <a ui-sref=\"home\">Home</a> | <a ui-sref=\"about\">About</a> | <a ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a ui-sref=\"contacts.detail({ id: contact.id })\">{{ contact.name }}</a>\n *     </li>\n * </ul>\n * </pre>\n * \n * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):\n * <pre>\n * <a href=\"#/home\" ui-sref=\"home\">Home</a> | <a href=\"#/about\" ui-sref=\"about\">About</a> | <a href=\"#/contacts?page=2\" ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/1\" ui-sref=\"contacts.detail({ id: contact.id })\">Joe</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/2\" ui-sref=\"contacts.detail({ id: contact.id })\">Alice</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/3\" ui-sref=\"contacts.detail({ id: contact.id })\">Bob</a>\n *     </li>\n * </ul>\n *\n * <a ui-sref=\"home\" ui-sref-opts=\"{reload: true}\">Home</a>\n * </pre>\n *\n * @param {string} ui-sref 'stateName' can be any valid absolute or relative state\n * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}\n */\n$StateRefDirective.$inject = ['$state', '$timeout'];\nfunction $StateRefDirective($state, $timeout) {\n  var allowedOptions = ['location', 'inherit', 'reload'];\n\n  return {\n    restrict: 'A',\n    require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n    link: function(scope, element, attrs, uiSrefActive) {\n      var ref = parseStateRef(attrs.uiSref, $state.current.name);\n      var params = null, url = null, base = stateContext(element) || $state.$current;\n      var newHref = null, isAnchor = element.prop(\"tagName\") === \"A\";\n      var isForm = element[0].nodeName === \"FORM\";\n      var attr = isForm ? \"action\" : \"href\", nav = true;\n\n      var options = { relative: base, inherit: true };\n      var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};\n\n      angular.forEach(allowedOptions, function(option) {\n        if (option in optionsOverride) {\n          options[option] = optionsOverride[option];\n        }\n      });\n\n      var update = function(newVal) {\n        if (newVal) params = angular.copy(newVal);\n        if (!nav) return;\n\n        newHref = $state.href(ref.state, params, options);\n\n        var activeDirective = uiSrefActive[1] || uiSrefActive[0];\n        if (activeDirective) {\n          activeDirective.$$setStateInfo(ref.state, params);\n        }\n        if (newHref === null) {\n          nav = false;\n          return false;\n        }\n        attrs.$set(attr, newHref);\n      };\n\n      if (ref.paramExpr) {\n        scope.$watch(ref.paramExpr, function(newVal, oldVal) {\n          if (newVal !== params) update(newVal);\n        }, true);\n        params = angular.copy(scope.$eval(ref.paramExpr));\n      }\n      update();\n\n      if (isForm) return;\n\n      element.bind(\"click\", function(e) {\n        var button = e.which || e.button;\n        if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {\n          // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n          var transition = $timeout(function() {\n            $state.go(ref.state, params, options);\n          });\n          e.preventDefault();\n\n          // if the state has no URL, ignore one preventDefault from the <a> directive.\n          var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;\n          e.preventDefault = function() {\n            if (ignorePreventDefaultCount-- <= 0)\n              $timeout.cancel(transition);\n          };\n        }\n      });\n    }\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * A directive working alongside ui-sref to add classes to an element when the\n * related ui-sref directive's state is active, and removing them when it is inactive.\n * The primary use-case is to simplify the special appearance of navigation menus\n * relying on `ui-sref`, by having the \"active\" state's menu button appear different,\n * distinguishing it from the inactive menu items.\n *\n * ui-sref-active can live on the same element as ui-sref or on a parent element. The first\n * ui-sref-active found at the same level or above the ui-sref will be used.\n *\n * Will activate when the ui-sref's target state or any child state is active. If you\n * need to activate only when the ui-sref target state is active and *not* any of\n * it's children, then you will use\n * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}\n *\n * @example\n * Given the following template:\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item\">\n *     <a href ui-sref=\"app.user({user: 'bilbobaggins'})\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n *\n * When the app state is \"app.user\" (or any children states), and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item active\">\n *     <a ui-sref=\"app.user({user: 'bilbobaggins'})\" href=\"/users/bilbobaggins\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n * The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * Multiple classes may be specified in a space-separated format:\n * <pre>\n * <ul>\n *   <li ui-sref-active='class1 class2 class3'>\n *     <a ui-sref=\"app.user\">link</a>\n *   </li>\n * </ul>\n * </pre>\n */\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active-eq\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate\n * when the exact target state used in the `ui-sref` is active; no child states.\n *\n */\n$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];\nfunction $StateRefActiveDirective($state, $stateParams, $interpolate) {\n  return  {\n    restrict: \"A\",\n    controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {\n      var state, params, activeClass;\n\n      // There probably isn't much point in $observing this\n      // uiSrefActive and uiSrefActiveEq share the same directive object with some\n      // slight difference in logic routing\n      activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);\n\n      // Allow uiSref to communicate with uiSrefActive[Equals]\n      this.$$setStateInfo = function (newState, newParams) {\n        state = $state.get(newState, stateContext($element));\n        params = newParams;\n        update();\n      };\n\n      $scope.$on('$stateChangeSuccess', update);\n\n      // Update route state\n      function update() {\n        if (isMatch()) {\n          $element.addClass(activeClass);\n        } else {\n          $element.removeClass(activeClass);\n        }\n      }\n\n      function isMatch() {\n        if (typeof $attrs.uiSrefActiveEq !== 'undefined') {\n          return state && $state.is(state.name, params);\n        } else {\n          return state && $state.includes(state.name, params);\n        }\n      }\n    }]\n  };\n}\n\nangular.module('ui.router.state')\n  .directive('uiSref', $StateRefDirective)\n  .directive('uiSrefActive', $StateRefActiveDirective)\n  .directive('uiSrefActiveEq', $StateRefActiveDirective);\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:isState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_is $state.is(\"stateName\")}.\n */\n$IsStateFilter.$inject = ['$state'];\nfunction $IsStateFilter($state) {\n  var isFilter = function (state) {\n    return $state.is(state);\n  };\n  isFilter.$stateful = true;\n  return isFilter;\n}\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:includedByState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.\n */\n$IncludedByStateFilter.$inject = ['$state'];\nfunction $IncludedByStateFilter($state) {\n  var includesFilter = function (state) {\n    return $state.includes(state);\n  };\n  includesFilter.$stateful = true;\n  return  includesFilter;\n}\n\nangular.module('ui.router.state')\n  .filter('isState', $IsStateFilter)\n  .filter('includedByState', $IncludedByStateFilter);\n})(window, window.angular);\n/*!\n * ionic.bundle.js is a concatenation of:\n * ionic.js, angular.js, angular-animate.js,\n * angular-sanitize.js, angular-ui-router.js,\n * and ionic-angular.js\n */\n\n/*!\n * Copyright 2014 Drifty Co.\n * http://drifty.com/\n *\n * Ionic, v1.0.0\n * A powerful HTML5 mobile app framework.\n * http://ionicframework.com/\n *\n * By @maxlynch, @benjsperry, @adamdbradley <3\n *\n * Licensed under the MIT license. Please see LICENSE for more information.\n *\n */\n\n(function() {\n/* eslint no-unused-vars:0 */\nvar IonicModule = angular.module('ionic', ['ngAnimate', 'ngSanitize', 'ui.router']),\n  extend = angular.extend,\n  forEach = angular.forEach,\n  isDefined = angular.isDefined,\n  isNumber = angular.isNumber,\n  isString = angular.isString,\n  jqLite = angular.element,\n  noop = angular.noop;\n\n/**\n * @ngdoc service\n * @name $ionicActionSheet\n * @module ionic\n * @description\n * The Action Sheet is a slide-up pane that lets the user choose from a set of options.\n * Dangerous options are highlighted in red and made obvious.\n *\n * There are easy ways to cancel out of the action sheet, such as tapping the backdrop or even\n * hitting escape on the keyboard for desktop testing.\n *\n * ![Action Sheet](http://ionicframework.com.s3.amazonaws.com/docs/controllers/actionSheet.gif)\n *\n * @usage\n * To trigger an Action Sheet in your code, use the $ionicActionSheet service in your angular controllers:\n *\n * ```js\n * angular.module('mySuperApp', ['ionic'])\n * .controller(function($scope, $ionicActionSheet, $timeout) {\n *\n *  // Triggered on a button click, or some other target\n *  $scope.show = function() {\n *\n *    // Show the action sheet\n *    var hideSheet = $ionicActionSheet.show({\n *      buttons: [\n *        { text: '<b>Share</b> This' },\n *        { text: 'Move' }\n *      ],\n *      destructiveText: 'Delete',\n *      titleText: 'Modify your album',\n *      cancelText: 'Cancel',\n *      cancel: function() {\n          // add cancel code..\n        },\n *      buttonClicked: function(index) {\n *        return true;\n *      }\n *    });\n *\n *    // For example's sake, hide the sheet after two seconds\n *    $timeout(function() {\n *      hideSheet();\n *    }, 2000);\n *\n *  };\n * });\n * ```\n *\n */\nIonicModule\n.factory('$ionicActionSheet', [\n  '$rootScope',\n  '$compile',\n  '$animate',\n  '$timeout',\n  '$ionicTemplateLoader',\n  '$ionicPlatform',\n  '$ionicBody',\n  'IONIC_BACK_PRIORITY',\nfunction($rootScope, $compile, $animate, $timeout, $ionicTemplateLoader, $ionicPlatform, $ionicBody, IONIC_BACK_PRIORITY) {\n\n  return {\n    show: actionSheet\n  };\n\n  /**\n   * @ngdoc method\n   * @name $ionicActionSheet#show\n   * @description\n   * Load and return a new action sheet.\n   *\n   * A new isolated scope will be created for the\n   * action sheet and the new element will be appended into the body.\n   *\n   * @param {object} options The options for this ActionSheet. Properties:\n   *\n   *  - `[Object]` `buttons` Which buttons to show.  Each button is an object with a `text` field.\n   *  - `{string}` `titleText` The title to show on the action sheet.\n   *  - `{string=}` `cancelText` the text for a 'cancel' button on the action sheet.\n   *  - `{string=}` `destructiveText` The text for a 'danger' on the action sheet.\n   *  - `{function=}` `cancel` Called if the cancel button is pressed, the backdrop is tapped or\n   *     the hardware back button is pressed.\n   *  - `{function=}` `buttonClicked` Called when one of the non-destructive buttons is clicked,\n   *     with the index of the button that was clicked and the button object. Return true to close\n   *     the action sheet, or false to keep it opened.\n   *  - `{function=}` `destructiveButtonClicked` Called when the destructive button is clicked.\n   *     Return true to close the action sheet, or false to keep it opened.\n   *  -  `{boolean=}` `cancelOnStateChange` Whether to cancel the actionSheet when navigating\n   *     to a new state.  Default true.\n   *  - `{string}` `cssClass` The custom CSS class name.\n   *\n   * @returns {function} `hideSheet` A function which, when called, hides & cancels the action sheet.\n   */\n  function actionSheet(opts) {\n    var scope = $rootScope.$new(true);\n\n    extend(scope, {\n      cancel: noop,\n      destructiveButtonClicked: noop,\n      buttonClicked: noop,\n      $deregisterBackButton: noop,\n      buttons: [],\n      cancelOnStateChange: true\n    }, opts || {});\n\n    function textForIcon(text) {\n      if (text && /icon/.test(text)) {\n        scope.$actionSheetHasIcon = true;\n      }\n    }\n\n    for (var x = 0; x < scope.buttons.length; x++) {\n      textForIcon(scope.buttons[x].text);\n    }\n    textForIcon(scope.cancelText);\n    textForIcon(scope.destructiveText);\n\n    // Compile the template\n    var element = scope.element = $compile('<ion-action-sheet ng-class=\"cssClass\" buttons=\"buttons\"></ion-action-sheet>')(scope);\n\n    // Grab the sheet element for animation\n    var sheetEl = jqLite(element[0].querySelector('.action-sheet-wrapper'));\n\n    var stateChangeListenDone = scope.cancelOnStateChange ?\n      $rootScope.$on('$stateChangeSuccess', function() { scope.cancel(); }) :\n      noop;\n\n    // removes the actionSheet from the screen\n    scope.removeSheet = function(done) {\n      if (scope.removed) return;\n\n      scope.removed = true;\n      sheetEl.removeClass('action-sheet-up');\n      $timeout(function() {\n        // wait to remove this due to a 300ms delay native\n        // click which would trigging whatever was underneath this\n        $ionicBody.removeClass('action-sheet-open');\n      }, 400);\n      scope.$deregisterBackButton();\n      stateChangeListenDone();\n\n      $animate.removeClass(element, 'active').then(function() {\n        scope.$destroy();\n        element.remove();\n        // scope.cancel.$scope is defined near the bottom\n        scope.cancel.$scope = sheetEl = null;\n        (done || noop)();\n      });\n    };\n\n    scope.showSheet = function(done) {\n      if (scope.removed) return;\n\n      $ionicBody.append(element)\n                .addClass('action-sheet-open');\n\n      $animate.addClass(element, 'active').then(function() {\n        if (scope.removed) return;\n        (done || noop)();\n      });\n      $timeout(function() {\n        if (scope.removed) return;\n        sheetEl.addClass('action-sheet-up');\n      }, 20, false);\n    };\n\n    // registerBackButtonAction returns a callback to deregister the action\n    scope.$deregisterBackButton = $ionicPlatform.registerBackButtonAction(\n      function() {\n        $timeout(scope.cancel);\n      },\n      IONIC_BACK_PRIORITY.actionSheet\n    );\n\n    // called when the user presses the cancel button\n    scope.cancel = function() {\n      // after the animation is out, call the cancel callback\n      scope.removeSheet(opts.cancel);\n    };\n\n    scope.buttonClicked = function(index) {\n      // Check if the button click event returned true, which means\n      // we can close the action sheet\n      if (opts.buttonClicked(index, opts.buttons[index]) === true) {\n        scope.removeSheet();\n      }\n    };\n\n    scope.destructiveButtonClicked = function() {\n      // Check if the destructive button click event returned true, which means\n      // we can close the action sheet\n      if (opts.destructiveButtonClicked() === true) {\n        scope.removeSheet();\n      }\n    };\n\n    scope.showSheet();\n\n    // Expose the scope on $ionicActionSheet's return value for the sake\n    // of testing it.\n    scope.cancel.$scope = scope;\n\n    return scope.cancel;\n  }\n}]);\n\n\njqLite.prototype.addClass = function(cssClasses) {\n  var x, y, cssClass, el, splitClasses, existingClasses;\n  if (cssClasses && cssClasses != 'ng-scope' && cssClasses != 'ng-isolate-scope') {\n    for (x = 0; x < this.length; x++) {\n      el = this[x];\n      if (el.setAttribute) {\n\n        if (cssClasses.indexOf(' ') < 0 && el.classList.add) {\n          el.classList.add(cssClasses);\n        } else {\n          existingClasses = (' ' + (el.getAttribute('class') || '') + ' ')\n            .replace(/[\\n\\t]/g, \" \");\n          splitClasses = cssClasses.split(' ');\n\n          for (y = 0; y < splitClasses.length; y++) {\n            cssClass = splitClasses[y].trim();\n            if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\n              existingClasses += cssClass + ' ';\n            }\n          }\n          el.setAttribute('class', existingClasses.trim());\n        }\n      }\n    }\n  }\n  return this;\n};\n\njqLite.prototype.removeClass = function(cssClasses) {\n  var x, y, splitClasses, cssClass, el;\n  if (cssClasses) {\n    for (x = 0; x < this.length; x++) {\n      el = this[x];\n      if (el.getAttribute) {\n        if (cssClasses.indexOf(' ') < 0 && el.classList.remove) {\n          el.classList.remove(cssClasses);\n        } else {\n          splitClasses = cssClasses.split(' ');\n\n          for (y = 0; y < splitClasses.length; y++) {\n            cssClass = splitClasses[y];\n            el.setAttribute('class', (\n                (\" \" + (el.getAttribute('class') || '') + \" \")\n                .replace(/[\\n\\t]/g, \" \")\n                .replace(\" \" + cssClass.trim() + \" \", \" \")).trim()\n            );\n          }\n        }\n      }\n    }\n  }\n  return this;\n};\n\n/**\n * @ngdoc service\n * @name $ionicBackdrop\n * @module ionic\n * @description\n * Shows and hides a backdrop over the UI.  Appears behind popups, loading,\n * and other overlays.\n *\n * Often, multiple UI components require a backdrop, but only one backdrop is\n * ever needed in the DOM at a time.\n *\n * Therefore, each component that requires the backdrop to be shown calls\n * `$ionicBackdrop.retain()` when it wants the backdrop, then `$ionicBackdrop.release()`\n * when it is done with the backdrop.\n *\n * For each time `retain` is called, the backdrop will be shown until `release` is called.\n *\n * For example, if `retain` is called three times, the backdrop will be shown until `release`\n * is called three times.\n *\n * @usage\n *\n * ```js\n * function MyController($scope, $ionicBackdrop, $timeout) {\n *   //Show a backdrop for one second\n *   $scope.action = function() {\n *     $ionicBackdrop.retain();\n *     $timeout(function() {\n *       $ionicBackdrop.release();\n *     }, 1000);\n *   };\n * }\n * ```\n */\nIonicModule\n.factory('$ionicBackdrop', [\n  '$document', '$timeout', '$$rAF',\nfunction($document, $timeout, $$rAF) {\n\n  var el = jqLite('<div class=\"backdrop\">');\n  var backdropHolds = 0;\n\n  $document[0].body.appendChild(el[0]);\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicBackdrop#retain\n     * @description Retains the backdrop.\n     */\n    retain: retain,\n    /**\n     * @ngdoc method\n     * @name $ionicBackdrop#release\n     * @description\n     * Releases the backdrop.\n     */\n    release: release,\n\n    getElement: getElement,\n\n    // exposed for testing\n    _element: el\n  };\n\n  function retain() {\n    backdropHolds++;\n    if (backdropHolds === 1) {\n      el.addClass('visible');\n      $$rAF(function() {\n        // If we're still at >0 backdropHolds after async...\n        if (backdropHolds >= 1) el.addClass('active');\n      });\n    }\n  }\n  function release() {\n    if (backdropHolds === 1) {\n      el.removeClass('active');\n      $timeout(function() {\n        // If we're still at 0 backdropHolds after async...\n        if (backdropHolds === 0) el.removeClass('visible');\n      }, 400, false);\n    }\n    backdropHolds = Math.max(0, backdropHolds - 1);\n  }\n\n  function getElement() {\n    return el;\n  }\n\n}]);\n\n/**\n * @private\n */\nIonicModule\n.factory('$ionicBind', ['$parse', '$interpolate', function($parse, $interpolate) {\n  var LOCAL_REGEXP = /^\\s*([@=&])(\\??)\\s*(\\w*)\\s*$/;\n  return function(scope, attrs, bindDefinition) {\n    forEach(bindDefinition || {}, function(definition, scopeName) {\n      //Adapted from angular.js $compile\n      var match = definition.match(LOCAL_REGEXP) || [],\n        attrName = match[3] || scopeName,\n        mode = match[1], // @, =, or &\n        parentGet,\n        unwatch;\n\n      switch (mode) {\n        case '@':\n          if (!attrs[attrName]) {\n            return;\n          }\n          attrs.$observe(attrName, function(value) {\n            scope[scopeName] = value;\n          });\n          // we trigger an interpolation to ensure\n          // the value is there for use immediately\n          if (attrs[attrName]) {\n            scope[scopeName] = $interpolate(attrs[attrName])(scope);\n          }\n          break;\n\n        case '=':\n          if (!attrs[attrName]) {\n            return;\n          }\n          unwatch = scope.$watch(attrs[attrName], function(value) {\n            scope[scopeName] = value;\n          });\n          //Destroy parent scope watcher when this scope is destroyed\n          scope.$on('$destroy', unwatch);\n          break;\n\n        case '&':\n          /* jshint -W044 */\n          if (attrs[attrName] && attrs[attrName].match(RegExp(scopeName + '\\(.*?\\)'))) {\n            throw new Error('& expression binding \"' + scopeName + '\" looks like it will recursively call \"' +\n                          attrs[attrName] + '\" and cause a stack overflow! Please choose a different scopeName.');\n          }\n          parentGet = $parse(attrs[attrName]);\n          scope[scopeName] = function(locals) {\n            return parentGet(scope, locals);\n          };\n          break;\n      }\n    });\n  };\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicBody\n * @module ionic\n * @description An angular utility service to easily and efficiently\n * add and remove CSS classes from the document's body element.\n */\nIonicModule\n.factory('$ionicBody', ['$document', function($document) {\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicBody#add\n     * @description Add a class to the document's body element.\n     * @param {string} class Each argument will be added to the body element.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    addClass: function() {\n      for (var x = 0; x < arguments.length; x++) {\n        $document[0].body.classList.add(arguments[x]);\n      }\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#removeClass\n     * @description Remove a class from the document's body element.\n     * @param {string} class Each argument will be removed from the body element.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    removeClass: function() {\n      for (var x = 0; x < arguments.length; x++) {\n        $document[0].body.classList.remove(arguments[x]);\n      }\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#enableClass\n     * @description Similar to the `add` method, except the first parameter accepts a boolean\n     * value determining if the class should be added or removed. Rather than writing user code,\n     * such as \"if true then add the class, else then remove the class\", this method can be\n     * given a true or false value which reduces redundant code.\n     * @param {boolean} shouldEnableClass A true/false value if the class should be added or removed.\n     * @param {string} class Each remaining argument would be added or removed depending on\n     * the first argument.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    enableClass: function(shouldEnableClass) {\n      var args = Array.prototype.slice.call(arguments).slice(1);\n      if (shouldEnableClass) {\n        this.addClass.apply(this, args);\n      } else {\n        this.removeClass.apply(this, args);\n      }\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#append\n     * @description Append a child to the document's body.\n     * @param {element} element The element to be appended to the body. The passed in element\n     * can be either a jqLite element, or a DOM element.\n     * @returns {$ionicBody} The $ionicBody service so methods can be chained.\n     */\n    append: function(ele) {\n      $document[0].body.appendChild(ele.length ? ele[0] : ele);\n      return this;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicBody#get\n     * @description Get the document's body element.\n     * @returns {element} Returns the document's body element.\n     */\n    get: function() {\n      return $document[0].body;\n    }\n  };\n}]);\n\nIonicModule\n.factory('$ionicClickBlock', [\n  '$document',\n  '$ionicBody',\n  '$timeout',\nfunction($document, $ionicBody, $timeout) {\n  var CSS_HIDE = 'click-block-hide';\n  var cbEle, fallbackTimer, pendingShow;\n\n  function preventClick(ev) {\n    ev.preventDefault();\n    ev.stopPropagation();\n  }\n\n  function addClickBlock() {\n    if (pendingShow) {\n      if (cbEle) {\n        cbEle.classList.remove(CSS_HIDE);\n      } else {\n        cbEle = $document[0].createElement('div');\n        cbEle.className = 'click-block';\n        $ionicBody.append(cbEle);\n        cbEle.addEventListener('touchstart', preventClick);\n        cbEle.addEventListener('mousedown', preventClick);\n      }\n      pendingShow = false;\n    }\n  }\n\n  function removeClickBlock() {\n    cbEle && cbEle.classList.add(CSS_HIDE);\n  }\n\n  return {\n    show: function(autoExpire) {\n      pendingShow = true;\n      $timeout.cancel(fallbackTimer);\n      fallbackTimer = $timeout(this.hide, autoExpire || 310, false);\n      addClickBlock();\n    },\n    hide: function() {\n      pendingShow = false;\n      $timeout.cancel(fallbackTimer);\n      removeClickBlock();\n    }\n  };\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicGesture\n * @module ionic\n * @description An angular service exposing ionic\n * {@link ionic.utility:ionic.EventController}'s gestures.\n */\nIonicModule\n.factory('$ionicGesture', [function() {\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicGesture#on\n     * @description Add an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#onGesture}.\n     * @param {string} eventType The gesture event to listen for.\n     * @param {function(e)} callback The function to call when the gesture\n     * happens.\n     * @param {element} $element The angular element to listen for the event on.\n     * @param {object} options object.\n     * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).\n     */\n    on: function(eventType, cb, $element, options) {\n      return window.ionic.onGesture(eventType, cb, $element[0], options);\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicGesture#off\n     * @description Remove an event listener for a gesture on an element. See {@link ionic.utility:ionic.EventController#offGesture}.\n     * @param {ionic.Gesture} gesture The gesture that should be removed.\n     * @param {string} eventType The gesture event to remove the listener for.\n     * @param {function(e)} callback The listener to remove.\n     */\n    off: function(gesture, eventType, cb) {\n      return window.ionic.offGesture(gesture, eventType, cb);\n    }\n  };\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicHistory\n * @module ionic\n * @description\n * $ionicHistory keeps track of views as the user navigates through an app. Similar to the way a\n * browser behaves, an Ionic app is able to keep track of the previous view, the current view, and\n * the forward view (if there is one).  However, a typical web browser only keeps track of one\n * history stack in a linear fashion.\n *\n * Unlike a traditional browser environment, apps and webapps have parallel independent histories,\n * such as with tabs. Should a user navigate few pages deep on one tab, and then switch to a new\n * tab and back, the back button relates not to the previous tab, but to the previous pages\n * visited within _that_ tab.\n *\n * `$ionicHistory` facilitates this parallel history architecture.\n */\n\nIonicModule\n.factory('$ionicHistory', [\n  '$rootScope',\n  '$state',\n  '$location',\n  '$window',\n  '$timeout',\n  '$ionicViewSwitcher',\n  '$ionicNavViewDelegate',\nfunction($rootScope, $state, $location, $window, $timeout, $ionicViewSwitcher, $ionicNavViewDelegate) {\n\n  // history actions while navigating views\n  var ACTION_INITIAL_VIEW = 'initialView';\n  var ACTION_NEW_VIEW = 'newView';\n  var ACTION_MOVE_BACK = 'moveBack';\n  var ACTION_MOVE_FORWARD = 'moveForward';\n\n  // direction of navigation\n  var DIRECTION_BACK = 'back';\n  var DIRECTION_FORWARD = 'forward';\n  var DIRECTION_ENTER = 'enter';\n  var DIRECTION_EXIT = 'exit';\n  var DIRECTION_SWAP = 'swap';\n  var DIRECTION_NONE = 'none';\n\n  var stateChangeCounter = 0;\n  var lastStateId, nextViewOptions, nextViewExpireTimer, forcedNav;\n\n  var viewHistory = {\n    histories: { root: { historyId: 'root', parentHistoryId: null, stack: [], cursor: -1 } },\n    views: {},\n    backView: null,\n    forwardView: null,\n    currentView: null\n  };\n\n  var View = function() {};\n  View.prototype.initialize = function(data) {\n    if (data) {\n      for (var name in data) this[name] = data[name];\n      return this;\n    }\n    return null;\n  };\n  View.prototype.go = function() {\n\n    if (this.stateName) {\n      return $state.go(this.stateName, this.stateParams);\n    }\n\n    if (this.url && this.url !== $location.url()) {\n\n      if (viewHistory.backView === this) {\n        return $window.history.go(-1);\n      } else if (viewHistory.forwardView === this) {\n        return $window.history.go(1);\n      }\n\n      $location.url(this.url);\n    }\n\n    return null;\n  };\n  View.prototype.destroy = function() {\n    if (this.scope) {\n      this.scope.$destroy && this.scope.$destroy();\n      this.scope = null;\n    }\n  };\n\n\n  function getViewById(viewId) {\n    return (viewId ? viewHistory.views[ viewId ] : null);\n  }\n\n  function getBackView(view) {\n    return (view ? getViewById(view.backViewId) : null);\n  }\n\n  function getForwardView(view) {\n    return (view ? getViewById(view.forwardViewId) : null);\n  }\n\n  function getHistoryById(historyId) {\n    return (historyId ? viewHistory.histories[ historyId ] : null);\n  }\n\n  function getHistory(scope) {\n    var histObj = getParentHistoryObj(scope);\n\n    if (!viewHistory.histories[ histObj.historyId ]) {\n      // this history object exists in parent scope, but doesn't\n      // exist in the history data yet\n      viewHistory.histories[ histObj.historyId ] = {\n        historyId: histObj.historyId,\n        parentHistoryId: getParentHistoryObj(histObj.scope.$parent).historyId,\n        stack: [],\n        cursor: -1\n      };\n    }\n    return getHistoryById(histObj.historyId);\n  }\n\n  function getParentHistoryObj(scope) {\n    var parentScope = scope;\n    while (parentScope) {\n      if (parentScope.hasOwnProperty('$historyId')) {\n        // this parent scope has a historyId\n        return { historyId: parentScope.$historyId, scope: parentScope };\n      }\n      // nothing found keep climbing up\n      parentScope = parentScope.$parent;\n    }\n    // no history for the parent, use the root\n    return { historyId: 'root', scope: $rootScope };\n  }\n\n  function setNavViews(viewId) {\n    viewHistory.currentView = getViewById(viewId);\n    viewHistory.backView = getBackView(viewHistory.currentView);\n    viewHistory.forwardView = getForwardView(viewHistory.currentView);\n  }\n\n  function getCurrentStateId() {\n    var id;\n    if ($state && $state.current && $state.current.name) {\n      id = $state.current.name;\n      if ($state.params) {\n        for (var key in $state.params) {\n          if ($state.params.hasOwnProperty(key) && $state.params[key]) {\n            id += \"_\" + key + \"=\" + $state.params[key];\n          }\n        }\n      }\n      return id;\n    }\n    // if something goes wrong make sure its got a unique stateId\n    return ionic.Utils.nextUid();\n  }\n\n  function getCurrentStateParams() {\n    var rtn;\n    if ($state && $state.params) {\n      for (var key in $state.params) {\n        if ($state.params.hasOwnProperty(key)) {\n          rtn = rtn || {};\n          rtn[key] = $state.params[key];\n        }\n      }\n    }\n    return rtn;\n  }\n\n\n  return {\n\n    register: function(parentScope, viewLocals) {\n\n      var currentStateId = getCurrentStateId(),\n          hist = getHistory(parentScope),\n          currentView = viewHistory.currentView,\n          backView = viewHistory.backView,\n          forwardView = viewHistory.forwardView,\n          viewId = null,\n          action = null,\n          direction = DIRECTION_NONE,\n          historyId = hist.historyId,\n          url = $location.url(),\n          tmp, x, ele;\n\n      if (lastStateId !== currentStateId) {\n        lastStateId = currentStateId;\n        stateChangeCounter++;\n      }\n\n      if (forcedNav) {\n        // we've previously set exactly what to do\n        viewId = forcedNav.viewId;\n        action = forcedNav.action;\n        direction = forcedNav.direction;\n        forcedNav = null;\n\n      } else if (backView && backView.stateId === currentStateId) {\n        // they went back one, set the old current view as a forward view\n        viewId = backView.viewId;\n        historyId = backView.historyId;\n        action = ACTION_MOVE_BACK;\n        if (backView.historyId === currentView.historyId) {\n          // went back in the same history\n          direction = DIRECTION_BACK;\n\n        } else if (currentView) {\n          direction = DIRECTION_EXIT;\n\n          tmp = getHistoryById(backView.historyId);\n          if (tmp && tmp.parentHistoryId === currentView.historyId) {\n            direction = DIRECTION_ENTER;\n\n          } else {\n            tmp = getHistoryById(currentView.historyId);\n            if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {\n              direction = DIRECTION_SWAP;\n            }\n          }\n        }\n\n      } else if (forwardView && forwardView.stateId === currentStateId) {\n        // they went to the forward one, set the forward view to no longer a forward view\n        viewId = forwardView.viewId;\n        historyId = forwardView.historyId;\n        action = ACTION_MOVE_FORWARD;\n        if (forwardView.historyId === currentView.historyId) {\n          direction = DIRECTION_FORWARD;\n\n        } else if (currentView) {\n          direction = DIRECTION_EXIT;\n\n          if (currentView.historyId === hist.parentHistoryId) {\n            direction = DIRECTION_ENTER;\n\n          } else {\n            tmp = getHistoryById(currentView.historyId);\n            if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {\n              direction = DIRECTION_SWAP;\n            }\n          }\n        }\n\n        tmp = getParentHistoryObj(parentScope);\n        if (forwardView.historyId && tmp.scope) {\n          // if a history has already been created by the forward view then make sure it stays the same\n          tmp.scope.$historyId = forwardView.historyId;\n          historyId = forwardView.historyId;\n        }\n\n      } else if (currentView && currentView.historyId !== historyId &&\n                hist.cursor > -1 && hist.stack.length > 0 && hist.cursor < hist.stack.length &&\n                hist.stack[hist.cursor].stateId === currentStateId) {\n        // they just changed to a different history and the history already has views in it\n        var switchToView = hist.stack[hist.cursor];\n        viewId = switchToView.viewId;\n        historyId = switchToView.historyId;\n        action = ACTION_MOVE_BACK;\n        direction = DIRECTION_SWAP;\n\n        tmp = getHistoryById(currentView.historyId);\n        if (tmp && tmp.parentHistoryId === historyId) {\n          direction = DIRECTION_EXIT;\n\n        } else {\n          tmp = getHistoryById(historyId);\n          if (tmp && tmp.parentHistoryId === currentView.historyId) {\n            direction = DIRECTION_ENTER;\n          }\n        }\n\n        // if switching to a different history, and the history of the view we're switching\n        // to has an existing back view from a different history than itself, then\n        // it's back view would be better represented using the current view as its back view\n        tmp = getViewById(switchToView.backViewId);\n        if (tmp && switchToView.historyId !== tmp.historyId) {\n          hist.stack[hist.cursor].backViewId = currentView.viewId;\n        }\n\n      } else {\n\n        // create an element from the viewLocals template\n        ele = $ionicViewSwitcher.createViewEle(viewLocals);\n        if (this.isAbstractEle(ele, viewLocals)) {\n          void 0;\n          return {\n            action: 'abstractView',\n            direction: DIRECTION_NONE,\n            ele: ele\n          };\n        }\n\n        // set a new unique viewId\n        viewId = ionic.Utils.nextUid();\n\n        if (currentView) {\n          // set the forward view if there is a current view (ie: if its not the first view)\n          currentView.forwardViewId = viewId;\n\n          action = ACTION_NEW_VIEW;\n\n          // check if there is a new forward view within the same history\n          if (forwardView && currentView.stateId !== forwardView.stateId &&\n             currentView.historyId === forwardView.historyId) {\n            // they navigated to a new view but the stack already has a forward view\n            // since its a new view remove any forwards that existed\n            tmp = getHistoryById(forwardView.historyId);\n            if (tmp) {\n              // the forward has a history\n              for (x = tmp.stack.length - 1; x >= forwardView.index; x--) {\n                // starting from the end destroy all forwards in this history from this point\n                var stackItem = tmp.stack[x];\n                stackItem && stackItem.destroy && stackItem.destroy();\n                tmp.stack.splice(x);\n              }\n              historyId = forwardView.historyId;\n            }\n          }\n\n          // its only moving forward if its in the same history\n          if (hist.historyId === currentView.historyId) {\n            direction = DIRECTION_FORWARD;\n\n          } else if (currentView.historyId !== hist.historyId) {\n            direction = DIRECTION_ENTER;\n\n            tmp = getHistoryById(currentView.historyId);\n            if (tmp && tmp.parentHistoryId === hist.parentHistoryId) {\n              direction = DIRECTION_SWAP;\n\n            } else {\n              tmp = getHistoryById(tmp.parentHistoryId);\n              if (tmp && tmp.historyId === hist.historyId) {\n                direction = DIRECTION_EXIT;\n              }\n            }\n          }\n\n        } else {\n          // there's no current view, so this must be the initial view\n          action = ACTION_INITIAL_VIEW;\n        }\n\n        if (stateChangeCounter < 2) {\n          // views that were spun up on the first load should not animate\n          direction = DIRECTION_NONE;\n        }\n\n        // add the new view\n        viewHistory.views[viewId] = this.createView({\n          viewId: viewId,\n          index: hist.stack.length,\n          historyId: hist.historyId,\n          backViewId: (currentView && currentView.viewId ? currentView.viewId : null),\n          forwardViewId: null,\n          stateId: currentStateId,\n          stateName: this.currentStateName(),\n          stateParams: getCurrentStateParams(),\n          url: url,\n          canSwipeBack: canSwipeBack(ele, viewLocals)\n        });\n\n        // add the new view to this history's stack\n        hist.stack.push(viewHistory.views[viewId]);\n      }\n\n      $timeout.cancel(nextViewExpireTimer);\n      if (nextViewOptions) {\n        if (nextViewOptions.disableAnimate) direction = DIRECTION_NONE;\n        if (nextViewOptions.disableBack) viewHistory.views[viewId].backViewId = null;\n        if (nextViewOptions.historyRoot) {\n          for (x = 0; x < hist.stack.length; x++) {\n            if (hist.stack[x].viewId === viewId) {\n              hist.stack[x].index = 0;\n              hist.stack[x].backViewId = hist.stack[x].forwardViewId = null;\n            } else {\n              delete viewHistory.views[hist.stack[x].viewId];\n            }\n          }\n          hist.stack = [viewHistory.views[viewId]];\n        }\n        nextViewOptions = null;\n      }\n\n      setNavViews(viewId);\n\n      if (viewHistory.backView && historyId == viewHistory.backView.historyId && currentStateId == viewHistory.backView.stateId && url == viewHistory.backView.url) {\n        for (x = 0; x < hist.stack.length; x++) {\n          if (hist.stack[x].viewId == viewId) {\n            action = 'dupNav';\n            direction = DIRECTION_NONE;\n            if (x > 0) {\n              hist.stack[x - 1].forwardViewId = null;\n            }\n            viewHistory.forwardView = null;\n            viewHistory.currentView.index = viewHistory.backView.index;\n            viewHistory.currentView.backViewId = viewHistory.backView.backViewId;\n            viewHistory.backView = getBackView(viewHistory.backView);\n            hist.stack.splice(x, 1);\n            break;\n          }\n        }\n      }\n\n      void 0;\n\n      hist.cursor = viewHistory.currentView.index;\n\n      return {\n        viewId: viewId,\n        action: action,\n        direction: direction,\n        historyId: historyId,\n        enableBack: this.enabledBack(viewHistory.currentView),\n        isHistoryRoot: (viewHistory.currentView.index === 0),\n        ele: ele\n      };\n    },\n\n    registerHistory: function(scope) {\n      scope.$historyId = ionic.Utils.nextUid();\n    },\n\n    createView: function(data) {\n      var newView = new View();\n      return newView.initialize(data);\n    },\n\n    getViewById: getViewById,\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#viewHistory\n     * @description The app's view history data, such as all the views and histories, along\n     * with how they are ordered and linked together within the navigation stack.\n     * @returns {object} Returns an object containing the apps view history data.\n     */\n    viewHistory: function() {\n      return viewHistory;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentView\n     * @description The app's current view.\n     * @returns {object} Returns the current view.\n     */\n    currentView: function(view) {\n      if (arguments.length) {\n        viewHistory.currentView = view;\n      }\n      return viewHistory.currentView;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentHistoryId\n     * @description The ID of the history stack which is the parent container of the current view.\n     * @returns {string} Returns the current history ID.\n     */\n    currentHistoryId: function() {\n      return viewHistory.currentView ? viewHistory.currentView.historyId : null;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentTitle\n     * @description Gets and sets the current view's title.\n     * @param {string=} val The title to update the current view with.\n     * @returns {string} Returns the current view's title.\n     */\n    currentTitle: function(val) {\n      if (viewHistory.currentView) {\n        if (arguments.length) {\n          viewHistory.currentView.title = val;\n        }\n        return viewHistory.currentView.title;\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#backView\n     * @description Returns the view that was before the current view in the history stack.\n     * If the user navigated from View A to View B, then View A would be the back view, and\n     * View B would be the current view.\n     * @returns {object} Returns the back view.\n     */\n    backView: function(view) {\n      if (arguments.length) {\n        viewHistory.backView = view;\n      }\n      return viewHistory.backView;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#backTitle\n     * @description Gets the back view's title.\n     * @returns {string} Returns the back view's title.\n     */\n    backTitle: function(view) {\n      var backView = (view && getViewById(view.backViewId)) || viewHistory.backView;\n      return backView && backView.title;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#forwardView\n     * @description Returns the view that was in front of the current view in the history stack.\n     * A forward view would exist if the user navigated from View A to View B, then\n     * navigated back to View A. At this point then View B would be the forward view, and View\n     * A would be the current view.\n     * @returns {object} Returns the forward view.\n     */\n    forwardView: function(view) {\n      if (arguments.length) {\n        viewHistory.forwardView = view;\n      }\n      return viewHistory.forwardView;\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#currentStateName\n     * @description Returns the current state name.\n     * @returns {string}\n     */\n    currentStateName: function() {\n      return ($state && $state.current ? $state.current.name : null);\n    },\n\n    isCurrentStateNavView: function(navView) {\n      return !!($state && $state.current && $state.current.views && $state.current.views[navView]);\n    },\n\n    goToHistoryRoot: function(historyId) {\n      if (historyId) {\n        var hist = getHistoryById(historyId);\n        if (hist && hist.stack.length) {\n          if (viewHistory.currentView && viewHistory.currentView.viewId === hist.stack[0].viewId) {\n            return;\n          }\n          forcedNav = {\n            viewId: hist.stack[0].viewId,\n            action: ACTION_MOVE_BACK,\n            direction: DIRECTION_BACK\n          };\n          hist.stack[0].go();\n        }\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#goBack\n     * @param {number=} backCount Optional negative integer setting how many views to go\n     * back. By default it'll go back one view by using the value `-1`. To go back two\n     * views you would use `-2`. If the number goes farther back than the number of views\n     * in the current history's stack then it'll go to the first view in the current history's\n     * stack. If the number is zero or greater then it'll do nothing. It also does not\n     * cross history stacks, meaning it can only go as far back as the current history.\n     * @description Navigates the app to the back view, if a back view exists.\n     */\n    goBack: function(backCount) {\n      if (isDefined(backCount) && backCount !== -1) {\n        if (backCount > -1) return;\n\n        var currentHistory = viewHistory.histories[this.currentHistoryId()];\n        var newCursor = currentHistory.cursor + backCount + 1;\n        if (newCursor < 1) {\n          newCursor = 1;\n        }\n\n        currentHistory.cursor = newCursor;\n        setNavViews(currentHistory.stack[newCursor].viewId);\n\n        var cursor = newCursor - 1;\n        var clearStateIds = [];\n        var fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);\n        while (fwdView) {\n          clearStateIds.push(fwdView.stateId || fwdView.viewId);\n          cursor++;\n          if (cursor >= currentHistory.stack.length) break;\n          fwdView = getViewById(currentHistory.stack[cursor].forwardViewId);\n        }\n\n        var self = this;\n        if (clearStateIds.length) {\n          $timeout(function() {\n            self.clearCache(clearStateIds);\n          }, 600);\n        }\n      }\n\n      viewHistory.backView && viewHistory.backView.go();\n    },\n\n\n    enabledBack: function(view) {\n      var backView = getBackView(view);\n      return !!(backView && backView.historyId === view.historyId);\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#clearHistory\n     * @description Clears out the app's entire history, except for the current view.\n     */\n    clearHistory: function() {\n      var\n      histories = viewHistory.histories,\n      currentView = viewHistory.currentView;\n\n      if (histories) {\n        for (var historyId in histories) {\n\n          if (histories[historyId].stack) {\n            histories[historyId].stack = [];\n            histories[historyId].cursor = -1;\n          }\n\n          if (currentView && currentView.historyId === historyId) {\n            currentView.backViewId = currentView.forwardViewId = null;\n            histories[historyId].stack.push(currentView);\n          } else if (histories[historyId].destroy) {\n            histories[historyId].destroy();\n          }\n\n        }\n      }\n\n      for (var viewId in viewHistory.views) {\n        if (viewId !== currentView.viewId) {\n          delete viewHistory.views[viewId];\n        }\n      }\n\n      if (currentView) {\n        setNavViews(currentView.viewId);\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#clearCache\n     * @description Removes all cached views within every {@link ionic.directive:ionNavView}.\n     * This both removes the view element from the DOM, and destroy it's scope.\n     */\n    clearCache: function(stateIds) {\n      $timeout(function() {\n        $ionicNavViewDelegate._instances.forEach(function(instance) {\n          instance.clearCache(stateIds);\n        });\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicHistory#nextViewOptions\n     * @description Sets options for the next view. This method can be useful to override\n     * certain view/transition defaults right before a view transition happens. For example,\n     * the {@link ionic.directive:menuClose} directive uses this method internally to ensure\n     * an animated view transition does not happen when a side menu is open, and also sets\n     * the next view as the root of its history stack. After the transition these options\n     * are set back to null.\n     *\n     * Available options:\n     *\n     * * `disableAnimate`: Do not animate the next transition.\n     * * `disableBack`: The next view should forget its back view, and set it to null.\n     * * `historyRoot`: The next view should become the root view in its history stack.\n     *\n     * ```js\n     * $ionicHistory.nextViewOptions({\n     *   disableAnimate: true,\n     *   disableBack: true\n     * });\n     * ```\n     */\n    nextViewOptions: function(opts) {\n      if (arguments.length) {\n        $timeout.cancel(nextViewExpireTimer);\n        if (opts === null) {\n          nextViewOptions = opts;\n        } else {\n          nextViewOptions = nextViewOptions || {};\n          extend(nextViewOptions, opts);\n          if (nextViewOptions.expire) {\n            nextViewExpireTimer = $timeout(function() {\n              nextViewOptions = null;\n            }, nextViewOptions.expire);\n          }\n        }\n      }\n      return nextViewOptions;\n    },\n\n    isAbstractEle: function(ele, viewLocals) {\n      if (viewLocals && viewLocals.$$state && viewLocals.$$state.self['abstract']) {\n        return true;\n      }\n      return !!(ele && (isAbstractTag(ele) || isAbstractTag(ele.children())));\n    },\n\n    isActiveScope: function(scope) {\n      if (!scope) return false;\n\n      var climbScope = scope;\n      var currentHistoryId = this.currentHistoryId();\n      var foundHistoryId;\n\n      while (climbScope) {\n        if (climbScope.$$disconnected) {\n          return false;\n        }\n\n        if (!foundHistoryId && climbScope.hasOwnProperty('$historyId')) {\n          foundHistoryId = true;\n        }\n\n        if (currentHistoryId) {\n          if (climbScope.hasOwnProperty('$historyId') && currentHistoryId == climbScope.$historyId) {\n            return true;\n          }\n          if (climbScope.hasOwnProperty('$activeHistoryId')) {\n            if (currentHistoryId == climbScope.$activeHistoryId) {\n              if (climbScope.hasOwnProperty('$historyId')) {\n                return true;\n              }\n              if (!foundHistoryId) {\n                return true;\n              }\n            }\n          }\n        }\n\n        if (foundHistoryId && climbScope.hasOwnProperty('$activeHistoryId')) {\n          foundHistoryId = false;\n        }\n\n        climbScope = climbScope.$parent;\n      }\n\n      return currentHistoryId ? currentHistoryId == 'root' : true;\n    }\n\n  };\n\n  function isAbstractTag(ele) {\n    return ele && ele.length && /ion-side-menus|ion-tabs/i.test(ele[0].tagName);\n  }\n\n  function canSwipeBack(ele, viewLocals) {\n    if (viewLocals && viewLocals.$$state && viewLocals.$$state.self.canSwipeBack === false) {\n      return false;\n    }\n    if (ele && ele.attr('can-swipe-back') === 'false') {\n      return false;\n    }\n    return true;\n  }\n\n}])\n\n.run([\n  '$rootScope',\n  '$state',\n  '$location',\n  '$document',\n  '$ionicPlatform',\n  '$ionicHistory',\n  'IONIC_BACK_PRIORITY',\nfunction($rootScope, $state, $location, $document, $ionicPlatform, $ionicHistory, IONIC_BACK_PRIORITY) {\n\n  // always reset the keyboard state when change stage\n  $rootScope.$on('$ionicView.beforeEnter', function() {\n    ionic.keyboard && ionic.keyboard.hide && ionic.keyboard.hide();\n  });\n\n  $rootScope.$on('$ionicHistory.change', function(e, data) {\n    if (!data) return null;\n\n    var viewHistory = $ionicHistory.viewHistory();\n\n    var hist = (data.historyId ? viewHistory.histories[ data.historyId ] : null);\n    if (hist && hist.cursor > -1 && hist.cursor < hist.stack.length) {\n      // the history they're going to already exists\n      // go to it's last view in its stack\n      var view = hist.stack[ hist.cursor ];\n      return view.go(data);\n    }\n\n    // this history does not have a URL, but it does have a uiSref\n    // figure out its URL from the uiSref\n    if (!data.url && data.uiSref) {\n      data.url = $state.href(data.uiSref);\n    }\n\n    if (data.url) {\n      // don't let it start with a #, messes with $location.url()\n      if (data.url.indexOf('#') === 0) {\n        data.url = data.url.replace('#', '');\n      }\n      if (data.url !== $location.url()) {\n        // we've got a good URL, ready GO!\n        $location.url(data.url);\n      }\n    }\n  });\n\n  $rootScope.$ionicGoBack = function(backCount) {\n    $ionicHistory.goBack(backCount);\n  };\n\n  // Set the document title when a new view is shown\n  $rootScope.$on('$ionicView.afterEnter', function(ev, data) {\n    if (data && data.title) {\n      $document[0].title = data.title;\n    }\n  });\n\n  // Triggered when devices with a hardware back button (Android) is clicked by the user\n  // This is a Cordova/Phonegap platform specifc method\n  function onHardwareBackButton(e) {\n    var backView = $ionicHistory.backView();\n    if (backView) {\n      // there is a back view, go to it\n      backView.go();\n    } else {\n      // there is no back view, so close the app instead\n      ionic.Platform.exitApp();\n    }\n    e.preventDefault();\n    return false;\n  }\n  $ionicPlatform.registerBackButtonAction(\n    onHardwareBackButton,\n    IONIC_BACK_PRIORITY.view\n  );\n\n}]);\n\n/**\n * @ngdoc provider\n * @name $ionicConfigProvider\n * @module ionic\n * @description\n * Ionic automatically takes platform configurations into account to adjust things like what\n * transition style to use and whether tab icons should show on the top or bottom. For example,\n * iOS will move forward by transitioning the entering view from right to center and the leaving\n * view from center to left. However, Android will transition with the entering view going from\n * bottom to center, covering the previous view, which remains stationary. It should be noted\n * that when a platform is not iOS or Android, then it'll default to iOS. So if you are\n * developing on a desktop browser, it's going to take on iOS default configs.\n *\n * These configs can be changed using the `$ionicConfigProvider` during the configuration phase\n * of your app. Additionally, `$ionicConfig` can also set and get config values during the run\n * phase and within the app itself.\n *\n * By default, all base config variables are set to `'platform'`, which means it'll take on the\n * default config of the platform on which it's running. Config variables can be set at this\n * level so all platforms follow the same setting, rather than its platform config.\n * The following code would set the same config variable for all platforms:\n *\n * ```js\n * $ionicConfigProvider.views.maxCache(10);\n * ```\n *\n * Additionally, each platform can have it's own config within the `$ionicConfigProvider.platform`\n * property. The config below would only apply to Android devices.\n *\n * ```js\n * $ionicConfigProvider.platform.android.views.maxCache(5);\n * ```\n *\n * @usage\n * ```js\n * var myApp = angular.module('reallyCoolApp', ['ionic']);\n *\n * myApp.config(function($ionicConfigProvider) {\n *   $ionicConfigProvider.views.maxCache(5);\n *\n *   // note that you can also chain configs\n *   $ionicConfigProvider.backButton.text('Go Back').icon('ion-chevron-left');\n * });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#views.transition\n * @description Animation style when transitioning between views. Default `platform`.\n *\n * @param {string} transition Which style of view transitioning to use.\n *\n * * `platform`: Dynamically choose the correct transition style depending on the platform\n * the app is running from. If the platform is not `ios` or `android` then it will default\n * to `ios`.\n * * `ios`: iOS style transition.\n * * `android`: Android style transition.\n * * `none`: Do not perform animated transitions.\n *\n * @returns {string} value\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#views.maxCache\n * @description  Maximum number of view elements to cache in the DOM. When the max number is\n * exceeded, the view with the longest time period since it was accessed is removed. Views that\n * stay in the DOM cache the view's scope, current state, and scroll position. The scope is\n * disconnected from the `$watch` cycle when it is cached and reconnected when it enters again.\n * When the maximum cache is `0`, the leaving view's element will be removed from the DOM after\n * each view transition, and the next time the same view is shown, it will have to re-compile,\n * attach to the DOM, and link the element again. This disables caching, in effect.\n * @param {number} maxNumber Maximum number of views to retain. Default `10`.\n * @returns {number} How many views Ionic will hold onto until the a view is removed.\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#views.forwardCache\n * @description  By default, when navigating, views that were recently visited are cached, and\n * the same instance data and DOM elements are referenced when navigating back. However, when\n * navigating back in the history, the \"forward\" views are removed from the cache. If you\n * navigate forward to the same view again, it'll create a new DOM element and controller\n * instance. Basically, any forward views are reset each time. Set this config to `true` to have\n * forward views cached and not reset on each load.\n * @param {boolean} value\n * @returns {boolean}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#scrolling.jsScrolling\n * @description  Whether to use JS or Native scrolling. Defaults to JS scrolling. Setting this to\n * `false` has the same effect as setting each `ion-content` to have `overflow-scroll='true'`.\n * @param {boolean} value Defaults to `true`\n * @returns {boolean}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#backButton.icon\n * @description Back button icon.\n * @param {string} value\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#backButton.text\n * @description Back button text.\n * @param {string} value Defaults to `Back`.\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#backButton.previousTitleText\n * @description If the previous title text should become the back button text. This\n * is the default for iOS.\n * @param {boolean} value\n * @returns {boolean}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#form.checkbox\n * @description Checkbox style. Android defaults to `square` and iOS defaults to `circle`.\n * @param {string} value\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#form.toggle\n * @description Toggle item style. Android defaults to `small` and iOS defaults to `large`.\n * @param {string} value\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#tabs.style\n * @description Tab style. Android defaults to `striped` and iOS defaults to `standard`.\n * @param {string} value Available values include `striped` and `standard`.\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#tabs.position\n * @description Tab position. Android defaults to `top` and iOS defaults to `bottom`.\n * @param {string} value Available values include `top` and `bottom`.\n * @returns {string}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#templates.maxPrefetch\n * @description Sets the maximum number of templates to prefetch from the templateUrls defined in\n * $stateProvider.state. If set to `0`, the user will have to wait\n * for a template to be fetched the first time when navigating to a new page. Default `30`.\n * @param {integer} value Max number of template to prefetch from the templateUrls defined in\n * `$stateProvider.state()`.\n * @returns {integer}\n */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#navBar.alignTitle\n * @description Which side of the navBar to align the title. Default `center`.\n *\n * @param {string} value side of the navBar to align the title.\n *\n * * `platform`: Dynamically choose the correct title style depending on the platform\n * the app is running from. If the platform is `ios`, it will default to `center`.\n * If the platform is `android`, it will default to `left`. If the platform is not\n * `ios` or `android`, it will default to `center`.\n *\n * * `left`: Left align the title in the navBar\n * * `center`: Center align the title in the navBar\n * * `right`: Right align the title in the navBar.\n *\n * @returns {string} value\n */\n\n/**\n  * @ngdoc method\n  * @name $ionicConfigProvider#navBar.positionPrimaryButtons\n  * @description Which side of the navBar to align the primary navBar buttons. Default `left`.\n  *\n  * @param {string} value side of the navBar to align the primary navBar buttons.\n  *\n  * * `platform`: Dynamically choose the correct title style depending on the platform\n  * the app is running from. If the platform is `ios`, it will default to `left`.\n  * If the platform is `android`, it will default to `right`. If the platform is not\n  * `ios` or `android`, it will default to `left`.\n  *\n  * * `left`: Left align the primary navBar buttons in the navBar\n  * * `right`: Right align the primary navBar buttons in the navBar.\n  *\n  * @returns {string} value\n  */\n\n/**\n * @ngdoc method\n * @name $ionicConfigProvider#navBar.positionSecondaryButtons\n * @description Which side of the navBar to align the secondary navBar buttons. Default `right`.\n *\n * @param {string} value side of the navBar to align the secondary navBar buttons.\n *\n * * `platform`: Dynamically choose the correct title style depending on the platform\n * the app is running from. If the platform is `ios`, it will default to `right`.\n * If the platform is `android`, it will default to `right`. If the platform is not\n * `ios` or `android`, it will default to `right`.\n *\n * * `left`: Left align the secondary navBar buttons in the navBar\n * * `right`: Right align the secondary navBar buttons in the navBar.\n *\n * @returns {string} value\n */\n\nIonicModule\n.provider('$ionicConfig', function() {\n\n  var provider = this;\n  provider.platform = {};\n  var PLATFORM = 'platform';\n\n  var configProperties = {\n    views: {\n      maxCache: PLATFORM,\n      forwardCache: PLATFORM,\n      transition: PLATFORM,\n      swipeBackEnabled: PLATFORM,\n      swipeBackHitWidth: PLATFORM\n    },\n    navBar: {\n      alignTitle: PLATFORM,\n      positionPrimaryButtons: PLATFORM,\n      positionSecondaryButtons: PLATFORM,\n      transition: PLATFORM\n    },\n    backButton: {\n      icon: PLATFORM,\n      text: PLATFORM,\n      previousTitleText: PLATFORM\n    },\n    form: {\n      checkbox: PLATFORM,\n      toggle: PLATFORM\n    },\n    scrolling: {\n      jsScrolling: PLATFORM\n    },\n    tabs: {\n      style: PLATFORM,\n      position: PLATFORM\n    },\n    templates: {\n      maxPrefetch: PLATFORM\n    },\n    platform: {}\n  };\n  createConfig(configProperties, provider, '');\n\n\n\n  // Default\n  // -------------------------\n  setPlatformConfig('default', {\n\n    views: {\n      maxCache: 10,\n      forwardCache: false,\n      transition: 'ios',\n      swipeBackEnabled: true,\n      swipeBackHitWidth: 45\n    },\n\n    navBar: {\n      alignTitle: 'center',\n      positionPrimaryButtons: 'left',\n      positionSecondaryButtons: 'right',\n      transition: 'view'\n    },\n\n    backButton: {\n      icon: 'ion-ios-arrow-back',\n      text: 'Back',\n      previousTitleText: true\n    },\n\n    form: {\n      checkbox: 'circle',\n      toggle: 'large'\n    },\n\n    scrolling: {\n      jsScrolling: true\n    },\n\n    tabs: {\n      style: 'standard',\n      position: 'bottom'\n    },\n\n    templates: {\n      maxPrefetch: 30\n    }\n\n  });\n\n\n\n  // iOS (it is the default already)\n  // -------------------------\n  setPlatformConfig('ios', {});\n\n\n\n  // Android\n  // -------------------------\n  setPlatformConfig('android', {\n\n    views: {\n      transition: 'android',\n      swipeBackEnabled: false\n    },\n\n    navBar: {\n      alignTitle: 'left',\n      positionPrimaryButtons: 'right',\n      positionSecondaryButtons: 'right'\n    },\n\n    backButton: {\n      icon: 'ion-android-arrow-back',\n      text: false,\n      previousTitleText: false\n    },\n\n    form: {\n      checkbox: 'square',\n      toggle: 'small'\n    },\n\n    tabs: {\n      style: 'striped',\n      position: 'top'\n    }\n\n  });\n\n  // Windows Phone\n  // -------------------------\n  setPlatformConfig('windowsphone', {\n    //scrolling: {\n    //  jsScrolling: false\n    //}\n  });\n\n\n  provider.transitions = {\n    views: {},\n    navBar: {}\n  };\n\n\n  // iOS Transitions\n  // -----------------------\n  provider.transitions.views.ios = function(enteringEle, leavingEle, direction, shouldAnimate) {\n\n    function setStyles(ele, opacity, x, boxShadowOpacity) {\n      var css = {};\n      css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;\n      css.opacity = opacity;\n      if (boxShadowOpacity > -1) {\n        css.boxShadow = '0 0 10px rgba(0,0,0,' + (d.shouldAnimate ? boxShadowOpacity * 0.45 : 0.3) + ')';\n      }\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';\n      ionic.DomUtil.cachedStyles(ele, css);\n    }\n\n    var d = {\n      run: function(step) {\n        if (direction == 'forward') {\n          setStyles(enteringEle, 1, (1 - step) * 99, 1 - step); // starting at 98% prevents a flicker\n          setStyles(leavingEle, (1 - 0.1 * step), step * -33, -1);\n\n        } else if (direction == 'back') {\n          setStyles(enteringEle, (1 - 0.1 * (1 - step)), (1 - step) * -33, -1);\n          setStyles(leavingEle, 1, step * 100, 1 - step);\n\n        } else {\n          // swap, enter, exit\n          setStyles(enteringEle, 1, 0, -1);\n          setStyles(leavingEle, 0, 0, -1);\n        }\n      },\n      shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')\n    };\n\n    return d;\n  };\n\n  provider.transitions.navBar.ios = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {\n\n    function setStyles(ctrl, opacity, titleX, backTextX) {\n      var css = {};\n      css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : '0ms';\n      css.opacity = opacity === 1 ? '' : opacity;\n\n      ctrl.setCss('buttons-left', css);\n      ctrl.setCss('buttons-right', css);\n      ctrl.setCss('back-button', css);\n\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + backTextX + 'px,0,0)';\n      ctrl.setCss('back-text', css);\n\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + titleX + 'px,0,0)';\n      ctrl.setCss('title', css);\n    }\n\n    function enter(ctrlA, ctrlB, step) {\n      if (!ctrlA || !ctrlB) return;\n      var titleX = (ctrlA.titleTextX() + ctrlA.titleWidth()) * (1 - step);\n      var backTextX = (ctrlB && (ctrlB.titleTextX() - ctrlA.backButtonTextLeft()) * (1 - step)) || 0;\n      setStyles(ctrlA, step, titleX, backTextX);\n    }\n\n    function leave(ctrlA, ctrlB, step) {\n      if (!ctrlA || !ctrlB) return;\n      var titleX = (-(ctrlA.titleTextX() - ctrlB.backButtonTextLeft()) - (ctrlA.titleLeftRight())) * step;\n      setStyles(ctrlA, 1 - step, titleX, 0);\n    }\n\n    var d = {\n      run: function(step) {\n        var enteringHeaderCtrl = enteringHeaderBar.controller();\n        var leavingHeaderCtrl = leavingHeaderBar && leavingHeaderBar.controller();\n        if (d.direction == 'back') {\n          leave(enteringHeaderCtrl, leavingHeaderCtrl, 1 - step);\n          enter(leavingHeaderCtrl, enteringHeaderCtrl, 1 - step);\n        } else {\n          enter(enteringHeaderCtrl, leavingHeaderCtrl, step);\n          leave(leavingHeaderCtrl, enteringHeaderCtrl, step);\n        }\n      },\n      direction: direction,\n      shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')\n    };\n\n    return d;\n  };\n\n\n  // Android Transitions\n  // -----------------------\n\n  provider.transitions.views.android = function(enteringEle, leavingEle, direction, shouldAnimate) {\n    shouldAnimate = shouldAnimate && (direction == 'forward' || direction == 'back');\n\n    function setStyles(ele, x) {\n      var css = {};\n      css[ionic.CSS.TRANSITION_DURATION] = d.shouldAnimate ? '' : 0;\n      css[ionic.CSS.TRANSFORM] = 'translate3d(' + x + '%,0,0)';\n      ionic.DomUtil.cachedStyles(ele, css);\n    }\n\n    var d = {\n      run: function(step) {\n        if (direction == 'forward') {\n          setStyles(enteringEle, (1 - step) * 99); // starting at 98% prevents a flicker\n          setStyles(leavingEle, step * -100);\n\n        } else if (direction == 'back') {\n          setStyles(enteringEle, (1 - step) * -100);\n          setStyles(leavingEle, step * 100);\n\n        } else {\n          // swap, enter, exit\n          setStyles(enteringEle, 0);\n          setStyles(leavingEle, 0);\n        }\n      },\n      shouldAnimate: shouldAnimate\n    };\n\n    return d;\n  };\n\n  provider.transitions.navBar.android = function(enteringHeaderBar, leavingHeaderBar, direction, shouldAnimate) {\n\n    function setStyles(ctrl, opacity) {\n      if (!ctrl) return;\n      var css = {};\n      css.opacity = opacity === 1 ? '' : opacity;\n\n      ctrl.setCss('buttons-left', css);\n      ctrl.setCss('buttons-right', css);\n      ctrl.setCss('back-button', css);\n      ctrl.setCss('back-text', css);\n      ctrl.setCss('title', css);\n    }\n\n    return {\n      run: function(step) {\n        setStyles(enteringHeaderBar.controller(), step);\n        setStyles(leavingHeaderBar && leavingHeaderBar.controller(), 1 - step);\n      },\n      shouldAnimate: shouldAnimate && (direction == 'forward' || direction == 'back')\n    };\n  };\n\n\n  // No Transition\n  // -----------------------\n\n  provider.transitions.views.none = function(enteringEle, leavingEle) {\n    return {\n      run: function(step) {\n        provider.transitions.views.android(enteringEle, leavingEle, false, false).run(step);\n      },\n      shouldAnimate: false\n    };\n  };\n\n  provider.transitions.navBar.none = function(enteringHeaderBar, leavingHeaderBar) {\n    return {\n      run: function(step) {\n        provider.transitions.navBar.ios(enteringHeaderBar, leavingHeaderBar, false, false).run(step);\n        provider.transitions.navBar.android(enteringHeaderBar, leavingHeaderBar, false, false).run(step);\n      },\n      shouldAnimate: false\n    };\n  };\n\n\n  // private: used to set platform configs\n  function setPlatformConfig(platformName, platformConfigs) {\n    configProperties.platform[platformName] = platformConfigs;\n    provider.platform[platformName] = {};\n\n    addConfig(configProperties, configProperties.platform[platformName]);\n\n    createConfig(configProperties.platform[platformName], provider.platform[platformName], '');\n  }\n\n\n  // private: used to recursively add new platform configs\n  function addConfig(configObj, platformObj) {\n    for (var n in configObj) {\n      if (n != PLATFORM && configObj.hasOwnProperty(n)) {\n        if (angular.isObject(configObj[n])) {\n          if (!isDefined(platformObj[n])) {\n            platformObj[n] = {};\n          }\n          addConfig(configObj[n], platformObj[n]);\n\n        } else if (!isDefined(platformObj[n])) {\n          platformObj[n] = null;\n        }\n      }\n    }\n  }\n\n\n  // private: create methods for each config to get/set\n  function createConfig(configObj, providerObj, platformPath) {\n    forEach(configObj, function(value, namespace) {\n\n      if (angular.isObject(configObj[namespace])) {\n        // recursively drill down the config object so we can create a method for each one\n        providerObj[namespace] = {};\n        createConfig(configObj[namespace], providerObj[namespace], platformPath + '.' + namespace);\n\n      } else {\n        // create a method for the provider/config methods that will be exposed\n        providerObj[namespace] = function(newValue) {\n          if (arguments.length) {\n            configObj[namespace] = newValue;\n            return providerObj;\n          }\n          if (configObj[namespace] == PLATFORM) {\n            // if the config is set to 'platform', then get this config's platform value\n            var platformConfig = stringObj(configProperties.platform, ionic.Platform.platform() + platformPath + '.' + namespace);\n            if (platformConfig || platformConfig === false) {\n              return platformConfig;\n            }\n            // didnt find a specific platform config, now try the default\n            return stringObj(configProperties.platform, 'default' + platformPath + '.' + namespace);\n          }\n          return configObj[namespace];\n        };\n      }\n\n    });\n  }\n\n  function stringObj(obj, str) {\n    str = str.split(\".\");\n    for (var i = 0; i < str.length; i++) {\n      if (obj && isDefined(obj[str[i]])) {\n        obj = obj[str[i]];\n      } else {\n        return null;\n      }\n    }\n    return obj;\n  }\n\n  provider.setPlatformConfig = setPlatformConfig;\n\n\n  // private: Service definition for internal Ionic use\n  /**\n   * @ngdoc service\n   * @name $ionicConfig\n   * @module ionic\n   * @private\n   */\n  provider.$get = function() {\n    return provider;\n  };\n})\n// Fix for URLs in Cordova apps on Windows Phone\n// http://blogs.msdn.com/b/msdn_answers/archive/2015/02/10/\n// running-cordova-apps-on-windows-and-windows-phone-8-1-using-ionic-angularjs-and-other-frameworks.aspx\n.config(['$compileProvider', function($compileProvider) {\n  $compileProvider.aHrefSanitizationWhitelist(/^\\s*(https?|tel|ftp|mailto|file|ghttps?|ms-appx|x-wmapp0):/);\n  $compileProvider.imgSrcSanitizationWhitelist(/^\\s*(https?|tel|ftp|file|blob|ms-appx|x-wmapp0):|data:image\\//);\n}]);\n\n\nvar LOADING_TPL =\n  '<div class=\"loading-container\">' +\n    '<div class=\"loading\">' +\n    '</div>' +\n  '</div>';\n\nvar LOADING_HIDE_DEPRECATED = '$ionicLoading instance.hide() has been deprecated. Use $ionicLoading.hide().';\nvar LOADING_SHOW_DEPRECATED = '$ionicLoading instance.show() has been deprecated. Use $ionicLoading.show().';\nvar LOADING_SET_DEPRECATED = '$ionicLoading instance.setContent() has been deprecated. Use $ionicLoading.show({ template: \\'my content\\' }).';\n\n/**\n * @ngdoc service\n * @name $ionicLoading\n * @module ionic\n * @description\n * An overlay that can be used to indicate activity while blocking user\n * interaction.\n *\n * @usage\n * ```js\n * angular.module('LoadingApp', ['ionic'])\n * .controller('LoadingCtrl', function($scope, $ionicLoading) {\n *   $scope.show = function() {\n *     $ionicLoading.show({\n *       template: 'Loading...'\n *     });\n *   };\n *   $scope.hide = function(){\n *     $ionicLoading.hide();\n *   };\n * });\n * ```\n */\n/**\n * @ngdoc object\n * @name $ionicLoadingConfig\n * @module ionic\n * @description\n * Set the default options to be passed to the {@link ionic.service:$ionicLoading} service.\n *\n * @usage\n * ```js\n * var app = angular.module('myApp', ['ionic'])\n * app.constant('$ionicLoadingConfig', {\n *   template: 'Default Loading Template...'\n * });\n * app.controller('AppCtrl', function($scope, $ionicLoading) {\n *   $scope.showLoading = function() {\n *     $ionicLoading.show(); //options default to values in $ionicLoadingConfig\n *   };\n * });\n * ```\n */\nIonicModule\n.constant('$ionicLoadingConfig', {\n  template: '<ion-spinner></ion-spinner>'\n})\n.factory('$ionicLoading', [\n  '$ionicLoadingConfig',\n  '$ionicBody',\n  '$ionicTemplateLoader',\n  '$ionicBackdrop',\n  '$timeout',\n  '$q',\n  '$log',\n  '$compile',\n  '$ionicPlatform',\n  '$rootScope',\n  'IONIC_BACK_PRIORITY',\nfunction($ionicLoadingConfig, $ionicBody, $ionicTemplateLoader, $ionicBackdrop, $timeout, $q, $log, $compile, $ionicPlatform, $rootScope, IONIC_BACK_PRIORITY) {\n\n  var loaderInstance;\n  //default values\n  var deregisterBackAction = noop;\n  var deregisterStateListener1 = noop;\n  var deregisterStateListener2 = noop;\n  var loadingShowDelay = $q.when();\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicLoading#show\n     * @description Shows a loading indicator. If the indicator is already shown,\n     * it will set the options given and keep the indicator shown.\n     * @param {object} opts The options for the loading indicator. Available properties:\n     *  - `{string=}` `template` The html content of the indicator.\n     *  - `{string=}` `templateUrl` The url of an html template to load as the content of the indicator.\n     *  - `{object=}` `scope` The scope to be a child of. Default: creates a child of $rootScope.\n     *  - `{boolean=}` `noBackdrop` Whether to hide the backdrop. By default it will be shown.\n     *  - `{boolean=}` `hideOnStateChange` Whether to hide the loading spinner when navigating\n     *    to a new state. Default false.\n     *  - `{number=}` `delay` How many milliseconds to delay showing the indicator. By default there is no delay.\n     *  - `{number=}` `duration` How many milliseconds to wait until automatically\n     *  hiding the indicator. By default, the indicator will be shown until `.hide()` is called.\n     */\n    show: showLoader,\n    /**\n     * @ngdoc method\n     * @name $ionicLoading#hide\n     * @description Hides the loading indicator, if shown.\n     */\n    hide: hideLoader,\n    /**\n     * @private for testing\n     */\n    _getLoader: getLoader\n  };\n\n  function getLoader() {\n    if (!loaderInstance) {\n      loaderInstance = $ionicTemplateLoader.compile({\n        template: LOADING_TPL,\n        appendTo: $ionicBody.get()\n      })\n      .then(function(self) {\n        self.show = function(options) {\n          var templatePromise = options.templateUrl ?\n            $ionicTemplateLoader.load(options.templateUrl) :\n            //options.content: deprecated\n            $q.when(options.template || options.content || '');\n\n          self.scope = options.scope || self.scope;\n\n          if (!self.isShown) {\n            //options.showBackdrop: deprecated\n            self.hasBackdrop = !options.noBackdrop && options.showBackdrop !== false;\n            if (self.hasBackdrop) {\n              $ionicBackdrop.retain();\n              $ionicBackdrop.getElement().addClass('backdrop-loading');\n            }\n          }\n\n          if (options.duration) {\n            $timeout.cancel(self.durationTimeout);\n            self.durationTimeout = $timeout(\n              angular.bind(self, self.hide),\n              +options.duration\n            );\n          }\n\n          deregisterBackAction();\n          //Disable hardware back button while loading\n          deregisterBackAction = $ionicPlatform.registerBackButtonAction(\n            noop,\n            IONIC_BACK_PRIORITY.loading\n          );\n\n          templatePromise.then(function(html) {\n            if (html) {\n              var loading = self.element.children();\n              loading.html(html);\n              $compile(loading.contents())(self.scope);\n            }\n\n            //Don't show until template changes\n            if (self.isShown) {\n              self.element.addClass('visible');\n              ionic.requestAnimationFrame(function() {\n                if (self.isShown) {\n                  self.element.addClass('active');\n                  $ionicBody.addClass('loading-active');\n                }\n              });\n            }\n          });\n\n          self.isShown = true;\n        };\n        self.hide = function() {\n\n          deregisterBackAction();\n          if (self.isShown) {\n            if (self.hasBackdrop) {\n              $ionicBackdrop.release();\n              $ionicBackdrop.getElement().removeClass('backdrop-loading');\n            }\n            self.element.removeClass('active');\n            $ionicBody.removeClass('loading-active');\n            setTimeout(function() {\n              !self.isShown && self.element.removeClass('visible');\n            }, 200);\n          }\n          $timeout.cancel(self.durationTimeout);\n          self.isShown = false;\n        };\n\n        return self;\n      });\n    }\n    return loaderInstance;\n  }\n\n  function showLoader(options) {\n    options = extend({}, $ionicLoadingConfig || {}, options || {});\n    var delay = options.delay || options.showDelay || 0;\n\n    deregisterStateListener1();\n    deregisterStateListener2();\n    if (options.hideOnStateChange) {\n      deregisterStateListener1 = $rootScope.$on('$stateChangeSuccess', hideLoader);\n      deregisterStateListener2 = $rootScope.$on('$stateChangeError', hideLoader);\n    }\n\n    //If loading.show() was called previously, cancel it and show with our new options\n    $timeout.cancel(loadingShowDelay);\n    loadingShowDelay = $timeout(noop, delay);\n    loadingShowDelay.then(getLoader).then(function(loader) {\n      return loader.show(options);\n    });\n\n    return {\n      hide: function deprecatedHide() {\n        $log.error(LOADING_HIDE_DEPRECATED);\n        return hideLoader.apply(this, arguments);\n      },\n      show: function deprecatedShow() {\n        $log.error(LOADING_SHOW_DEPRECATED);\n        return showLoader.apply(this, arguments);\n      },\n      setContent: function deprecatedSetContent(content) {\n        $log.error(LOADING_SET_DEPRECATED);\n        return getLoader().then(function(loader) {\n          loader.show({ template: content });\n        });\n      }\n    };\n  }\n\n  function hideLoader() {\n    deregisterStateListener1();\n    deregisterStateListener2();\n    $timeout.cancel(loadingShowDelay);\n    getLoader().then(function(loader) {\n      loader.hide();\n    });\n  }\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicModal\n * @module ionic\n * @description\n *\n * Related: {@link ionic.controller:ionicModal ionicModal controller}.\n *\n * The Modal is a content pane that can go over the user's main view\n * temporarily.  Usually used for making a choice or editing an item.\n *\n * Put the content of the modal inside of an `<ion-modal-view>` element.\n *\n * **Notes:**\n * - A modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating\n * scope, passing in itself as an event argument. Both the modal.removed and modal.hidden events are\n * called when the modal is removed.\n *\n * - This example assumes your modal is in your main index file or another template file. If it is in its own\n * template file, remove the script tags and call it by file name.\n *\n * @usage\n * ```html\n * <script id=\"my-modal.html\" type=\"text/ng-template\">\n *   <ion-modal-view>\n *     <ion-header-bar>\n *       <h1 class=\"title\">My Modal title</h1>\n *     </ion-header-bar>\n *     <ion-content>\n *       Hello!\n *     </ion-content>\n *   </ion-modal-view>\n * </script>\n * ```\n * ```js\n * angular.module('testApp', ['ionic'])\n * .controller('MyController', function($scope, $ionicModal) {\n *   $ionicModal.fromTemplateUrl('my-modal.html', {\n *     scope: $scope,\n *     animation: 'slide-in-up'\n *   }).then(function(modal) {\n *     $scope.modal = modal;\n *   });\n *   $scope.openModal = function() {\n *     $scope.modal.show();\n *   };\n *   $scope.closeModal = function() {\n *     $scope.modal.hide();\n *   };\n *   //Cleanup the modal when we're done with it!\n *   $scope.$on('$destroy', function() {\n *     $scope.modal.remove();\n *   });\n *   // Execute action on hide modal\n *   $scope.$on('modal.hidden', function() {\n *     // Execute action\n *   });\n *   // Execute action on remove modal\n *   $scope.$on('modal.removed', function() {\n *     // Execute action\n *   });\n * });\n * ```\n */\nIonicModule\n.factory('$ionicModal', [\n  '$rootScope',\n  '$ionicBody',\n  '$compile',\n  '$timeout',\n  '$ionicPlatform',\n  '$ionicTemplateLoader',\n  '$$q',\n  '$log',\n  '$ionicClickBlock',\n  '$window',\n  'IONIC_BACK_PRIORITY',\nfunction($rootScope, $ionicBody, $compile, $timeout, $ionicPlatform, $ionicTemplateLoader, $$q, $log, $ionicClickBlock, $window, IONIC_BACK_PRIORITY) {\n\n  /**\n   * @ngdoc controller\n   * @name ionicModal\n   * @module ionic\n   * @description\n   * Instantiated by the {@link ionic.service:$ionicModal} service.\n   *\n   * Be sure to call [remove()](#remove) when you are done with each modal\n   * to clean it up and avoid memory leaks.\n   *\n   * Note: a modal will broadcast 'modal.shown', 'modal.hidden', and 'modal.removed' events from its originating\n   * scope, passing in itself as an event argument. Note: both modal.removed and modal.hidden are\n   * called when the modal is removed.\n   */\n  var ModalView = ionic.views.Modal.inherit({\n    /**\n     * @ngdoc method\n     * @name ionicModal#initialize\n     * @description Creates a new modal controller instance.\n     * @param {object} options An options object with the following properties:\n     *  - `{object=}` `scope` The scope to be a child of.\n     *    Default: creates a child of $rootScope.\n     *  - `{string=}` `animation` The animation to show & hide with.\n     *    Default: 'slide-in-up'\n     *  - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of\n     *    the modal when shown. Will only show the keyboard on iOS, to force the keyboard to show\n     *    on Android, please use the [Ionic keyboard plugin](https://github.com/driftyco/ionic-plugin-keyboard#keyboardshow).\n     *    Default: false.\n     *  - `{boolean=}` `backdropClickToClose` Whether to close the modal on clicking the backdrop.\n     *    Default: true.\n     *  - `{boolean=}` `hardwareBackButtonClose` Whether the modal can be closed using the hardware\n     *    back button on Android and similar devices.  Default: true.\n     */\n    initialize: function(opts) {\n      ionic.views.Modal.prototype.initialize.call(this, opts);\n      this.animation = opts.animation || 'slide-in-up';\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#show\n     * @description Show this modal instance.\n     * @returns {promise} A promise which is resolved when the modal is finished animating in.\n     */\n    show: function(target) {\n      var self = this;\n\n      if (self.scope.$$destroyed) {\n        $log.error('Cannot call ' + self.viewType + '.show() after remove(). Please create a new ' + self.viewType + ' instance.');\n        return $$q.when();\n      }\n\n      // on iOS, clicks will sometimes bleed through/ghost click on underlying\n      // elements\n      $ionicClickBlock.show(600);\n\n      var modalEl = jqLite(self.modalEl);\n\n      self.el.classList.remove('hide');\n      $timeout(function() {\n        if (!self._isShown) return;\n        $ionicBody.addClass(self.viewType + '-open');\n      }, 400, false);\n\n      if (!self.el.parentElement) {\n        modalEl.addClass(self.animation);\n        $ionicBody.append(self.el);\n      }\n\n      // if modal was closed while the keyboard was up, reset scroll view on\n      // next show since we can only resize it once it's visible\n      var scrollCtrl = modalEl.data('$$ionicScrollController');\n      scrollCtrl && scrollCtrl.resize();\n\n      if (target && self.positionView) {\n        self.positionView(target, modalEl);\n        // set up a listener for in case the window size changes\n\n        self._onWindowResize = function() {\n          if (self._isShown) self.positionView(target, modalEl);\n        };\n        ionic.on('resize', self._onWindowResize, window);\n      }\n\n      modalEl.addClass('ng-enter active')\n             .removeClass('ng-leave ng-leave-active');\n\n      self._isShown = true;\n      self._deregisterBackButton = $ionicPlatform.registerBackButtonAction(\n        self.hardwareBackButtonClose ? angular.bind(self, self.hide) : noop,\n        IONIC_BACK_PRIORITY.modal\n      );\n\n      ionic.views.Modal.prototype.show.call(self);\n\n      $timeout(function() {\n        if (!self._isShown) return;\n        modalEl.addClass('ng-enter-active');\n        ionic.trigger('resize');\n        self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.shown', self);\n        self.el.classList.add('active');\n        self.scope.$broadcast('$ionicHeader.align');\n      }, 20);\n\n      return $timeout(function() {\n        if (!self._isShown) return;\n        //After animating in, allow hide on backdrop click\n        self.$el.on('click', function(e) {\n          if (self.backdropClickToClose && e.target === self.el) {\n            self.hide();\n          }\n        });\n      }, 400);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#hide\n     * @description Hide this modal instance.\n     * @returns {promise} A promise which is resolved when the modal is finished animating out.\n     */\n    hide: function() {\n      var self = this;\n      var modalEl = jqLite(self.modalEl);\n\n      // on iOS, clicks will sometimes bleed through/ghost click on underlying\n      // elements\n      $ionicClickBlock.show(600);\n\n      self.el.classList.remove('active');\n      modalEl.addClass('ng-leave');\n\n      $timeout(function() {\n        if (self._isShown) return;\n        modalEl.addClass('ng-leave-active')\n               .removeClass('ng-enter ng-enter-active active');\n      }, 20, false);\n\n      self.$el.off('click');\n      self._isShown = false;\n      self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.hidden', self);\n      self._deregisterBackButton && self._deregisterBackButton();\n\n      ionic.views.Modal.prototype.hide.call(self);\n\n      // clean up event listeners\n      if (self.positionView) {\n        ionic.off('resize', self._onWindowResize, window);\n      }\n\n      return $timeout(function() {\n        $ionicBody.removeClass(self.viewType + '-open');\n        self.el.classList.add('hide');\n      }, self.hideDelay || 320);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#remove\n     * @description Remove this modal instance from the DOM and clean up.\n     * @returns {promise} A promise which is resolved when the modal is finished animating out.\n     */\n    remove: function() {\n      var self = this;\n      self.scope.$parent && self.scope.$parent.$broadcast(self.viewType + '.removed', self);\n\n      return self.hide().then(function() {\n        self.scope.$destroy();\n        self.$el.remove();\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionicModal#isShown\n     * @returns boolean Whether this modal is currently shown.\n     */\n    isShown: function() {\n      return !!this._isShown;\n    }\n  });\n\n  var createModal = function(templateString, options) {\n    // Create a new scope for the modal\n    var scope = options.scope && options.scope.$new() || $rootScope.$new(true);\n\n    options.viewType = options.viewType || 'modal';\n\n    extend(scope, {\n      $hasHeader: false,\n      $hasSubheader: false,\n      $hasFooter: false,\n      $hasSubfooter: false,\n      $hasTabs: false,\n      $hasTabsTop: false\n    });\n\n    // Compile the template\n    var element = $compile('<ion-' + options.viewType + '>' + templateString + '</ion-' + options.viewType + '>')(scope);\n\n    options.$el = element;\n    options.el = element[0];\n    options.modalEl = options.el.querySelector('.' + options.viewType);\n    var modal = new ModalView(options);\n\n    modal.scope = scope;\n\n    // If this wasn't a defined scope, we can assign the viewType to the isolated scope\n    // we created\n    if (!options.scope) {\n      scope[ options.viewType ] = modal;\n    }\n\n    return modal;\n  };\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicModal#fromTemplate\n     * @param {string} templateString The template string to use as the modal's\n     * content.\n     * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.\n     * @returns {object} An instance of an {@link ionic.controller:ionicModal}\n     * controller.\n     */\n    fromTemplate: function(templateString, options) {\n      var modal = createModal(templateString, options || {});\n      return modal;\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicModal#fromTemplateUrl\n     * @param {string} templateUrl The url to load the template from.\n     * @param {object} options Options to be passed {@link ionic.controller:ionicModal#initialize ionicModal#initialize} method.\n     * options object.\n     * @returns {promise} A promise that will be resolved with an instance of\n     * an {@link ionic.controller:ionicModal} controller.\n     */\n    fromTemplateUrl: function(url, options, _) {\n      var cb;\n      //Deprecated: allow a callback as second parameter. Now we return a promise.\n      if (angular.isFunction(options)) {\n        cb = options;\n        options = _;\n      }\n      return $ionicTemplateLoader.load(url).then(function(templateString) {\n        var modal = createModal(templateString, options || {});\n        cb && cb(modal);\n        return modal;\n      });\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc service\n * @name $ionicNavBarDelegate\n * @module ionic\n * @description\n * Delegate for controlling the {@link ionic.directive:ionNavBar} directive.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MyCtrl\">\n *   <ion-nav-bar>\n *     <button ng-click=\"setNavTitle('banana')\">\n *       Set title to banana!\n *     </button>\n *   </ion-nav-bar>\n * </body>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicNavBarDelegate) {\n *   $scope.setNavTitle = function(title) {\n *     $ionicNavBarDelegate.title(title);\n *   }\n * }\n * ```\n */\nIonicModule\n.service('$ionicNavBarDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#align\n   * @description Aligns the title with the buttons in a given direction.\n   * @param {string=} direction The direction to the align the title text towards.\n   * Available: 'left', 'right', 'center'. Default: 'center'.\n   */\n  'align',\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#showBackButton\n   * @description\n   * Set/get whether the {@link ionic.directive:ionNavBackButton} is shown\n   * (if it exists and there is a previous view that can be navigated to).\n   * @param {boolean=} show Whether to show the back button.\n   * @returns {boolean} Whether the back button is shown.\n   */\n  'showBackButton',\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#showBar\n   * @description\n   * Set/get whether the {@link ionic.directive:ionNavBar} is shown.\n   * @param {boolean} show Whether to show the bar.\n   * @returns {boolean} Whether the bar is shown.\n   */\n  'showBar',\n  /**\n   * @ngdoc method\n   * @name $ionicNavBarDelegate#title\n   * @description\n   * Set the title for the {@link ionic.directive:ionNavBar}.\n   * @param {string} title The new title to show.\n   */\n  'title',\n\n  // DEPRECATED, as of v1.0.0-beta14 -------\n  'changeTitle',\n  'setTitle',\n  'getTitle',\n  'back',\n  'getPreviousTitle'\n  // END DEPRECATED -------\n]));\n\n\nIonicModule\n.service('$ionicNavViewDelegate', ionic.DelegateService([\n  'clearCache'\n]));\n\n\n\n/**\n * @ngdoc service\n * @name $ionicPlatform\n * @module ionic\n * @description\n * An angular abstraction of {@link ionic.utility:ionic.Platform}.\n *\n * Used to detect the current platform, as well as do things like override the\n * Android back button in PhoneGap/Cordova.\n */\nIonicModule\n.constant('IONIC_BACK_PRIORITY', {\n  view: 100,\n  sideMenu: 150,\n  modal: 200,\n  actionSheet: 300,\n  popup: 400,\n  loading: 500\n})\n.provider('$ionicPlatform', function() {\n  return {\n    $get: ['$q', function($q) {\n      var self = {\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#onHardwareBackButton\n         * @description\n         * Some platforms have a hardware back button, so this is one way to\n         * bind to it.\n         * @param {function} callback the callback to trigger when this event occurs\n         */\n        onHardwareBackButton: function(cb) {\n          ionic.Platform.ready(function() {\n            document.addEventListener('backbutton', cb, false);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#offHardwareBackButton\n         * @description\n         * Remove an event listener for the backbutton.\n         * @param {function} callback The listener function that was\n         * originally bound.\n         */\n        offHardwareBackButton: function(fn) {\n          ionic.Platform.ready(function() {\n            document.removeEventListener('backbutton', fn);\n          });\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#registerBackButtonAction\n         * @description\n         * Register a hardware back button action. Only one action will execute\n         * when the back button is clicked, so this method decides which of\n         * the registered back button actions has the highest priority.\n         *\n         * For example, if an actionsheet is showing, the back button should\n         * close the actionsheet, but it should not also go back a page view\n         * or close a modal which may be open.\n         *\n         * The priorities for the existing back button hooks are as follows:\n         *   Return to previous view = 100\n         *   Close side menu = 150\n         *   Dismiss modal = 200\n         *   Close action sheet = 300\n         *   Dismiss popup = 400\n         *   Dismiss loading overlay = 500\n         *\n         * Your back button action will override each of the above actions\n         * whose priority is less than the priority you provide. For example,\n         * an action assigned a priority of 101 will override the 'return to\n         * previous view' action, but not any of the other actions.\n         *\n         * @param {function} callback Called when the back button is pressed,\n         * if this listener is the highest priority.\n         * @param {number} priority Only the highest priority will execute.\n         * @param {*=} actionId The id to assign this action. Default: a\n         * random unique id.\n         * @returns {function} A function that, when called, will deregister\n         * this backButtonAction.\n         */\n        $backButtonActions: {},\n        registerBackButtonAction: function(fn, priority, actionId) {\n\n          if (!self._hasBackButtonHandler) {\n            // add a back button listener if one hasn't been setup yet\n            self.$backButtonActions = {};\n            self.onHardwareBackButton(self.hardwareBackButtonClick);\n            self._hasBackButtonHandler = true;\n          }\n\n          var action = {\n            id: (actionId ? actionId : ionic.Utils.nextUid()),\n            priority: (priority ? priority : 0),\n            fn: fn\n          };\n          self.$backButtonActions[action.id] = action;\n\n          // return a function to de-register this back button action\n          return function() {\n            delete self.$backButtonActions[action.id];\n          };\n        },\n\n        /**\n         * @private\n         */\n        hardwareBackButtonClick: function(e) {\n          // loop through all the registered back button actions\n          // and only run the last one of the highest priority\n          var priorityAction, actionId;\n          for (actionId in self.$backButtonActions) {\n            if (!priorityAction || self.$backButtonActions[actionId].priority >= priorityAction.priority) {\n              priorityAction = self.$backButtonActions[actionId];\n            }\n          }\n          if (priorityAction) {\n            priorityAction.fn(e);\n            return priorityAction;\n          }\n        },\n\n        is: function(type) {\n          return ionic.Platform.is(type);\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#on\n         * @description\n         * Add Cordova event listeners, such as `pause`, `resume`, `volumedownbutton`, `batterylow`,\n         * `offline`, etc. More information about available event types can be found in\n         * [Cordova's event documentation](https://cordova.apache.org/docs/en/edge/cordova_events_events.md.html#Events).\n         * @param {string} type Cordova [event type](https://cordova.apache.org/docs/en/edge/cordova_events_events.md.html#Events).\n         * @param {function} callback Called when the Cordova event is fired.\n         * @returns {function} Returns a deregistration function to remove the event listener.\n         */\n        on: function(type, cb) {\n          ionic.Platform.ready(function() {\n            document.addEventListener(type, cb, false);\n          });\n          return function() {\n            ionic.Platform.ready(function() {\n              document.removeEventListener(type, cb);\n            });\n          };\n        },\n\n        /**\n         * @ngdoc method\n         * @name $ionicPlatform#ready\n         * @description\n         * Trigger a callback once the device is ready,\n         * or immediately if the device is already ready.\n         * @param {function=} callback The function to call.\n         * @returns {promise} A promise which is resolved when the device is ready.\n         */\n        ready: function(cb) {\n          var q = $q.defer();\n\n          ionic.Platform.ready(function() {\n            q.resolve();\n            cb && cb();\n          });\n\n          return q.promise;\n        }\n      };\n      return self;\n    }]\n  };\n\n});\n\n/**\n * @ngdoc service\n * @name $ionicPopover\n * @module ionic\n * @description\n *\n * Related: {@link ionic.controller:ionicPopover ionicPopover controller}.\n *\n * The Popover is a view that floats above an app’s content. Popovers provide an\n * easy way to present or gather information from the user and are\n * commonly used in the following situations:\n *\n * - Show more info about the current view\n * - Select a commonly used tool or configuration\n * - Present a list of actions to perform inside one of your views\n *\n * Put the content of the popover inside of an `<ion-popover-view>` element.\n *\n * @usage\n * ```html\n * <p>\n *   <button ng-click=\"openPopover($event)\">Open Popover</button>\n * </p>\n *\n * <script id=\"my-popover.html\" type=\"text/ng-template\">\n *   <ion-popover-view>\n *     <ion-header-bar>\n *       <h1 class=\"title\">My Popover Title</h1>\n *     </ion-header-bar>\n *     <ion-content>\n *       Hello!\n *     </ion-content>\n *   </ion-popover-view>\n * </script>\n * ```\n * ```js\n * angular.module('testApp', ['ionic'])\n * .controller('MyController', function($scope, $ionicPopover) {\n *\n *   // .fromTemplate() method\n *   var template = '<ion-popover-view><ion-header-bar> <h1 class=\"title\">My Popover Title</h1> </ion-header-bar> <ion-content> Hello! </ion-content></ion-popover-view>';\n *\n *   $scope.popover = $ionicPopover.fromTemplate(template, {\n *     scope: $scope\n *   });\n *\n *   // .fromTemplateUrl() method\n *   $ionicPopover.fromTemplateUrl('my-popover.html', {\n *     scope: $scope\n *   }).then(function(popover) {\n *     $scope.popover = popover;\n *   });\n *\n *\n *   $scope.openPopover = function($event) {\n *     $scope.popover.show($event);\n *   };\n *   $scope.closePopover = function() {\n *     $scope.popover.hide();\n *   };\n *   //Cleanup the popover when we're done with it!\n *   $scope.$on('$destroy', function() {\n *     $scope.popover.remove();\n *   });\n *   // Execute action on hide popover\n *   $scope.$on('popover.hidden', function() {\n *     // Execute action\n *   });\n *   // Execute action on remove popover\n *   $scope.$on('popover.removed', function() {\n *     // Execute action\n *   });\n * });\n * ```\n */\n\n\nIonicModule\n.factory('$ionicPopover', ['$ionicModal', '$ionicPosition', '$document', '$window',\nfunction($ionicModal, $ionicPosition, $document, $window) {\n\n  var POPOVER_BODY_PADDING = 6;\n\n  var POPOVER_OPTIONS = {\n    viewType: 'popover',\n    hideDelay: 1,\n    animation: 'none',\n    positionView: positionView\n  };\n\n  function positionView(target, popoverEle) {\n    var targetEle = jqLite(target.target || target);\n    var buttonOffset = $ionicPosition.offset(targetEle);\n    var popoverWidth = popoverEle.prop('offsetWidth');\n    var popoverHeight = popoverEle.prop('offsetHeight');\n    // Use innerWidth and innerHeight, because clientWidth and clientHeight\n    // doesn't work consistently for body on all platforms\n    var bodyWidth = $window.innerWidth;\n    var bodyHeight = $window.innerHeight;\n\n    var popoverCSS = {\n      left: buttonOffset.left + buttonOffset.width / 2 - popoverWidth / 2\n    };\n    var arrowEle = jqLite(popoverEle[0].querySelector('.popover-arrow'));\n\n    if (popoverCSS.left < POPOVER_BODY_PADDING) {\n      popoverCSS.left = POPOVER_BODY_PADDING;\n    } else if (popoverCSS.left + popoverWidth + POPOVER_BODY_PADDING > bodyWidth) {\n      popoverCSS.left = bodyWidth - popoverWidth - POPOVER_BODY_PADDING;\n    }\n\n    // If the popover when popped down stretches past bottom of screen,\n    // make it pop up if there's room above\n    if (buttonOffset.top + buttonOffset.height + popoverHeight > bodyHeight &&\n        buttonOffset.top - popoverHeight > 0) {\n      popoverCSS.top = buttonOffset.top - popoverHeight;\n      popoverEle.addClass('popover-bottom');\n    } else {\n      popoverCSS.top = buttonOffset.top + buttonOffset.height;\n      popoverEle.removeClass('popover-bottom');\n    }\n\n    arrowEle.css({\n      left: buttonOffset.left + buttonOffset.width / 2 -\n        arrowEle.prop('offsetWidth') / 2 - popoverCSS.left + 'px'\n    });\n\n    popoverEle.css({\n      top: popoverCSS.top + 'px',\n      left: popoverCSS.left + 'px',\n      marginLeft: '0',\n      opacity: '1'\n    });\n\n  }\n\n  /**\n   * @ngdoc controller\n   * @name ionicPopover\n   * @module ionic\n   * @description\n   * Instantiated by the {@link ionic.service:$ionicPopover} service.\n   *\n   * Be sure to call [remove()](#remove) when you are done with each popover\n   * to clean it up and avoid memory leaks.\n   *\n   * Note: a popover will broadcast 'popover.shown', 'popover.hidden', and 'popover.removed' events from its originating\n   * scope, passing in itself as an event argument. Both the popover.removed and popover.hidden events are\n   * called when the popover is removed.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#initialize\n   * @description Creates a new popover controller instance.\n   * @param {object} options An options object with the following properties:\n   *  - `{object=}` `scope` The scope to be a child of.\n   *    Default: creates a child of $rootScope.\n   *  - `{boolean=}` `focusFirstInput` Whether to autofocus the first input of\n   *    the popover when shown.  Default: false.\n   *  - `{boolean=}` `backdropClickToClose` Whether to close the popover on clicking the backdrop.\n   *    Default: true.\n   *  - `{boolean=}` `hardwareBackButtonClose` Whether the popover can be closed using the hardware\n   *    back button on Android and similar devices.  Default: true.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#show\n   * @description Show this popover instance.\n   * @param {$event} $event The $event or target element which the popover should align\n   * itself next to.\n   * @returns {promise} A promise which is resolved when the popover is finished animating in.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#hide\n   * @description Hide this popover instance.\n   * @returns {promise} A promise which is resolved when the popover is finished animating out.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#remove\n   * @description Remove this popover instance from the DOM and clean up.\n   * @returns {promise} A promise which is resolved when the popover is finished animating out.\n   */\n\n  /**\n   * @ngdoc method\n   * @name ionicPopover#isShown\n   * @returns boolean Whether this popover is currently shown.\n   */\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicPopover#fromTemplate\n     * @param {string} templateString The template string to use as the popovers's\n     * content.\n     * @param {object} options Options to be passed to the initialize method.\n     * @returns {object} An instance of an {@link ionic.controller:ionicPopover}\n     * controller (ionicPopover is built on top of $ionicPopover).\n     */\n    fromTemplate: function(templateString, options) {\n      return $ionicModal.fromTemplate(templateString, ionic.Utils.extend(POPOVER_OPTIONS, options || {}));\n    },\n    /**\n     * @ngdoc method\n     * @name $ionicPopover#fromTemplateUrl\n     * @param {string} templateUrl The url to load the template from.\n     * @param {object} options Options to be passed to the initialize method.\n     * @returns {promise} A promise that will be resolved with an instance of\n     * an {@link ionic.controller:ionicPopover} controller (ionicPopover is built on top of $ionicPopover).\n     */\n    fromTemplateUrl: function(url, options) {\n      return $ionicModal.fromTemplateUrl(url, ionic.Utils.extend(POPOVER_OPTIONS, options || {}));\n    }\n  };\n\n}]);\n\n\nvar POPUP_TPL =\n  '<div class=\"popup-container\" ng-class=\"cssClass\">' +\n    '<div class=\"popup\">' +\n      '<div class=\"popup-head\">' +\n        '<h3 class=\"popup-title\" ng-bind-html=\"title\"></h3>' +\n        '<h5 class=\"popup-sub-title\" ng-bind-html=\"subTitle\" ng-if=\"subTitle\"></h5>' +\n      '</div>' +\n      '<div class=\"popup-body\">' +\n      '</div>' +\n      '<div class=\"popup-buttons\" ng-show=\"buttons.length\">' +\n        '<button ng-repeat=\"button in buttons\" ng-click=\"$buttonTapped(button, $event)\" class=\"button\" ng-class=\"button.type || \\'button-default\\'\" ng-bind-html=\"button.text\"></button>' +\n      '</div>' +\n    '</div>' +\n  '</div>';\n\n/**\n * @ngdoc service\n * @name $ionicPopup\n * @module ionic\n * @restrict E\n * @codepen zkmhJ\n * @description\n *\n * The Ionic Popup service allows programmatically creating and showing popup\n * windows that require the user to respond in order to continue.\n *\n * The popup system has support for more flexible versions of the built in `alert()`, `prompt()`,\n * and `confirm()` functions that users are used to, in addition to allowing popups with completely\n * custom content and look.\n *\n * An input can be given an `autofocus` attribute so it automatically receives focus when\n * the popup first shows. However, depending on certain use-cases this can cause issues with\n * the tap/click system, which is why Ionic prefers using the `autofocus` attribute as\n * an opt-in feature and not the default.\n *\n * @usage\n * A few basic examples, see below for details about all of the options available.\n *\n * ```js\n *angular.module('mySuperApp', ['ionic'])\n *.controller('PopupCtrl',function($scope, $ionicPopup, $timeout) {\n *\n * // Triggered on a button click, or some other target\n * $scope.showPopup = function() {\n *   $scope.data = {}\n *\n *   // An elaborate, custom popup\n *   var myPopup = $ionicPopup.show({\n *     template: '<input type=\"password\" ng-model=\"data.wifi\">',\n *     title: 'Enter Wi-Fi Password',\n *     subTitle: 'Please use normal things',\n *     scope: $scope,\n *     buttons: [\n *       { text: 'Cancel' },\n *       {\n *         text: '<b>Save</b>',\n *         type: 'button-positive',\n *         onTap: function(e) {\n *           if (!$scope.data.wifi) {\n *             //don't allow the user to close unless he enters wifi password\n *             e.preventDefault();\n *           } else {\n *             return $scope.data.wifi;\n *           }\n *         }\n *       }\n *     ]\n *   });\n *   myPopup.then(function(res) {\n *     console.log('Tapped!', res);\n *   });\n *   $timeout(function() {\n *      myPopup.close(); //close the popup after 3 seconds for some reason\n *   }, 3000);\n *  };\n *  // A confirm dialog\n *  $scope.showConfirm = function() {\n *    var confirmPopup = $ionicPopup.confirm({\n *      title: 'Consume Ice Cream',\n *      template: 'Are you sure you want to eat this ice cream?'\n *    });\n *    confirmPopup.then(function(res) {\n *      if(res) {\n *        console.log('You are sure');\n *      } else {\n *        console.log('You are not sure');\n *      }\n *    });\n *  };\n *\n *  // An alert dialog\n *  $scope.showAlert = function() {\n *    var alertPopup = $ionicPopup.alert({\n *      title: 'Don\\'t eat that!',\n *      template: 'It might taste good'\n *    });\n *    alertPopup.then(function(res) {\n *      console.log('Thank you for not eating my delicious ice cream cone');\n *    });\n *  };\n *});\n *```\n */\n\nIonicModule\n.factory('$ionicPopup', [\n  '$ionicTemplateLoader',\n  '$ionicBackdrop',\n  '$q',\n  '$timeout',\n  '$rootScope',\n  '$ionicBody',\n  '$compile',\n  '$ionicPlatform',\n  'IONIC_BACK_PRIORITY',\nfunction($ionicTemplateLoader, $ionicBackdrop, $q, $timeout, $rootScope, $ionicBody, $compile, $ionicPlatform, IONIC_BACK_PRIORITY) {\n  //TODO allow this to be configured\n  var config = {\n    stackPushDelay: 75\n  };\n  var popupStack = [];\n\n  var $ionicPopup = {\n    /**\n     * @ngdoc method\n     * @description\n     * Show a complex popup. This is the master show function for all popups.\n     *\n     * A complex popup has a `buttons` array, with each button having a `text` and `type`\n     * field, in addition to an `onTap` function.  The `onTap` function, called when\n     * the corresponding button on the popup is tapped, will by default close the popup\n     * and resolve the popup promise with its return value.  If you wish to prevent the\n     * default and keep the popup open on button tap, call `event.preventDefault()` on the\n     * passed in tap event.  Details below.\n     *\n     * @name $ionicPopup#show\n     * @param {object} options The options for the new popup, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   scope: null, // Scope (optional). A scope to link to the popup content.\n     *   buttons: [{ // Array[Object] (optional). Buttons to place in the popup footer.\n     *     text: 'Cancel',\n     *     type: 'button-default',\n     *     onTap: function(e) {\n     *       // e.preventDefault() will stop the popup from closing when tapped.\n     *       e.preventDefault();\n     *     }\n     *   }, {\n     *     text: 'OK',\n     *     type: 'button-positive',\n     *     onTap: function(e) {\n     *       // Returning a value will cause the promise to resolve with the given value.\n     *       return scope.data.response;\n     *     }\n     *   }]\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has an additional\n     * `close` function, which can be used to programmatically close the popup.\n     */\n    show: showPopup,\n\n    /**\n     * @ngdoc method\n     * @name $ionicPopup#alert\n     * @description Show a simple alert popup with a message and one button that the user can\n     * tap to close the popup.\n     *\n     * @param {object} options The options for showing the alert, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   okText: '', // String (default: 'OK'). The text of the OK button.\n     *   okType: '', // String (default: 'button-positive'). The type of the OK button.\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has one additional\n     * function `close`, which can be called with any value to programmatically close the popup\n     * with the given value.\n     */\n    alert: showAlert,\n\n    /**\n     * @ngdoc method\n     * @name $ionicPopup#confirm\n     * @description\n     * Show a simple confirm popup with a Cancel and OK button.\n     *\n     * Resolves the promise with true if the user presses the OK button, and false if the\n     * user presses the Cancel button.\n     *\n     * @param {object} options The options for showing the confirm popup, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   cancelText: '', // String (default: 'Cancel'). The text of the Cancel button.\n     *   cancelType: '', // String (default: 'button-default'). The type of the Cancel button.\n     *   okText: '', // String (default: 'OK'). The text of the OK button.\n     *   okType: '', // String (default: 'button-positive'). The type of the OK button.\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has one additional\n     * function `close`, which can be called with any value to programmatically close the popup\n     * with the given value.\n     */\n    confirm: showConfirm,\n\n    /**\n     * @ngdoc method\n     * @name $ionicPopup#prompt\n     * @description Show a simple prompt popup, which has an input, OK button, and Cancel button.\n     * Resolves the promise with the value of the input if the user presses OK, and with undefined\n     * if the user presses Cancel.\n     *\n     * ```javascript\n     *  $ionicPopup.prompt({\n     *    title: 'Password Check',\n     *    template: 'Enter your secret password',\n     *    inputType: 'password',\n     *    inputPlaceholder: 'Your password'\n     *  }).then(function(res) {\n     *    console.log('Your password is', res);\n     *  });\n     * ```\n     * @param {object} options The options for showing the prompt popup, of the form:\n     *\n     * ```\n     * {\n     *   title: '', // String. The title of the popup.\n     *   cssClass: '', // String, The custom CSS class name\n     *   subTitle: '', // String (optional). The sub-title of the popup.\n     *   template: '', // String (optional). The html template to place in the popup body.\n     *   templateUrl: '', // String (optional). The URL of an html template to place in the popup   body.\n     *   inputType: // String (default: 'text'). The type of input to use\n     *   inputPlaceholder: // String (default: ''). A placeholder to use for the input.\n     *   cancelText: // String (default: 'Cancel'. The text of the Cancel button.\n     *   cancelType: // String (default: 'button-default'). The type of the Cancel button.\n     *   okText: // String (default: 'OK'). The text of the OK button.\n     *   okType: // String (default: 'button-positive'). The type of the OK button.\n     * }\n     * ```\n     *\n     * @returns {object} A promise which is resolved when the popup is closed. Has one additional\n     * function `close`, which can be called with any value to programmatically close the popup\n     * with the given value.\n     */\n    prompt: showPrompt,\n    /**\n     * @private for testing\n     */\n    _createPopup: createPopup,\n    _popupStack: popupStack\n  };\n\n  return $ionicPopup;\n\n  function createPopup(options) {\n    options = extend({\n      scope: null,\n      title: '',\n      buttons: []\n    }, options || {});\n\n    var self = {};\n    self.scope = (options.scope || $rootScope).$new();\n    self.element = jqLite(POPUP_TPL);\n    self.responseDeferred = $q.defer();\n\n    $ionicBody.get().appendChild(self.element[0]);\n    $compile(self.element)(self.scope);\n\n    extend(self.scope, {\n      title: options.title,\n      buttons: options.buttons,\n      subTitle: options.subTitle,\n      cssClass: options.cssClass,\n      $buttonTapped: function(button, event) {\n        var result = (button.onTap || noop)(event);\n        event = event.originalEvent || event; //jquery events\n\n        if (!event.defaultPrevented) {\n          self.responseDeferred.resolve(result);\n        }\n      }\n    });\n\n    $q.when(\n      options.templateUrl ?\n      $ionicTemplateLoader.load(options.templateUrl) :\n        (options.template || options.content || '')\n    ).then(function(template) {\n      var popupBody = jqLite(self.element[0].querySelector('.popup-body'));\n      if (template) {\n        popupBody.html(template);\n        $compile(popupBody.contents())(self.scope);\n      } else {\n        popupBody.remove();\n      }\n    });\n\n    self.show = function() {\n      if (self.isShown || self.removed) return;\n\n      self.isShown = true;\n      ionic.requestAnimationFrame(function() {\n        //if hidden while waiting for raf, don't show\n        if (!self.isShown) return;\n\n        self.element.removeClass('popup-hidden');\n        self.element.addClass('popup-showing active');\n        focusInput(self.element);\n      });\n    };\n\n    self.hide = function(callback) {\n      callback = callback || noop;\n      if (!self.isShown) return callback();\n\n      self.isShown = false;\n      self.element.removeClass('active');\n      self.element.addClass('popup-hidden');\n      $timeout(callback, 250, false);\n    };\n\n    self.remove = function() {\n      if (self.removed) return;\n\n      self.hide(function() {\n        self.element.remove();\n        self.scope.$destroy();\n      });\n\n      self.removed = true;\n    };\n\n    return self;\n  }\n\n  function onHardwareBackButton() {\n    var last = popupStack[popupStack.length - 1];\n    last && last.responseDeferred.resolve();\n  }\n\n  function showPopup(options) {\n    var popup = $ionicPopup._createPopup(options);\n    var showDelay = 0;\n\n    if (popupStack.length > 0) {\n      popupStack[popupStack.length - 1].hide();\n      showDelay = config.stackPushDelay;\n    } else {\n      //Add popup-open & backdrop if this is first popup\n      $ionicBody.addClass('popup-open');\n      $ionicBackdrop.retain();\n      //only show the backdrop on the first popup\n      $ionicPopup._backButtonActionDone = $ionicPlatform.registerBackButtonAction(\n        onHardwareBackButton,\n        IONIC_BACK_PRIORITY.popup\n      );\n    }\n\n    // Expose a 'close' method on the returned promise\n    popup.responseDeferred.promise.close = function popupClose(result) {\n      if (!popup.removed) popup.responseDeferred.resolve(result);\n    };\n    //DEPRECATED: notify the promise with an object with a close method\n    popup.responseDeferred.notify({ close: popup.responseDeferred.close });\n\n    doShow();\n\n    return popup.responseDeferred.promise;\n\n    function doShow() {\n      popupStack.push(popup);\n      $timeout(popup.show, showDelay, false);\n\n      popup.responseDeferred.promise.then(function(result) {\n        var index = popupStack.indexOf(popup);\n        if (index !== -1) {\n          popupStack.splice(index, 1);\n        }\n\n        if (popupStack.length > 0) {\n          popupStack[popupStack.length - 1].show();\n        } else {\n          $ionicBackdrop.release();\n          //Remove popup-open & backdrop if this is last popup\n          $timeout(function() {\n            // wait to remove this due to a 300ms delay native\n            // click which would trigging whatever was underneath this\n            if (!popupStack.length) {\n              $ionicBody.removeClass('popup-open');\n            }\n          }, 400, false);\n          ($ionicPopup._backButtonActionDone || noop)();\n        }\n\n        popup.remove();\n\n        return result;\n      });\n\n    }\n\n  }\n\n  function focusInput(element) {\n    var focusOn = element[0].querySelector('[autofocus]');\n    if (focusOn) {\n      focusOn.focus();\n    }\n  }\n\n  function showAlert(opts) {\n    return showPopup(extend({\n      buttons: [{\n        text: opts.okText || 'OK',\n        type: opts.okType || 'button-positive',\n        onTap: function() {\n          return true;\n        }\n      }]\n    }, opts || {}));\n  }\n\n  function showConfirm(opts) {\n    return showPopup(extend({\n      buttons: [{\n        text: opts.cancelText || 'Cancel',\n        type: opts.cancelType || 'button-default',\n        onTap: function() { return false; }\n      }, {\n        text: opts.okText || 'OK',\n        type: opts.okType || 'button-positive',\n        onTap: function() { return true; }\n      }]\n    }, opts || {}));\n  }\n\n  function showPrompt(opts) {\n    var scope = $rootScope.$new(true);\n    scope.data = {};\n    var text = '';\n    if (opts.template && /<[a-z][\\s\\S]*>/i.test(opts.template) === false) {\n      text = '<span>' + opts.template + '</span>';\n      delete opts.template;\n    }\n    return showPopup(extend({\n      template: text + '<input ng-model=\"data.response\" type=\"' + (opts.inputType || 'text') +\n        '\" placeholder=\"' + (opts.inputPlaceholder || '') + '\">',\n      scope: scope,\n      buttons: [{\n        text: opts.cancelText || 'Cancel',\n        type: opts.cancelType || 'button-default',\n        onTap: function() {}\n      }, {\n        text: opts.okText || 'OK',\n        type: opts.okType || 'button-positive',\n        onTap: function() {\n          return scope.data.response || '';\n        }\n      }]\n    }, opts || {}));\n  }\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicPosition\n * @module ionic\n * @description\n * A set of utility methods that can be use to retrieve position of DOM elements.\n * It is meant to be used where we need to absolute-position DOM elements in\n * relation to other, existing elements (this is the case for tooltips, popovers, etc.).\n *\n * Adapted from [AngularUI Bootstrap](https://github.com/angular-ui/bootstrap/blob/master/src/position/position.js),\n * ([license](https://github.com/angular-ui/bootstrap/blob/master/LICENSE))\n */\nIonicModule\n.factory('$ionicPosition', ['$document', '$window', function($document, $window) {\n\n  function getStyle(el, cssprop) {\n    if (el.currentStyle) { //IE\n      return el.currentStyle[cssprop];\n    } else if ($window.getComputedStyle) {\n      return $window.getComputedStyle(el)[cssprop];\n    }\n    // finally try and get inline style\n    return el.style[cssprop];\n  }\n\n  /**\n   * Checks if a given element is statically positioned\n   * @param element - raw DOM element\n   */\n  function isStaticPositioned(element) {\n    return (getStyle(element, 'position') || 'static') === 'static';\n  }\n\n  /**\n   * returns the closest, non-statically positioned parentOffset of a given element\n   * @param element\n   */\n  var parentOffsetEl = function(element) {\n    var docDomEl = $document[0];\n    var offsetParent = element.offsetParent || docDomEl;\n    while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent)) {\n      offsetParent = offsetParent.offsetParent;\n    }\n    return offsetParent || docDomEl;\n  };\n\n  return {\n    /**\n     * @ngdoc method\n     * @name $ionicPosition#position\n     * @description Get the current coordinates of the element, relative to the offset parent.\n     * Read-only equivalent of [jQuery's position function](http://api.jquery.com/position/).\n     * @param {element} element The element to get the position of.\n     * @returns {object} Returns an object containing the properties top, left, width and height.\n     */\n    position: function(element) {\n      var elBCR = this.offset(element);\n      var offsetParentBCR = { top: 0, left: 0 };\n      var offsetParentEl = parentOffsetEl(element[0]);\n      if (offsetParentEl != $document[0]) {\n        offsetParentBCR = this.offset(jqLite(offsetParentEl));\n        offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;\n        offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;\n      }\n\n      var boundingClientRect = element[0].getBoundingClientRect();\n      return {\n        width: boundingClientRect.width || element.prop('offsetWidth'),\n        height: boundingClientRect.height || element.prop('offsetHeight'),\n        top: elBCR.top - offsetParentBCR.top,\n        left: elBCR.left - offsetParentBCR.left\n      };\n    },\n\n    /**\n     * @ngdoc method\n     * @name $ionicPosition#offset\n     * @description Get the current coordinates of the element, relative to the document.\n     * Read-only equivalent of [jQuery's offset function](http://api.jquery.com/offset/).\n     * @param {element} element The element to get the offset of.\n     * @returns {object} Returns an object containing the properties top, left, width and height.\n     */\n    offset: function(element) {\n      var boundingClientRect = element[0].getBoundingClientRect();\n      return {\n        width: boundingClientRect.width || element.prop('offsetWidth'),\n        height: boundingClientRect.height || element.prop('offsetHeight'),\n        top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),\n        left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)\n      };\n    }\n\n  };\n}]);\n\n\n/**\n * @ngdoc service\n * @name $ionicScrollDelegate\n * @module ionic\n * @description\n * Delegate for controlling scrollViews (created by\n * {@link ionic.directive:ionContent} and\n * {@link ionic.directive:ionScroll} directives).\n *\n * Methods called directly on the $ionicScrollDelegate service will control all scroll\n * views.  Use the {@link ionic.service:$ionicScrollDelegate#$getByHandle $getByHandle}\n * method to control specific scrollViews.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MainCtrl\">\n *   <ion-content>\n *     <button ng-click=\"scrollTop()\">Scroll to Top!</button>\n *   </ion-content>\n * </body>\n * ```\n * ```js\n * function MainCtrl($scope, $ionicScrollDelegate) {\n *   $scope.scrollTop = function() {\n *     $ionicScrollDelegate.scrollTop();\n *   };\n * }\n * ```\n *\n * Example of advanced usage, with two scroll areas using `delegate-handle`\n * for fine control.\n *\n * ```html\n * <body ng-controller=\"MainCtrl\">\n *   <ion-content delegate-handle=\"mainScroll\">\n *     <button ng-click=\"scrollMainToTop()\">\n *       Scroll content to top!\n *     </button>\n *     <ion-scroll delegate-handle=\"small\" style=\"height: 100px;\">\n *       <button ng-click=\"scrollSmallToTop()\">\n *         Scroll small area to top!\n *       </button>\n *     </ion-scroll>\n *   </ion-content>\n * </body>\n * ```\n * ```js\n * function MainCtrl($scope, $ionicScrollDelegate) {\n *   $scope.scrollMainToTop = function() {\n *     $ionicScrollDelegate.$getByHandle('mainScroll').scrollTop();\n *   };\n *   $scope.scrollSmallToTop = function() {\n *     $ionicScrollDelegate.$getByHandle('small').scrollTop();\n *   };\n * }\n * ```\n */\nIonicModule\n.service('$ionicScrollDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#resize\n   * @description Tell the scrollView to recalculate the size of its container.\n   */\n  'resize',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollTop\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollTop',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollBottom\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollBottom',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollTo\n   * @param {number} left The x-value to scroll to.\n   * @param {number} top The y-value to scroll to.\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollTo',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#scrollBy\n   * @param {number} left The x-offset to scroll by.\n   * @param {number} top The y-offset to scroll by.\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'scrollBy',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#zoomTo\n   * @param {number} level Level to zoom to.\n   * @param {boolean=} animate Whether to animate the zoom.\n   * @param {number=} originLeft Zoom in at given left coordinate.\n   * @param {number=} originTop Zoom in at given top coordinate.\n   */\n  'zoomTo',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#zoomBy\n   * @param {number} factor The factor to zoom by.\n   * @param {boolean=} animate Whether to animate the zoom.\n   * @param {number=} originLeft Zoom in at given left coordinate.\n   * @param {number=} originTop Zoom in at given top coordinate.\n   */\n  'zoomBy',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#getScrollPosition\n   * @returns {object} The scroll position of this view, with the following properties:\n   *  - `{number}` `left` The distance the user has scrolled from the left (starts at 0).\n   *  - `{number}` `top` The distance the user has scrolled from the top (starts at 0).\n   */\n  'getScrollPosition',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#anchorScroll\n   * @description Tell the scrollView to scroll to the element with an id\n   * matching window.location.hash.\n   *\n   * If no matching element is found, it will scroll to top.\n   *\n   * @param {boolean=} shouldAnimate Whether the scroll should animate.\n   */\n  'anchorScroll',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#freezeScroll\n   * @description Does not allow this scroll view to scroll either x or y.\n   * @param {boolean=} shouldFreeze Should this scroll view be prevented from scrolling or not.\n   * @returns {object} If the scroll view is being prevented from scrolling or not.\n   */\n  'freezeScroll',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#freezeAllScrolls\n   * @description Does not allow any of the app's scroll views to scroll either x or y.\n   * @param {boolean=} shouldFreeze Should all app scrolls be prevented from scrolling or not.\n   */\n  'freezeAllScrolls',\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#getScrollView\n   * @returns {object} The scrollView associated with this delegate.\n   */\n  'getScrollView'\n  /**\n   * @ngdoc method\n   * @name $ionicScrollDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * scrollViews with `delegate-handle` matching the given handle.\n   *\n   * Example: `$ionicScrollDelegate.$getByHandle('my-handle').scrollTop();`\n   */\n]));\n\n\n/**\n * @ngdoc service\n * @name $ionicSideMenuDelegate\n * @module ionic\n *\n * @description\n * Delegate for controlling the {@link ionic.directive:ionSideMenus} directive.\n *\n * Methods called directly on the $ionicSideMenuDelegate service will control all side\n * menus.  Use the {@link ionic.service:$ionicSideMenuDelegate#$getByHandle $getByHandle}\n * method to control specific ionSideMenus instances.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MainCtrl\">\n *   <ion-side-menus>\n *     <ion-side-menu-content>\n *       Content!\n *       <button ng-click=\"toggleLeftSideMenu()\">\n *         Toggle Left Side Menu\n *       </button>\n *     </ion-side-menu-content>\n *     <ion-side-menu side=\"left\">\n *       Left Menu!\n *     <ion-side-menu>\n *   </ion-side-menus>\n * </body>\n * ```\n * ```js\n * function MainCtrl($scope, $ionicSideMenuDelegate) {\n *   $scope.toggleLeftSideMenu = function() {\n *     $ionicSideMenuDelegate.toggleLeft();\n *   };\n * }\n * ```\n */\nIonicModule\n.service('$ionicSideMenuDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#toggleLeft\n   * @description Toggle the left side menu (if it exists).\n   * @param {boolean=} isOpen Whether to open or close the menu.\n   * Default: Toggles the menu.\n   */\n  'toggleLeft',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#toggleRight\n   * @description Toggle the right side menu (if it exists).\n   * @param {boolean=} isOpen Whether to open or close the menu.\n   * Default: Toggles the menu.\n   */\n  'toggleRight',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#getOpenRatio\n   * @description Gets the ratio of open amount over menu width. For example, a\n   * menu of width 100 that is opened by 50 pixels is 50% opened, and would return\n   * a ratio of 0.5.\n   *\n   * @returns {float} 0 if nothing is open, between 0 and 1 if left menu is\n   * opened/opening, and between 0 and -1 if right menu is opened/opening.\n   */\n  'getOpenRatio',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#isOpen\n   * @returns {boolean} Whether either the left or right menu is currently opened.\n   */\n  'isOpen',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#isOpenLeft\n   * @returns {boolean} Whether the left menu is currently opened.\n   */\n  'isOpenLeft',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#isOpenRight\n   * @returns {boolean} Whether the right menu is currently opened.\n   */\n  'isOpenRight',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#canDragContent\n   * @param {boolean=} canDrag Set whether the content can or cannot be dragged to open\n   * side menus.\n   * @returns {boolean} Whether the content can be dragged to open side menus.\n   */\n  'canDragContent',\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#edgeDragThreshold\n   * @param {boolean|number=} value Set whether the content drag can only start if it is below a certain threshold distance from the edge of the screen. Accepts three different values:\n   *  - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.\n   *  - If true is given, the default number of pixels (25) is used as the maximum allowed distance.\n   *  - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.\n   * @returns {boolean} Whether the drag can start only from within the edge of screen threshold.\n   */\n  'edgeDragThreshold'\n  /**\n   * @ngdoc method\n   * @name $ionicSideMenuDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionSideMenus} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicSideMenuDelegate.$getByHandle('my-handle').toggleLeft();`\n   */\n]));\n\n\n/**\n * @ngdoc service\n * @name $ionicSlideBoxDelegate\n * @module ionic\n * @description\n * Delegate that controls the {@link ionic.directive:ionSlideBox} directive.\n *\n * Methods called directly on the $ionicSlideBoxDelegate service will control all slide boxes.  Use the {@link ionic.service:$ionicSlideBoxDelegate#$getByHandle $getByHandle}\n * method to control specific slide box instances.\n *\n * @usage\n *\n * ```html\n * <ion-view>\n *   <ion-slide-box>\n *     <ion-slide>\n *       <div class=\"box blue\">\n *         <button ng-click=\"nextSlide()\">Next slide!</button>\n *       </div>\n *     </ion-slide>\n *     <ion-slide>\n *       <div class=\"box red\">\n *         Slide 2!\n *       </div>\n *     </ion-slide>\n *   </ion-slide-box>\n * </ion-view>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicSlideBoxDelegate) {\n *   $scope.nextSlide = function() {\n *     $ionicSlideBoxDelegate.next();\n *   }\n * }\n * ```\n */\nIonicModule\n.service('$ionicSlideBoxDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#update\n   * @description\n   * Update the slidebox (for example if using Angular with ng-repeat,\n   * resize it for the elements inside).\n   */\n  'update',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#slide\n   * @param {number} to The index to slide to.\n   * @param {number=} speed The number of milliseconds the change should take.\n   */\n  'slide',\n  'select',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#enableSlide\n   * @param {boolean=} shouldEnable Whether to enable sliding the slidebox.\n   * @returns {boolean} Whether sliding is enabled.\n   */\n  'enableSlide',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#previous\n   * @param {number=} speed The number of milliseconds the change should take.\n   * @description Go to the previous slide. Wraps around if at the beginning.\n   */\n  'previous',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#next\n   * @param {number=} speed The number of milliseconds the change should take.\n   * @description Go to the next slide. Wraps around if at the end.\n   */\n  'next',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#stop\n   * @description Stop sliding. The slideBox will not move again until\n   * explicitly told to do so.\n   */\n  'stop',\n  'autoPlay',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#start\n   * @description Start sliding again if the slideBox was stopped.\n   */\n  'start',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#currentIndex\n   * @returns number The index of the current slide.\n   */\n  'currentIndex',\n  'selected',\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#slidesCount\n   * @returns number The number of slides there are currently.\n   */\n  'slidesCount',\n  'count',\n  'loop'\n  /**\n   * @ngdoc method\n   * @name $ionicSlideBoxDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionSlideBox} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicSlideBoxDelegate.$getByHandle('my-handle').stop();`\n   */\n]));\n\n\n/**\n * @ngdoc service\n * @name $ionicTabsDelegate\n * @module ionic\n *\n * @description\n * Delegate for controlling the {@link ionic.directive:ionTabs} directive.\n *\n * Methods called directly on the $ionicTabsDelegate service will control all ionTabs\n * directives. Use the {@link ionic.service:$ionicTabsDelegate#$getByHandle $getByHandle}\n * method to control specific ionTabs instances.\n *\n * @usage\n *\n * ```html\n * <body ng-controller=\"MyCtrl\">\n *   <ion-tabs>\n *\n *     <ion-tab title=\"Tab 1\">\n *       Hello tab 1!\n *       <button ng-click=\"selectTabWithIndex(1)\">Select tab 2!</button>\n *     </ion-tab>\n *     <ion-tab title=\"Tab 2\">Hello tab 2!</ion-tab>\n *\n *   </ion-tabs>\n * </body>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicTabsDelegate) {\n *   $scope.selectTabWithIndex = function(index) {\n *     $ionicTabsDelegate.select(index);\n *   }\n * }\n * ```\n */\nIonicModule\n.service('$ionicTabsDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicTabsDelegate#select\n   * @description Select the tab matching the given index.\n   *\n   * @param {number} index Index of the tab to select.\n   */\n  'select',\n  /**\n   * @ngdoc method\n   * @name $ionicTabsDelegate#selectedIndex\n   * @returns `number` The index of the selected tab, or -1.\n   */\n  'selectedIndex'\n  /**\n   * @ngdoc method\n   * @name $ionicTabsDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionTabs} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicTabsDelegate.$getByHandle('my-handle').select(0);`\n   */\n]));\n\n\n// closure to keep things neat\n(function() {\n  var templatesToCache = [];\n\n/**\n * @ngdoc service\n * @name $ionicTemplateCache\n * @module ionic\n * @description A service that preemptively caches template files to eliminate transition flicker and boost performance.\n * @usage\n * State templates are cached automatically, but you can optionally cache other templates.\n *\n * ```js\n * $ionicTemplateCache('myNgIncludeTemplate.html');\n * ```\n *\n * Optionally disable all preemptive caching with the `$ionicConfigProvider` or individual states by setting `prefetchTemplate`\n * in the `$state` definition\n *\n * ```js\n *   angular.module('myApp', ['ionic'])\n *   .config(function($stateProvider, $ionicConfigProvider) {\n *\n *     // disable preemptive template caching globally\n *     $ionicConfigProvider.templates.prefetch(false);\n *\n *     // disable individual states\n *     $stateProvider\n *       .state('tabs', {\n *         url: \"/tab\",\n *         abstract: true,\n *         prefetchTemplate: false,\n *         templateUrl: \"tabs-templates/tabs.html\"\n *       })\n *       .state('tabs.home', {\n *         url: \"/home\",\n *         views: {\n *           'home-tab': {\n *             prefetchTemplate: false,\n *             templateUrl: \"tabs-templates/home.html\",\n *             controller: 'HomeTabCtrl'\n *           }\n *         }\n *       });\n *   });\n * ```\n */\nIonicModule\n.factory('$ionicTemplateCache', [\n'$http',\n'$templateCache',\n'$timeout',\nfunction($http, $templateCache, $timeout) {\n  var toCache = templatesToCache,\n      hasRun;\n\n  function $ionicTemplateCache(templates) {\n    if (typeof templates === 'undefined') {\n      return run();\n    }\n    if (isString(templates)) {\n      templates = [templates];\n    }\n    forEach(templates, function(template) {\n      toCache.push(template);\n    });\n    if (hasRun) {\n      run();\n    }\n  }\n\n  // run through methods - internal method\n  function run() {\n    var template;\n    $ionicTemplateCache._runCount++;\n\n    hasRun = true;\n    // ignore if race condition already zeroed out array\n    if (toCache.length === 0) return;\n\n    var i = 0;\n    while (i < 4 && (template = toCache.pop())) {\n      // note that inline templates are ignored by this request\n      if (isString(template)) $http.get(template, { cache: $templateCache });\n      i++;\n    }\n    // only preload 3 templates a second\n    if (toCache.length) {\n      $timeout(run, 1000);\n    }\n  }\n\n  // exposing for testing\n  $ionicTemplateCache._runCount = 0;\n  // default method\n  return $ionicTemplateCache;\n}])\n\n// Intercepts the $stateprovider.state() command to look for templateUrls that can be cached\n.config([\n'$stateProvider',\n'$ionicConfigProvider',\nfunction($stateProvider, $ionicConfigProvider) {\n  var stateProviderState = $stateProvider.state;\n  $stateProvider.state = function(stateName, definition) {\n    // don't even bother if it's disabled. note, another config may run after this, so it's not a catch-all\n    if (typeof definition === 'object') {\n      var enabled = definition.prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();\n      if (enabled && isString(definition.templateUrl)) templatesToCache.push(definition.templateUrl);\n      if (angular.isObject(definition.views)) {\n        for (var key in definition.views) {\n          enabled = definition.views[key].prefetchTemplate !== false && templatesToCache.length < $ionicConfigProvider.templates.maxPrefetch();\n          if (enabled && isString(definition.views[key].templateUrl)) templatesToCache.push(definition.views[key].templateUrl);\n        }\n      }\n    }\n    return stateProviderState.call($stateProvider, stateName, definition);\n  };\n}])\n\n// process the templateUrls collected by the $stateProvider, adding them to the cache\n.run(['$ionicTemplateCache', function($ionicTemplateCache) {\n  $ionicTemplateCache();\n}]);\n\n})();\n\nIonicModule\n.factory('$ionicTemplateLoader', [\n  '$compile',\n  '$controller',\n  '$http',\n  '$q',\n  '$rootScope',\n  '$templateCache',\nfunction($compile, $controller, $http, $q, $rootScope, $templateCache) {\n\n  return {\n    load: fetchTemplate,\n    compile: loadAndCompile\n  };\n\n  function fetchTemplate(url) {\n    return $http.get(url, {cache: $templateCache})\n    .then(function(response) {\n      return response.data && response.data.trim();\n    });\n  }\n\n  function loadAndCompile(options) {\n    options = extend({\n      template: '',\n      templateUrl: '',\n      scope: null,\n      controller: null,\n      locals: {},\n      appendTo: null\n    }, options || {});\n\n    var templatePromise = options.templateUrl ?\n      this.load(options.templateUrl) :\n      $q.when(options.template);\n\n    return templatePromise.then(function(template) {\n      var controller;\n      var scope = options.scope || $rootScope.$new();\n\n      //Incase template doesn't have just one root element, do this\n      var element = jqLite('<div>').html(template).contents();\n\n      if (options.controller) {\n        controller = $controller(\n          options.controller,\n          extend(options.locals, {\n            $scope: scope\n          })\n        );\n        element.children().data('$ngControllerController', controller);\n      }\n      if (options.appendTo) {\n        jqLite(options.appendTo).append(element);\n      }\n\n      $compile(element)(scope);\n\n      return {\n        element: element,\n        scope: scope\n      };\n    });\n  }\n\n}]);\n\n/**\n * @private\n * DEPRECATED, as of v1.0.0-beta14 -------\n */\nIonicModule\n.factory('$ionicViewService', ['$ionicHistory', '$log', function($ionicHistory, $log) {\n\n  function warn(oldMethod, newMethod) {\n    $log.warn('$ionicViewService' + oldMethod + ' is deprecated, please use $ionicHistory' + newMethod + ' instead: http://ionicframework.com/docs/nightly/api/service/$ionicHistory/');\n  }\n\n  warn('', '');\n\n  var methodsMap = {\n    getCurrentView: 'currentView',\n    getBackView: 'backView',\n    getForwardView: 'forwardView',\n    getCurrentStateName: 'currentStateName',\n    nextViewOptions: 'nextViewOptions',\n    clearHistory: 'clearHistory'\n  };\n\n  forEach(methodsMap, function(newMethod, oldMethod) {\n    methodsMap[oldMethod] = function() {\n      warn('.' + oldMethod, '.' + newMethod);\n      return $ionicHistory[newMethod].apply(this, arguments);\n    };\n  });\n\n  return methodsMap;\n\n}]);\n\n/**\n * @private\n * TODO document\n */\n\nIonicModule.factory('$ionicViewSwitcher', [\n  '$timeout',\n  '$document',\n  '$q',\n  '$ionicClickBlock',\n  '$ionicConfig',\n  '$ionicNavBarDelegate',\nfunction($timeout, $document, $q, $ionicClickBlock, $ionicConfig, $ionicNavBarDelegate) {\n\n  var TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';\n  var DATA_NO_CACHE = '$noCache';\n  var DATA_DESTROY_ELE = '$destroyEle';\n  var DATA_ELE_IDENTIFIER = '$eleId';\n  var DATA_VIEW_ACCESSED = '$accessed';\n  var DATA_FALLBACK_TIMER = '$fallbackTimer';\n  var DATA_VIEW = '$viewData';\n  var NAV_VIEW_ATTR = 'nav-view';\n  var VIEW_STATUS_ACTIVE = 'active';\n  var VIEW_STATUS_CACHED = 'cached';\n  var VIEW_STATUS_STAGED = 'stage';\n\n  var transitionCounter = 0;\n  var nextTransition, nextDirection;\n  ionic.transition = ionic.transition || {};\n  ionic.transition.isActive = false;\n  var isActiveTimer;\n  var cachedAttr = ionic.DomUtil.cachedAttr;\n  var transitionPromises = [];\n  var defaultTimeout = 1100;\n\n  var ionicViewSwitcher = {\n\n    create: function(navViewCtrl, viewLocals, enteringView, leavingView, renderStart, renderEnd) {\n      // get a reference to an entering/leaving element if they exist\n      // loop through to see if the view is already in the navViewElement\n      var enteringEle, leavingEle;\n      var transitionId = ++transitionCounter;\n      var alreadyInDom;\n\n      var switcher = {\n\n        init: function(registerData, callback) {\n          ionicViewSwitcher.isTransitioning(true);\n\n          switcher.loadViewElements(registerData);\n\n          switcher.render(registerData, function() {\n            callback && callback();\n          });\n        },\n\n        loadViewElements: function(registerData) {\n          var x, l, viewEle;\n          var viewElements = navViewCtrl.getViewElements();\n          var enteringEleIdentifier = getViewElementIdentifier(viewLocals, enteringView);\n          var navViewActiveEleId = navViewCtrl.activeEleId();\n\n          for (x = 0, l = viewElements.length; x < l; x++) {\n            viewEle = viewElements.eq(x);\n\n            if (viewEle.data(DATA_ELE_IDENTIFIER) === enteringEleIdentifier) {\n              // we found an existing element in the DOM that should be entering the view\n              if (viewEle.data(DATA_NO_CACHE)) {\n                // the existing element should not be cached, don't use it\n                viewEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier + ionic.Utils.nextUid());\n                viewEle.data(DATA_DESTROY_ELE, true);\n\n              } else {\n                enteringEle = viewEle;\n              }\n\n            } else if (isDefined(navViewActiveEleId) && viewEle.data(DATA_ELE_IDENTIFIER) === navViewActiveEleId) {\n              leavingEle = viewEle;\n            }\n\n            if (enteringEle && leavingEle) break;\n          }\n\n          alreadyInDom = !!enteringEle;\n\n          if (!alreadyInDom) {\n            // still no existing element to use\n            // create it using existing template/scope/locals\n            enteringEle = registerData.ele || ionicViewSwitcher.createViewEle(viewLocals);\n\n            // existing elements in the DOM are looked up by their state name and state id\n            enteringEle.data(DATA_ELE_IDENTIFIER, enteringEleIdentifier);\n          }\n\n          if (renderEnd) {\n            navViewCtrl.activeEleId(enteringEleIdentifier);\n          }\n\n          registerData.ele = null;\n        },\n\n        render: function(registerData, callback) {\n          if (alreadyInDom) {\n            // it was already found in the DOM, just reconnect the scope\n            ionic.Utils.reconnectScope(enteringEle.scope());\n\n          } else {\n            // the entering element is not already in the DOM\n            // set that the entering element should be \"staged\" and its\n            // styles of where this element will go before it hits the DOM\n            navViewAttr(enteringEle, VIEW_STATUS_STAGED);\n\n            var enteringData = getTransitionData(viewLocals, enteringEle, registerData.direction, enteringView);\n            var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;\n            transitionFn(enteringEle, null, enteringData.direction, true).run(0);\n\n            enteringEle.data(DATA_VIEW, {\n              viewId: enteringData.viewId,\n              historyId: enteringData.historyId,\n              stateName: enteringData.stateName,\n              stateParams: enteringData.stateParams\n            });\n\n            // if the current state has cache:false\n            // or the element has cache-view=\"false\" attribute\n            if (viewState(viewLocals).cache === false || viewState(viewLocals).cache === 'false' ||\n                enteringEle.attr('cache-view') == 'false' || $ionicConfig.views.maxCache() === 0) {\n              enteringEle.data(DATA_NO_CACHE, true);\n            }\n\n            // append the entering element to the DOM, create a new scope and run link\n            var viewScope = navViewCtrl.appendViewElement(enteringEle, viewLocals);\n\n            delete enteringData.direction;\n            delete enteringData.transition;\n            viewScope.$emit('$ionicView.loaded', enteringData);\n          }\n\n          // update that this view was just accessed\n          enteringEle.data(DATA_VIEW_ACCESSED, Date.now());\n\n          callback && callback();\n        },\n\n        transition: function(direction, enableBack, allowAnimate) {\n          var deferred;\n          var enteringData = getTransitionData(viewLocals, enteringEle, direction, enteringView);\n          var leavingData = extend(extend({}, enteringData), getViewData(leavingView));\n          enteringData.transitionId = leavingData.transitionId = transitionId;\n          enteringData.fromCache = !!alreadyInDom;\n          enteringData.enableBack = !!enableBack;\n          enteringData.renderStart = renderStart;\n          enteringData.renderEnd = renderEnd;\n\n          cachedAttr(enteringEle.parent(), 'nav-view-transition', enteringData.transition);\n          cachedAttr(enteringEle.parent(), 'nav-view-direction', enteringData.direction);\n\n          // cancel any previous transition complete fallbacks\n          $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));\n\n          // get the transition ready and see if it'll animate\n          var transitionFn = $ionicConfig.transitions.views[enteringData.transition] || $ionicConfig.transitions.views.none;\n          var viewTransition = transitionFn(enteringEle, leavingEle, enteringData.direction,\n                                            enteringData.shouldAnimate && allowAnimate && renderEnd);\n\n          if (viewTransition.shouldAnimate) {\n            // attach transitionend events (and fallback timer)\n            enteringEle.on(TRANSITIONEND_EVENT, completeOnTransitionEnd);\n            enteringEle.data(DATA_FALLBACK_TIMER, $timeout(transitionComplete, defaultTimeout));\n            $ionicClickBlock.show(defaultTimeout);\n          }\n\n          if (renderStart) {\n            // notify the views \"before\" the transition starts\n            switcher.emit('before', enteringData, leavingData);\n\n            // stage entering element, opacity 0, no transition duration\n            navViewAttr(enteringEle, VIEW_STATUS_STAGED);\n\n            // render the elements in the correct location for their starting point\n            viewTransition.run(0);\n          }\n\n          if (renderEnd) {\n            // create a promise so we can keep track of when all transitions finish\n            // only required if this transition should complete\n            deferred = $q.defer();\n            transitionPromises.push(deferred.promise);\n          }\n\n          if (renderStart && renderEnd) {\n            // CSS \"auto\" transitioned, not manually transitioned\n            // wait a frame so the styles apply before auto transitioning\n            $timeout(onReflow, 16);\n\n          } else if (!renderEnd) {\n            // just the start of a manual transition\n            // but it will not render the end of the transition\n            navViewAttr(enteringEle, 'entering');\n            navViewAttr(leavingEle, 'leaving');\n\n            // return the transition run method so each step can be ran manually\n            return {\n              run: viewTransition.run,\n              cancel: function(shouldAnimate) {\n                if (shouldAnimate) {\n                  enteringEle.on(TRANSITIONEND_EVENT, cancelOnTransitionEnd);\n                  enteringEle.data(DATA_FALLBACK_TIMER, $timeout(cancelTransition, defaultTimeout));\n                  $ionicClickBlock.show(defaultTimeout);\n                } else {\n                  cancelTransition();\n                }\n                viewTransition.shouldAnimate = shouldAnimate;\n                viewTransition.run(0);\n                viewTransition = null;\n              }\n            };\n\n          } else if (renderEnd) {\n            // just the end of a manual transition\n            // happens after the manual transition has completed\n            // and a full history change has happened\n            onReflow();\n          }\n\n\n          function onReflow() {\n            // remove that we're staging the entering element so it can auto transition\n            navViewAttr(enteringEle, viewTransition.shouldAnimate ? 'entering' : VIEW_STATUS_ACTIVE);\n            navViewAttr(leavingEle, viewTransition.shouldAnimate ? 'leaving' : VIEW_STATUS_CACHED);\n\n            // start the auto transition and let the CSS take over\n            viewTransition.run(1);\n\n            // trigger auto transitions on the associated nav bars\n            $ionicNavBarDelegate._instances.forEach(function(instance) {\n              instance.triggerTransitionStart(transitionId);\n            });\n\n            if (!viewTransition.shouldAnimate) {\n              // no animated auto transition\n              transitionComplete();\n            }\n          }\n\n          // Make sure that transitionend events bubbling up from children won't fire\n          // transitionComplete. Will only go forward if ev.target == the element listening.\n          function completeOnTransitionEnd(ev) {\n            if (ev.target !== this) return;\n            transitionComplete();\n          }\n          function transitionComplete() {\n            if (transitionComplete.x) return;\n            transitionComplete.x = true;\n\n            enteringEle.off(TRANSITIONEND_EVENT, completeOnTransitionEnd);\n            $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));\n            leavingEle && $timeout.cancel(leavingEle.data(DATA_FALLBACK_TIMER));\n\n            // emit that the views have finished transitioning\n            // each parent nav-view will update which views are active and cached\n            switcher.emit('after', enteringData, leavingData);\n\n            // resolve that this one transition (there could be many w/ nested views)\n            deferred && deferred.resolve(navViewCtrl);\n\n            // the most recent transition added has completed and all the active\n            // transition promises should be added to the services array of promises\n            if (transitionId === transitionCounter) {\n              $q.all(transitionPromises).then(ionicViewSwitcher.transitionEnd);\n              switcher.cleanup(enteringData);\n            }\n\n            // tell the nav bars that the transition has ended\n            $ionicNavBarDelegate._instances.forEach(function(instance) {\n              instance.triggerTransitionEnd();\n            });\n\n            // remove any references that could cause memory issues\n            nextTransition = nextDirection = enteringView = leavingView = enteringEle = leavingEle = null;\n          }\n\n          // Make sure that transitionend events bubbling up from children won't fire\n          // transitionComplete. Will only go forward if ev.target == the element listening.\n          function cancelOnTransitionEnd(ev) {\n            if (ev.target !== this) return;\n            cancelTransition();\n          }\n          function cancelTransition() {\n            navViewAttr(enteringEle, VIEW_STATUS_CACHED);\n            navViewAttr(leavingEle, VIEW_STATUS_ACTIVE);\n            enteringEle.off(TRANSITIONEND_EVENT, cancelOnTransitionEnd);\n            $timeout.cancel(enteringEle.data(DATA_FALLBACK_TIMER));\n            ionicViewSwitcher.transitionEnd([navViewCtrl]);\n          }\n\n        },\n\n        emit: function(step, enteringData, leavingData) {\n          var scope = enteringEle.scope();\n          if (scope) {\n            scope.$emit('$ionicView.' + step + 'Enter', enteringData);\n            if (step == 'after') {\n              scope.$emit('$ionicView.enter', enteringData);\n            }\n          }\n\n          if (leavingEle) {\n            scope = leavingEle.scope();\n            if (scope) {\n              scope.$emit('$ionicView.' + step + 'Leave', leavingData);\n              if (step == 'after') {\n                scope.$emit('$ionicView.leave', leavingData);\n              }\n            }\n\n          } else if (scope && leavingData && leavingData.viewId) {\n            scope.$emit('$ionicNavView.' + step + 'Leave', leavingData);\n            if (step == 'after') {\n              scope.$emit('$ionicNavView.leave', leavingData);\n            }\n          }\n        },\n\n        cleanup: function(transData) {\n          // check if any views should be removed\n          if (leavingEle && transData.direction == 'back' && !$ionicConfig.views.forwardCache()) {\n            // if they just navigated back we can destroy the forward view\n            // do not remove forward views if cacheForwardViews config is true\n            destroyViewEle(leavingEle);\n          }\n\n          var viewElements = navViewCtrl.getViewElements();\n          var viewElementsLength = viewElements.length;\n          var x, viewElement;\n          var removeOldestAccess = (viewElementsLength - 1) > $ionicConfig.views.maxCache();\n          var removableEle;\n          var oldestAccess = Date.now();\n\n          for (x = 0; x < viewElementsLength; x++) {\n            viewElement = viewElements.eq(x);\n\n            if (removeOldestAccess && viewElement.data(DATA_VIEW_ACCESSED) < oldestAccess) {\n              // remember what was the oldest element to be accessed so it can be destroyed\n              oldestAccess = viewElement.data(DATA_VIEW_ACCESSED);\n              removableEle = viewElements.eq(x);\n\n            } else if (viewElement.data(DATA_DESTROY_ELE) && navViewAttr(viewElement) != VIEW_STATUS_ACTIVE) {\n              destroyViewEle(viewElement);\n            }\n          }\n\n          destroyViewEle(removableEle);\n\n          if (enteringEle.data(DATA_NO_CACHE)) {\n            enteringEle.data(DATA_DESTROY_ELE, true);\n          }\n        },\n\n        enteringEle: function() { return enteringEle; },\n        leavingEle: function() { return leavingEle; }\n\n      };\n\n      return switcher;\n    },\n\n    transitionEnd: function(navViewCtrls) {\n      forEach(navViewCtrls, function(navViewCtrl) {\n        navViewCtrl.transitionEnd();\n      });\n\n      ionicViewSwitcher.isTransitioning(false);\n      $ionicClickBlock.hide();\n      transitionPromises = [];\n    },\n\n    nextTransition: function(val) {\n      nextTransition = val;\n    },\n\n    nextDirection: function(val) {\n      nextDirection = val;\n    },\n\n    isTransitioning: function(val) {\n      if (arguments.length) {\n        ionic.transition.isActive = !!val;\n        $timeout.cancel(isActiveTimer);\n        if (val) {\n          isActiveTimer = $timeout(function() {\n            ionicViewSwitcher.isTransitioning(false);\n          }, 999);\n        }\n      }\n      return ionic.transition.isActive;\n    },\n\n    createViewEle: function(viewLocals) {\n      var containerEle = $document[0].createElement('div');\n      if (viewLocals && viewLocals.$template) {\n        containerEle.innerHTML = viewLocals.$template;\n        if (containerEle.children.length === 1) {\n          containerEle.children[0].classList.add('pane');\n          return jqLite(containerEle.children[0]);\n        }\n      }\n      containerEle.className = \"pane\";\n      return jqLite(containerEle);\n    },\n\n    viewEleIsActive: function(viewEle, isActiveAttr) {\n      navViewAttr(viewEle, isActiveAttr ? VIEW_STATUS_ACTIVE : VIEW_STATUS_CACHED);\n    },\n\n    getTransitionData: getTransitionData,\n    navViewAttr: navViewAttr,\n    destroyViewEle: destroyViewEle\n\n  };\n\n  return ionicViewSwitcher;\n\n\n  function getViewElementIdentifier(locals, view) {\n    if (viewState(locals)['abstract']) return viewState(locals).name;\n    if (view) return view.stateId || view.viewId;\n    return ionic.Utils.nextUid();\n  }\n\n  function viewState(locals) {\n    return locals && locals.$$state && locals.$$state.self || {};\n  }\n\n  function getTransitionData(viewLocals, enteringEle, direction, view) {\n    // Priority\n    // 1) attribute directive on the button/link to this view\n    // 2) entering element's attribute\n    // 3) entering view's $state config property\n    // 4) view registration data\n    // 5) global config\n    // 6) fallback value\n\n    var state = viewState(viewLocals);\n    var viewTransition = nextTransition || cachedAttr(enteringEle, 'view-transition') || state.viewTransition || $ionicConfig.views.transition() || 'ios';\n    var navBarTransition = $ionicConfig.navBar.transition();\n    direction = nextDirection || cachedAttr(enteringEle, 'view-direction') || state.viewDirection || direction || 'none';\n\n    return extend(getViewData(view), {\n      transition: viewTransition,\n      navBarTransition: navBarTransition === 'view' ? viewTransition : navBarTransition,\n      direction: direction,\n      shouldAnimate: (viewTransition !== 'none' && direction !== 'none')\n    });\n  }\n\n  function getViewData(view) {\n    view = view || {};\n    return {\n      viewId: view.viewId,\n      historyId: view.historyId,\n      stateId: view.stateId,\n      stateName: view.stateName,\n      stateParams: view.stateParams\n    };\n  }\n\n  function navViewAttr(ele, value) {\n    if (arguments.length > 1) {\n      cachedAttr(ele, NAV_VIEW_ATTR, value);\n    } else {\n      return cachedAttr(ele, NAV_VIEW_ATTR);\n    }\n  }\n\n  function destroyViewEle(ele) {\n    // we found an element that should be removed\n    // destroy its scope, then remove the element\n    if (ele && ele.length) {\n      var viewScope = ele.scope();\n      if (viewScope) {\n        viewScope.$emit('$ionicView.unloaded', ele.data(DATA_VIEW));\n        viewScope.$destroy();\n      }\n      ele.remove();\n    }\n  }\n\n}]);\n\n/**\n * @private\n * Parts of Ionic requires that $scope data is attached to the element.\n * We do not want to disable adding $scope data to the $element when\n * $compileProvider.debugInfoEnabled(false) is used.\n */\nIonicModule.config(['$provide', function($provide) {\n  $provide.decorator('$compile', ['$delegate', function($compile) {\n     $compile.$$addScopeInfo = function $$addScopeInfo($element, scope, isolated, noTemplate) {\n       var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n       $element.data(dataName, scope);\n     };\n     return $compile;\n  }]);\n}]);\n\n/**\n * @private\n */\nIonicModule.config([\n  '$provide',\nfunction($provide) {\n  function $LocationDecorator($location, $timeout) {\n\n    $location.__hash = $location.hash;\n    //Fix: when window.location.hash is set, the scrollable area\n    //found nearest to body's scrollTop is set to scroll to an element\n    //with that ID.\n    $location.hash = function(value) {\n      if (isDefined(value)) {\n        $timeout(function() {\n          var scroll = document.querySelector('.scroll-content');\n          if (scroll) {\n            scroll.scrollTop = 0;\n          }\n        }, 0, false);\n      }\n      return $location.__hash(value);\n    };\n\n    return $location;\n  }\n\n  $provide.decorator('$location', ['$delegate', '$timeout', $LocationDecorator]);\n}]);\n\nIonicModule\n\n.controller('$ionicHeaderBar', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$q',\n  '$ionicConfig',\n  '$ionicHistory',\nfunction($scope, $element, $attrs, $q, $ionicConfig, $ionicHistory) {\n  var TITLE = 'title';\n  var BACK_TEXT = 'back-text';\n  var BACK_BUTTON = 'back-button';\n  var DEFAULT_TITLE = 'default-title';\n  var PREVIOUS_TITLE = 'previous-title';\n  var HIDE = 'hide';\n\n  var self = this;\n  var titleText = '';\n  var previousTitleText = '';\n  var titleLeft = 0;\n  var titleRight = 0;\n  var titleCss = '';\n  var isBackEnabled = false;\n  var isBackShown = true;\n  var isNavBackShown = true;\n  var isBackElementShown = false;\n  var titleTextWidth = 0;\n\n\n  self.beforeEnter = function(viewData) {\n    $scope.$broadcast('$ionicView.beforeEnter', viewData);\n  };\n\n\n  self.title = function(newTitleText) {\n    if (arguments.length && newTitleText !== titleText) {\n      getEle(TITLE).innerHTML = newTitleText;\n      titleText = newTitleText;\n      titleTextWidth = 0;\n    }\n    return titleText;\n  };\n\n\n  self.enableBack = function(shouldEnable, disableReset) {\n    // whether or not the back button show be visible, according\n    // to the navigation and history\n    if (arguments.length) {\n      isBackEnabled = shouldEnable;\n      if (!disableReset) self.updateBackButton();\n    }\n    return isBackEnabled;\n  };\n\n\n  self.showBack = function(shouldShow, disableReset) {\n    // different from enableBack() because this will always have the back\n    // visually hidden if false, even if the history says it should show\n    if (arguments.length) {\n      isBackShown = shouldShow;\n      if (!disableReset) self.updateBackButton();\n    }\n    return isBackShown;\n  };\n\n\n  self.showNavBack = function(shouldShow) {\n    // different from showBack() because this is for the entire nav bar's\n    // setting for all of it's child headers. For internal use.\n    isNavBackShown = shouldShow;\n    self.updateBackButton();\n  };\n\n\n  self.updateBackButton = function() {\n    var ele;\n    if ((isBackShown && isNavBackShown && isBackEnabled) !== isBackElementShown) {\n      isBackElementShown = isBackShown && isNavBackShown && isBackEnabled;\n      ele = getEle(BACK_BUTTON);\n      ele && ele.classList[ isBackElementShown ? 'remove' : 'add' ](HIDE);\n    }\n\n    if (isBackEnabled) {\n      ele = ele || getEle(BACK_BUTTON);\n      if (ele) {\n        if (self.backButtonIcon !== $ionicConfig.backButton.icon()) {\n          ele = getEle(BACK_BUTTON + ' .icon');\n          if (ele) {\n            self.backButtonIcon = $ionicConfig.backButton.icon();\n            ele.className = 'icon ' + self.backButtonIcon;\n          }\n        }\n\n        if (self.backButtonText !== $ionicConfig.backButton.text()) {\n          ele = getEle(BACK_BUTTON + ' .back-text');\n          if (ele) {\n            ele.textContent = self.backButtonText = $ionicConfig.backButton.text();\n          }\n        }\n      }\n    }\n  };\n\n\n  self.titleTextWidth = function() {\n    if (!titleTextWidth) {\n      var bounds = ionic.DomUtil.getTextBounds(getEle(TITLE));\n      titleTextWidth = Math.min(bounds && bounds.width || 30);\n    }\n    return titleTextWidth;\n  };\n\n\n  self.titleWidth = function() {\n    var titleWidth = self.titleTextWidth();\n    var offsetWidth = getEle(TITLE).offsetWidth;\n    if (offsetWidth < titleWidth) {\n      titleWidth = offsetWidth + (titleLeft - titleRight - 5);\n    }\n    return titleWidth;\n  };\n\n\n  self.titleTextX = function() {\n    return ($element[0].offsetWidth / 2) - (self.titleWidth() / 2);\n  };\n\n\n  self.titleLeftRight = function() {\n    return titleLeft - titleRight;\n  };\n\n\n  self.backButtonTextLeft = function() {\n    var offsetLeft = 0;\n    var ele = getEle(BACK_TEXT);\n    while (ele) {\n      offsetLeft += ele.offsetLeft;\n      ele = ele.parentElement;\n    }\n    return offsetLeft;\n  };\n\n\n  self.resetBackButton = function(viewData) {\n    if ($ionicConfig.backButton.previousTitleText()) {\n      var previousTitleEle = getEle(PREVIOUS_TITLE);\n      if (previousTitleEle) {\n        previousTitleEle.classList.remove(HIDE);\n\n        var view = (viewData && $ionicHistory.getViewById(viewData.viewId));\n        var newPreviousTitleText = $ionicHistory.backTitle(view);\n\n        if (newPreviousTitleText !== previousTitleText) {\n          previousTitleText = previousTitleEle.innerHTML = newPreviousTitleText;\n        }\n      }\n      var defaultTitleEle = getEle(DEFAULT_TITLE);\n      if (defaultTitleEle) {\n        defaultTitleEle.classList.remove(HIDE);\n      }\n    }\n  };\n\n\n  self.align = function(textAlign) {\n    var titleEle = getEle(TITLE);\n\n    textAlign = textAlign || $attrs.alignTitle || $ionicConfig.navBar.alignTitle();\n\n    var widths = self.calcWidths(textAlign, false);\n\n    if (isBackShown && previousTitleText && $ionicConfig.backButton.previousTitleText()) {\n      var previousTitleWidths = self.calcWidths(textAlign, true);\n\n      var availableTitleWidth = $element[0].offsetWidth - previousTitleWidths.titleLeft - previousTitleWidths.titleRight;\n\n      if (self.titleTextWidth() <= availableTitleWidth) {\n        widths = previousTitleWidths;\n      }\n    }\n\n    return self.updatePositions(titleEle, widths.titleLeft, widths.titleRight, widths.buttonsLeft, widths.buttonsRight, widths.css, widths.showPrevTitle);\n  };\n\n\n  self.calcWidths = function(textAlign, isPreviousTitle) {\n    var titleEle = getEle(TITLE);\n    var backBtnEle = getEle(BACK_BUTTON);\n    var x, y, z, b, c, d, childSize, bounds;\n    var childNodes = $element[0].childNodes;\n    var buttonsLeft = 0;\n    var buttonsRight = 0;\n    var isCountRightOfTitle;\n    var updateTitleLeft = 0;\n    var updateTitleRight = 0;\n    var updateCss = '';\n    var backButtonWidth = 0;\n\n    // Compute how wide the left children are\n    // Skip all titles (there may still be two titles, one leaving the dom)\n    // Once we encounter a titleEle, realize we are now counting the right-buttons, not left\n    for (x = 0; x < childNodes.length; x++) {\n      c = childNodes[x];\n\n      childSize = 0;\n      if (c.nodeType == 1) {\n        // element node\n        if (c === titleEle) {\n          isCountRightOfTitle = true;\n          continue;\n        }\n\n        if (c.classList.contains(HIDE)) {\n          continue;\n        }\n\n        if (isBackShown && c === backBtnEle) {\n\n          for (y = 0; y < c.childNodes.length; y++) {\n            b = c.childNodes[y];\n\n            if (b.nodeType == 1) {\n\n              if (b.classList.contains(BACK_TEXT)) {\n                for (z = 0; z < b.children.length; z++) {\n                  d = b.children[z];\n\n                  if (isPreviousTitle) {\n                    if (d.classList.contains(DEFAULT_TITLE)) continue;\n                    backButtonWidth += d.offsetWidth;\n                  } else {\n                    if (d.classList.contains(PREVIOUS_TITLE)) continue;\n                    backButtonWidth += d.offsetWidth;\n                  }\n                }\n\n              } else {\n                backButtonWidth += b.offsetWidth;\n              }\n\n            } else if (b.nodeType == 3 && b.nodeValue.trim()) {\n              bounds = ionic.DomUtil.getTextBounds(b);\n              backButtonWidth += bounds && bounds.width || 0;\n            }\n\n          }\n          childSize = backButtonWidth || c.offsetWidth;\n\n        } else {\n          // not the title, not the back button, not a hidden element\n          childSize = c.offsetWidth;\n        }\n\n      } else if (c.nodeType == 3 && c.nodeValue.trim()) {\n        // text node\n        bounds = ionic.DomUtil.getTextBounds(c);\n        childSize = bounds && bounds.width || 0;\n      }\n\n      if (isCountRightOfTitle) {\n        buttonsRight += childSize;\n      } else {\n        buttonsLeft += childSize;\n      }\n    }\n\n    // Size and align the header titleEle based on the sizes of the left and\n    // right children, and the desired alignment mode\n    if (textAlign == 'left') {\n      updateCss = 'title-left';\n      if (buttonsLeft) {\n        updateTitleLeft = buttonsLeft + 15;\n      }\n      if (buttonsRight) {\n        updateTitleRight = buttonsRight + 15;\n      }\n\n    } else if (textAlign == 'right') {\n      updateCss = 'title-right';\n      if (buttonsLeft) {\n        updateTitleLeft = buttonsLeft + 15;\n      }\n      if (buttonsRight) {\n        updateTitleRight = buttonsRight + 15;\n      }\n\n    } else {\n      // center the default\n      var margin = Math.max(buttonsLeft, buttonsRight) + 10;\n      if (margin > 10) {\n        updateTitleLeft = updateTitleRight = margin;\n      }\n    }\n\n    return {\n      backButtonWidth: backButtonWidth,\n      buttonsLeft: buttonsLeft,\n      buttonsRight: buttonsRight,\n      titleLeft: updateTitleLeft,\n      titleRight: updateTitleRight,\n      showPrevTitle: isPreviousTitle,\n      css: updateCss\n    };\n  };\n\n\n  self.updatePositions = function(titleEle, updateTitleLeft, updateTitleRight, buttonsLeft, buttonsRight, updateCss, showPreviousTitle) {\n    var deferred = $q.defer();\n\n    // only make DOM updates when there are actual changes\n    if (titleEle) {\n      if (updateTitleLeft !== titleLeft) {\n        titleEle.style.left = updateTitleLeft ? updateTitleLeft + 'px' : '';\n        titleLeft = updateTitleLeft;\n      }\n      if (updateTitleRight !== titleRight) {\n        titleEle.style.right = updateTitleRight ? updateTitleRight + 'px' : '';\n        titleRight = updateTitleRight;\n      }\n\n      if (updateCss !== titleCss) {\n        updateCss && titleEle.classList.add(updateCss);\n        titleCss && titleEle.classList.remove(titleCss);\n        titleCss = updateCss;\n      }\n    }\n\n    if ($ionicConfig.backButton.previousTitleText()) {\n      var prevTitle = getEle(PREVIOUS_TITLE);\n      var defaultTitle = getEle(DEFAULT_TITLE);\n\n      prevTitle && prevTitle.classList[ showPreviousTitle ? 'remove' : 'add'](HIDE);\n      defaultTitle && defaultTitle.classList[ showPreviousTitle ? 'add' : 'remove'](HIDE);\n    }\n\n    ionic.requestAnimationFrame(function() {\n      if (titleEle && titleEle.offsetWidth + 10 < titleEle.scrollWidth) {\n        var minRight = buttonsRight + 5;\n        var testRight = $element[0].offsetWidth - titleLeft - self.titleTextWidth() - 20;\n        updateTitleRight = testRight < minRight ? minRight : testRight;\n        if (updateTitleRight !== titleRight) {\n          titleEle.style.right = updateTitleRight + 'px';\n          titleRight = updateTitleRight;\n        }\n      }\n      deferred.resolve();\n    });\n\n    return deferred.promise;\n  };\n\n\n  self.setCss = function(elementClassname, css) {\n    ionic.DomUtil.cachedStyles(getEle(elementClassname), css);\n  };\n\n\n  var eleCache = {};\n  function getEle(className) {\n    if (!eleCache[className]) {\n      eleCache[className] = $element[0].querySelector('.' + className);\n    }\n    return eleCache[className];\n  }\n\n\n  $scope.$on('$destroy', function() {\n    for (var n in eleCache) eleCache[n] = null;\n  });\n\n}]);\n\nIonicModule\n.controller('$ionInfiniteScroll', [\n  '$scope',\n  '$attrs',\n  '$element',\n  '$timeout',\nfunction($scope, $attrs, $element, $timeout) {\n  var self = this;\n  self.isLoading = false;\n\n  $scope.icon = function() {\n    return isDefined($attrs.icon) ? $attrs.icon : 'ion-load-d';\n  };\n\n  $scope.spinner = function() {\n    return isDefined($attrs.spinner) ? $attrs.spinner : '';\n  };\n\n  $scope.$on('scroll.infiniteScrollComplete', function() {\n    finishInfiniteScroll();\n  });\n\n  $scope.$on('$destroy', function() {\n    if (self.scrollCtrl && self.scrollCtrl.$element) self.scrollCtrl.$element.off('scroll', self.checkBounds);\n    if (self.scrollEl && self.scrollEl.removeEventListener) {\n      self.scrollEl.removeEventListener('scroll', self.checkBounds);\n    }\n  });\n\n  // debounce checking infinite scroll events\n  self.checkBounds = ionic.Utils.throttle(checkInfiniteBounds, 300);\n\n  function onInfinite() {\n    ionic.requestAnimationFrame(function() {\n      $element[0].classList.add('active');\n    });\n    self.isLoading = true;\n    $scope.$parent && $scope.$parent.$apply($attrs.onInfinite || '');\n  }\n\n  function finishInfiniteScroll() {\n    ionic.requestAnimationFrame(function() {\n      $element[0].classList.remove('active');\n    });\n    $timeout(function() {\n      if (self.jsScrolling) self.scrollView.resize();\n      // only check bounds again immediately if the page isn't cached (scroll el has height)\n      if ((self.jsScrolling && self.scrollView.__container && self.scrollView.__container.offsetHeight > 0) ||\n      !self.jsScrolling) {\n        self.checkBounds();\n      }\n    }, 30, false);\n    self.isLoading = false;\n  }\n\n  // check if we've scrolled far enough to trigger an infinite scroll\n  function checkInfiniteBounds() {\n    if (self.isLoading) return;\n    var maxScroll = {};\n\n    if (self.jsScrolling) {\n      maxScroll = self.getJSMaxScroll();\n      var scrollValues = self.scrollView.getValues();\n      if ((maxScroll.left !== -1 && scrollValues.left >= maxScroll.left) ||\n        (maxScroll.top !== -1 && scrollValues.top >= maxScroll.top)) {\n        onInfinite();\n      }\n    } else {\n      maxScroll = self.getNativeMaxScroll();\n      if ((\n        maxScroll.left !== -1 &&\n        self.scrollEl.scrollLeft >= maxScroll.left - self.scrollEl.clientWidth\n        ) || (\n        maxScroll.top !== -1 &&\n        self.scrollEl.scrollTop >= maxScroll.top - self.scrollEl.clientHeight\n        )) {\n        onInfinite();\n      }\n    }\n  }\n\n  // determine the threshold at which we should fire an infinite scroll\n  // note: this gets processed every scroll event, can it be cached?\n  self.getJSMaxScroll = function() {\n    var maxValues = self.scrollView.getScrollMax();\n    return {\n      left: self.scrollView.options.scrollingX ?\n        calculateMaxValue(maxValues.left) :\n        -1,\n      top: self.scrollView.options.scrollingY ?\n        calculateMaxValue(maxValues.top) :\n        -1\n    };\n  };\n\n  self.getNativeMaxScroll = function() {\n    var maxValues = {\n      left: self.scrollEl.scrollWidth,\n      top: self.scrollEl.scrollHeight\n    };\n    var computedStyle = window.getComputedStyle(self.scrollEl) || {};\n    return {\n      left: computedStyle.overflowX === 'scroll' ||\n      computedStyle.overflowX === 'auto' ||\n      self.scrollEl.style['overflow-x'] === 'scroll' ?\n        calculateMaxValue(maxValues.left) : -1,\n      top: computedStyle.overflowY === 'scroll' ||\n      computedStyle.overflowY === 'auto' ||\n      self.scrollEl.style['overflow-y'] === 'scroll' ?\n        calculateMaxValue(maxValues.top) : -1\n    };\n  };\n\n  // determine pixel refresh distance based on % or value\n  function calculateMaxValue(maximum) {\n    var distance = ($attrs.distance || '2.5%').trim();\n    var isPercent = distance.indexOf('%') !== -1;\n    return isPercent ?\n    maximum * (1 - parseFloat(distance) / 100) :\n    maximum - parseFloat(distance);\n  }\n\n  //for testing\n  self.__finishInfiniteScroll = finishInfiniteScroll;\n\n}]);\n\n/**\n * @ngdoc service\n * @name $ionicListDelegate\n * @module ionic\n *\n * @description\n * Delegate for controlling the {@link ionic.directive:ionList} directive.\n *\n * Methods called directly on the $ionicListDelegate service will control all lists.\n * Use the {@link ionic.service:$ionicListDelegate#$getByHandle $getByHandle}\n * method to control specific ionList instances.\n *\n * @usage\n *\n * ````html\n * <ion-content ng-controller=\"MyCtrl\">\n *   <button class=\"button\" ng-click=\"showDeleteButtons()\"></button>\n *   <ion-list>\n *     <ion-item ng-repeat=\"i in items\">\n *       {% raw %}Hello, {{i}}!{% endraw %}\n *       <ion-delete-button class=\"ion-minus-circled\"></ion-delete-button>\n *     </ion-item>\n *   </ion-list>\n * </ion-content>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicListDelegate) {\n *   $scope.showDeleteButtons = function() {\n *     $ionicListDelegate.showDelete(true);\n *   };\n * }\n * ```\n */\nIonicModule.service('$ionicListDelegate', ionic.DelegateService([\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#showReorder\n   * @param {boolean=} showReorder Set whether or not this list is showing its reorder buttons.\n   * @returns {boolean} Whether the reorder buttons are shown.\n   */\n  'showReorder',\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#showDelete\n   * @param {boolean=} showDelete Set whether or not this list is showing its delete buttons.\n   * @returns {boolean} Whether the delete buttons are shown.\n   */\n  'showDelete',\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#canSwipeItems\n   * @param {boolean=} canSwipeItems Set whether or not this list is able to swipe to show\n   * option buttons.\n   * @returns {boolean} Whether the list is able to swipe to show option buttons.\n   */\n  'canSwipeItems',\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#closeOptionButtons\n   * @description Closes any option buttons on the list that are swiped open.\n   */\n  'closeOptionButtons'\n  /**\n   * @ngdoc method\n   * @name $ionicListDelegate#$getByHandle\n   * @param {string} handle\n   * @returns `delegateInstance` A delegate instance that controls only the\n   * {@link ionic.directive:ionList} directives with `delegate-handle` matching\n   * the given handle.\n   *\n   * Example: `$ionicListDelegate.$getByHandle('my-handle').showReorder(true);`\n   */\n]))\n\n.controller('$ionicList', [\n  '$scope',\n  '$attrs',\n  '$ionicListDelegate',\n  '$ionicHistory',\nfunction($scope, $attrs, $ionicListDelegate, $ionicHistory) {\n  var self = this;\n  var isSwipeable = true;\n  var isReorderShown = false;\n  var isDeleteShown = false;\n\n  var deregisterInstance = $ionicListDelegate._registerInstance(\n    self, $attrs.delegateHandle, function() {\n      return $ionicHistory.isActiveScope($scope);\n    }\n  );\n  $scope.$on('$destroy', deregisterInstance);\n\n  self.showReorder = function(show) {\n    if (arguments.length) {\n      isReorderShown = !!show;\n    }\n    return isReorderShown;\n  };\n\n  self.showDelete = function(show) {\n    if (arguments.length) {\n      isDeleteShown = !!show;\n    }\n    return isDeleteShown;\n  };\n\n  self.canSwipeItems = function(can) {\n    if (arguments.length) {\n      isSwipeable = !!can;\n    }\n    return isSwipeable;\n  };\n\n  self.closeOptionButtons = function() {\n    self.listView && self.listView.clearDragEffects();\n  };\n}]);\n\nIonicModule\n\n.controller('$ionicNavBar', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$compile',\n  '$timeout',\n  '$ionicNavBarDelegate',\n  '$ionicConfig',\n  '$ionicHistory',\nfunction($scope, $element, $attrs, $compile, $timeout, $ionicNavBarDelegate, $ionicConfig, $ionicHistory) {\n\n  var CSS_HIDE = 'hide';\n  var DATA_NAV_BAR_CTRL = '$ionNavBarController';\n  var PRIMARY_BUTTONS = 'primaryButtons';\n  var SECONDARY_BUTTONS = 'secondaryButtons';\n  var BACK_BUTTON = 'backButton';\n  var ITEM_TYPES = 'primaryButtons secondaryButtons leftButtons rightButtons title'.split(' ');\n\n  var self = this;\n  var headerBars = [];\n  var navElementHtml = {};\n  var isVisible = true;\n  var queuedTransitionStart, queuedTransitionEnd, latestTransitionId;\n\n  $element.parent().data(DATA_NAV_BAR_CTRL, self);\n\n  var delegateHandle = $attrs.delegateHandle || 'navBar' + ionic.Utils.nextUid();\n\n  var deregisterInstance = $ionicNavBarDelegate._registerInstance(self, delegateHandle);\n\n\n  self.init = function() {\n    $element.addClass('nav-bar-container');\n    ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', $ionicConfig.views.transition());\n\n    // create two nav bar blocks which will trade out which one is shown\n    self.createHeaderBar(false);\n    self.createHeaderBar(true);\n\n    $scope.$emit('ionNavBar.init', delegateHandle);\n  };\n\n\n  self.createHeaderBar = function(isActive) {\n    var containerEle = jqLite('<div class=\"nav-bar-block\">');\n    ionic.DomUtil.cachedAttr(containerEle, 'nav-bar', isActive ? 'active' : 'cached');\n\n    var alignTitle = $attrs.alignTitle || $ionicConfig.navBar.alignTitle();\n    var headerBarEle = jqLite('<ion-header-bar>').addClass($attrs['class']).attr('align-title', alignTitle);\n    if (isDefined($attrs.noTapScroll)) headerBarEle.attr('no-tap-scroll', $attrs.noTapScroll);\n    var titleEle = jqLite('<div class=\"title title-' + alignTitle + '\">');\n    var navEle = {};\n    var lastViewItemEle = {};\n    var leftButtonsEle, rightButtonsEle;\n\n    navEle[BACK_BUTTON] = createNavElement(BACK_BUTTON);\n    navEle[BACK_BUTTON] && headerBarEle.append(navEle[BACK_BUTTON]);\n\n    // append title in the header, this is the rock to where buttons append\n    headerBarEle.append(titleEle);\n\n    forEach(ITEM_TYPES, function(itemType) {\n      // create default button elements\n      navEle[itemType] = createNavElement(itemType);\n      // append and position buttons\n      positionItem(navEle[itemType], itemType);\n    });\n\n    // add header-item to the root children\n    for (var x = 0; x < headerBarEle[0].children.length; x++) {\n      headerBarEle[0].children[x].classList.add('header-item');\n    }\n\n    // compile header and append to the DOM\n    containerEle.append(headerBarEle);\n    $element.append($compile(containerEle)($scope.$new()));\n\n    var headerBarCtrl = headerBarEle.data('$ionHeaderBarController');\n    headerBarCtrl.backButtonIcon = $ionicConfig.backButton.icon();\n    headerBarCtrl.backButtonText = $ionicConfig.backButton.text();\n\n    var headerBarInstance = {\n      isActive: isActive,\n      title: function(newTitleText) {\n        headerBarCtrl.title(newTitleText);\n      },\n      setItem: function(navBarItemEle, itemType) {\n        // first make sure any exiting nav bar item has been removed\n        headerBarInstance.removeItem(itemType);\n\n        if (navBarItemEle) {\n          if (itemType === 'title') {\n            // clear out the text based title\n            headerBarInstance.title(\"\");\n          }\n\n          // there's a custom nav bar item\n          positionItem(navBarItemEle, itemType);\n\n          if (navEle[itemType]) {\n            // make sure the default on this itemType is hidden\n            navEle[itemType].addClass(CSS_HIDE);\n          }\n          lastViewItemEle[itemType] = navBarItemEle;\n\n        } else if (navEle[itemType]) {\n          // there's a default button for this side and no view button\n          navEle[itemType].removeClass(CSS_HIDE);\n        }\n      },\n      removeItem: function(itemType) {\n        if (lastViewItemEle[itemType]) {\n          lastViewItemEle[itemType].scope().$destroy();\n          lastViewItemEle[itemType].remove();\n          lastViewItemEle[itemType] = null;\n        }\n      },\n      containerEle: function() {\n        return containerEle;\n      },\n      headerBarEle: function() {\n        return headerBarEle;\n      },\n      afterLeave: function() {\n        forEach(ITEM_TYPES, function(itemType) {\n          headerBarInstance.removeItem(itemType);\n        });\n        headerBarCtrl.resetBackButton();\n      },\n      controller: function() {\n        return headerBarCtrl;\n      },\n      destroy: function() {\n        forEach(ITEM_TYPES, function(itemType) {\n          headerBarInstance.removeItem(itemType);\n        });\n        containerEle.scope().$destroy();\n        for (var n in navEle) {\n          if (navEle[n]) {\n            navEle[n].removeData();\n            navEle[n] = null;\n          }\n        }\n        leftButtonsEle && leftButtonsEle.removeData();\n        rightButtonsEle && rightButtonsEle.removeData();\n        titleEle.removeData();\n        headerBarEle.removeData();\n        containerEle.remove();\n        containerEle = headerBarEle = titleEle = leftButtonsEle = rightButtonsEle = null;\n      }\n    };\n\n    function positionItem(ele, itemType) {\n      if (!ele) return;\n\n      if (itemType === 'title') {\n        // title element\n        titleEle.append(ele);\n\n      } else if (itemType == 'rightButtons' ||\n                (itemType == SECONDARY_BUTTONS && $ionicConfig.navBar.positionSecondaryButtons() != 'left') ||\n                (itemType == PRIMARY_BUTTONS && $ionicConfig.navBar.positionPrimaryButtons() == 'right')) {\n        // right side\n        if (!rightButtonsEle) {\n          rightButtonsEle = jqLite('<div class=\"buttons buttons-right\">');\n          headerBarEle.append(rightButtonsEle);\n        }\n        if (itemType == SECONDARY_BUTTONS) {\n          rightButtonsEle.append(ele);\n        } else {\n          rightButtonsEle.prepend(ele);\n        }\n\n      } else {\n        // left side\n        if (!leftButtonsEle) {\n          leftButtonsEle = jqLite('<div class=\"buttons buttons-left\">');\n          if (navEle[BACK_BUTTON]) {\n            navEle[BACK_BUTTON].after(leftButtonsEle);\n          } else {\n            headerBarEle.prepend(leftButtonsEle);\n          }\n        }\n        if (itemType == SECONDARY_BUTTONS) {\n          leftButtonsEle.append(ele);\n        } else {\n          leftButtonsEle.prepend(ele);\n        }\n      }\n\n    }\n\n    headerBars.push(headerBarInstance);\n\n    return headerBarInstance;\n  };\n\n\n  self.navElement = function(type, html) {\n    if (isDefined(html)) {\n      navElementHtml[type] = html;\n    }\n    return navElementHtml[type];\n  };\n\n\n  self.update = function(viewData) {\n    var showNavBar = !viewData.hasHeaderBar && viewData.showNavBar;\n    viewData.transition = $ionicConfig.views.transition();\n\n    if (!showNavBar) {\n      viewData.direction = 'none';\n    }\n\n    self.enable(showNavBar);\n    var enteringHeaderBar = self.isInitialized ? getOffScreenHeaderBar() : getOnScreenHeaderBar();\n    var leavingHeaderBar = self.isInitialized ? getOnScreenHeaderBar() : null;\n    var enteringHeaderCtrl = enteringHeaderBar.controller();\n\n    // update if the entering header should show the back button or not\n    enteringHeaderCtrl.enableBack(viewData.enableBack, true);\n    enteringHeaderCtrl.showBack(viewData.showBack, true);\n    enteringHeaderCtrl.updateBackButton();\n\n    // update the entering header bar's title\n    self.title(viewData.title, enteringHeaderBar);\n\n    self.showBar(showNavBar);\n\n    // update the nav bar items, depending if the view has their own or not\n    if (viewData.navBarItems) {\n      forEach(ITEM_TYPES, function(itemType) {\n        enteringHeaderBar.setItem(viewData.navBarItems[itemType], itemType);\n      });\n    }\n\n    // begin transition of entering and leaving header bars\n    self.transition(enteringHeaderBar, leavingHeaderBar, viewData);\n\n    self.isInitialized = true;\n    navSwipeAttr('');\n  };\n\n\n  self.transition = function(enteringHeaderBar, leavingHeaderBar, viewData) {\n    var enteringHeaderBarCtrl = enteringHeaderBar.controller();\n    var transitionFn = $ionicConfig.transitions.navBar[viewData.navBarTransition] || $ionicConfig.transitions.navBar.none;\n    var transitionId = viewData.transitionId;\n\n    enteringHeaderBarCtrl.beforeEnter(viewData);\n\n    var navBarTransition = transitionFn(enteringHeaderBar, leavingHeaderBar, viewData.direction, viewData.shouldAnimate && self.isInitialized);\n\n    ionic.DomUtil.cachedAttr($element, 'nav-bar-transition', viewData.navBarTransition);\n    ionic.DomUtil.cachedAttr($element, 'nav-bar-direction', viewData.direction);\n\n    if (navBarTransition.shouldAnimate && viewData.renderEnd) {\n      navBarAttr(enteringHeaderBar, 'stage');\n    } else {\n      navBarAttr(enteringHeaderBar, 'entering');\n      navBarAttr(leavingHeaderBar, 'leaving');\n    }\n\n    enteringHeaderBarCtrl.resetBackButton(viewData);\n\n    navBarTransition.run(0);\n\n    self.activeTransition = {\n      run: function(step) {\n        navBarTransition.shouldAnimate = false;\n        navBarTransition.direction = 'back';\n        navBarTransition.run(step);\n      },\n      cancel: function(shouldAnimate, speed, cancelData) {\n        navSwipeAttr(speed);\n        navBarAttr(leavingHeaderBar, 'active');\n        navBarAttr(enteringHeaderBar, 'cached');\n        navBarTransition.shouldAnimate = shouldAnimate;\n        navBarTransition.run(0);\n        self.activeTransition = navBarTransition = null;\n\n        var runApply;\n        if (cancelData.showBar !== self.showBar()) {\n          self.showBar(cancelData.showBar);\n        }\n        if (cancelData.showBackButton !== self.showBackButton()) {\n          self.showBackButton(cancelData.showBackButton);\n        }\n        if (runApply) {\n          $scope.$apply();\n        }\n      },\n      complete: function(shouldAnimate, speed) {\n        navSwipeAttr(speed);\n        navBarTransition.shouldAnimate = shouldAnimate;\n        navBarTransition.run(1);\n        queuedTransitionEnd = transitionEnd;\n      }\n    };\n\n    $timeout(enteringHeaderBarCtrl.align, 16);\n\n    queuedTransitionStart = function() {\n      if (latestTransitionId !== transitionId) return;\n\n      navBarAttr(enteringHeaderBar, 'entering');\n      navBarAttr(leavingHeaderBar, 'leaving');\n\n      navBarTransition.run(1);\n\n      queuedTransitionEnd = function() {\n        if (latestTransitionId == transitionId || !navBarTransition.shouldAnimate) {\n          transitionEnd();\n        }\n      };\n\n      queuedTransitionStart = null;\n    };\n\n    function transitionEnd() {\n      for (var x = 0; x < headerBars.length; x++) {\n        headerBars[x].isActive = false;\n      }\n      enteringHeaderBar.isActive = true;\n\n      navBarAttr(enteringHeaderBar, 'active');\n      navBarAttr(leavingHeaderBar, 'cached');\n\n      self.activeTransition = navBarTransition = queuedTransitionEnd = null;\n    }\n\n    queuedTransitionStart();\n  };\n\n\n  self.triggerTransitionStart = function(triggerTransitionId) {\n    latestTransitionId = triggerTransitionId;\n    queuedTransitionStart && queuedTransitionStart();\n  };\n\n\n  self.triggerTransitionEnd = function() {\n    queuedTransitionEnd && queuedTransitionEnd();\n  };\n\n\n  self.showBar = function(shouldShow) {\n    if (arguments.length) {\n      self.visibleBar(shouldShow);\n      $scope.$parent.$hasHeader = !!shouldShow;\n    }\n    return !!$scope.$parent.$hasHeader;\n  };\n\n\n  self.visibleBar = function(shouldShow) {\n    if (shouldShow && !isVisible) {\n      $element.removeClass(CSS_HIDE);\n      self.align();\n    } else if (!shouldShow && isVisible) {\n      $element.addClass(CSS_HIDE);\n    }\n    isVisible = shouldShow;\n  };\n\n\n  self.enable = function(val) {\n    // set primary to show first\n    self.visibleBar(val);\n\n    // set non primary to hide second\n    for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {\n      if ($ionicNavBarDelegate._instances[x] !== self) $ionicNavBarDelegate._instances[x].visibleBar(false);\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavBar#showBackButton\n   * @description Show/hide the nav bar back button when there is a\n   * back view. If the back button is not possible, for example, the\n   * first view in the stack, then this will not force the back button\n   * to show.\n   */\n  self.showBackButton = function(shouldShow) {\n    if (arguments.length) {\n      for (var x = 0; x < headerBars.length; x++) {\n        headerBars[x].controller().showNavBack(!!shouldShow);\n      }\n      $scope.$isBackButtonShown = !!shouldShow;\n    }\n    return $scope.$isBackButtonShown;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavBar#showActiveBackButton\n   * @description Show/hide only the active header bar's back button.\n   */\n  self.showActiveBackButton = function(shouldShow) {\n    var headerBar = getOnScreenHeaderBar();\n    if (headerBar) {\n      if (arguments.length) {\n        return headerBar.controller().showBack(shouldShow);\n      }\n      return headerBar.controller().showBack();\n    }\n  };\n\n\n  self.title = function(newTitleText, headerBar) {\n    if (isDefined(newTitleText)) {\n      newTitleText = newTitleText || '';\n      headerBar = headerBar || getOnScreenHeaderBar();\n      headerBar && headerBar.title(newTitleText);\n      $scope.$title = newTitleText;\n      $ionicHistory.currentTitle(newTitleText);\n    }\n    return $scope.$title;\n  };\n\n\n  self.align = function(val, headerBar) {\n    headerBar = headerBar || getOnScreenHeaderBar();\n    headerBar && headerBar.controller().align(val);\n  };\n\n\n  self.hasTabsTop = function(isTabsTop) {\n    $element[isTabsTop ? 'addClass' : 'removeClass']('nav-bar-tabs-top');\n  };\n\n  self.hasBarSubheader = function(isBarSubheader) {\n    $element[isBarSubheader ? 'addClass' : 'removeClass']('nav-bar-has-subheader');\n  };\n\n  // DEPRECATED, as of v1.0.0-beta14 -------\n  self.changeTitle = function(val) {\n    deprecatedWarning('changeTitle(val)', 'title(val)');\n    self.title(val);\n  };\n  self.setTitle = function(val) {\n    deprecatedWarning('setTitle(val)', 'title(val)');\n    self.title(val);\n  };\n  self.getTitle = function() {\n    deprecatedWarning('getTitle()', 'title()');\n    return self.title();\n  };\n  self.back = function() {\n    deprecatedWarning('back()', '$ionicHistory.goBack()');\n    $ionicHistory.goBack();\n  };\n  self.getPreviousTitle = function() {\n    deprecatedWarning('getPreviousTitle()', '$ionicHistory.backTitle()');\n    $ionicHistory.goBack();\n  };\n  function deprecatedWarning(oldMethod, newMethod) {\n    var warn = console.warn || console.log;\n    warn && warn.call(console, 'navBarController.' + oldMethod + ' is deprecated, please use ' + newMethod + ' instead');\n  }\n  // END DEPRECATED -------\n\n\n  function createNavElement(type) {\n    if (navElementHtml[type]) {\n      return jqLite(navElementHtml[type]);\n    }\n  }\n\n\n  function getOnScreenHeaderBar() {\n    for (var x = 0; x < headerBars.length; x++) {\n      if (headerBars[x].isActive) return headerBars[x];\n    }\n  }\n\n\n  function getOffScreenHeaderBar() {\n    for (var x = 0; x < headerBars.length; x++) {\n      if (!headerBars[x].isActive) return headerBars[x];\n    }\n  }\n\n\n  function navBarAttr(ctrl, val) {\n    ctrl && ionic.DomUtil.cachedAttr(ctrl.containerEle(), 'nav-bar', val);\n  }\n\n  function navSwipeAttr(val) {\n    ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);\n  }\n\n\n  $scope.$on('$destroy', function() {\n    $scope.$parent.$hasHeader = false;\n    $element.parent().removeData(DATA_NAV_BAR_CTRL);\n    for (var x = 0; x < headerBars.length; x++) {\n      headerBars[x].destroy();\n    }\n    $element.remove();\n    $element = headerBars = null;\n    deregisterInstance();\n  });\n\n}]);\n\nIonicModule\n.controller('$ionicNavView', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$compile',\n  '$controller',\n  '$ionicNavBarDelegate',\n  '$ionicNavViewDelegate',\n  '$ionicHistory',\n  '$ionicViewSwitcher',\n  '$ionicConfig',\n  '$ionicScrollDelegate',\nfunction($scope, $element, $attrs, $compile, $controller, $ionicNavBarDelegate, $ionicNavViewDelegate, $ionicHistory, $ionicViewSwitcher, $ionicConfig, $ionicScrollDelegate) {\n\n  var DATA_ELE_IDENTIFIER = '$eleId';\n  var DATA_DESTROY_ELE = '$destroyEle';\n  var DATA_NO_CACHE = '$noCache';\n  var VIEW_STATUS_ACTIVE = 'active';\n  var VIEW_STATUS_CACHED = 'cached';\n\n  var self = this;\n  var direction;\n  var isPrimary = false;\n  var navBarDelegate;\n  var activeEleId;\n  var navViewAttr = $ionicViewSwitcher.navViewAttr;\n  var disableRenderStartViewId, disableAnimation;\n\n  self.scope = $scope;\n  self.element = $element;\n\n  self.init = function() {\n    var navViewName = $attrs.name || '';\n\n    // Find the details of the parent view directive (if any) and use it\n    // to derive our own qualified view name, then hang our own details\n    // off the DOM so child directives can find it.\n    var parent = $element.parent().inheritedData('$uiView');\n    var parentViewName = ((parent && parent.state) ? parent.state.name : '');\n    if (navViewName.indexOf('@') < 0) navViewName = navViewName + '@' + parentViewName;\n\n    var viewData = { name: navViewName, state: null };\n    $element.data('$uiView', viewData);\n\n    var deregisterInstance = $ionicNavViewDelegate._registerInstance(self, $attrs.delegateHandle);\n    $scope.$on('$destroy', function() {\n      deregisterInstance();\n\n      // ensure no scrolls have been left frozen\n      if (self.isSwipeFreeze) {\n        $ionicScrollDelegate.freezeAllScrolls(false);\n      }\n    });\n\n    $scope.$on('$ionicHistory.deselect', self.cacheCleanup);\n    $scope.$on('$ionicTabs.top', onTabsTop);\n    $scope.$on('$ionicSubheader', onBarSubheader);\n\n    $scope.$on('$ionicTabs.beforeLeave', onTabsLeave);\n    $scope.$on('$ionicTabs.afterLeave', onTabsLeave);\n    $scope.$on('$ionicTabs.leave', onTabsLeave);\n\n    ionic.Platform.ready(function() {\n      if (ionic.Platform.isWebView() && $ionicConfig.views.swipeBackEnabled()) {\n        self.initSwipeBack();\n      }\n    });\n\n    return viewData;\n  };\n\n\n  self.register = function(viewLocals) {\n    var leavingView = extend({}, $ionicHistory.currentView());\n\n    // register that a view is coming in and get info on how it should transition\n    var registerData = $ionicHistory.register($scope, viewLocals);\n\n    // update which direction\n    self.update(registerData);\n\n    // begin rendering and transitioning\n    var enteringView = $ionicHistory.getViewById(registerData.viewId) || {};\n\n    var renderStart = (disableRenderStartViewId !== registerData.viewId);\n    self.render(registerData, viewLocals, enteringView, leavingView, renderStart, true);\n  };\n\n\n  self.update = function(registerData) {\n    // always reset that this is the primary navView\n    isPrimary = true;\n\n    // remember what direction this navView should use\n    // this may get updated later by a child navView\n    direction = registerData.direction;\n\n    var parentNavViewCtrl = $element.parent().inheritedData('$ionNavViewController');\n    if (parentNavViewCtrl) {\n      // this navView is nested inside another one\n      // update the parent to use this direction and not\n      // the other it originally was set to\n\n      // inform the parent navView that it is not the primary navView\n      parentNavViewCtrl.isPrimary(false);\n\n      if (direction === 'enter' || direction === 'exit') {\n        // they're entering/exiting a history\n        // find parent navViewController\n        parentNavViewCtrl.direction(direction);\n\n        if (direction === 'enter') {\n          // reset the direction so this navView doesn't animate\n          // because it's parent will\n          direction = 'none';\n        }\n      }\n    }\n  };\n\n\n  self.render = function(registerData, viewLocals, enteringView, leavingView, renderStart, renderEnd) {\n    // register the view and figure out where it lives in the various\n    // histories and nav stacks, along with how views should enter/leave\n    var switcher = $ionicViewSwitcher.create(self, viewLocals, enteringView, leavingView, renderStart, renderEnd);\n\n    // init the rendering of views for this navView directive\n    switcher.init(registerData, function() {\n      // the view is now compiled, in the dom and linked, now lets transition the views.\n      // this uses a callback incase THIS nav-view has a nested nav-view, and after the NESTED\n      // nav-view links, the NESTED nav-view would update which direction THIS nav-view should use\n\n      // kick off the transition of views\n      switcher.transition(self.direction(), registerData.enableBack, !disableAnimation);\n\n      // reset private vars for next time\n      disableRenderStartViewId = disableAnimation = null;\n    });\n\n  };\n\n\n  self.beforeEnter = function(transitionData) {\n    if (isPrimary) {\n      // only update this nav-view's nav-bar if this is the primary nav-view\n      navBarDelegate = transitionData.navBarDelegate;\n      var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n      associatedNavBarCtrl && associatedNavBarCtrl.update(transitionData);\n      navSwipeAttr('');\n    }\n  };\n\n\n  self.activeEleId = function(eleId) {\n    if (arguments.length) {\n      activeEleId = eleId;\n    }\n    return activeEleId;\n  };\n\n\n  self.transitionEnd = function() {\n    var viewElements = $element.children();\n    var x, l, viewElement;\n\n    for (x = 0, l = viewElements.length; x < l; x++) {\n      viewElement = viewElements.eq(x);\n\n      if (viewElement.data(DATA_ELE_IDENTIFIER) === activeEleId) {\n        // this is the active element\n        navViewAttr(viewElement, VIEW_STATUS_ACTIVE);\n\n      } else if (navViewAttr(viewElement) === 'leaving' || navViewAttr(viewElement) === VIEW_STATUS_ACTIVE || navViewAttr(viewElement) === VIEW_STATUS_CACHED) {\n        // this is a leaving element or was the former active element, or is an cached element\n        if (viewElement.data(DATA_DESTROY_ELE) || viewElement.data(DATA_NO_CACHE)) {\n          // this element shouldn't stay cached\n          $ionicViewSwitcher.destroyViewEle(viewElement);\n\n        } else {\n          // keep in the DOM, mark as cached\n          navViewAttr(viewElement, VIEW_STATUS_CACHED);\n\n          // disconnect the leaving scope\n          ionic.Utils.disconnectScope(viewElement.scope());\n        }\n      }\n    }\n\n    navSwipeAttr('');\n\n    // ensure no scrolls have been left frozen\n    if (self.isSwipeFreeze) {\n      $ionicScrollDelegate.freezeAllScrolls(false);\n    }\n  };\n\n\n  function onTabsLeave(ev, data) {\n    var viewElements = $element.children();\n    var viewElement, viewScope;\n\n    for (var x = 0, l = viewElements.length; x < l; x++) {\n      viewElement = viewElements.eq(x);\n      if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {\n        viewScope = viewElement.scope();\n        viewScope && viewScope.$emit(ev.name.replace('Tabs', 'View'), data);\n        break;\n      }\n    }\n  }\n\n\n  self.cacheCleanup = function() {\n    var viewElements = $element.children();\n    for (var x = 0, l = viewElements.length; x < l; x++) {\n      if (viewElements.eq(x).data(DATA_DESTROY_ELE)) {\n        $ionicViewSwitcher.destroyViewEle(viewElements.eq(x));\n      }\n    }\n  };\n\n\n  self.clearCache = function(stateIds) {\n    var viewElements = $element.children();\n    var viewElement, viewScope, x, l, y, eleIdentifier;\n\n    for (x = 0, l = viewElements.length; x < l; x++) {\n      viewElement = viewElements.eq(x);\n\n      if (stateIds) {\n        eleIdentifier = viewElement.data(DATA_ELE_IDENTIFIER);\n\n        for (y = 0; y < stateIds.length; y++) {\n          if (eleIdentifier === stateIds[y]) {\n            $ionicViewSwitcher.destroyViewEle(viewElement);\n          }\n        }\n        continue;\n      }\n\n      if (navViewAttr(viewElement) == VIEW_STATUS_CACHED) {\n        $ionicViewSwitcher.destroyViewEle(viewElement);\n\n      } else if (navViewAttr(viewElement) == VIEW_STATUS_ACTIVE) {\n        viewScope = viewElement.scope();\n        viewScope && viewScope.$broadcast('$ionicView.clearCache');\n      }\n\n    }\n  };\n\n\n  self.getViewElements = function() {\n    return $element.children();\n  };\n\n\n  self.appendViewElement = function(viewEle, viewLocals) {\n    // compile the entering element and get the link function\n    var linkFn = $compile(viewEle);\n\n    $element.append(viewEle);\n\n    var viewScope = $scope.$new();\n\n    if (viewLocals && viewLocals.$$controller) {\n      viewLocals.$scope = viewScope;\n      var controller = $controller(viewLocals.$$controller, viewLocals);\n      $element.children().data('$ngControllerController', controller);\n    }\n\n    linkFn(viewScope);\n\n    return viewScope;\n  };\n\n\n  self.title = function(val) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.title(val);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavView#enableBackButton\n   * @description Enable/disable if the back button can be shown or not. For\n   * example, the very first view in the navigation stack would not have a\n   * back view, so the back button would be disabled.\n   */\n  self.enableBackButton = function(shouldEnable) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.enableBackButton(shouldEnable);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $ionicNavView#showBackButton\n   * @description Show/hide the nav bar active back button. If the back button\n   * is not possible this will not force the back button to show. The\n   * `enableBackButton()` method handles if a back button is even possible or not.\n   */\n  self.showBackButton = function(shouldShow) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    if (associatedNavBarCtrl) {\n      if (arguments.length) {\n        return associatedNavBarCtrl.showActiveBackButton(shouldShow);\n      }\n      return associatedNavBarCtrl.showActiveBackButton();\n    }\n    return true;\n  };\n\n\n  self.showBar = function(val) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    if (associatedNavBarCtrl) {\n      if (arguments.length) {\n        return associatedNavBarCtrl.showBar(val);\n      }\n      return associatedNavBarCtrl.showBar();\n    }\n    return true;\n  };\n\n\n  self.isPrimary = function(val) {\n    if (arguments.length) {\n      isPrimary = val;\n    }\n    return isPrimary;\n  };\n\n\n  self.direction = function(val) {\n    if (arguments.length) {\n      direction = val;\n    }\n    return direction;\n  };\n\n\n  self.initSwipeBack = function() {\n    var swipeBackHitWidth = $ionicConfig.views.swipeBackHitWidth();\n    var viewTransition, associatedNavBarCtrl, backView;\n    var deregDragStart, deregDrag, deregRelease;\n    var windowWidth, startDragX, dragPoints;\n    var cancelData = {};\n\n    function onDragStart(ev) {\n      if (!isPrimary) return;\n\n      startDragX = getDragX(ev);\n      if (startDragX > swipeBackHitWidth) return;\n\n      backView = $ionicHistory.backView();\n\n      var currentView = $ionicHistory.currentView();\n\n      if (!backView || backView.historyId !== currentView.historyId || currentView.canSwipeBack === false) return;\n\n      if (!windowWidth) windowWidth = window.innerWidth;\n\n      self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(true);\n\n      var registerData = {\n        direction: 'back'\n      };\n\n      dragPoints = [];\n\n      cancelData = {\n        showBar: self.showBar(),\n        showBackButton: self.showBackButton()\n      };\n\n      var switcher = $ionicViewSwitcher.create(self, registerData, backView, currentView, true, false);\n      switcher.loadViewElements(registerData);\n      switcher.render(registerData);\n\n      viewTransition = switcher.transition('back', $ionicHistory.enabledBack(backView), true);\n\n      associatedNavBarCtrl = getAssociatedNavBarCtrl();\n\n      deregDrag = ionic.onGesture('drag', onDrag, $element[0]);\n      deregRelease = ionic.onGesture('release', onRelease, $element[0]);\n    }\n\n    function onDrag(ev) {\n      if (isPrimary && viewTransition) {\n        var dragX = getDragX(ev);\n\n        dragPoints.push({\n          t: Date.now(),\n          x: dragX\n        });\n\n        if (dragX >= windowWidth - 15) {\n          onRelease(ev);\n\n        } else {\n          var step = Math.min(Math.max(getSwipeCompletion(dragX), 0), 1);\n          viewTransition.run(step);\n          associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.run(step);\n        }\n\n      }\n    }\n\n    function onRelease(ev) {\n      if (isPrimary && viewTransition && dragPoints && dragPoints.length > 1) {\n\n        var now = Date.now();\n        var releaseX = getDragX(ev);\n        var startDrag = dragPoints[dragPoints.length - 1];\n\n        for (var x = dragPoints.length - 2; x >= 0; x--) {\n          if (now - startDrag.t > 200) {\n            break;\n          }\n          startDrag = dragPoints[x];\n        }\n\n        var isSwipingRight = (releaseX >= dragPoints[dragPoints.length - 2].x);\n        var releaseSwipeCompletion = getSwipeCompletion(releaseX);\n        var velocity = Math.abs(startDrag.x - releaseX) / (now - startDrag.t);\n\n        // private variables because ui-router has no way to pass custom data using $state.go\n        disableRenderStartViewId = backView.viewId;\n        disableAnimation = (releaseSwipeCompletion < 0.03 || releaseSwipeCompletion > 0.97);\n\n        if (isSwipingRight && (releaseSwipeCompletion > 0.5 || velocity > 0.1)) {\n          // complete view transition on release\n          var speed = (velocity > 0.5 || velocity < 0.05 || releaseX > windowWidth - 45) ? 'fast' : 'slow';\n          navSwipeAttr(disableAnimation ? '' : speed);\n          backView.go();\n          associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.complete(!disableAnimation, speed);\n\n        } else {\n          // cancel view transition on release\n          navSwipeAttr(disableAnimation ? '' : 'fast');\n          disableRenderStartViewId = null;\n          viewTransition.cancel(!disableAnimation);\n          associatedNavBarCtrl && associatedNavBarCtrl.activeTransition && associatedNavBarCtrl.activeTransition.cancel(!disableAnimation, 'fast', cancelData);\n          disableAnimation = null;\n        }\n\n      }\n\n      ionic.offGesture(deregDrag, 'drag', onDrag);\n      ionic.offGesture(deregRelease, 'release', onRelease);\n\n      windowWidth = viewTransition = dragPoints = null;\n\n      self.isSwipeFreeze = $ionicScrollDelegate.freezeAllScrolls(false);\n    }\n\n    function getDragX(ev) {\n      return ionic.tap.pointerCoord(ev.gesture.srcEvent).x;\n    }\n\n    function getSwipeCompletion(dragX) {\n      return (dragX - startDragX) / windowWidth;\n    }\n\n    deregDragStart = ionic.onGesture('dragstart', onDragStart, $element[0]);\n\n    $scope.$on('$destroy', function() {\n      ionic.offGesture(deregDragStart, 'dragstart', onDragStart);\n      ionic.offGesture(deregDrag, 'drag', onDrag);\n      ionic.offGesture(deregRelease, 'release', onRelease);\n      self.element = viewTransition = associatedNavBarCtrl = null;\n    });\n  };\n\n\n  function navSwipeAttr(val) {\n    ionic.DomUtil.cachedAttr($element, 'nav-swipe', val);\n  }\n\n\n  function onTabsTop(ev, isTabsTop) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.hasTabsTop(isTabsTop);\n  }\n\n  function onBarSubheader(ev, isBarSubheader) {\n    var associatedNavBarCtrl = getAssociatedNavBarCtrl();\n    associatedNavBarCtrl && associatedNavBarCtrl.hasBarSubheader(isBarSubheader);\n  }\n\n  function getAssociatedNavBarCtrl() {\n    if (navBarDelegate) {\n      for (var x = 0; x < $ionicNavBarDelegate._instances.length; x++) {\n        if ($ionicNavBarDelegate._instances[x].$$delegateHandle == navBarDelegate) {\n          return $ionicNavBarDelegate._instances[x];\n        }\n      }\n    }\n    return $element.inheritedData('$ionNavBarController');\n  }\n\n}]);\n\nIonicModule\n.controller('$ionicRefresher', [\n  '$scope',\n  '$attrs',\n  '$element',\n  '$ionicBind',\n  '$timeout',\n  function($scope, $attrs, $element, $ionicBind, $timeout) {\n    var self = this,\n        isDragging = false,\n        isOverscrolling = false,\n        dragOffset = 0,\n        lastOverscroll = 0,\n        ptrThreshold = 60,\n        activated = false,\n        scrollTime = 500,\n        startY = null,\n        deltaY = null,\n        canOverscroll = true,\n        scrollParent,\n        scrollChild;\n\n    if (!isDefined($attrs.pullingIcon)) {\n      $attrs.$set('pullingIcon', 'ion-android-arrow-down');\n    }\n\n    $scope.showSpinner = !isDefined($attrs.refreshingIcon) && $attrs.spinner != 'none';\n\n    $scope.showIcon = isDefined($attrs.refreshingIcon);\n\n    $ionicBind($scope, $attrs, {\n      pullingIcon: '@',\n      pullingText: '@',\n      refreshingIcon: '@',\n      refreshingText: '@',\n      spinner: '@',\n      disablePullingRotation: '@',\n      $onRefresh: '&onRefresh',\n      $onPulling: '&onPulling'\n    });\n\n    function handleTouchend() {\n      // if this wasn't an overscroll, get out immediately\n      if (!canOverscroll && !isDragging) {\n        return;\n      }\n      // reset Y\n      startY = null;\n      // the user has overscrolled but went back to native scrolling\n      if (!isDragging) {\n        dragOffset = 0;\n        isOverscrolling = false;\n        setScrollLock(false);\n      } else {\n        isDragging = false;\n        dragOffset = 0;\n\n        // the user has scroll far enough to trigger a refresh\n        if (lastOverscroll > ptrThreshold) {\n          start();\n          scrollTo(ptrThreshold, scrollTime);\n\n        // the user has overscrolled but not far enough to trigger a refresh\n        } else {\n          scrollTo(0, scrollTime, deactivate);\n          isOverscrolling = false;\n        }\n      }\n    }\n\n    function handleTouchmove(e) {\n      // if multitouch or regular scroll event, get out immediately\n      if (!canOverscroll || e.touches.length > 1) {\n        return;\n      }\n      //if this is a new drag, keep track of where we start\n      if (startY === null) {\n        startY = parseInt(e.touches[0].screenY, 10);\n      }\n\n      // kitkat fix for touchcancel events http://updates.html5rocks.com/2014/05/A-More-Compatible-Smoother-Touch\n      if (ionic.Platform.isAndroid() && ionic.Platform.version() === 4.4 && scrollParent.scrollTop === 0) {\n        isDragging = true;\n        e.preventDefault();\n      }\n\n      // how far have we dragged so far?\n      deltaY = parseInt(e.touches[0].screenY, 10) - startY;\n\n      // if we've dragged up and back down in to native scroll territory\n      if (deltaY - dragOffset <= 0 || scrollParent.scrollTop !== 0) {\n\n        if (isOverscrolling) {\n          isOverscrolling = false;\n          setScrollLock(false);\n        }\n\n        if (isDragging) {\n          nativescroll(scrollParent, parseInt(deltaY - dragOffset, 10) * -1);\n        }\n\n        // if we're not at overscroll 0 yet, 0 out\n        if (lastOverscroll !== 0) {\n          overscroll(0);\n        }\n        return;\n\n      } else if (deltaY > 0 && scrollParent.scrollTop === 0 && !isOverscrolling) {\n        // starting overscroll, but drag started below scrollTop 0, so we need to offset the position\n        dragOffset = deltaY;\n      }\n\n      // prevent native scroll events while overscrolling\n      e.preventDefault();\n\n      // if not overscrolling yet, initiate overscrolling\n      if (!isOverscrolling) {\n        isOverscrolling = true;\n        setScrollLock(true);\n      }\n\n      isDragging = true;\n      // overscroll according to the user's drag so far\n      overscroll(parseInt((deltaY - dragOffset) / 3, 10));\n\n      // update the icon accordingly\n      if (!activated && lastOverscroll > ptrThreshold) {\n        activated = true;\n        ionic.requestAnimationFrame(activate);\n\n      } else if (activated && lastOverscroll < ptrThreshold) {\n        activated = false;\n        ionic.requestAnimationFrame(deactivate);\n      }\n    }\n\n    function handleScroll(e) {\n      // canOverscrol is used to greatly simplify the drag handler during normal scrolling\n      canOverscroll = (e.target.scrollTop === 0) || isDragging;\n    }\n\n    function overscroll(val) {\n      scrollChild.style[ionic.CSS.TRANSFORM] = 'translateY(' + val + 'px)';\n      lastOverscroll = val;\n    }\n\n    function nativescroll(target, newScrollTop) {\n      // creates a scroll event that bubbles, can be cancelled, and with its view\n      // and detail property initialized to window and 1, respectively\n      target.scrollTop = newScrollTop;\n      var e = document.createEvent(\"UIEvents\");\n      e.initUIEvent(\"scroll\", true, true, window, 1);\n      target.dispatchEvent(e);\n    }\n\n    function setScrollLock(enabled) {\n      // set the scrollbar to be position:fixed in preparation to overscroll\n      // or remove it so the app can be natively scrolled\n      if (enabled) {\n        ionic.requestAnimationFrame(function() {\n          scrollChild.classList.add('overscroll');\n          show();\n        });\n\n      } else {\n        ionic.requestAnimationFrame(function() {\n          scrollChild.classList.remove('overscroll');\n          hide();\n          deactivate();\n        });\n      }\n    }\n\n    $scope.$on('scroll.refreshComplete', function() {\n      // prevent the complete from firing before the scroll has started\n      $timeout(function() {\n\n        ionic.requestAnimationFrame(tail);\n\n        // scroll back to home during tail animation\n        scrollTo(0, scrollTime, deactivate);\n\n        // return to native scrolling after tail animation has time to finish\n        $timeout(function() {\n\n          if (isOverscrolling) {\n            isOverscrolling = false;\n            setScrollLock(false);\n          }\n\n        }, scrollTime);\n\n      }, scrollTime);\n    });\n\n    function scrollTo(Y, duration, callback) {\n      // scroll animation loop w/ easing\n      // credit https://gist.github.com/dezinezync/5487119\n      var start = Date.now(),\n          from = lastOverscroll;\n\n      if (from === Y) {\n        callback();\n        return; /* Prevent scrolling to the Y point if already there */\n      }\n\n      // decelerating to zero velocity\n      function easeOutCubic(t) {\n        return (--t) * t * t + 1;\n      }\n\n      // scroll loop\n      function scroll() {\n        var currentTime = Date.now(),\n          time = Math.min(1, ((currentTime - start) / duration)),\n          // where .5 would be 50% of time on a linear scale easedT gives a\n          // fraction based on the easing method\n          easedT = easeOutCubic(time);\n\n        overscroll(parseInt((easedT * (Y - from)) + from, 10));\n\n        if (time < 1) {\n          ionic.requestAnimationFrame(scroll);\n\n        } else {\n\n          if (Y < 5 && Y > -5) {\n            isOverscrolling = false;\n            setScrollLock(false);\n          }\n\n          callback && callback();\n        }\n      }\n\n      // start scroll loop\n      ionic.requestAnimationFrame(scroll);\n    }\n\n\n    self.init = function() {\n      scrollParent = $element.parent().parent()[0];\n      scrollChild = $element.parent()[0];\n\n      if (!scrollParent || !scrollParent.classList.contains('ionic-scroll') ||\n        !scrollChild || !scrollChild.classList.contains('scroll')) {\n        throw new Error('Refresher must be immediate child of ion-content or ion-scroll');\n      }\n\n      ionic.on('touchmove', handleTouchmove, scrollChild);\n      ionic.on('touchend', handleTouchend, scrollChild);\n      ionic.on('scroll', handleScroll, scrollParent);\n\n      // cleanup when done\n      $scope.$on('$destroy', destroy);\n    };\n\n    function destroy() {\n      ionic.off('touchmove', handleTouchmove, scrollChild);\n      ionic.off('touchend', handleTouchend, scrollChild);\n      ionic.off('scroll', handleScroll, scrollParent);\n      scrollParent = null;\n      scrollChild = null;\n    }\n\n    // DOM manipulation and broadcast methods shared by JS and Native Scrolling\n    // getter used by JS Scrolling\n    self.getRefresherDomMethods = function() {\n      return {\n        activate: activate,\n        deactivate: deactivate,\n        start: start,\n        show: show,\n        hide: hide,\n        tail: tail\n      };\n    };\n\n    function activate() {\n      $element[0].classList.add('active');\n      $scope.$onPulling();\n    }\n\n    function deactivate() {\n      // give tail 150ms to finish\n      $timeout(function() {\n        // deactivateCallback\n        $element.removeClass('active refreshing refreshing-tail');\n        if (activated) activated = false;\n      }, 150);\n    }\n\n    function start() {\n      // startCallback\n      $element[0].classList.add('refreshing');\n      $scope.$onRefresh();\n    }\n\n    function show() {\n      // showCallback\n      $element[0].classList.remove('invisible');\n    }\n\n    function hide() {\n      // showCallback\n      $element[0].classList.add('invisible');\n    }\n\n    function tail() {\n      // tailCallback\n      $element[0].classList.add('refreshing-tail');\n    }\n\n    // for testing\n    self.__handleTouchmove = handleTouchmove;\n    self.__getScrollChild = function() { return scrollChild; };\n    self.__getScrollParent = function() { return scrollParent; };\n  }\n]);\n\n/**\n * @private\n */\nIonicModule\n\n.controller('$ionicScroll', [\n  '$scope',\n  'scrollViewOptions',\n  '$timeout',\n  '$window',\n  '$location',\n  '$document',\n  '$ionicScrollDelegate',\n  '$ionicHistory',\nfunction($scope,\n         scrollViewOptions,\n         $timeout,\n         $window,\n         $location,\n         $document,\n         $ionicScrollDelegate,\n         $ionicHistory) {\n\n  var self = this;\n  // for testing\n  self.__timeout = $timeout;\n\n  self._scrollViewOptions = scrollViewOptions; //for testing\n  self.isNative = function() {\n    return !!scrollViewOptions.nativeScrolling;\n  };\n\n  var element = self.element = scrollViewOptions.el;\n  var $element = self.$element = jqLite(element);\n  var scrollView;\n  if (self.isNative()) {\n    scrollView = self.scrollView = new ionic.views.ScrollNative(scrollViewOptions);\n  } else {\n    scrollView = self.scrollView = new ionic.views.Scroll(scrollViewOptions);\n  }\n\n\n  //Attach self to element as a controller so other directives can require this controller\n  //through `require: '$ionicScroll'\n  //Also attach to parent so that sibling elements can require this\n  ($element.parent().length ? $element.parent() : $element)\n    .data('$$ionicScrollController', self);\n\n  var deregisterInstance = $ionicScrollDelegate._registerInstance(\n    self, scrollViewOptions.delegateHandle, function() {\n      return $ionicHistory.isActiveScope($scope);\n    }\n  );\n\n  if (!isDefined(scrollViewOptions.bouncing)) {\n    ionic.Platform.ready(function() {\n      if (scrollView.options) {\n        scrollView.options.bouncing = true;\n        if (ionic.Platform.isAndroid()) {\n          // No bouncing by default on Android\n          scrollView.options.bouncing = false;\n          // Faster scroll decel\n          scrollView.options.deceleration = 0.95;\n        }\n      }\n    });\n  }\n\n  var resize = angular.bind(scrollView, scrollView.resize);\n  angular.element($window).on('resize', resize);\n\n  var scrollFunc = function(e) {\n    var detail = (e.originalEvent || e).detail || {};\n    $scope.$onScroll && $scope.$onScroll({\n      event: e,\n      scrollTop: detail.scrollTop || 0,\n      scrollLeft: detail.scrollLeft || 0\n    });\n  };\n\n  $element.on('scroll', scrollFunc);\n\n  $scope.$on('$destroy', function() {\n    deregisterInstance();\n    scrollView && scrollView.__cleanup && scrollView.__cleanup();\n    angular.element($window).off('resize', resize);\n    $element.off('scroll', scrollFunc);\n    scrollView = self.scrollView = scrollViewOptions = self._scrollViewOptions = scrollViewOptions.el = self._scrollViewOptions.el = $element = self.$element = element = null;\n  });\n\n  $timeout(function() {\n    scrollView && scrollView.run && scrollView.run();\n  });\n\n  self.getScrollView = function() {\n    return scrollView;\n  };\n\n  self.getScrollPosition = function() {\n    return scrollView.getValues();\n  };\n\n  self.resize = function() {\n    return $timeout(resize, 0, false).then(function() {\n      $element && $element.triggerHandler('scroll-resize');\n    });\n  };\n\n  self.scrollTop = function(shouldAnimate) {\n    self.resize().then(function() {\n      scrollView.scrollTo(0, 0, !!shouldAnimate);\n    });\n  };\n\n  self.scrollBottom = function(shouldAnimate) {\n    self.resize().then(function() {\n      var max = scrollView.getScrollMax();\n      scrollView.scrollTo(max.left, max.top, !!shouldAnimate);\n    });\n  };\n\n  self.scrollTo = function(left, top, shouldAnimate) {\n    self.resize().then(function() {\n      scrollView.scrollTo(left, top, !!shouldAnimate);\n    });\n  };\n\n  self.zoomTo = function(zoom, shouldAnimate, originLeft, originTop) {\n    self.resize().then(function() {\n      scrollView.zoomTo(zoom, !!shouldAnimate, originLeft, originTop);\n    });\n  };\n\n  self.zoomBy = function(zoom, shouldAnimate, originLeft, originTop) {\n    self.resize().then(function() {\n      scrollView.zoomBy(zoom, !!shouldAnimate, originLeft, originTop);\n    });\n  };\n\n  self.scrollBy = function(left, top, shouldAnimate) {\n    self.resize().then(function() {\n      scrollView.scrollBy(left, top, !!shouldAnimate);\n    });\n  };\n\n  self.anchorScroll = function(shouldAnimate) {\n    self.resize().then(function() {\n      var hash = $location.hash();\n      var elm = hash && $document[0].getElementById(hash);\n      if (!(hash && elm)) {\n        scrollView.scrollTo(0, 0, !!shouldAnimate);\n        return;\n      }\n      var curElm = elm;\n      var scrollLeft = 0, scrollTop = 0;\n      do {\n        if (curElm !== null) scrollLeft += curElm.offsetLeft;\n        if (curElm !== null) scrollTop += curElm.offsetTop;\n        curElm = curElm.offsetParent;\n      } while (curElm.attributes != self.element.attributes && curElm.offsetParent);\n      scrollView.scrollTo(scrollLeft, scrollTop, !!shouldAnimate);\n    });\n  };\n\n  self.freezeScroll = scrollView.freeze;\n\n  self.freezeAllScrolls = function(shouldFreeze) {\n    for (var i = 0; i < $ionicScrollDelegate._instances.length; i++) {\n      $ionicScrollDelegate._instances[i].freezeScroll(shouldFreeze);\n    }\n  };\n\n\n  /**\n   * @private\n   */\n  self._setRefresher = function(refresherScope, refresherElement, refresherMethods) {\n    self.refresher = refresherElement;\n    var refresherHeight = self.refresher.clientHeight || 60;\n    scrollView.activatePullToRefresh(\n      refresherHeight,\n      refresherMethods\n    );\n  };\n\n}]);\n\nIonicModule\n.controller('$ionicSideMenus', [\n  '$scope',\n  '$attrs',\n  '$ionicSideMenuDelegate',\n  '$ionicPlatform',\n  '$ionicBody',\n  '$ionicHistory',\n  '$ionicScrollDelegate',\n  'IONIC_BACK_PRIORITY',\nfunction($scope, $attrs, $ionicSideMenuDelegate, $ionicPlatform, $ionicBody, $ionicHistory, $ionicScrollDelegate, IONIC_BACK_PRIORITY) {\n  var self = this;\n  var rightShowing, leftShowing, isDragging;\n  var startX, lastX, offsetX, isAsideExposed;\n  var enableMenuWithBackViews = true;\n\n  self.$scope = $scope;\n\n  self.initialize = function(options) {\n    self.left = options.left;\n    self.right = options.right;\n    self.setContent(options.content);\n    self.dragThresholdX = options.dragThresholdX || 10;\n    $ionicHistory.registerHistory(self.$scope);\n  };\n\n  /**\n   * Set the content view controller if not passed in the constructor options.\n   *\n   * @param {object} content\n   */\n  self.setContent = function(content) {\n    if (content) {\n      self.content = content;\n\n      self.content.onDrag = function(e) {\n        self._handleDrag(e);\n      };\n\n      self.content.endDrag = function(e) {\n        self._endDrag(e);\n      };\n    }\n  };\n\n  self.isOpenLeft = function() {\n    return self.getOpenAmount() > 0;\n  };\n\n  self.isOpenRight = function() {\n    return self.getOpenAmount() < 0;\n  };\n\n  /**\n   * Toggle the left menu to open 100%\n   */\n  self.toggleLeft = function(shouldOpen) {\n    if (isAsideExposed || !self.left.isEnabled) return;\n    var openAmount = self.getOpenAmount();\n    if (arguments.length === 0) {\n      shouldOpen = openAmount <= 0;\n    }\n    self.content.enableAnimation();\n    if (!shouldOpen) {\n      self.openPercentage(0);\n    } else {\n      self.openPercentage(100);\n    }\n  };\n\n  /**\n   * Toggle the right menu to open 100%\n   */\n  self.toggleRight = function(shouldOpen) {\n    if (isAsideExposed || !self.right.isEnabled) return;\n    var openAmount = self.getOpenAmount();\n    if (arguments.length === 0) {\n      shouldOpen = openAmount >= 0;\n    }\n    self.content.enableAnimation();\n    if (!shouldOpen) {\n      self.openPercentage(0);\n    } else {\n      self.openPercentage(-100);\n    }\n  };\n\n  self.toggle = function(side) {\n    if (side == 'right') {\n      self.toggleRight();\n    } else {\n      self.toggleLeft();\n    }\n  };\n\n  /**\n   * Close all menus.\n   */\n  self.close = function() {\n    self.openPercentage(0);\n  };\n\n  /**\n   * @return {float} The amount the side menu is open, either positive or negative for left (positive), or right (negative)\n   */\n  self.getOpenAmount = function() {\n    return self.content && self.content.getTranslateX() || 0;\n  };\n\n  /**\n   * @return {float} The ratio of open amount over menu width. For example, a\n   * menu of width 100 open 50 pixels would be open 50% or a ratio of 0.5. Value is negative\n   * for right menu.\n   */\n  self.getOpenRatio = function() {\n    var amount = self.getOpenAmount();\n    if (amount >= 0) {\n      return amount / self.left.width;\n    }\n    return amount / self.right.width;\n  };\n\n  self.isOpen = function() {\n    return self.getOpenAmount() !== 0;\n  };\n\n  /**\n   * @return {float} The percentage of open amount over menu width. For example, a\n   * menu of width 100 open 50 pixels would be open 50%. Value is negative\n   * for right menu.\n   */\n  self.getOpenPercentage = function() {\n    return self.getOpenRatio() * 100;\n  };\n\n  /**\n   * Open the menu with a given percentage amount.\n   * @param {float} percentage The percentage (positive or negative for left/right) to open the menu.\n   */\n  self.openPercentage = function(percentage) {\n    var p = percentage / 100;\n\n    if (self.left && percentage >= 0) {\n      self.openAmount(self.left.width * p);\n    } else if (self.right && percentage < 0) {\n      self.openAmount(self.right.width * p);\n    }\n\n    // add the CSS class \"menu-open\" if the percentage does not\n    // equal 0, otherwise remove the class from the body element\n    $ionicBody.enableClass((percentage !== 0), 'menu-open');\n\n    freezeAllScrolls(false);\n  };\n\n  function freezeAllScrolls(shouldFreeze) {\n    if (shouldFreeze && !self.isScrollFreeze) {\n      $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);\n\n    } else if (!shouldFreeze && self.isScrollFreeze) {\n      $ionicScrollDelegate.freezeAllScrolls(false);\n    }\n    self.isScrollFreeze = shouldFreeze;\n  }\n\n  /**\n   * Open the menu the given pixel amount.\n   * @param {float} amount the pixel amount to open the menu. Positive value for left menu,\n   * negative value for right menu (only one menu will be visible at a time).\n   */\n  self.openAmount = function(amount) {\n    var maxLeft = self.left && self.left.width || 0;\n    var maxRight = self.right && self.right.width || 0;\n\n    // Check if we can move to that side, depending if the left/right panel is enabled\n    if (!(self.left && self.left.isEnabled) && amount > 0) {\n      self.content.setTranslateX(0);\n      return;\n    }\n\n    if (!(self.right && self.right.isEnabled) && amount < 0) {\n      self.content.setTranslateX(0);\n      return;\n    }\n\n    if (leftShowing && amount > maxLeft) {\n      self.content.setTranslateX(maxLeft);\n      return;\n    }\n\n    if (rightShowing && amount < -maxRight) {\n      self.content.setTranslateX(-maxRight);\n      return;\n    }\n\n    self.content.setTranslateX(amount);\n\n    if (amount >= 0) {\n      leftShowing = true;\n      rightShowing = false;\n\n      if (amount > 0) {\n        // Push the z-index of the right menu down\n        self.right && self.right.pushDown && self.right.pushDown();\n        // Bring the z-index of the left menu up\n        self.left && self.left.bringUp && self.left.bringUp();\n      }\n    } else {\n      rightShowing = true;\n      leftShowing = false;\n\n      // Bring the z-index of the right menu up\n      self.right && self.right.bringUp && self.right.bringUp();\n      // Push the z-index of the left menu down\n      self.left && self.left.pushDown && self.left.pushDown();\n    }\n  };\n\n  /**\n   * Given an event object, find the final resting position of this side\n   * menu. For example, if the user \"throws\" the content to the right and\n   * releases the touch, the left menu should snap open (animated, of course).\n   *\n   * @param {Event} e the gesture event to use for snapping\n   */\n  self.snapToRest = function(e) {\n    // We want to animate at the end of this\n    self.content.enableAnimation();\n    isDragging = false;\n\n    // Check how much the panel is open after the drag, and\n    // what the drag velocity is\n    var ratio = self.getOpenRatio();\n\n    if (ratio === 0) {\n      // Just to be safe\n      self.openPercentage(0);\n      return;\n    }\n\n    var velocityThreshold = 0.3;\n    var velocityX = e.gesture.velocityX;\n    var direction = e.gesture.direction;\n\n    // Going right, less than half, too slow (snap back)\n    if (ratio > 0 && ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {\n      self.openPercentage(0);\n    }\n\n    // Going left, more than half, too slow (snap back)\n    else if (ratio > 0.5 && direction == 'left' && velocityX < velocityThreshold) {\n      self.openPercentage(100);\n    }\n\n    // Going left, less than half, too slow (snap back)\n    else if (ratio < 0 && ratio > -0.5 && direction == 'left' && velocityX < velocityThreshold) {\n      self.openPercentage(0);\n    }\n\n    // Going right, more than half, too slow (snap back)\n    else if (ratio < 0.5 && direction == 'right' && velocityX < velocityThreshold) {\n      self.openPercentage(-100);\n    }\n\n    // Going right, more than half, or quickly (snap open)\n    else if (direction == 'right' && ratio >= 0 && (ratio >= 0.5 || velocityX > velocityThreshold)) {\n      self.openPercentage(100);\n    }\n\n    // Going left, more than half, or quickly (span open)\n    else if (direction == 'left' && ratio <= 0 && (ratio <= -0.5 || velocityX > velocityThreshold)) {\n      self.openPercentage(-100);\n    }\n\n    // Snap back for safety\n    else {\n      self.openPercentage(0);\n    }\n  };\n\n  self.enableMenuWithBackViews = function(val) {\n    if (arguments.length) {\n      enableMenuWithBackViews = !!val;\n    }\n    return enableMenuWithBackViews;\n  };\n\n  self.isAsideExposed = function() {\n    return !!isAsideExposed;\n  };\n\n  self.exposeAside = function(shouldExposeAside) {\n    if (!(self.left && self.left.isEnabled) && !(self.right && self.right.isEnabled)) return;\n    self.close();\n\n    isAsideExposed = shouldExposeAside;\n    if (self.left && self.left.isEnabled) {\n      // set the left marget width if it should be exposed\n      // otherwise set false so there's no left margin\n      self.content.setMarginLeft(isAsideExposed ? self.left.width : 0);\n    } else if (self.right && self.right.isEnabled) {\n      self.content.setMarginRight(isAsideExposed ? self.right.width : 0);\n    }\n\n    self.$scope.$emit('$ionicExposeAside', isAsideExposed);\n  };\n\n  self.activeAsideResizing = function(isResizing) {\n    $ionicBody.enableClass(isResizing, 'aside-resizing');\n  };\n\n  // End a drag with the given event\n  self._endDrag = function(e) {\n    freezeAllScrolls(false);\n\n    if (isAsideExposed) return;\n\n    if (isDragging) {\n      self.snapToRest(e);\n    }\n    startX = null;\n    lastX = null;\n    offsetX = null;\n  };\n\n  // Handle a drag event\n  self._handleDrag = function(e) {\n    if (isAsideExposed || !$scope.dragContent) return;\n\n    // If we don't have start coords, grab and store them\n    if (!startX) {\n      startX = e.gesture.touches[0].pageX;\n      lastX = startX;\n    } else {\n      // Grab the current tap coords\n      lastX = e.gesture.touches[0].pageX;\n    }\n\n    // Calculate difference from the tap points\n    if (!isDragging && Math.abs(lastX - startX) > self.dragThresholdX) {\n      // if the difference is greater than threshold, start dragging using the current\n      // point as the starting point\n      startX = lastX;\n\n      isDragging = true;\n      // Initialize dragging\n      self.content.disableAnimation();\n      offsetX = self.getOpenAmount();\n    }\n\n    if (isDragging) {\n      self.openAmount(offsetX + (lastX - startX));\n      freezeAllScrolls(true);\n    }\n  };\n\n  self.canDragContent = function(canDrag) {\n    if (arguments.length) {\n      $scope.dragContent = !!canDrag;\n    }\n    return $scope.dragContent;\n  };\n\n  self.edgeThreshold = 25;\n  self.edgeThresholdEnabled = false;\n  self.edgeDragThreshold = function(value) {\n    if (arguments.length) {\n      if (isNumber(value) && value > 0) {\n        self.edgeThreshold = value;\n        self.edgeThresholdEnabled = true;\n      } else {\n        self.edgeThresholdEnabled = !!value;\n      }\n    }\n    return self.edgeThresholdEnabled;\n  };\n\n  self.isDraggableTarget = function(e) {\n    //Only restrict edge when sidemenu is closed and restriction is enabled\n    var shouldOnlyAllowEdgeDrag = self.edgeThresholdEnabled && !self.isOpen();\n    var startX = e.gesture.startEvent && e.gesture.startEvent.center &&\n      e.gesture.startEvent.center.pageX;\n\n    var dragIsWithinBounds = !shouldOnlyAllowEdgeDrag ||\n      startX <= self.edgeThreshold ||\n      startX >= self.content.element.offsetWidth - self.edgeThreshold;\n\n    var backView = $ionicHistory.backView();\n    var menuEnabled = enableMenuWithBackViews ? true : !backView;\n    if (!menuEnabled) {\n      var currentView = $ionicHistory.currentView() || {};\n      return backView.historyId !== currentView.historyId;\n    }\n\n    return ($scope.dragContent || self.isOpen()) &&\n      dragIsWithinBounds &&\n      !e.gesture.srcEvent.defaultPrevented &&\n      menuEnabled &&\n      !e.target.tagName.match(/input|textarea|select|object|embed/i) &&\n      !e.target.isContentEditable &&\n      !(e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll') == 'true');\n  };\n\n  $scope.sideMenuContentTranslateX = 0;\n\n  var deregisterBackButtonAction = noop;\n  var closeSideMenu = angular.bind(self, self.close);\n\n  $scope.$watch(function() {\n    return self.getOpenAmount() !== 0;\n  }, function(isOpen) {\n    deregisterBackButtonAction();\n    if (isOpen) {\n      deregisterBackButtonAction = $ionicPlatform.registerBackButtonAction(\n        closeSideMenu,\n        IONIC_BACK_PRIORITY.sideMenu\n      );\n    }\n  });\n\n  var deregisterInstance = $ionicSideMenuDelegate._registerInstance(\n    self, $attrs.delegateHandle, function() {\n      return $ionicHistory.isActiveScope($scope);\n    }\n  );\n\n  $scope.$on('$destroy', function() {\n    deregisterInstance();\n    deregisterBackButtonAction();\n    self.$scope = null;\n    if (self.content) {\n      self.content.element = null;\n      self.content = null;\n    }\n\n    // ensure scrolls are unfrozen\n    freezeAllScrolls(false);\n  });\n\n  self.initialize({\n    left: {\n      width: 275\n    },\n    right: {\n      width: 275\n    }\n  });\n\n}]);\n\n(function(ionic) {\n\n  var TRANSLATE32 = 'translate(32,32)';\n  var STROKE_OPACITY = 'stroke-opacity';\n  var ROUND = 'round';\n  var INDEFINITE = 'indefinite';\n  var DURATION = '750ms';\n  var NONE = 'none';\n  var SHORTCUTS = {\n    a: 'animate',\n    an: 'attributeName',\n    at: 'animateTransform',\n    c: 'circle',\n    da: 'stroke-dasharray',\n    os: 'stroke-dashoffset',\n    f: 'fill',\n    lc: 'stroke-linecap',\n    rc: 'repeatCount',\n    sw: 'stroke-width',\n    t: 'transform',\n    v: 'values'\n  };\n\n  var SPIN_ANIMATION = {\n    v: '0,32,32;360,32,32',\n    an: 'transform',\n    type: 'rotate',\n    rc: INDEFINITE,\n    dur: DURATION\n  };\n\n  function createSvgElement(tagName, data, parent, spinnerName) {\n    var ele = document.createElement(SHORTCUTS[tagName] || tagName);\n    var k, x, y;\n\n    for (k in data) {\n\n      if (angular.isArray(data[k])) {\n        for (x = 0; x < data[k].length; x++) {\n          if (data[k][x].fn) {\n            for (y = 0; y < data[k][x].t; y++) {\n              createSvgElement(k, data[k][x].fn(y, spinnerName), ele, spinnerName);\n            }\n          } else {\n            createSvgElement(k, data[k][x], ele, spinnerName);\n          }\n        }\n\n      } else {\n        setSvgAttribute(ele, k, data[k]);\n      }\n    }\n\n    parent.appendChild(ele);\n  }\n\n  function setSvgAttribute(ele, k, v) {\n    ele.setAttribute(SHORTCUTS[k] || k, v);\n  }\n\n  function animationValues(strValues, i) {\n    var values = strValues.split(';');\n    var back = values.slice(i);\n    var front = values.slice(0, values.length - back.length);\n    values = back.concat(front).reverse();\n    return values.join(';') + ';' + values[0];\n  }\n\n  var IOS_SPINNER = {\n    sw: 4,\n    lc: ROUND,\n    line: [{\n      fn: function(i, spinnerName) {\n        return {\n          y1: spinnerName == 'ios' ? 17 : 12,\n          y2: spinnerName == 'ios' ? 29 : 20,\n          t: TRANSLATE32 + ' rotate(' + (30 * i + (i < 6 ? 180 : -180)) + ')',\n          a: [{\n            fn: function() {\n              return {\n                an: STROKE_OPACITY,\n                dur: DURATION,\n                v: animationValues('0;.1;.15;.25;.35;.45;.55;.65;.7;.85;1', i),\n                rc: INDEFINITE\n              };\n            },\n            t: 1\n          }]\n        };\n      },\n      t: 12\n    }]\n  };\n\n  var spinners = {\n\n    android: {\n      c: [{\n        sw: 6,\n        da: 128,\n        os: 82,\n        r: 26,\n        cx: 32,\n        cy: 32,\n        f: NONE\n      }]\n    },\n\n    ios: IOS_SPINNER,\n\n    'ios-small': IOS_SPINNER,\n\n    bubbles: {\n      sw: 0,\n      c: [{\n        fn: function(i) {\n          return {\n            cx: 24 * Math.cos(2 * Math.PI * i / 8),\n            cy: 24 * Math.sin(2 * Math.PI * i / 8),\n            t: TRANSLATE32,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'r',\n                  dur: DURATION,\n                  v: animationValues('1;2;3;4;5;6;7;8', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 8\n      }]\n    },\n\n    circles: {\n\n      c: [{\n        fn: function(i) {\n          return {\n            r: 5,\n            cx: 24 * Math.cos(2 * Math.PI * i / 8),\n            cy: 24 * Math.sin(2 * Math.PI * i / 8),\n            t: TRANSLATE32,\n            sw: 0,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'fill-opacity',\n                  dur: DURATION,\n                  v: animationValues('.3;.3;.3;.4;.7;.85;.9;1', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 8\n      }]\n    },\n\n    crescent: {\n      c: [{\n        sw: 4,\n        da: 128,\n        os: 82,\n        r: 26,\n        cx: 32,\n        cy: 32,\n        f: NONE,\n        at: [SPIN_ANIMATION]\n      }]\n    },\n\n    dots: {\n\n      c: [{\n        fn: function(i) {\n          return {\n            cx: 16 + (16 * i),\n            cy: 32,\n            sw: 0,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'fill-opacity',\n                  dur: DURATION,\n                  v: animationValues('.5;.6;.8;1;.8;.6;.5', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: 'r',\n                  dur: DURATION,\n                  v: animationValues('4;5;6;5;4;3;3', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 3\n      }]\n    },\n\n    lines: {\n      sw: 7,\n      lc: ROUND,\n      line: [{\n        fn: function(i) {\n          return {\n            x1: 10 + (i * 14),\n            x2: 10 + (i * 14),\n            a: [{\n              fn: function() {\n                return {\n                  an: 'y1',\n                  dur: DURATION,\n                  v: animationValues('16;18;28;18;16', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: 'y2',\n                  dur: DURATION,\n                  v: animationValues('48;44;36;46;48', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: STROKE_OPACITY,\n                  dur: DURATION,\n                  v: animationValues('1;.8;.5;.4;1', i),\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 4\n      }]\n    },\n\n    ripple: {\n      f: NONE,\n      'fill-rule': 'evenodd',\n      sw: 3,\n      circle: [{\n        fn: function(i) {\n          return {\n            cx: 32,\n            cy: 32,\n            a: [{\n              fn: function() {\n                return {\n                  an: 'r',\n                  begin: (i * -1) + 's',\n                  dur: '2s',\n                  v: '0;24',\n                  keyTimes: '0;1',\n                  keySplines: '0.1,0.2,0.3,1',\n                  calcMode: 'spline',\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }, {\n              fn: function() {\n                return {\n                  an: STROKE_OPACITY,\n                  begin: (i * -1) + 's',\n                  dur: '2s',\n                  v: '.2;1;.2;0',\n                  rc: INDEFINITE\n                };\n              },\n              t: 1\n            }]\n          };\n        },\n        t: 2\n      }]\n    },\n\n    spiral: {\n      defs: [{\n        linearGradient: [{\n          id: 'sGD',\n          gradientUnits: 'userSpaceOnUse',\n          x1: 55, y1: 46, x2: 2, y2: 46,\n          stop: [{\n            offset: 0.1,\n            class: 'stop1'\n          }, {\n            offset: 1,\n            class: 'stop2'\n          }]\n        }]\n      }],\n      g: [{\n        sw: 4,\n        lc: ROUND,\n        f: NONE,\n        path: [{\n          stroke: 'url(#sGD)',\n          d: 'M4,32 c0,15,12,28,28,28c8,0,16-4,21-9'\n        }, {\n          d: 'M60,32 C60,16,47.464,4,32,4S4,16,4,32'\n        }],\n        at: [SPIN_ANIMATION]\n      }]\n    }\n\n  };\n\n  var animations = {\n\n    android: function(ele) {\n      var rIndex = 0;\n      var rotateCircle = 0;\n      var startTime;\n      var svgEle = ele.querySelector('g');\n      var circleEle = ele.querySelector('circle');\n\n      function run() {\n        var v = easeInOutCubic(Date.now() - startTime, 650);\n        var scaleX = 1;\n        var translateX = 0;\n        var dasharray = (188 - (58 * v));\n        var dashoffset = (182 - (182 * v));\n\n        if (rIndex % 2) {\n          scaleX = -1;\n          translateX = -64;\n          dasharray = (128 - (-58 * v));\n          dashoffset = (182 * v);\n        }\n\n        var rotateLine = [0, -101, -90, -11, -180, 79, -270, -191][rIndex];\n\n        setSvgAttribute(circleEle, 'da', Math.max(Math.min(dasharray, 188), 128));\n        setSvgAttribute(circleEle, 'os', Math.max(Math.min(dashoffset, 182), 0));\n        setSvgAttribute(circleEle, 't', 'scale(' + scaleX + ',1) translate(' + translateX + ',0) rotate(' + rotateLine + ',32,32)');\n\n        rotateCircle += 4.1;\n        if (rotateCircle > 359) rotateCircle = 0;\n        setSvgAttribute(svgEle, 't', 'rotate(' + rotateCircle + ',32,32)');\n\n        if (v >= 1) {\n          rIndex++;\n          if (rIndex > 7) rIndex = 0;\n          startTime = Date.now();\n        }\n\n        ionic.requestAnimationFrame(run);\n      }\n\n      return function() {\n        startTime = Date.now();\n        run();\n      };\n\n    }\n\n  };\n\n  function easeInOutCubic(t, c) {\n    t /= c / 2;\n    if (t < 1) return 1 / 2 * t * t * t;\n    t -= 2;\n    return 1 / 2 * (t * t * t + 2);\n  }\n\n\n  IonicModule\n  .controller('$ionicSpinner', [\n    '$element',\n    '$attrs',\n  function($element, $attrs) {\n    var spinnerName, spinner;\n\n    this.init = function() {\n      var override = null;\n      if (ionic.Platform.platform() === 'windowsphone') {\n        override = 'android';\n      }\n      spinnerName = $attrs.icon || override || ionic.Platform.platform();\n      spinner = spinners[spinnerName];\n      if (!spinner) {\n        spinnerName = 'ios';\n        spinner = spinners.ios;\n      }\n\n      var container = document.createElement('div');\n      createSvgElement('svg', {\n        viewBox: '0 0 64 64',\n        g: [spinners[spinnerName]]\n      }, container, spinnerName);\n\n      // Specifically for animations to work,\n      // Android 4.3 and below requires the element to be\n      // added as an html string, rather than dynmically\n      // building up the svg element and appending it.\n      $element.html(container.innerHTML);\n\n      this.start();\n\n      return spinnerName;\n    };\n\n    this.start = function() {\n      animations[spinnerName] && animations[spinnerName]($element[0])();\n    };\n\n  }]);\n\n})(ionic);\n\nIonicModule\n.controller('$ionicTab', [\n  '$scope',\n  '$ionicHistory',\n  '$attrs',\n  '$location',\n  '$state',\nfunction($scope, $ionicHistory, $attrs, $location, $state) {\n  this.$scope = $scope;\n\n  //All of these exposed for testing\n  this.hrefMatchesState = function() {\n    return $attrs.href && $location.path().indexOf(\n      $attrs.href.replace(/^#/, '').replace(/\\/$/, '')\n    ) === 0;\n  };\n  this.srefMatchesState = function() {\n    return $attrs.uiSref && $state.includes($attrs.uiSref.split('(')[0]);\n  };\n  this.navNameMatchesState = function() {\n    return this.navViewName && $ionicHistory.isCurrentStateNavView(this.navViewName);\n  };\n\n  this.tabMatchesState = function() {\n    return this.hrefMatchesState() || this.srefMatchesState() || this.navNameMatchesState();\n  };\n}]);\n\nIonicModule\n.controller('$ionicTabs', [\n  '$scope',\n  '$element',\n  '$ionicHistory',\nfunction($scope, $element, $ionicHistory) {\n  var self = this;\n  var selectedTab = null;\n  var previousSelectedTab = null;\n  var selectedTabIndex;\n  self.tabs = [];\n\n  self.selectedIndex = function() {\n    return self.tabs.indexOf(selectedTab);\n  };\n  self.selectedTab = function() {\n    return selectedTab;\n  };\n  self.previousSelectedTab = function() {\n    return previousSelectedTab;\n  };\n\n  self.add = function(tab) {\n    $ionicHistory.registerHistory(tab);\n    self.tabs.push(tab);\n  };\n\n  self.remove = function(tab) {\n    var tabIndex = self.tabs.indexOf(tab);\n    if (tabIndex === -1) {\n      return;\n    }\n    //Use a field like '$tabSelected' so developers won't accidentally set it in controllers etc\n    if (tab.$tabSelected) {\n      self.deselect(tab);\n      //Try to select a new tab if we're removing a tab\n      if (self.tabs.length === 1) {\n        //Do nothing if there are no other tabs to select\n      } else {\n        //Select previous tab if it's the last tab, else select next tab\n        var newTabIndex = tabIndex === self.tabs.length - 1 ? tabIndex - 1 : tabIndex + 1;\n        self.select(self.tabs[newTabIndex]);\n      }\n    }\n    self.tabs.splice(tabIndex, 1);\n  };\n\n  self.deselect = function(tab) {\n    if (tab.$tabSelected) {\n      previousSelectedTab = selectedTab;\n      selectedTab = selectedTabIndex = null;\n      tab.$tabSelected = false;\n      (tab.onDeselect || noop)();\n      tab.$broadcast && tab.$broadcast('$ionicHistory.deselect');\n    }\n  };\n\n  self.select = function(tab, shouldEmitEvent) {\n    var tabIndex;\n    if (isNumber(tab)) {\n      tabIndex = tab;\n      if (tabIndex >= self.tabs.length) return;\n      tab = self.tabs[tabIndex];\n    } else {\n      tabIndex = self.tabs.indexOf(tab);\n    }\n\n    if (arguments.length === 1) {\n      shouldEmitEvent = !!(tab.navViewName || tab.uiSref);\n    }\n\n    if (selectedTab && selectedTab.$historyId == tab.$historyId) {\n      if (shouldEmitEvent) {\n        $ionicHistory.goToHistoryRoot(tab.$historyId);\n      }\n\n    } else if (selectedTabIndex !== tabIndex) {\n      forEach(self.tabs, function(tab) {\n        self.deselect(tab);\n      });\n\n      selectedTab = tab;\n      selectedTabIndex = tabIndex;\n\n      if (self.$scope && self.$scope.$parent) {\n        self.$scope.$parent.$activeHistoryId = tab.$historyId;\n      }\n\n      //Use a funny name like $tabSelected so the developer doesn't overwrite the var in a child scope\n      tab.$tabSelected = true;\n      (tab.onSelect || noop)();\n\n      if (shouldEmitEvent) {\n        $scope.$emit('$ionicHistory.change', {\n          type: 'tab',\n          tabIndex: tabIndex,\n          historyId: tab.$historyId,\n          navViewName: tab.navViewName,\n          hasNavView: !!tab.navViewName,\n          title: tab.title,\n          url: tab.href,\n          uiSref: tab.uiSref\n        });\n      }\n    }\n  };\n\n  self.hasActiveScope = function() {\n    for (var x = 0; x < self.tabs.length; x++) {\n      if ($ionicHistory.isActiveScope(self.tabs[x])) {\n        return true;\n      }\n    }\n    return false;\n  };\n\n}]);\n\nIonicModule\n.controller('$ionicView', [\n  '$scope',\n  '$element',\n  '$attrs',\n  '$compile',\n  '$rootScope',\nfunction($scope, $element, $attrs, $compile, $rootScope) {\n  var self = this;\n  var navElementHtml = {};\n  var navViewCtrl;\n  var navBarDelegateHandle;\n  var hasViewHeaderBar;\n  var deregisters = [];\n  var viewTitle;\n\n  var deregIonNavBarInit = $scope.$on('ionNavBar.init', function(ev, delegateHandle) {\n    // this view has its own ion-nav-bar, remember the navBarDelegateHandle for this view\n    ev.stopPropagation();\n    navBarDelegateHandle = delegateHandle;\n  });\n\n\n  self.init = function() {\n    deregIonNavBarInit();\n\n    var modalCtrl = $element.inheritedData('$ionModalController');\n    navViewCtrl = $element.inheritedData('$ionNavViewController');\n\n    // don't bother if inside a modal or there's no parent navView\n    if (!navViewCtrl || modalCtrl) return;\n\n    // add listeners for when this view changes\n    $scope.$on('$ionicView.beforeEnter', self.beforeEnter);\n    $scope.$on('$ionicView.afterEnter', afterEnter);\n    $scope.$on('$ionicView.beforeLeave', deregisterFns);\n  };\n\n  self.beforeEnter = function(ev, transData) {\n    // this event was emitted, starting at intial ion-view, then bubbles up\n    // only the first ion-view should do something with it, parent ion-views should ignore\n    if (transData && !transData.viewNotified) {\n      transData.viewNotified = true;\n\n      if (!$rootScope.$$phase) $scope.$digest();\n      viewTitle = isDefined($attrs.viewTitle) ? $attrs.viewTitle : $attrs.title;\n\n      var navBarItems = {};\n      for (var n in navElementHtml) {\n        navBarItems[n] = generateNavBarItem(navElementHtml[n]);\n      }\n\n      navViewCtrl.beforeEnter(extend(transData, {\n        title: viewTitle,\n        showBack: !attrTrue('hideBackButton'),\n        navBarItems: navBarItems,\n        navBarDelegate: navBarDelegateHandle || null,\n        showNavBar: !attrTrue('hideNavBar'),\n        hasHeaderBar: !!hasViewHeaderBar\n      }));\n\n      // make sure any existing observers are cleaned up\n      deregisterFns();\n    }\n  };\n\n\n  function afterEnter() {\n    // only listen for title updates after it has entered\n    // but also deregister the observe before it leaves\n    var viewTitleAttr = isDefined($attrs.viewTitle) && 'viewTitle' || isDefined($attrs.title) && 'title';\n    if (viewTitleAttr) {\n      titleUpdate($attrs[viewTitleAttr]);\n      deregisters.push($attrs.$observe(viewTitleAttr, titleUpdate));\n    }\n\n    if (isDefined($attrs.hideBackButton)) {\n      deregisters.push($scope.$watch($attrs.hideBackButton, function(val) {\n        navViewCtrl.showBackButton(!val);\n      }));\n    }\n\n    if (isDefined($attrs.hideNavBar)) {\n      deregisters.push($scope.$watch($attrs.hideNavBar, function(val) {\n        navViewCtrl.showBar(!val);\n      }));\n    }\n  }\n\n\n  function titleUpdate(newTitle) {\n    if (isDefined(newTitle) && newTitle !== viewTitle) {\n      viewTitle = newTitle;\n      navViewCtrl.title(viewTitle);\n    }\n  }\n\n\n  function deregisterFns() {\n    // remove all existing $attrs.$observe's\n    for (var x = 0; x < deregisters.length; x++) {\n      deregisters[x]();\n    }\n    deregisters = [];\n  }\n\n\n  function generateNavBarItem(html) {\n    if (html) {\n      // every time a view enters we need to recreate its view buttons if they exist\n      return $compile(html)($scope.$new());\n    }\n  }\n\n\n  function attrTrue(key) {\n    return !!$scope.$eval($attrs[key]);\n  }\n\n\n  self.navElement = function(type, html) {\n    navElementHtml[type] = html;\n  };\n\n}]);\n\n/*\n * We don't document the ionActionSheet directive, we instead document\n * the $ionicActionSheet service\n */\nIonicModule\n.directive('ionActionSheet', ['$document', function($document) {\n  return {\n    restrict: 'E',\n    scope: true,\n    replace: true,\n    link: function($scope, $element) {\n\n      var keyUp = function(e) {\n        if (e.which == 27) {\n          $scope.cancel();\n          $scope.$apply();\n        }\n      };\n\n      var backdropClick = function(e) {\n        if (e.target == $element[0]) {\n          $scope.cancel();\n          $scope.$apply();\n        }\n      };\n      $scope.$on('$destroy', function() {\n        $element.remove();\n        $document.unbind('keyup', keyUp);\n      });\n\n      $document.bind('keyup', keyUp);\n      $element.bind('click', backdropClick);\n    },\n    template: '<div class=\"action-sheet-backdrop\">' +\n                '<div class=\"action-sheet-wrapper\">' +\n                  '<div class=\"action-sheet\" ng-class=\"{\\'action-sheet-has-icons\\': $actionSheetHasIcon}\">' +\n                    '<div class=\"action-sheet-group action-sheet-options\">' +\n                      '<div class=\"action-sheet-title\" ng-if=\"titleText\" ng-bind-html=\"titleText\"></div>' +\n                      '<button class=\"button action-sheet-option\" ng-click=\"buttonClicked($index)\" ng-repeat=\"b in buttons\" ng-bind-html=\"b.text\"></button>' +\n                      '<button class=\"button destructive action-sheet-destructive\" ng-if=\"destructiveText\" ng-click=\"destructiveButtonClicked()\" ng-bind-html=\"destructiveText\"></button>' +\n                    '</div>' +\n                    '<div class=\"action-sheet-group action-sheet-cancel\" ng-if=\"cancelText\">' +\n                      '<button class=\"button\" ng-click=\"cancel()\" ng-bind-html=\"cancelText\"></button>' +\n                    '</div>' +\n                  '</div>' +\n                '</div>' +\n              '</div>'\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @name ionCheckbox\n * @module ionic\n * @restrict E\n * @codepen hqcju\n * @description\n * The checkbox is no different than the HTML checkbox input, except it's styled differently.\n *\n * The checkbox behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]).\n *\n * @usage\n * ```html\n * <ion-checkbox ng-model=\"isChecked\">Checkbox Label</ion-checkbox>\n * ```\n */\n\nIonicModule\n.directive('ionCheckbox', ['$ionicConfig', function($ionicConfig) {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '?ngModel',\n    transclude: true,\n    template:\n      '<label class=\"item item-checkbox\">' +\n        '<div class=\"checkbox checkbox-input-hidden disable-pointer-events\">' +\n          '<input type=\"checkbox\">' +\n          '<i class=\"checkbox-icon\"></i>' +\n        '</div>' +\n        '<div class=\"item-content disable-pointer-events\" ng-transclude></div>' +\n      '</label>',\n    compile: function(element, attr) {\n      var input = element.find('input');\n      forEach({\n        'name': attr.name,\n        'ng-value': attr.ngValue,\n        'ng-model': attr.ngModel,\n        'ng-checked': attr.ngChecked,\n        'ng-disabled': attr.ngDisabled,\n        'ng-true-value': attr.ngTrueValue,\n        'ng-false-value': attr.ngFalseValue,\n        'ng-change': attr.ngChange,\n        'ng-required': attr.ngRequired,\n        'required': attr.required\n      }, function(value, name) {\n        if (isDefined(value)) {\n          input.attr(name, value);\n        }\n      });\n      var checkboxWrapper = element[0].querySelector('.checkbox');\n      checkboxWrapper.classList.add('checkbox-' + $ionicConfig.form.checkbox());\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @restrict A\n * @name collectionRepeat\n * @module ionic\n * @codepen 7ec1ec58f2489ab8f359fa1a0fe89c15\n * @description\n * `collection-repeat` allows an app to show huge lists of items much more performantly than\n * `ng-repeat`.\n *\n * It renders into the DOM only as many items as are currently visible.\n *\n * This means that on a phone screen that can fit eight items, only the eight items matching\n * the current scroll position will be rendered.\n *\n * **The Basics**:\n *\n * - The data given to collection-repeat must be an array.\n * - If the `item-height` and `item-width` attributes are not supplied, it will be assumed that\n *   every item in the list has the same dimensions as the first item.\n * - Don't use angular one-time binding (`::`) with collection-repeat. The scope of each item is\n *   assigned new data and re-digested as you scroll. Bindings need to update, and one-time bindings\n *   won't.\n *\n * **Performance Tips**:\n *\n * - The iOS webview has a performance bottleneck when switching out `<img src>` attributes.\n *   To increase performance of images on iOS, cache your images in advance and,\n *   if possible, lower the number of unique images. We're working on [a solution](https://github.com/driftyco/ionic/issues/3194).\n *\n * @usage\n * #### Basic Item List ([codepen](http://codepen.io/ionic/pen/0c2c35a34a8b18ad4d793fef0b081693))\n * ```html\n * <ion-content>\n *   <ion-item collection-repeat=\"item in items\">\n *     {% raw %}{{item}}{% endraw %}\n *   </ion-item>\n * </ion-content>\n * ```\n *\n * #### Grid of Images ([codepen](http://codepen.io/ionic/pen/5515d4efd9d66f780e96787387f41664))\n * ```html\n * <ion-content>\n *   <img collection-repeat=\"photo in photos\"\n *     item-width=\"33%\"\n *     item-height=\"200px\"\n *     ng-src=\"{% raw %}{{photo.url}}{% endraw %}\">\n * </ion-content>\n * ```\n *\n * #### Horizontal Scroller, Dynamic Item Width ([codepen](http://codepen.io/ionic/pen/67cc56b349124a349acb57a0740e030e))\n * ```html\n * <ion-content>\n *   <h2>Available Kittens:</h2>\n *   <ion-scroll direction=\"x\" class=\"available-scroller\">\n *     <div class=\"photo\" collection-repeat=\"photo in main.photos\"\n *        item-height=\"250\" item-width=\"photo.width + 30\">\n *        <img ng-src=\"{{photo.src}}\">\n *     </div>\n *   </ion-scroll>\n * </ion-content>\n * ```\n *\n * @param {expression} collection-repeat The expression indicating how to enumerate a collection,\n *   of the format  `variable in expression` – where variable is the user defined loop variable\n *   and `expression` is a scope expression giving the collection to enumerate.\n *   For example: `album in artist.albums` or `album in artist.albums | orderBy:'name'`.\n * @param {expression=} item-width The width of the repeated element. The expression must return\n *   a number (pixels) or a percentage. Defaults to the width of the first item in the list.\n *   (previously named collection-item-width)\n * @param {expression=} item-height The height of the repeated element. The expression must return\n *   a number (pixels) or a percentage. Defaults to the height of the first item in the list.\n *   (previously named collection-item-height)\n * @param {number=} item-render-buffer The number of items to load before and after the visible\n *   items in the list. Default 3. Tip: set this higher if you have lots of images to preload, but\n *   don't set it too high or you'll see performance loss.\n * @param {boolean=} force-refresh-images Force images to refresh as you scroll. This fixes a problem\n *   where, when an element is interchanged as scrolling, its image will still have the old src\n *   while the new src loads. Setting this to true comes with a small performance loss.\n */\n\nIonicModule\n.directive('collectionRepeat', CollectionRepeatDirective)\n.factory('$ionicCollectionManager', RepeatManagerFactory);\n\nvar ONE_PX_TRANSPARENT_IMG_SRC = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';\nvar WIDTH_HEIGHT_REGEX = /height:.*?px;\\s*width:.*?px/;\nvar DEFAULT_RENDER_BUFFER = 3;\n\nCollectionRepeatDirective.$inject = ['$ionicCollectionManager', '$parse', '$window', '$$rAF', '$rootScope', '$timeout'];\nfunction CollectionRepeatDirective($ionicCollectionManager, $parse, $window, $$rAF, $rootScope, $timeout) {\n  return {\n    restrict: 'A',\n    priority: 1000,\n    transclude: 'element',\n    $$tlb: true,\n    require: '^^$ionicScroll',\n    link: postLink\n  };\n\n  function postLink(scope, element, attr, scrollCtrl, transclude) {\n    var scrollView = scrollCtrl.scrollView;\n    var node = element[0];\n    var containerNode = angular.element('<div class=\"collection-repeat-container\">')[0];\n    node.parentNode.replaceChild(containerNode, node);\n\n    if (scrollView.options.scrollingX && scrollView.options.scrollingY) {\n      throw new Error(\"collection-repeat expected a parent x or y scrollView, not \" +\n                      \"an xy scrollView.\");\n    }\n\n    var repeatExpr = attr.collectionRepeat;\n    var match = repeatExpr.match(/^\\s*([\\s\\S]+?)\\s+in\\s+([\\s\\S]+?)(?:\\s+track\\s+by\\s+([\\s\\S]+?))?\\s*$/);\n    if (!match) {\n      throw new Error(\"collection-repeat expected expression in form of '_item_ in \" +\n                      \"_collection_[ track by _id_]' but got '\" + attr.collectionRepeat + \"'.\");\n    }\n    var keyExpr = match[1];\n    var listExpr = match[2];\n    var listGetter = $parse(listExpr);\n    var heightData = {};\n    var widthData = {};\n    var computedStyleDimensions = {};\n    var data = [];\n    var repeatManager;\n\n    // attr.collectionBufferSize is deprecated\n    var renderBufferExpr = attr.itemRenderBuffer || attr.collectionBufferSize;\n    var renderBuffer = angular.isDefined(renderBufferExpr) ?\n      parseInt(renderBufferExpr) :\n      DEFAULT_RENDER_BUFFER;\n\n    // attr.collectionItemHeight is deprecated\n    var heightExpr = attr.itemHeight || attr.collectionItemHeight;\n    // attr.collectionItemWidth is deprecated\n    var widthExpr = attr.itemWidth || attr.collectionItemWidth;\n\n    var afterItemsContainer = initAfterItemsContainer();\n\n    var changeValidator = makeChangeValidator();\n    initDimensions();\n\n    // Dimensions are refreshed on resize or data change.\n    scrollCtrl.$element.on('scroll-resize', refreshDimensions);\n\n    angular.element($window).on('resize', onResize);\n    var unlistenToExposeAside = $rootScope.$on('$ionicExposeAside', ionic.animationFrameThrottle(function() {\n      scrollCtrl.scrollView.resize();\n      onResize();\n    }));\n    $timeout(refreshDimensions, 0, false);\n\n    function onResize() {\n      if (changeValidator.resizeRequiresRefresh(scrollView.__clientWidth, scrollView.__clientHeight)) {\n        refreshDimensions();\n      }\n    }\n\n    scope.$watchCollection(listGetter, function(newValue) {\n      data = newValue || (newValue = []);\n      if (!angular.isArray(newValue)) {\n        throw new Error(\"collection-repeat expected an array for '\" + listExpr + \"', \" +\n          \"but got a \" + typeof value);\n      }\n      // Wait for this digest to end before refreshing everything.\n      scope.$$postDigest(function() {\n        getRepeatManager().setData(data);\n        if (changeValidator.dataChangeRequiresRefresh(data)) refreshDimensions();\n      });\n    });\n\n    scope.$on('$destroy', function() {\n      angular.element($window).off('resize', onResize);\n      unlistenToExposeAside();\n      scrollCtrl.$element && scrollCtrl.$element.off('scroll-resize', refreshDimensions);\n\n      computedStyleNode && computedStyleNode.parentNode &&\n        computedStyleNode.parentNode.removeChild(computedStyleNode);\n      computedStyleScope && computedStyleScope.$destroy();\n      computedStyleScope = computedStyleNode = null;\n\n      repeatManager && repeatManager.destroy();\n      repeatManager = null;\n    });\n\n    function makeChangeValidator() {\n      var self;\n      return (self = {\n        dataLength: 0,\n        width: 0,\n        height: 0,\n        // A resize triggers a refresh only if we have data, the scrollView has size,\n        // and the size has changed.\n        resizeRequiresRefresh: function(newWidth, newHeight) {\n          var requiresRefresh = self.dataLength && newWidth && newHeight &&\n            (newWidth !== self.width || newHeight !== self.height);\n\n          self.width = newWidth;\n          self.height = newHeight;\n\n          return !!requiresRefresh;\n        },\n        // A change in data only triggers a refresh if the data has length, or if the data's\n        // length is less than before.\n        dataChangeRequiresRefresh: function(newData) {\n          var requiresRefresh = newData.length > 0 || newData.length < self.dataLength;\n\n          self.dataLength = newData.length;\n\n          return !!requiresRefresh;\n        }\n      });\n    }\n\n    function getRepeatManager() {\n      return repeatManager || (repeatManager = new $ionicCollectionManager({\n        afterItemsNode: afterItemsContainer[0],\n        containerNode: containerNode,\n        heightData: heightData,\n        widthData: widthData,\n        forceRefreshImages: !!(isDefined(attr.forceRefreshImages) && attr.forceRefreshImages !== 'false'),\n        keyExpression: keyExpr,\n        renderBuffer: renderBuffer,\n        scope: scope,\n        scrollView: scrollCtrl.scrollView,\n        transclude: transclude\n      }));\n    }\n\n    function initAfterItemsContainer() {\n      var container = angular.element(\n        scrollView.__content.querySelector('.collection-repeat-after-container')\n      );\n      // Put everything in the view after the repeater into a container.\n      if (!container.length) {\n        var elementIsAfterRepeater = false;\n        var afterNodes = [].filter.call(scrollView.__content.childNodes, function(node) {\n          if (ionic.DomUtil.contains(node, containerNode)) {\n            elementIsAfterRepeater = true;\n            return false;\n          }\n          return elementIsAfterRepeater;\n        });\n        container = angular.element('<span class=\"collection-repeat-after-container\">');\n        if (scrollView.options.scrollingX) {\n          container.addClass('horizontal');\n        }\n        container.append(afterNodes);\n        scrollView.__content.appendChild(container[0]);\n      }\n      return container;\n    }\n\n    function initDimensions() {\n      //Height and width have four 'modes':\n      //1) Computed Mode\n      //  - Nothing is supplied, so we getComputedStyle() on one element in the list and use\n      //    that width and height value for the width and height of every item. This is re-computed\n      //    every resize.\n      //2) Constant Mode, Static Integer\n      //  - The user provides a constant number for width or height, in pixels. We parse it,\n      //    store it on the `value` field, and it never changes\n      //3) Constant Mode, Percent\n      //  - The user provides a percent string for width or height. The getter for percent is\n      //    stored on the `getValue()` field, and is re-evaluated once every resize. The result\n      //    is stored on the `value` field.\n      //4) Dynamic Mode\n      //  - The user provides a dynamic expression for the width or height.  This is re-evaluated\n      //    for every item, stored on the `.getValue()` field.\n      if (heightExpr) {\n        parseDimensionAttr(heightExpr, heightData);\n      } else {\n        heightData.computed = true;\n      }\n      if (widthExpr) {\n        parseDimensionAttr(widthExpr, widthData);\n      } else {\n        widthData.computed = true;\n      }\n    }\n\n    function refreshDimensions() {\n      var hasData = data.length > 0;\n\n      if (hasData && (heightData.computed || widthData.computed)) {\n        computeStyleDimensions();\n      }\n\n      if (hasData && heightData.computed) {\n        heightData.value = computedStyleDimensions.height;\n        if (!heightData.value) {\n          throw new Error('collection-repeat tried to compute the height of repeated elements \"' +\n            repeatExpr + '\", but was unable to. Please provide the \"item-height\" attribute. ' +\n            'http://ionicframework.com/docs/api/directive/collectionRepeat/');\n        }\n      } else if (!heightData.dynamic && heightData.getValue) {\n        // If it's a constant with a getter (eg percent), we just refresh .value after resize\n        heightData.value = heightData.getValue();\n      }\n\n      if (hasData && widthData.computed) {\n        widthData.value = computedStyleDimensions.width;\n        if (!widthData.value) {\n          throw new Error('collection-repeat tried to compute the width of repeated elements \"' +\n            repeatExpr + '\", but was unable to. Please provide the \"item-width\" attribute. ' +\n            'http://ionicframework.com/docs/api/directive/collectionRepeat/');\n        }\n      } else if (!widthData.dynamic && widthData.getValue) {\n        // If it's a constant with a getter (eg percent), we just refresh .value after resize\n        widthData.value = widthData.getValue();\n      }\n      // Dynamic dimensions aren't updated on resize. Since they're already dynamic anyway,\n      // .getValue() will be used.\n\n      getRepeatManager().refreshLayout();\n    }\n\n    function parseDimensionAttr(attrValue, dimensionData) {\n      if (!attrValue) return;\n\n      var parsedValue;\n      // Try to just parse the plain attr value\n      try {\n        parsedValue = $parse(attrValue);\n      } catch (e) {\n        // If the parse fails and the value has `px` or `%` in it, surround the attr in\n        // quotes, to attempt to let the user provide a simple `attr=\"100%\"` or `attr=\"100px\"`\n        if (attrValue.trim().match(/\\d+(px|%)$/)) {\n          attrValue = '\"' + attrValue + '\"';\n        }\n        parsedValue = $parse(attrValue);\n      }\n\n      var constantAttrValue = attrValue.replace(/(\\'|\\\"|px|%)/g, '').trim();\n      var isConstant = constantAttrValue.length && !/([a-zA-Z]|\\$|:|\\?)/.test(constantAttrValue);\n      dimensionData.attrValue = attrValue;\n\n      // If it's a constant, it's either a percent or just a constant pixel number.\n      if (isConstant) {\n        var intValue = parseInt(parsedValue());\n\n        // For percents, store the percent getter on .getValue()\n        if (attrValue.indexOf('%') > -1) {\n          var decimalValue = intValue / 100;\n          dimensionData.getValue = dimensionData === heightData ?\n            function() { return Math.floor(decimalValue * scrollView.__clientHeight); } :\n            function() { return Math.floor(decimalValue * scrollView.__clientWidth); };\n        } else {\n          // For static constants, just store the static constant.\n          dimensionData.value = intValue;\n        }\n\n      } else {\n        dimensionData.dynamic = true;\n        dimensionData.getValue = dimensionData === heightData ?\n          function heightGetter(scope, locals) {\n            var result = parsedValue(scope, locals);\n            if (result.charAt && result.charAt(result.length - 1) === '%') {\n              return Math.floor(parseInt(result) / 100 * scrollView.__clientHeight);\n            }\n            return parseInt(result);\n          } :\n          function widthGetter(scope, locals) {\n            var result = parsedValue(scope, locals);\n            if (result.charAt && result.charAt(result.length - 1) === '%') {\n              return Math.floor(parseInt(result) / 100 * scrollView.__clientWidth);\n            }\n            return parseInt(result);\n          };\n      }\n    }\n\n    var computedStyleNode;\n    var computedStyleScope;\n    function computeStyleDimensions() {\n      if (!computedStyleNode) {\n        transclude(computedStyleScope = scope.$new(), function(clone) {\n          clone[0].removeAttribute('collection-repeat'); // remove absolute position styling\n          computedStyleNode = clone[0];\n        });\n      }\n\n      computedStyleScope[keyExpr] = (listGetter(scope) || [])[0];\n      if (!$rootScope.$$phase) computedStyleScope.$digest();\n      containerNode.appendChild(computedStyleNode);\n\n      var style = $window.getComputedStyle(computedStyleNode);\n      computedStyleDimensions.width = parseInt(style.width);\n      computedStyleDimensions.height = parseInt(style.height);\n\n      containerNode.removeChild(computedStyleNode);\n    }\n\n  }\n\n}\n\nRepeatManagerFactory.$inject = ['$rootScope', '$window', '$$rAF'];\nfunction RepeatManagerFactory($rootScope, $window, $$rAF) {\n  var EMPTY_DIMENSION = { primaryPos: 0, secondaryPos: 0, primarySize: 0, secondarySize: 0, rowPrimarySize: 0 };\n\n  return function RepeatController(options) {\n    var afterItemsNode = options.afterItemsNode;\n    var containerNode = options.containerNode;\n    var forceRefreshImages = options.forceRefreshImages;\n    var heightData = options.heightData;\n    var widthData = options.widthData;\n    var keyExpression = options.keyExpression;\n    var renderBuffer = options.renderBuffer;\n    var scope = options.scope;\n    var scrollView = options.scrollView;\n    var transclude = options.transclude;\n\n    var data = [];\n\n    var getterLocals = {};\n    var heightFn = heightData.getValue || function() { return heightData.value; };\n    var heightGetter = function(index, value) {\n      getterLocals[keyExpression] = value;\n      getterLocals.$index = index;\n      return heightFn(scope, getterLocals);\n    };\n\n    var widthFn = widthData.getValue || function() { return widthData.value; };\n    var widthGetter = function(index, value) {\n      getterLocals[keyExpression] = value;\n      getterLocals.$index = index;\n      return widthFn(scope, getterLocals);\n    };\n\n    var isVertical = !!scrollView.options.scrollingY;\n\n    // We say it's a grid view if we're either dynamic or not 100% width\n    var isGridView = isVertical ?\n      (widthData.dynamic || widthData.value !== scrollView.__clientWidth) :\n      (heightData.dynamic || heightData.value !== scrollView.__clientHeight);\n\n    var isStaticView = !heightData.dynamic && !widthData.dynamic;\n\n    var PRIMARY = 'PRIMARY';\n    var SECONDARY = 'SECONDARY';\n    var TRANSLATE_TEMPLATE_STR = isVertical ?\n      'translate3d(SECONDARYpx,PRIMARYpx,0)' :\n      'translate3d(PRIMARYpx,SECONDARYpx,0)';\n    var WIDTH_HEIGHT_TEMPLATE_STR = isVertical ?\n      'height: PRIMARYpx; width: SECONDARYpx;' :\n      'height: SECONDARYpx; width: PRIMARYpx;';\n\n    var estimatedHeight;\n    var estimatedWidth;\n\n    var repeaterBeforeSize = 0;\n    var repeaterAfterSize = 0;\n\n    var renderStartIndex = -1;\n    var renderEndIndex = -1;\n    var renderAfterBoundary = -1;\n    var renderBeforeBoundary = -1;\n\n    var itemsPool = [];\n    var itemsLeaving = [];\n    var itemsEntering = [];\n    var itemsShownMap = {};\n    var nextItemId = 0;\n\n    var scrollViewSetDimensions = isVertical ?\n      function() { scrollView.setDimensions(null, null, null, view.getContentSize(), true); } :\n      function() { scrollView.setDimensions(null, null, view.getContentSize(), null, true); };\n\n    // view is a mix of list/grid methods + static/dynamic methods.\n    // See bottom for implementations. Available methods:\n    //\n    // getEstimatedPrimaryPos(i), getEstimatedSecondaryPos(i), getEstimatedIndex(scrollTop),\n    // calculateDimensions(toIndex), getDimensions(index),\n    // updateRenderRange(scrollTop, scrollValueEnd), onRefreshLayout(), onRefreshData()\n    var view = isVertical ? new VerticalViewType() : new HorizontalViewType();\n    (isGridView ? GridViewType : ListViewType).call(view);\n    (isStaticView ? StaticViewType : DynamicViewType).call(view);\n\n    var contentSizeStr = isVertical ? 'getContentHeight' : 'getContentWidth';\n    var originalGetContentSize = scrollView.options[contentSizeStr];\n    scrollView.options[contentSizeStr] = angular.bind(view, view.getContentSize);\n\n    scrollView.__$callback = scrollView.__callback;\n    scrollView.__callback = function(transformLeft, transformTop, zoom, wasResize) {\n      var scrollValue = view.getScrollValue();\n      if (renderStartIndex === -1 ||\n          scrollValue + view.scrollPrimarySize > renderAfterBoundary ||\n          scrollValue < renderBeforeBoundary) {\n        render();\n      }\n      scrollView.__$callback(transformLeft, transformTop, zoom, wasResize);\n    };\n\n    var isLayoutReady = false;\n    var isDataReady = false;\n    this.refreshLayout = function() {\n      if (data.length) {\n        estimatedHeight = heightGetter(0, data[0]);\n        estimatedWidth = widthGetter(0, data[0]);\n      } else {\n        // If we don't have any data in our array, just guess.\n        estimatedHeight = 100;\n        estimatedWidth = 100;\n      }\n\n      // Get the size of every element AFTER the repeater. We have to get the margin before and\n      // after the first/last element to fix a browser bug with getComputedStyle() not counting\n      // the first/last child's margins into height.\n      var style = getComputedStyle(afterItemsNode) || {};\n      var firstStyle = afterItemsNode.firstElementChild && getComputedStyle(afterItemsNode.firstElementChild) || {};\n      var lastStyle = afterItemsNode.lastElementChild && getComputedStyle(afterItemsNode.lastElementChild) || {};\n      repeaterAfterSize = (parseInt(style[isVertical ? 'height' : 'width']) || 0) +\n        (firstStyle && parseInt(firstStyle[isVertical ? 'marginTop' : 'marginLeft']) || 0) +\n        (lastStyle && parseInt(lastStyle[isVertical ? 'marginBottom' : 'marginRight']) || 0);\n\n      // Get the offsetTop of the repeater.\n      repeaterBeforeSize = 0;\n      var current = containerNode;\n      do {\n        repeaterBeforeSize += current[isVertical ? 'offsetTop' : 'offsetLeft'];\n      } while ( ionic.DomUtil.contains(scrollView.__content, current = current.offsetParent) );\n\n      var containerPrevNode = containerNode.previousElementSibling;\n      var beforeStyle = containerPrevNode ? $window.getComputedStyle(containerPrevNode) : {};\n      var beforeMargin = parseInt(beforeStyle[isVertical ? 'marginBottom' : 'marginRight'] || 0);\n\n      // Because we position the collection container with position: relative, it doesn't take\n      // into account where to position itself relative to the previous element's marginBottom.\n      // To compensate, we translate the container up by the previous element's margin.\n      containerNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR\n        .replace(PRIMARY, -beforeMargin)\n        .replace(SECONDARY, 0);\n      repeaterBeforeSize -= beforeMargin;\n\n      if (!scrollView.__clientHeight || !scrollView.__clientWidth) {\n        scrollView.__clientWidth = scrollView.__container.clientWidth;\n        scrollView.__clientHeight = scrollView.__container.clientHeight;\n      }\n\n      (view.onRefreshLayout || angular.noop)();\n      view.refreshDirection();\n      scrollViewSetDimensions();\n\n      // Create the pool of items for reuse, setting the size to (estimatedItemsOnScreen) * 2,\n      // plus the size of the renderBuffer.\n      if (!isLayoutReady) {\n        var poolSize = Math.max(20, renderBuffer * 3);\n        for (var i = 0; i < poolSize; i++) {\n          itemsPool.push(new RepeatItem());\n        }\n      }\n\n      isLayoutReady = true;\n      if (isLayoutReady && isDataReady) {\n        // If the resize or latest data change caused the scrollValue to\n        // now be out of bounds, resize the scrollView.\n        if (scrollView.__scrollLeft > scrollView.__maxScrollLeft ||\n            scrollView.__scrollTop > scrollView.__maxScrollTop) {\n          scrollView.resize();\n        }\n        forceRerender(true);\n      }\n    };\n\n    this.setData = function(newData) {\n      data = newData;\n      (view.onRefreshData || angular.noop)();\n      isDataReady = true;\n    };\n\n    this.destroy = function() {\n      render.destroyed = true;\n\n      itemsPool.forEach(function(item) {\n        item.scope.$destroy();\n        item.scope = item.element = item.node = item.images = null;\n      });\n      itemsPool.length = itemsEntering.length = itemsLeaving.length = 0;\n      itemsShownMap = {};\n\n      //Restore the scrollView's normal behavior and resize it to normal size.\n      scrollView.options[contentSizeStr] = originalGetContentSize;\n      scrollView.__callback = scrollView.__$callback;\n      scrollView.resize();\n\n      (view.onDestroy || angular.noop)();\n    };\n\n    function forceRerender() {\n      return render(true);\n    }\n    function render(forceRerender) {\n      if (render.destroyed) return;\n      var i;\n      var ii;\n      var item;\n      var dim;\n      var scope;\n      var scrollValue = view.getScrollValue();\n      var scrollValueEnd = scrollValue + view.scrollPrimarySize;\n\n      view.updateRenderRange(scrollValue, scrollValueEnd);\n\n      renderStartIndex = Math.max(0, renderStartIndex - renderBuffer);\n      renderEndIndex = Math.min(data.length - 1, renderEndIndex + renderBuffer);\n\n      for (i in itemsShownMap) {\n        if (i < renderStartIndex || i > renderEndIndex) {\n          item = itemsShownMap[i];\n          delete itemsShownMap[i];\n          itemsLeaving.push(item);\n          item.isShown = false;\n        }\n      }\n\n      // Render indicies that aren't shown yet\n      //\n      // NOTE(ajoslin): this may sound crazy, but calling any other functions during this render\n      // loop will often push the render time over the edge from less than one frame to over\n      // one frame, causing visible jank.\n      // DON'T call any other functions inside this loop unless it's vital.\n      for (i = renderStartIndex; i <= renderEndIndex; i++) {\n        // We only go forward with render if the index is in data, the item isn't already shown,\n        // or forceRerender is on.\n        if (i >= data.length || (itemsShownMap[i] && !forceRerender)) continue;\n\n        item = itemsShownMap[i] || (itemsShownMap[i] = itemsLeaving.length ? itemsLeaving.pop() :\n                                    itemsPool.length ? itemsPool.shift() :\n                                    new RepeatItem());\n        itemsEntering.push(item);\n        item.isShown = true;\n\n        scope = item.scope;\n        scope.$index = i;\n        scope[keyExpression] = data[i];\n        scope.$first = (i === 0);\n        scope.$last = (i === (data.length - 1));\n        scope.$middle = !(scope.$first || scope.$last);\n        scope.$odd = !(scope.$even = (i & 1) === 0);\n\n        if (scope.$$disconnected) ionic.Utils.reconnectScope(item.scope);\n\n        dim = view.getDimensions(i);\n        if (item.secondaryPos !== dim.secondaryPos || item.primaryPos !== dim.primaryPos) {\n          item.node.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR\n            .replace(PRIMARY, (item.primaryPos = dim.primaryPos))\n            .replace(SECONDARY, (item.secondaryPos = dim.secondaryPos));\n        }\n        if (item.secondarySize !== dim.secondarySize || item.primarySize !== dim.primarySize) {\n          item.node.style.cssText = item.node.style.cssText\n            .replace(WIDTH_HEIGHT_REGEX, WIDTH_HEIGHT_TEMPLATE_STR\n              //TODO fix item.primarySize + 1 hack\n              .replace(PRIMARY, (item.primarySize = dim.primarySize) + 1)\n              .replace(SECONDARY, (item.secondarySize = dim.secondarySize))\n            );\n        }\n\n      }\n\n      // If we reach the end of the list, render the afterItemsNode - this contains all the\n      // elements the developer placed after the collection-repeat\n      if (renderEndIndex === data.length - 1) {\n        dim = view.getDimensions(data.length - 1) || EMPTY_DIMENSION;\n        afterItemsNode.style[ionic.CSS.TRANSFORM] = TRANSLATE_TEMPLATE_STR\n          .replace(PRIMARY, dim.primaryPos + dim.primarySize)\n          .replace(SECONDARY, 0);\n      }\n\n      while (itemsLeaving.length) {\n        item = itemsLeaving.pop();\n        item.scope.$broadcast('$collectionRepeatLeave');\n        ionic.Utils.disconnectScope(item.scope);\n        itemsPool.push(item);\n        item.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';\n        item.primaryPos = item.secondaryPos = null;\n      }\n\n      if (forceRefreshImages) {\n        for (i = 0, ii = itemsEntering.length; i < ii && (item = itemsEntering[i]); i++) {\n          if (!item.images) continue;\n          for (var j = 0, jj = item.images.length, img; j < jj && (img = item.images[j]); j++) {\n            var src = img.src;\n            img.src = ONE_PX_TRANSPARENT_IMG_SRC;\n            img.src = src;\n          }\n        }\n      }\n      if (forceRerender) {\n        var rootScopePhase = $rootScope.$$phase;\n        while (itemsEntering.length) {\n          item = itemsEntering.pop();\n          if (!rootScopePhase) item.scope.$digest();\n        }\n      } else {\n        digestEnteringItems();\n      }\n    }\n\n    function digestEnteringItems() {\n      var item;\n      if (digestEnteringItems.running) return;\n      digestEnteringItems.running = true;\n\n      $$rAF(function process() {\n        var rootScopePhase = $rootScope.$$phase;\n        while (itemsEntering.length) {\n          item = itemsEntering.pop();\n          if (item.isShown) {\n            if (!rootScopePhase) item.scope.$digest();\n          }\n        }\n        digestEnteringItems.running = false;\n      });\n    }\n\n    function RepeatItem() {\n      var self = this;\n      this.scope = scope.$new();\n      this.id = 'item' + (nextItemId++);\n      transclude(this.scope, function(clone) {\n        self.element = clone;\n        self.element.data('$$collectionRepeatItem', self);\n        // TODO destroy\n        self.node = clone[0];\n        // Batch style setting to lower repaints\n        self.node.style[ionic.CSS.TRANSFORM] = 'translate3d(-9999px,-9999px,0)';\n        self.node.style.cssText += ' height: 0px; width: 0px;';\n        ionic.Utils.disconnectScope(self.scope);\n        containerNode.appendChild(self.node);\n        self.images = clone[0].getElementsByTagName('img');\n      });\n    }\n\n    function VerticalViewType() {\n      this.getItemPrimarySize = heightGetter;\n      this.getItemSecondarySize = widthGetter;\n\n      this.getScrollValue = function() {\n        return Math.max(0, Math.min(scrollView.__scrollTop - repeaterBeforeSize,\n          scrollView.__maxScrollTop - repeaterBeforeSize - repeaterAfterSize));\n      };\n\n      this.refreshDirection = function() {\n        this.scrollPrimarySize = scrollView.__clientHeight;\n        this.scrollSecondarySize = scrollView.__clientWidth;\n\n        this.estimatedPrimarySize = estimatedHeight;\n        this.estimatedSecondarySize = estimatedWidth;\n        this.estimatedItemsAcross = isGridView &&\n          Math.floor(scrollView.__clientWidth / estimatedWidth) ||\n          1;\n      };\n    }\n    function HorizontalViewType() {\n      this.getItemPrimarySize = widthGetter;\n      this.getItemSecondarySize = heightGetter;\n\n      this.getScrollValue = function() {\n        return Math.max(0, Math.min(scrollView.__scrollLeft - repeaterBeforeSize,\n          scrollView.__maxScrollLeft - repeaterBeforeSize - repeaterAfterSize));\n      };\n\n      this.refreshDirection = function() {\n        this.scrollPrimarySize = scrollView.__clientWidth;\n        this.scrollSecondarySize = scrollView.__clientHeight;\n\n        this.estimatedPrimarySize = estimatedWidth;\n        this.estimatedSecondarySize = estimatedHeight;\n        this.estimatedItemsAcross = isGridView &&\n          Math.floor(scrollView.__clientHeight / estimatedHeight) ||\n          1;\n      };\n    }\n\n    function GridViewType() {\n      this.getEstimatedSecondaryPos = function(index) {\n        return (index % this.estimatedItemsAcross) * this.estimatedSecondarySize;\n      };\n      this.getEstimatedPrimaryPos = function(index) {\n        return Math.floor(index / this.estimatedItemsAcross) * this.estimatedPrimarySize;\n      };\n      this.getEstimatedIndex = function(scrollValue) {\n        return Math.floor(scrollValue / this.estimatedPrimarySize) *\n          this.estimatedItemsAcross;\n      };\n    }\n\n    function ListViewType() {\n      this.getEstimatedSecondaryPos = function() {\n        return 0;\n      };\n      this.getEstimatedPrimaryPos = function(index) {\n        return index * this.estimatedPrimarySize;\n      };\n      this.getEstimatedIndex = function(scrollValue) {\n        return Math.floor((scrollValue) / this.estimatedPrimarySize);\n      };\n    }\n\n    function StaticViewType() {\n      this.getContentSize = function() {\n        return this.getEstimatedPrimaryPos(data.length - 1) + this.estimatedPrimarySize +\n          repeaterBeforeSize + repeaterAfterSize;\n      };\n      // static view always returns the same object for getDimensions, to avoid memory allocation\n      // while scrolling. This could be dangerous if this was a public function, but it's not.\n      // Only we use it.\n      var dim = {};\n      this.getDimensions = function(index) {\n        dim.primaryPos = this.getEstimatedPrimaryPos(index);\n        dim.secondaryPos = this.getEstimatedSecondaryPos(index);\n        dim.primarySize = this.estimatedPrimarySize;\n        dim.secondarySize = this.estimatedSecondarySize;\n        return dim;\n      };\n      this.updateRenderRange = function(scrollValue, scrollValueEnd) {\n        renderStartIndex = Math.max(0, this.getEstimatedIndex(scrollValue));\n\n        // Make sure the renderEndIndex takes into account all the items on the row\n        renderEndIndex = Math.min(data.length - 1,\n          this.getEstimatedIndex(scrollValueEnd) + this.estimatedItemsAcross - 1);\n\n        renderBeforeBoundary = Math.max(0,\n          this.getEstimatedPrimaryPos(renderStartIndex));\n        renderAfterBoundary = this.getEstimatedPrimaryPos(renderEndIndex) +\n          this.estimatedPrimarySize;\n      };\n    }\n\n    function DynamicViewType() {\n      var self = this;\n      var debouncedScrollViewSetDimensions = ionic.debounce(scrollViewSetDimensions, 25, true);\n      var calculateDimensions = isGridView ? calculateDimensionsGrid : calculateDimensionsList;\n      var dimensionsIndex;\n      var dimensions = [];\n\n\n      // Get the dimensions at index. {width, height, left, top}.\n      // We start with no dimensions calculated, then any time dimensions are asked for at an\n      // index we calculate dimensions up to there.\n      function calculateDimensionsList(toIndex) {\n        var i, prevDimension, dim;\n        for (i = Math.max(0, dimensionsIndex); i <= toIndex && (dim = dimensions[i]); i++) {\n          prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;\n          dim.primarySize = self.getItemPrimarySize(i, data[i]);\n          dim.secondarySize = self.scrollSecondarySize;\n          dim.primaryPos = prevDimension.primaryPos + prevDimension.primarySize;\n          dim.secondaryPos = 0;\n        }\n      }\n      function calculateDimensionsGrid(toIndex) {\n        var i, prevDimension, dim;\n        for (i = Math.max(dimensionsIndex, 0); i <= toIndex && (dim = dimensions[i]); i++) {\n          prevDimension = dimensions[i - 1] || EMPTY_DIMENSION;\n          dim.secondarySize = Math.min(\n            self.getItemSecondarySize(i, data[i]),\n            self.scrollSecondarySize\n          );\n          dim.secondaryPos = prevDimension.secondaryPos + prevDimension.secondarySize;\n\n          if (i === 0 || dim.secondaryPos + dim.secondarySize > self.scrollSecondarySize) {\n            dim.secondaryPos = 0;\n            dim.primarySize = self.getItemPrimarySize(i, data[i]);\n            dim.primaryPos = prevDimension.primaryPos + prevDimension.rowPrimarySize;\n\n            dim.rowStartIndex = i;\n            dim.rowPrimarySize = dim.primarySize;\n          } else {\n            dim.primarySize = self.getItemPrimarySize(i, data[i]);\n            dim.primaryPos = prevDimension.primaryPos;\n            dim.rowStartIndex = prevDimension.rowStartIndex;\n\n            dimensions[dim.rowStartIndex].rowPrimarySize = dim.rowPrimarySize = Math.max(\n              dimensions[dim.rowStartIndex].rowPrimarySize,\n              dim.primarySize\n            );\n            dim.rowPrimarySize = Math.max(dim.primarySize, dim.rowPrimarySize);\n          }\n        }\n      }\n\n      this.getContentSize = function() {\n        var dim = dimensions[dimensionsIndex] || EMPTY_DIMENSION;\n        return ((dim.primaryPos + dim.primarySize) || 0) +\n          this.getEstimatedPrimaryPos(data.length - dimensionsIndex - 1) +\n          repeaterBeforeSize + repeaterAfterSize;\n      };\n      this.onDestroy = function() {\n        dimensions.length = 0;\n      };\n\n      this.onRefreshData = function() {\n        var i;\n        var ii;\n        // Make sure dimensions has as many items as data.length.\n        // This is to be sure we don't have to allocate objects while scrolling.\n        for (i = dimensions.length, ii = data.length; i < ii; i++) {\n          dimensions.push({});\n        }\n        dimensionsIndex = -1;\n      };\n      this.onRefreshLayout = function() {\n        dimensionsIndex = -1;\n      };\n      this.getDimensions = function(index) {\n        index = Math.min(index, data.length - 1);\n\n        if (dimensionsIndex < index) {\n          // Once we start asking for dimensions near the end of the list, go ahead and calculate\n          // everything. This is to make sure when the user gets to the end of the list, the\n          // scroll height of the list is 100% accurate (not estimated anymore).\n          if (index > data.length * 0.9) {\n            calculateDimensions(data.length - 1);\n            dimensionsIndex = data.length - 1;\n            scrollViewSetDimensions();\n          } else {\n            calculateDimensions(index);\n            dimensionsIndex = index;\n            debouncedScrollViewSetDimensions();\n          }\n\n        }\n        return dimensions[index];\n      };\n\n      var oldRenderStartIndex = -1;\n      var oldScrollValue = -1;\n      this.updateRenderRange = function(scrollValue, scrollValueEnd) {\n        var i;\n        var len;\n        var dim;\n\n        // Calculate more dimensions than we estimate we'll need, to be sure.\n        this.getDimensions( this.getEstimatedIndex(scrollValueEnd) * 2 );\n\n        // -- Calculate renderStartIndex\n        // base case: start at 0\n        if (oldRenderStartIndex === -1 || scrollValue === 0) {\n          i = 0;\n        // scrolling down\n        } else if (scrollValue >= oldScrollValue) {\n          for (i = oldRenderStartIndex, len = data.length; i < len; i++) {\n            if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize >= scrollValue) {\n              break;\n            }\n          }\n        // scrolling up\n        } else {\n          for (i = oldRenderStartIndex; i >= 0; i--) {\n            if ((dim = this.getDimensions(i)) && dim.primaryPos <= scrollValue) {\n              // when grid view, make sure the render starts at the beginning of a row.\n              i = isGridView ? dim.rowStartIndex : i;\n              break;\n            }\n          }\n        }\n\n        renderStartIndex = Math.min(Math.max(0, i), data.length - 1);\n        renderBeforeBoundary = renderStartIndex !== -1 ? this.getDimensions(renderStartIndex).primaryPos : -1;\n\n        // -- Calculate renderEndIndex\n        var lastRowDim;\n        for (i = renderStartIndex + 1, len = data.length; i < len; i++) {\n          if ((dim = this.getDimensions(i)) && dim.primaryPos + dim.rowPrimarySize > scrollValueEnd) {\n\n            // Go all the way to the end of the row if we're in a grid\n            if (isGridView) {\n              lastRowDim = dim;\n              while (i < len - 1 &&\n                    (dim = this.getDimensions(i + 1)).primaryPos === lastRowDim.primaryPos) {\n                i++;\n              }\n            }\n            break;\n          }\n        }\n\n        renderEndIndex = Math.min(i, data.length - 1);\n        renderAfterBoundary = renderEndIndex !== -1 ?\n          ((dim = this.getDimensions(renderEndIndex)).primaryPos + (dim.rowPrimarySize || dim.primarySize)) :\n          -1;\n\n        oldScrollValue = scrollValue;\n        oldRenderStartIndex = renderStartIndex;\n      };\n    }\n\n\n  };\n\n}\n\n/**\n * @ngdoc directive\n * @name ionContent\n * @module ionic\n * @delegate ionic.service:$ionicScrollDelegate\n * @restrict E\n *\n * @description\n * The ionContent directive provides an easy to use content area that can be configured\n * to use Ionic's custom Scroll View, or the built in overflow scrolling of the browser.\n *\n * While we recommend using the custom Scroll features in Ionic in most cases, sometimes\n * (for performance reasons) only the browser's native overflow scrolling will suffice,\n * and so we've made it easy to toggle between the Ionic scroll implementation and\n * overflow scrolling.\n *\n * You can implement pull-to-refresh with the {@link ionic.directive:ionRefresher}\n * directive, and infinite scrolling with the {@link ionic.directive:ionInfiniteScroll}\n * directive.\n *\n * If there is any dynamic content inside the ion-content, be sure to call `.resize()` with {@link ionic.service:$ionicScrollDelegate}\n * after the content has been added.\n *\n * Be aware that this directive gets its own child scope. If you do not understand why this\n * is important, you can read [https://docs.angularjs.org/guide/scope](https://docs.angularjs.org/guide/scope).\n *\n * @param {string=} delegate-handle The handle used to identify this scrollView\n * with {@link ionic.service:$ionicScrollDelegate}.\n * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.\n * @param {boolean=} locking Whether to lock scrolling in one direction at a time. Useful to set to false when zoomed in or scrolling in two directions. Default true.\n * @param {boolean=} padding Whether to add padding to the content.\n * of the content.  Defaults to true on iOS, false on Android.\n * @param {boolean=} scroll Whether to allow scrolling of content.  Defaults to true.\n * @param {boolean=} overflow-scroll Whether to use overflow-scrolling instead of\n * Ionic scroll. See {@link ionic.provider:$ionicConfigProvider} to set this as the global default.\n * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.\n * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.\n * @param {string=} start-x Initial horizontal scroll position. Default 0.\n * @param {string=} start-y Initial vertical scroll position. Default 0.\n * @param {expression=} on-scroll Expression to evaluate when the content is scrolled.\n * @param {expression=} on-scroll-complete Expression to evaluate when a scroll action completes. Has access to 'scrollLeft' and 'scrollTop' locals.\n * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges\n * of the content.  Defaults to true on iOS, false on Android.\n * @param {number=} scroll-event-interval Number of milliseconds between each firing of the 'on-scroll' expression. Default 10.\n */\nIonicModule\n.directive('ionContent', [\n  '$timeout',\n  '$controller',\n  '$ionicBind',\n  '$ionicConfig',\nfunction($timeout, $controller, $ionicBind, $ionicConfig) {\n  return {\n    restrict: 'E',\n    require: '^?ionNavView',\n    scope: true,\n    priority: 800,\n    compile: function(element, attr) {\n      var innerElement;\n      var scrollCtrl;\n\n      element.addClass('scroll-content ionic-scroll');\n\n      if (attr.scroll != 'false') {\n        //We cannot use normal transclude here because it breaks element.data()\n        //inheritance on compile\n        innerElement = jqLite('<div class=\"scroll\"></div>');\n        innerElement.append(element.contents());\n        element.append(innerElement);\n      } else {\n        element.addClass('scroll-content-false');\n      }\n\n      var nativeScrolling = attr.overflowScroll === \"true\" || !$ionicConfig.scrolling.jsScrolling();\n\n      // collection-repeat requires JS scrolling\n      if (nativeScrolling) {\n        nativeScrolling = !element[0].querySelector('[collection-repeat]');\n      }\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attr) {\n        var parentScope = $scope.$parent;\n        $scope.$watch(function() {\n          return (parentScope.$hasHeader ? ' has-header' : '') +\n            (parentScope.$hasSubheader ? ' has-subheader' : '') +\n            (parentScope.$hasFooter ? ' has-footer' : '') +\n            (parentScope.$hasSubfooter ? ' has-subfooter' : '') +\n            (parentScope.$hasTabs ? ' has-tabs' : '') +\n            (parentScope.$hasTabsTop ? ' has-tabs-top' : '');\n        }, function(className, oldClassName) {\n          $element.removeClass(oldClassName);\n          $element.addClass(className);\n        });\n\n        //Only this ionContent should use these variables from parent scopes\n        $scope.$hasHeader = $scope.$hasSubheader =\n          $scope.$hasFooter = $scope.$hasSubfooter =\n          $scope.$hasTabs = $scope.$hasTabsTop =\n          false;\n        $ionicBind($scope, $attr, {\n          $onScroll: '&onScroll',\n          $onScrollComplete: '&onScrollComplete',\n          hasBouncing: '@',\n          padding: '@',\n          direction: '@',\n          scrollbarX: '@',\n          scrollbarY: '@',\n          startX: '@',\n          startY: '@',\n          scrollEventInterval: '@'\n        });\n        $scope.direction = $scope.direction || 'y';\n\n        if (isDefined($attr.padding)) {\n          $scope.$watch($attr.padding, function(newVal) {\n              (innerElement || $element).toggleClass('padding', !!newVal);\n          });\n        }\n\n        if ($attr.scroll === \"false\") {\n          //do nothing\n        } else {\n          var scrollViewOptions = {};\n\n          // determined in compile phase above\n          if (nativeScrolling) {\n            // use native scrolling\n            $element.addClass('overflow-scroll');\n\n            scrollViewOptions = {\n              el: $element[0],\n              delegateHandle: attr.delegateHandle,\n              startX: $scope.$eval($scope.startX) || 0,\n              startY: $scope.$eval($scope.startY) || 0,\n              nativeScrolling: true\n            };\n\n          } else {\n            // Use JS scrolling\n            scrollViewOptions = {\n              el: $element[0],\n              delegateHandle: attr.delegateHandle,\n              locking: (attr.locking || 'true') === 'true',\n              bouncing: $scope.$eval($scope.hasBouncing),\n              startX: $scope.$eval($scope.startX) || 0,\n              startY: $scope.$eval($scope.startY) || 0,\n              scrollbarX: $scope.$eval($scope.scrollbarX) !== false,\n              scrollbarY: $scope.$eval($scope.scrollbarY) !== false,\n              scrollingX: $scope.direction.indexOf('x') >= 0,\n              scrollingY: $scope.direction.indexOf('y') >= 0,\n              scrollEventInterval: parseInt($scope.scrollEventInterval, 10) || 10,\n              scrollingComplete: onScrollComplete\n            };\n          }\n\n          // init scroll controller with appropriate options\n          scrollCtrl = $controller('$ionicScroll', {\n            $scope: $scope,\n            scrollViewOptions: scrollViewOptions\n          });\n\n          $scope.$on('$destroy', function() {\n            if (scrollViewOptions) {\n              scrollViewOptions.scrollingComplete = noop;\n              delete scrollViewOptions.el;\n            }\n            innerElement = null;\n            $element = null;\n            attr.$$element = null;\n          });\n        }\n\n        function onScrollComplete() {\n          $scope.$onScrollComplete({\n            scrollTop: scrollCtrl.scrollView.__scrollTop,\n            scrollLeft: scrollCtrl.scrollView.__scrollLeft\n          });\n        }\n\n      }\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name exposeAsideWhen\n * @module ionic\n * @restrict A\n * @parent ionic.directive:ionSideMenus\n *\n * @description\n * It is common for a tablet application to hide a menu when in portrait mode, but to show the\n * same menu on the left side when the tablet is in landscape mode. The `exposeAsideWhen` attribute\n * directive can be used to accomplish a similar interface.\n *\n * By default, side menus are hidden underneath its side menu content, and can be opened by either\n * swiping the content left or right, or toggling a button to show the side menu. However, by adding the\n * `exposeAsideWhen` attribute directive to an {@link ionic.directive:ionSideMenu} element directive,\n * a side menu can be given instructions on \"when\" the menu should be exposed (always viewable). For\n * example, the `expose-aside-when=\"large\"` attribute will keep the side menu hidden when the viewport's\n * width is less than `768px`, but when the viewport's width is `768px` or greater, the menu will then\n * always be shown and can no longer be opened or closed like it could when it was hidden for smaller\n * viewports.\n *\n * Using `large` as the attribute's value is a shortcut value to `(min-width:768px)` since it is\n * the most common use-case. However, for added flexibility, any valid media query could be added\n * as the value, such as `(min-width:600px)` or even multiple queries such as\n * `(min-width:750px) and (max-width:1200px)`.\n\n * @usage\n * ```html\n * <ion-side-menus>\n *   <!-- Center content -->\n *   <ion-side-menu-content>\n *   </ion-side-menu-content>\n *\n *   <!-- Left menu -->\n *   <ion-side-menu expose-aside-when=\"large\">\n *   </ion-side-menu>\n * </ion-side-menus>\n * ```\n * For a complete side menu example, see the\n * {@link ionic.directive:ionSideMenus} documentation.\n */\nIonicModule.directive('exposeAsideWhen', ['$window', function($window) {\n  return {\n    restrict: 'A',\n    require: '^ionSideMenus',\n    link: function($scope, $element, $attr, sideMenuCtrl) {\n\n      function checkAsideExpose() {\n        var mq = $attr.exposeAsideWhen == 'large' ? '(min-width:768px)' : $attr.exposeAsideWhen;\n        sideMenuCtrl.exposeAside($window.matchMedia(mq).matches);\n        sideMenuCtrl.activeAsideResizing(false);\n      }\n\n      function onResize() {\n        sideMenuCtrl.activeAsideResizing(true);\n        debouncedCheck();\n      }\n\n      var debouncedCheck = ionic.debounce(function() {\n        $scope.$apply(checkAsideExpose);\n      }, 300, false);\n\n      $scope.$evalAsync(checkAsideExpose);\n\n      ionic.on('resize', onResize, $window);\n\n      $scope.$on('$destroy', function() {\n        ionic.off('resize', onResize, $window);\n      });\n\n    }\n  };\n}]);\n\n\nvar GESTURE_DIRECTIVES = 'onHold onTap onDoubleTap onTouch onRelease onDrag onDragUp onDragRight onDragDown onDragLeft onSwipe onSwipeUp onSwipeRight onSwipeDown onSwipeLeft'.split(' ');\n\nGESTURE_DIRECTIVES.forEach(function(name) {\n  IonicModule.directive(name, gestureDirective(name));\n});\n\n\n/**\n * @ngdoc directive\n * @name onHold\n * @module ionic\n * @restrict A\n *\n * @description\n * Touch stays at the same location for 500ms. Similar to long touch events available for AngularJS and jQuery.\n *\n * @usage\n * ```html\n * <button on-hold=\"onHold()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onTap\n * @module ionic\n * @restrict A\n *\n * @description\n * Quick touch at a location. If the duration of the touch goes\n * longer than 250ms it is no longer a tap gesture.\n *\n * @usage\n * ```html\n * <button on-tap=\"onTap()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDoubleTap\n * @module ionic\n * @restrict A\n *\n * @description\n * Double tap touch at a location.\n *\n * @usage\n * ```html\n * <button on-double-tap=\"onDoubleTap()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onTouch\n * @module ionic\n * @restrict A\n *\n * @description\n * Called immediately when the user first begins a touch. This\n * gesture does not wait for a touchend/mouseup.\n *\n * @usage\n * ```html\n * <button on-touch=\"onTouch()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onRelease\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the user ends a touch.\n *\n * @usage\n * ```html\n * <button on-release=\"onRelease()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDrag\n * @module ionic\n * @restrict A\n *\n * @description\n * Move with one touch around on the page. Blocking the scrolling when\n * moving left and right is a good practice. When all the drag events are\n * blocking you disable scrolling on that area.\n *\n * @usage\n * ```html\n * <button on-drag=\"onDrag()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragUp\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged up.\n *\n * @usage\n * ```html\n * <button on-drag-up=\"onDragUp()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragRight\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged to the right.\n *\n * @usage\n * ```html\n * <button on-drag-right=\"onDragRight()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragDown\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged down.\n *\n * @usage\n * ```html\n * <button on-drag-down=\"onDragDown()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onDragLeft\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when the element is dragged to the left.\n *\n * @usage\n * ```html\n * <button on-drag-left=\"onDragLeft()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipe\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity in any direction.\n *\n * @usage\n * ```html\n * <button on-swipe=\"onSwipe()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeUp\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving up.\n *\n * @usage\n * ```html\n * <button on-swipe-up=\"onSwipeUp()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeRight\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving to the right.\n *\n * @usage\n * ```html\n * <button on-swipe-right=\"onSwipeRight()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeDown\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving down.\n *\n * @usage\n * ```html\n * <button on-swipe-down=\"onSwipeDown()\" class=\"button\">Test</button>\n * ```\n */\n\n\n/**\n * @ngdoc directive\n * @name onSwipeLeft\n * @module ionic\n * @restrict A\n *\n * @description\n * Called when a moving touch has a high velocity moving to the left.\n *\n * @usage\n * ```html\n * <button on-swipe-left=\"onSwipeLeft()\" class=\"button\">Test</button>\n * ```\n */\n\n\nfunction gestureDirective(directiveName) {\n  return ['$ionicGesture', '$parse', function($ionicGesture, $parse) {\n    var eventType = directiveName.substr(2).toLowerCase();\n\n    return function(scope, element, attr) {\n      var fn = $parse( attr[directiveName] );\n\n      var listener = function(ev) {\n        scope.$apply(function() {\n          fn(scope, {\n            $event: ev\n          });\n        });\n      };\n\n      var gesture = $ionicGesture.on(eventType, listener, element);\n\n      scope.$on('$destroy', function() {\n        $ionicGesture.off(gesture, eventType, listener);\n      });\n    };\n  }];\n}\n\n\nIonicModule\n.directive('ionHeaderBar', tapScrollToTopDirective())\n\n/**\n * @ngdoc directive\n * @name ionHeaderBar\n * @module ionic\n * @restrict E\n *\n * @description\n * Adds a fixed header bar above some content.\n *\n * Can also be a subheader (lower down) if the 'bar-subheader' class is applied.\n * See [the header CSS docs](/docs/components/#subheader).\n *\n * @param {string=} align-title How to align the title. By default the title\n * will be aligned the same as how the platform aligns its titles (iOS centers\n * titles, Android aligns them left).\n * Available: 'left', 'right', or 'center'.  Defaults to the same as the platform.\n * @param {boolean=} no-tap-scroll By default, the header bar will scroll the\n * content to the top when tapped.  Set no-tap-scroll to true to disable this\n * behavior.\n * Available: true or false.  Defaults to false.\n *\n * @usage\n * ```html\n * <ion-header-bar align-title=\"left\" class=\"bar-positive\">\n *   <div class=\"buttons\">\n *     <button class=\"button\" ng-click=\"doSomething()\">Left Button</button>\n *   </div>\n *   <h1 class=\"title\">Title!</h1>\n *   <div class=\"buttons\">\n *     <button class=\"button\">Right Button</button>\n *   </div>\n * </ion-header-bar>\n * <ion-content>\n *   Some content!\n * </ion-content>\n * ```\n */\n.directive('ionHeaderBar', headerFooterBarDirective(true))\n\n/**\n * @ngdoc directive\n * @name ionFooterBar\n * @module ionic\n * @restrict E\n *\n * @description\n * Adds a fixed footer bar below some content.\n *\n * Can also be a subfooter (higher up) if the 'bar-subfooter' class is applied.\n * See [the footer CSS docs](/docs/components/#footer).\n *\n * Note: If you use ionFooterBar in combination with ng-if, the surrounding content\n * will not align correctly.  This will be fixed soon.\n *\n * @param {string=} align-title Where to align the title.\n * Available: 'left', 'right', or 'center'.  Defaults to 'center'.\n *\n * @usage\n * ```html\n * <ion-content>\n *   Some content!\n * </ion-content>\n * <ion-footer-bar align-title=\"left\" class=\"bar-assertive\">\n *   <div class=\"buttons\">\n *     <button class=\"button\">Left Button</button>\n *   </div>\n *   <h1 class=\"title\">Title!</h1>\n *   <div class=\"buttons\" ng-click=\"doSomething()\">\n *     <button class=\"button\">Right Button</button>\n *   </div>\n * </ion-footer-bar>\n * ```\n */\n.directive('ionFooterBar', headerFooterBarDirective(false));\n\nfunction tapScrollToTopDirective() {\n  return ['$ionicScrollDelegate', function($ionicScrollDelegate) {\n    return {\n      restrict: 'E',\n      link: function($scope, $element, $attr) {\n        if ($attr.noTapScroll == 'true') {\n          return;\n        }\n        ionic.on('tap', onTap, $element[0]);\n        $scope.$on('$destroy', function() {\n          ionic.off('tap', onTap, $element[0]);\n        });\n\n        function onTap(e) {\n          var depth = 3;\n          var current = e.target;\n          //Don't scroll to top in certain cases\n          while (depth-- && current) {\n            if (current.classList.contains('button') ||\n                current.tagName.match(/input|textarea|select/i) ||\n                current.isContentEditable) {\n              return;\n            }\n            current = current.parentNode;\n          }\n          var touch = e.gesture && e.gesture.touches[0] || e.detail.touches[0];\n          var bounds = $element[0].getBoundingClientRect();\n          if (ionic.DomUtil.rectContains(\n            touch.pageX, touch.pageY,\n            bounds.left, bounds.top - 20,\n            bounds.left + bounds.width, bounds.top + bounds.height\n          )) {\n            $ionicScrollDelegate.scrollTop(true);\n          }\n        }\n      }\n    };\n  }];\n}\n\nfunction headerFooterBarDirective(isHeader) {\n  return ['$document', '$timeout', function($document, $timeout) {\n    return {\n      restrict: 'E',\n      controller: '$ionicHeaderBar',\n      compile: function(tElement) {\n        tElement.addClass(isHeader ? 'bar bar-header' : 'bar bar-footer');\n        // top style tabs? if so, remove bottom border for seamless display\n        $timeout(function() {\n          if (isHeader && $document[0].getElementsByClassName('tabs-top').length) tElement.addClass('has-tabs-top');\n        });\n\n        return { pre: prelink };\n        function prelink($scope, $element, $attr, ctrl) {\n          if (isHeader) {\n            $scope.$watch(function() { return $element[0].className; }, function(value) {\n              var isShown = value.indexOf('ng-hide') === -1;\n              var isSubheader = value.indexOf('bar-subheader') !== -1;\n              $scope.$hasHeader = isShown && !isSubheader;\n              $scope.$hasSubheader = isShown && isSubheader;\n              $scope.$emit('$ionicSubheader', $scope.$hasSubheader);\n            });\n            $scope.$on('$destroy', function() {\n              delete $scope.$hasHeader;\n              delete $scope.$hasSubheader;\n            });\n            ctrl.align();\n            $scope.$on('$ionicHeader.align', function() {\n              ionic.requestAnimationFrame(function() {\n                ctrl.align();\n              });\n            });\n\n          } else {\n            $scope.$watch(function() { return $element[0].className; }, function(value) {\n              var isShown = value.indexOf('ng-hide') === -1;\n              var isSubfooter = value.indexOf('bar-subfooter') !== -1;\n              $scope.$hasFooter = isShown && !isSubfooter;\n              $scope.$hasSubfooter = isShown && isSubfooter;\n            });\n            $scope.$on('$destroy', function() {\n              delete $scope.$hasFooter;\n              delete $scope.$hasSubfooter;\n            });\n            $scope.$watch('$hasTabs', function(val) {\n              $element.toggleClass('has-tabs', !!val);\n            });\n          }\n        }\n      }\n    };\n  }];\n}\n\n/**\n * @ngdoc directive\n * @name ionInfiniteScroll\n * @module ionic\n * @parent ionic.directive:ionContent, ionic.directive:ionScroll\n * @restrict E\n *\n * @description\n * The ionInfiniteScroll directive allows you to call a function whenever\n * the user gets to the bottom of the page or near the bottom of the page.\n *\n * The expression you pass in for `on-infinite` is called when the user scrolls\n * greater than `distance` away from the bottom of the content.  Once `on-infinite`\n * is done loading new data, it should broadcast the `scroll.infiniteScrollComplete`\n * event from your controller (see below example).\n *\n * @param {expression} on-infinite What to call when the scroller reaches the\n * bottom.\n * @param {string=} distance The distance from the bottom that the scroll must\n * reach to trigger the on-infinite expression. Default: 1%.\n * @param {string=} spinner The {@link ionic.directive:ionSpinner} to show while loading. The SVG\n * {@link ionic.directive:ionSpinner} is now the default, replacing rotating font icons.\n * @param {string=} icon The icon to show while loading. Default: 'ion-load-d'.  This is depreicated\n * in favor of the SVG {@link ionic.directive:ionSpinner}.\n * @param {boolean=} immediate-check Whether to check the infinite scroll bounds immediately on load.\n *\n * @usage\n * ```html\n * <ion-content ng-controller=\"MyController\">\n *   <ion-list>\n *   ....\n *   ....\n *   </ion-list>\n *\n *   <ion-infinite-scroll\n *     on-infinite=\"loadMore()\"\n *     distance=\"1%\">\n *   </ion-infinite-scroll>\n * </ion-content>\n * ```\n * ```js\n * function MyController($scope, $http) {\n *   $scope.items = [];\n *   $scope.loadMore = function() {\n *     $http.get('/more-items').success(function(items) {\n *       useItems(items);\n *       $scope.$broadcast('scroll.infiniteScrollComplete');\n *     });\n *   };\n *\n *   $scope.$on('$stateChangeSuccess', function() {\n *     $scope.loadMore();\n *   });\n * }\n * ```\n *\n * An easy to way to stop infinite scroll once there is no more data to load\n * is to use angular's `ng-if` directive:\n *\n * ```html\n * <ion-infinite-scroll\n *   ng-if=\"moreDataCanBeLoaded()\"\n *   icon=\"ion-loading-c\"\n *   on-infinite=\"loadMoreData()\">\n * </ion-infinite-scroll>\n * ```\n */\nIonicModule\n.directive('ionInfiniteScroll', ['$timeout', function($timeout) {\n  return {\n    restrict: 'E',\n    require: ['?^$ionicScroll', 'ionInfiniteScroll'],\n    template: function($element, $attrs) {\n      if ($attrs.icon) return '<i class=\"icon {{icon()}} icon-refreshing {{scrollingType}}\"></i>';\n      return '<ion-spinner icon=\"{{spinner()}}\"></ion-spinner>';\n    },\n    scope: true,\n    controller: '$ionInfiniteScroll',\n    link: function($scope, $element, $attrs, ctrls) {\n      var infiniteScrollCtrl = ctrls[1];\n      var scrollCtrl = infiniteScrollCtrl.scrollCtrl = ctrls[0];\n      var jsScrolling = infiniteScrollCtrl.jsScrolling = !scrollCtrl.isNative();\n\n      // if this view is not beneath a scrollCtrl, it can't be injected, proceed w/ native scrolling\n      if (jsScrolling) {\n        infiniteScrollCtrl.scrollView = scrollCtrl.scrollView;\n        $scope.scrollingType = 'js-scrolling';\n        //bind to JS scroll events\n        scrollCtrl.$element.on('scroll', infiniteScrollCtrl.checkBounds);\n      } else {\n        // grabbing the scrollable element, to determine dimensions, and current scroll pos\n        var scrollEl = ionic.DomUtil.getParentOrSelfWithClass($element[0].parentNode, 'overflow-scroll');\n        infiniteScrollCtrl.scrollEl = scrollEl;\n        // if there's no scroll controller, and no overflow scroll div, infinite scroll wont work\n        if (!scrollEl) {\n          throw 'Infinite scroll must be used inside a scrollable div';\n        }\n        //bind to native scroll events\n        infiniteScrollCtrl.scrollEl.addEventListener('scroll', infiniteScrollCtrl.checkBounds);\n      }\n\n      // Optionally check bounds on start after scrollView is fully rendered\n      var doImmediateCheck = isDefined($attrs.immediateCheck) ? $scope.$eval($attrs.immediateCheck) : true;\n      if (doImmediateCheck) {\n        $timeout(function() { infiniteScrollCtrl.checkBounds(); });\n      }\n    }\n  };\n}]);\n\n/**\n* @ngdoc directive\n* @name ionItem\n* @parent ionic.directive:ionList\n* @module ionic\n* @restrict E\n* Creates a list-item that can easily be swiped,\n* deleted, reordered, edited, and more.\n*\n* See {@link ionic.directive:ionList} for a complete example & explanation.\n*\n* Can be assigned any item class name. See the\n* [list CSS documentation](/docs/components/#list).\n*\n* @usage\n*\n* ```html\n* <ion-list>\n*   <ion-item>Hello!</ion-item>\n*   <ion-item href=\"#/detail\">\n*     Link to detail page\n*   </ion-item>\n* </ion-list>\n* ```\n*/\nIonicModule\n.directive('ionItem', ['$$rAF', function($$rAF) {\n  return {\n    restrict: 'E',\n    controller: ['$scope', '$element', function($scope, $element) {\n      this.$scope = $scope;\n      this.$element = $element;\n    }],\n    scope: true,\n    compile: function($element, $attrs) {\n      var isAnchor = isDefined($attrs.href) ||\n                     isDefined($attrs.ngHref) ||\n                     isDefined($attrs.uiSref);\n      var isComplexItem = isAnchor ||\n        //Lame way of testing, but we have to know at compile what to do with the element\n        /ion-(delete|option|reorder)-button/i.test($element.html());\n\n      if (isComplexItem) {\n        var innerElement = jqLite(isAnchor ? '<a></a>' : '<div></div>');\n        innerElement.addClass('item-content');\n\n        if (isDefined($attrs.href) || isDefined($attrs.ngHref)) {\n          innerElement.attr('ng-href', '{{$href()}}');\n          if (isDefined($attrs.target)) {\n            innerElement.attr('target', '{{$target()}}');\n          }\n        }\n\n        innerElement.append($element.contents());\n\n        $element.addClass('item item-complex')\n                .append(innerElement);\n      } else {\n        $element.addClass('item');\n      }\n\n      return function link($scope, $element, $attrs) {\n        $scope.$href = function() {\n          return $attrs.href || $attrs.ngHref;\n        };\n        $scope.$target = function() {\n          return $attrs.target;\n        };\n\n        var content = $element[0].querySelector('.item-content');\n        if (content) {\n          $scope.$on('$collectionRepeatLeave', function() {\n            if (content && content.$$ionicOptionsOpen) {\n              content.style[ionic.CSS.TRANSFORM] = '';\n              content.style[ionic.CSS.TRANSITION] = 'none';\n              $$rAF(function() {\n                content.style[ionic.CSS.TRANSITION] = '';\n              });\n              content.$$ionicOptionsOpen = false;\n            }\n          });\n        }\n      };\n\n    }\n  };\n}]);\n\nvar ITEM_TPL_DELETE_BUTTON =\n  '<div class=\"item-left-edit item-delete enable-pointer-events\">' +\n  '</div>';\n/**\n* @ngdoc directive\n* @name ionDeleteButton\n* @parent ionic.directive:ionItem\n* @module ionic\n* @restrict E\n* Creates a delete button inside a list item, that is visible when the\n* {@link ionic.directive:ionList ionList parent's} `show-delete` evaluates to true or\n* `$ionicListDelegate.showDelete(true)` is called.\n*\n* Takes any ionicon as a class.\n*\n* See {@link ionic.directive:ionList} for a complete example & explanation.\n*\n* @usage\n*\n* ```html\n* <ion-list show-delete=\"shouldShowDelete\">\n*   <ion-item>\n*     <ion-delete-button class=\"ion-minus-circled\"></ion-delete-button>\n*     Hello, list item!\n*   </ion-item>\n* </ion-list>\n* <ion-toggle ng-model=\"shouldShowDelete\">\n*   Show Delete?\n* </ion-toggle>\n* ```\n*/\nIonicModule\n.directive('ionDeleteButton', function() {\n\n  function stopPropagation(ev) {\n    ev.stopPropagation();\n  }\n\n  return {\n    restrict: 'E',\n    require: ['^^ionItem', '^?ionList'],\n    //Run before anything else, so we can move it before other directives process\n    //its location (eg ngIf relies on the location of the directive in the dom)\n    priority: Number.MAX_VALUE,\n    compile: function($element, $attr) {\n      //Add the classes we need during the compile phase, so that they stay\n      //even if something else like ngIf removes the element and re-addss it\n      $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);\n      return function($scope, $element, $attr, ctrls) {\n        var itemCtrl = ctrls[0];\n        var listCtrl = ctrls[1];\n        var container = jqLite(ITEM_TPL_DELETE_BUTTON);\n        container.append($element);\n        itemCtrl.$element.append(container).addClass('item-left-editable');\n\n        //Don't bubble click up to main .item\n        $element.on('click', stopPropagation);\n\n        init();\n        $scope.$on('$ionic.reconnectScope', init);\n        function init() {\n          listCtrl = listCtrl || $element.controller('ionList');\n          if (listCtrl && listCtrl.showDelete()) {\n            container.addClass('visible active');\n          }\n        }\n      };\n    }\n  };\n});\n\n\nIonicModule\n.directive('itemFloatingLabel', function() {\n  return {\n    restrict: 'C',\n    link: function(scope, element) {\n      var el = element[0];\n      var input = el.querySelector('input, textarea');\n      var inputLabel = el.querySelector('.input-label');\n\n      if (!input || !inputLabel) return;\n\n      var onInput = function() {\n        if (input.value) {\n          inputLabel.classList.add('has-input');\n        } else {\n          inputLabel.classList.remove('has-input');\n        }\n      };\n\n      input.addEventListener('input', onInput);\n\n      var ngModelCtrl = jqLite(input).controller('ngModel');\n      if (ngModelCtrl) {\n        ngModelCtrl.$render = function() {\n          input.value = ngModelCtrl.$viewValue || '';\n          onInput();\n        };\n      }\n\n      scope.$on('$destroy', function() {\n        input.removeEventListener('input', onInput);\n      });\n    }\n  };\n});\n\nvar ITEM_TPL_OPTION_BUTTONS =\n  '<div class=\"item-options invisible\">' +\n  '</div>';\n/**\n* @ngdoc directive\n* @name ionOptionButton\n* @parent ionic.directive:ionItem\n* @module ionic\n* @restrict E\n* Creates an option button inside a list item, that is visible when the item is swiped\n* to the left by the user.  Swiped open option buttons can be hidden with\n* {@link ionic.service:$ionicListDelegate#closeOptionButtons $ionicListDelegate#closeOptionButtons}.\n*\n* Can be assigned any button class.\n*\n* See {@link ionic.directive:ionList} for a complete example & explanation.\n*\n* @usage\n*\n* ```html\n* <ion-list>\n*   <ion-item>\n*     I love kittens!\n*     <ion-option-button class=\"button-positive\">Share</ion-option-button>\n*     <ion-option-button class=\"button-assertive\">Edit</ion-option-button>\n*   </ion-item>\n* </ion-list>\n* ```\n*/\nIonicModule.directive('ionOptionButton', [function() {\n  function stopPropagation(e) {\n    e.stopPropagation();\n  }\n  return {\n    restrict: 'E',\n    require: '^ionItem',\n    priority: Number.MAX_VALUE,\n    compile: function($element, $attr) {\n      $attr.$set('class', ($attr['class'] || '') + ' button', true);\n      return function($scope, $element, $attr, itemCtrl) {\n        if (!itemCtrl.optionsContainer) {\n          itemCtrl.optionsContainer = jqLite(ITEM_TPL_OPTION_BUTTONS);\n          itemCtrl.$element.append(itemCtrl.optionsContainer);\n        }\n        itemCtrl.optionsContainer.append($element);\n\n        itemCtrl.$element.addClass('item-right-editable');\n\n        //Don't bubble click up to main .item\n        $element.on('click', stopPropagation);\n      };\n    }\n  };\n}]);\n\nvar ITEM_TPL_REORDER_BUTTON =\n  '<div data-prevent-scroll=\"true\" class=\"item-right-edit item-reorder enable-pointer-events\">' +\n  '</div>';\n\n/**\n* @ngdoc directive\n* @name ionReorderButton\n* @parent ionic.directive:ionItem\n* @module ionic\n* @restrict E\n* Creates a reorder button inside a list item, that is visible when the\n* {@link ionic.directive:ionList ionList parent's} `show-reorder` evaluates to true or\n* `$ionicListDelegate.showReorder(true)` is called.\n*\n* Can be dragged to reorder items in the list. Takes any ionicon class.\n*\n* Note: Reordering works best when used with `ng-repeat`.  Be sure that all `ion-item` children of an `ion-list` are part of the same `ng-repeat` expression.\n*\n* When an item reorder is complete, the expression given in the `on-reorder` attribute is called. The `on-reorder` expression is given two locals that can be used: `$fromIndex` and `$toIndex`.  See below for an example.\n*\n* Look at {@link ionic.directive:ionList} for more examples.\n*\n* @usage\n*\n* ```html\n* <ion-list ng-controller=\"MyCtrl\" show-reorder=\"true\">\n*   <ion-item ng-repeat=\"item in items\">\n*     Item {{item}}\n*     <ion-reorder-button class=\"ion-navicon\"\n*                         on-reorder=\"moveItem(item, $fromIndex, $toIndex)\">\n*     </ion-reorder-button>\n*   </ion-item>\n* </ion-list>\n* ```\n* ```js\n* function MyCtrl($scope) {\n*   $scope.items = [1, 2, 3, 4];\n*   $scope.moveItem = function(item, fromIndex, toIndex) {\n*     //Move the item in the array\n*     $scope.items.splice(fromIndex, 1);\n*     $scope.items.splice(toIndex, 0, item);\n*   };\n* }\n* ```\n*\n* @param {expression=} on-reorder Expression to call when an item is reordered.\n* Parameters given: $fromIndex, $toIndex.\n*/\nIonicModule\n.directive('ionReorderButton', ['$parse', function($parse) {\n  return {\n    restrict: 'E',\n    require: ['^ionItem', '^?ionList'],\n    priority: Number.MAX_VALUE,\n    compile: function($element, $attr) {\n      $attr.$set('class', ($attr['class'] || '') + ' button icon button-icon', true);\n      $element[0].setAttribute('data-prevent-scroll', true);\n      return function($scope, $element, $attr, ctrls) {\n        var itemCtrl = ctrls[0];\n        var listCtrl = ctrls[1];\n        var onReorderFn = $parse($attr.onReorder);\n\n        $scope.$onReorder = function(oldIndex, newIndex) {\n          onReorderFn($scope, {\n            $fromIndex: oldIndex,\n            $toIndex: newIndex\n          });\n        };\n\n        // prevent clicks from bubbling up to the item\n        if (!$attr.ngClick && !$attr.onClick && !$attr.onclick) {\n          $element[0].onclick = function(e) {\n            e.stopPropagation();\n            return false;\n          };\n        }\n\n        var container = jqLite(ITEM_TPL_REORDER_BUTTON);\n        container.append($element);\n        itemCtrl.$element.append(container).addClass('item-right-editable');\n\n        if (listCtrl && listCtrl.showReorder()) {\n          container.addClass('visible active');\n        }\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name keyboardAttach\n * @module ionic\n * @restrict A\n *\n * @description\n * keyboard-attach is an attribute directive which will cause an element to float above\n * the keyboard when the keyboard shows. Currently only supports the\n * [ion-footer-bar]({{ page.versionHref }}/api/directive/ionFooterBar/) directive.\n *\n * ### Notes\n * - This directive requires the\n * [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard).\n * - On Android not in fullscreen mode, i.e. you have\n *   `<preference name=\"Fullscreen\" value=\"false\" />` or no preference in your `config.xml` file,\n *   this directive is unnecessary since it is the default behavior.\n * - On iOS, if there is an input in your footer, you will need to set\n *   `cordova.plugins.Keyboard.disableScroll(true)`.\n *\n * @usage\n *\n * ```html\n *  <ion-footer-bar align-title=\"left\" keyboard-attach class=\"bar-assertive\">\n *    <h1 class=\"title\">Title!</h1>\n *  </ion-footer-bar>\n * ```\n */\n\nIonicModule\n.directive('keyboardAttach', function() {\n  return function(scope, element) {\n    ionic.on('native.keyboardshow', onShow, window);\n    ionic.on('native.keyboardhide', onHide, window);\n\n    //deprecated\n    ionic.on('native.showkeyboard', onShow, window);\n    ionic.on('native.hidekeyboard', onHide, window);\n\n\n    var scrollCtrl;\n\n    function onShow(e) {\n      if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {\n        return;\n      }\n\n      //for testing\n      var keyboardHeight = e.keyboardHeight || e.detail.keyboardHeight;\n      element.css('bottom', keyboardHeight + \"px\");\n      scrollCtrl = element.controller('$ionicScroll');\n      if (scrollCtrl) {\n        scrollCtrl.scrollView.__container.style.bottom = keyboardHeight + keyboardAttachGetClientHeight(element[0]) + \"px\";\n      }\n    }\n\n    function onHide() {\n      if (ionic.Platform.isAndroid() && !ionic.Platform.isFullScreen) {\n        return;\n      }\n\n      element.css('bottom', '');\n      if (scrollCtrl) {\n        scrollCtrl.scrollView.__container.style.bottom = '';\n      }\n    }\n\n    scope.$on('$destroy', function() {\n      ionic.off('native.keyboardshow', onShow, window);\n      ionic.off('native.keyboardhide', onHide, window);\n\n      //deprecated\n      ionic.off('native.showkeyboard', onShow, window);\n      ionic.off('native.hidekeyboard', onHide, window);\n    });\n  };\n});\n\nfunction keyboardAttachGetClientHeight(element) {\n  return element.clientHeight;\n}\n\n/**\n* @ngdoc directive\n* @name ionList\n* @module ionic\n* @delegate ionic.service:$ionicListDelegate\n* @codepen JsHjf\n* @restrict E\n* @description\n* The List is a widely used interface element in almost any mobile app, and can include\n* content ranging from basic text all the way to buttons, toggles, icons, and thumbnails.\n*\n* Both the list, which contains items, and the list items themselves can be any HTML\n* element. The containing element requires the `list` class and each list item requires\n* the `item` class.\n*\n* However, using the ionList and ionItem directives make it easy to support various\n* interaction modes such as swipe to edit, drag to reorder, and removing items.\n*\n* Related: {@link ionic.directive:ionItem}, {@link ionic.directive:ionOptionButton}\n* {@link ionic.directive:ionReorderButton}, {@link ionic.directive:ionDeleteButton}, [`list CSS documentation`](/docs/components/#list).\n*\n* @usage\n*\n* Basic Usage:\n*\n* ```html\n* <ion-list>\n*   <ion-item ng-repeat=\"item in items\">\n*     {% raw %}Hello, {{item}}!{% endraw %}\n*   </ion-item>\n* </ion-list>\n* ```\n*\n* Advanced Usage: Thumbnails, Delete buttons, Reordering, Swiping\n*\n* ```html\n* <ion-list ng-controller=\"MyCtrl\"\n*           show-delete=\"shouldShowDelete\"\n*           show-reorder=\"shouldShowReorder\"\n*           can-swipe=\"listCanSwipe\">\n*   <ion-item ng-repeat=\"item in items\"\n*             class=\"item-thumbnail-left\">\n*\n*     {% raw %}<img ng-src=\"{{item.img}}\">\n*     <h2>{{item.title}}</h2>\n*     <p>{{item.description}}</p>{% endraw %}\n*     <ion-option-button class=\"button-positive\"\n*                        ng-click=\"share(item)\">\n*       Share\n*     </ion-option-button>\n*     <ion-option-button class=\"button-info\"\n*                        ng-click=\"edit(item)\">\n*       Edit\n*     </ion-option-button>\n*     <ion-delete-button class=\"ion-minus-circled\"\n*                        ng-click=\"items.splice($index, 1)\">\n*     </ion-delete-button>\n*     <ion-reorder-button class=\"ion-navicon\"\n*                         on-reorder=\"reorderItem(item, $fromIndex, $toIndex)\">\n*     </ion-reorder-button>\n*\n*   </ion-item>\n* </ion-list>\n* ```\n*\n*```javascript\n* app.controller('MyCtrl', function($scope) {\n*  $scope.shouldShowDelete = false;\n*  $scope.shouldShowReorder = false;\n*  $scope.listCanSwipe = true\n* });\n*```\n*\n* @param {string=} delegate-handle The handle used to identify this list with\n* {@link ionic.service:$ionicListDelegate}.\n* @param type {string=} The type of list to use (list-inset or card)\n* @param show-delete {boolean=} Whether the delete buttons for the items in the list are\n* currently shown or hidden.\n* @param show-reorder {boolean=} Whether the reorder buttons for the items in the list are\n* currently shown or hidden.\n* @param can-swipe {boolean=} Whether the items in the list are allowed to be swiped to reveal\n* option buttons. Default: true.\n*/\nIonicModule\n.directive('ionList', [\n  '$timeout',\nfunction($timeout) {\n  return {\n    restrict: 'E',\n    require: ['ionList', '^?$ionicScroll'],\n    controller: '$ionicList',\n    compile: function($element, $attr) {\n      var listEl = jqLite('<div class=\"list\">')\n        .append($element.contents())\n        .addClass($attr.type);\n\n      $element.append(listEl);\n\n      return function($scope, $element, $attrs, ctrls) {\n        var listCtrl = ctrls[0];\n        var scrollCtrl = ctrls[1];\n\n        // Wait for child elements to render...\n        $timeout(init);\n\n        function init() {\n          var listView = listCtrl.listView = new ionic.views.ListView({\n            el: $element[0],\n            listEl: $element.children()[0],\n            scrollEl: scrollCtrl && scrollCtrl.element,\n            scrollView: scrollCtrl && scrollCtrl.scrollView,\n            onReorder: function(el, oldIndex, newIndex) {\n              var itemScope = jqLite(el).scope();\n              if (itemScope && itemScope.$onReorder) {\n                // Make sure onReorder is called in apply cycle,\n                // but also make sure it has no conflicts by doing\n                // $evalAsync\n                $timeout(function() {\n                  itemScope.$onReorder(oldIndex, newIndex);\n                });\n              }\n            },\n            canSwipe: function() {\n              return listCtrl.canSwipeItems();\n            }\n          });\n\n          $scope.$on('$destroy', function() {\n            if (listView) {\n              listView.deregister && listView.deregister();\n              listView = null;\n            }\n          });\n\n          if (isDefined($attr.canSwipe)) {\n            $scope.$watch('!!(' + $attr.canSwipe + ')', function(value) {\n              listCtrl.canSwipeItems(value);\n            });\n          }\n          if (isDefined($attr.showDelete)) {\n            $scope.$watch('!!(' + $attr.showDelete + ')', function(value) {\n              listCtrl.showDelete(value);\n            });\n          }\n          if (isDefined($attr.showReorder)) {\n            $scope.$watch('!!(' + $attr.showReorder + ')', function(value) {\n              listCtrl.showReorder(value);\n            });\n          }\n\n          $scope.$watch(function() {\n            return listCtrl.showDelete();\n          }, function(isShown, wasShown) {\n            //Only use isShown=false if it was already shown\n            if (!isShown && !wasShown) { return; }\n\n            if (isShown) listCtrl.closeOptionButtons();\n            listCtrl.canSwipeItems(!isShown);\n\n            $element.children().toggleClass('list-left-editing', isShown);\n            $element.toggleClass('disable-pointer-events', isShown);\n\n            var deleteButton = jqLite($element[0].getElementsByClassName('item-delete'));\n            setButtonShown(deleteButton, listCtrl.showDelete);\n          });\n\n          $scope.$watch(function() {\n            return listCtrl.showReorder();\n          }, function(isShown, wasShown) {\n            //Only use isShown=false if it was already shown\n            if (!isShown && !wasShown) { return; }\n\n            if (isShown) listCtrl.closeOptionButtons();\n            listCtrl.canSwipeItems(!isShown);\n\n            $element.children().toggleClass('list-right-editing', isShown);\n            $element.toggleClass('disable-pointer-events', isShown);\n\n            var reorderButton = jqLite($element[0].getElementsByClassName('item-reorder'));\n            setButtonShown(reorderButton, listCtrl.showReorder);\n          });\n\n          function setButtonShown(el, shown) {\n            shown() && el.addClass('visible') || el.removeClass('active');\n            ionic.requestAnimationFrame(function() {\n              shown() && el.addClass('active') || el.removeClass('visible');\n            });\n          }\n        }\n\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name menuClose\n * @module ionic\n * @restrict AC\n *\n * @description\n * `menu-close` is an attribute directive that closes a currently opened side menu.\n * Note that by default, navigation transitions will not animate between views when\n * the menu is open. Additionally, this directive will reset the entering view's\n * history stack, making the new page the root of the history stack. This is done\n * to replicate the user experience seen in most side menu implementations, which is\n * to not show the back button at the root of the stack and show only the\n * menu button. We recommend that you also use the `enable-menu-with-back-views=\"false\"`\n * {@link ionic.directive:ionSideMenus} attribute when using the menuClose directive.\n *\n * @usage\n * Below is an example of a link within a side menu. Tapping this link would\n * automatically close the currently opened menu.\n *\n * ```html\n * <a menu-close href=\"#/home\" class=\"item\">Home</a>\n * ```\n */\nIonicModule\n.directive('menuClose', ['$ionicHistory', function($ionicHistory) {\n  return {\n    restrict: 'AC',\n    link: function($scope, $element) {\n      $element.bind('click', function() {\n        var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');\n        if (sideMenuCtrl) {\n          $ionicHistory.nextViewOptions({\n            historyRoot: true,\n            disableAnimate: true,\n            expire: 300\n          });\n          sideMenuCtrl.close();\n        }\n      });\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name menuToggle\n * @module ionic\n * @restrict AC\n *\n * @description\n * Toggle a side menu on the given side.\n *\n * @usage\n * Below is an example of a link within a nav bar. Tapping this button\n * would open the given side menu, and tapping it again would close it.\n *\n * ```html\n * <ion-nav-bar>\n *   <ion-nav-buttons side=\"left\">\n *    <button menu-toggle=\"left\" class=\"button button-icon icon ion-navicon\"></button>\n *   </ion-nav-buttons>\n * </ion-nav-bar>\n * ```\n *\n * ### Button Hidden On Child Views\n * By default, the menu toggle button will only appear on a root\n * level side-menu page. Navigating in to child views will hide the menu-\n * toggle button. They can be made visible on child pages by setting the\n * enable-menu-with-back-views attribute of the {@link ionic.directive:ionSideMenus}\n * directive to true.\n *\n * ```html\n * <ion-side-menus enable-menu-with-back-views=\"true\">\n * ```\n */\nIonicModule\n.directive('menuToggle', function() {\n  return {\n    restrict: 'AC',\n    link: function($scope, $element, $attr) {\n      $scope.$on('$ionicView.beforeEnter', function(ev, viewData) {\n        if (viewData.enableBack) {\n          var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');\n          if (!sideMenuCtrl.enableMenuWithBackViews()) {\n            $element.addClass('hide');\n          }\n        } else {\n          $element.removeClass('hide');\n        }\n      });\n\n      $element.bind('click', function() {\n        var sideMenuCtrl = $element.inheritedData('$ionSideMenusController');\n        sideMenuCtrl && sideMenuCtrl.toggle($attr.menuToggle);\n      });\n    }\n  };\n});\n\n/*\n * We don't document the ionModal directive, we instead document\n * the $ionicModal service\n */\nIonicModule\n.directive('ionModal', [function() {\n  return {\n    restrict: 'E',\n    transclude: true,\n    replace: true,\n    controller: [function() {}],\n    template: '<div class=\"modal-backdrop\">' +\n                '<div class=\"modal-backdrop-bg\"></div>' +\n                '<div class=\"modal-wrapper\" ng-transclude></div>' +\n              '</div>'\n  };\n}]);\n\nIonicModule\n.directive('ionModalView', function() {\n  return {\n    restrict: 'E',\n    compile: function(element) {\n      element.addClass('modal');\n    }\n  };\n});\n\n/**\n * @ngdoc directive\n * @name ionNavBackButton\n * @module ionic\n * @restrict E\n * @parent ionNavBar\n * @description\n * Creates a back button inside an {@link ionic.directive:ionNavBar}.\n *\n * The back button will appear when the user is able to go back in the current navigation stack. By\n * default, the markup of the back button is automatically built using platform-appropriate defaults\n * (iOS back button icon on iOS and Android icon on Android).\n *\n * Additionally, the button is automatically set to `$ionicGoBack()` on click/tap. By default, the\n * app will navigate back one view when the back button is clicked.  More advanced behavior is also\n * possible, as outlined below.\n *\n * @usage\n *\n * Recommended markup for default settings:\n *\n * ```html\n * <ion-nav-bar>\n *   <ion-nav-back-button>\n *   </ion-nav-back-button>\n * </ion-nav-bar>\n * ```\n *\n * With custom inner markup, and automatically adds a default click action:\n *\n * ```html\n * <ion-nav-bar>\n *   <ion-nav-back-button class=\"button-clear\">\n *     <i class=\"ion-arrow-left-c\"></i> Back\n *   </ion-nav-back-button>\n * </ion-nav-bar>\n * ```\n *\n * With custom inner markup and custom click action, using {@link ionic.service:$ionicHistory}:\n *\n * ```html\n * <ion-nav-bar ng-controller=\"MyCtrl\">\n *   <ion-nav-back-button class=\"button-clear\"\n *     ng-click=\"myGoBack()\">\n *     <i class=\"ion-arrow-left-c\"></i> Back\n *   </ion-nav-back-button>\n * </ion-nav-bar>\n * ```\n * ```js\n * function MyCtrl($scope, $ionicHistory) {\n *   $scope.myGoBack = function() {\n *     $ionicHistory.goBack();\n *   };\n * }\n * ```\n */\nIonicModule\n.directive('ionNavBackButton', ['$ionicConfig', '$document', function($ionicConfig, $document) {\n  return {\n    restrict: 'E',\n    require: '^ionNavBar',\n    compile: function(tElement, tAttrs) {\n\n      // clone the back button, but as a <div>\n      var buttonEle = $document[0].createElement('button');\n      for (var n in tAttrs.$attr) {\n        buttonEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);\n      }\n\n      if (!tAttrs.ngClick) {\n        buttonEle.setAttribute('ng-click', '$ionicGoBack()');\n      }\n\n      buttonEle.className = 'button back-button hide buttons ' + (tElement.attr('class') || '');\n      buttonEle.innerHTML = tElement.html() || '';\n\n      var childNode;\n      var hasIcon = hasIconClass(tElement[0]);\n      var hasInnerText;\n      var hasButtonText;\n      var hasPreviousTitle;\n\n      for (var x = 0; x < tElement[0].childNodes.length; x++) {\n        childNode = tElement[0].childNodes[x];\n        if (childNode.nodeType === 1) {\n          if (hasIconClass(childNode)) {\n            hasIcon = true;\n          } else if (childNode.classList.contains('default-title')) {\n            hasButtonText = true;\n          } else if (childNode.classList.contains('previous-title')) {\n            hasPreviousTitle = true;\n          }\n        } else if (!hasInnerText && childNode.nodeType === 3) {\n          hasInnerText = !!childNode.nodeValue.trim();\n        }\n      }\n\n      function hasIconClass(ele) {\n        return /ion-|icon/.test(ele.className);\n      }\n\n      var defaultIcon = $ionicConfig.backButton.icon();\n      if (!hasIcon && defaultIcon && defaultIcon !== 'none') {\n        buttonEle.innerHTML = '<i class=\"icon ' + defaultIcon + '\"></i> ' + buttonEle.innerHTML;\n        buttonEle.className += ' button-clear';\n      }\n\n      if (!hasInnerText) {\n        var buttonTextEle = $document[0].createElement('span');\n        buttonTextEle.className = 'back-text';\n\n        if (!hasButtonText && $ionicConfig.backButton.text()) {\n          buttonTextEle.innerHTML += '<span class=\"default-title\">' + $ionicConfig.backButton.text() + '</span>';\n        }\n        if (!hasPreviousTitle && $ionicConfig.backButton.previousTitleText()) {\n          buttonTextEle.innerHTML += '<span class=\"previous-title\"></span>';\n        }\n        buttonEle.appendChild(buttonTextEle);\n\n      }\n\n      tElement.attr('class', 'hide');\n      tElement.empty();\n\n      return {\n        pre: function($scope, $element, $attr, navBarCtrl) {\n          // only register the plain HTML, the navBarCtrl takes care of scope/compile/link\n          navBarCtrl.navElement('backButton', buttonEle.outerHTML);\n          buttonEle = null;\n        }\n      };\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @name ionNavBar\n * @module ionic\n * @delegate ionic.service:$ionicNavBarDelegate\n * @restrict E\n *\n * @description\n * If we have an {@link ionic.directive:ionNavView} directive, we can also create an\n * `<ion-nav-bar>`, which will create a topbar that updates as the application state changes.\n *\n * We can add a back button by putting an {@link ionic.directive:ionNavBackButton} inside.\n *\n * We can add buttons depending on the currently visible view using\n * {@link ionic.directive:ionNavButtons}.\n *\n * Note that the ion-nav-bar element will only work correctly if your content has an\n * ionView around it.\n *\n * @usage\n *\n * ```html\n * <body ng-app=\"starter\">\n *   <!-- The nav bar that will be updated as we navigate -->\n *   <ion-nav-bar class=\"bar-positive\">\n *   </ion-nav-bar>\n *\n *   <!-- where the initial view template will be rendered -->\n *   <ion-nav-view>\n *     <ion-view>\n *       <ion-content>Hello!</ion-content>\n *     </ion-view>\n *   </ion-nav-view>\n * </body>\n * ```\n *\n * @param {string=} delegate-handle The handle used to identify this navBar\n * with {@link ionic.service:$ionicNavBarDelegate}.\n * @param align-title {string=} Where to align the title of the navbar.\n * Available: 'left', 'right', 'center'. Defaults to 'center'.\n * @param {boolean=} no-tap-scroll By default, the navbar will scroll the content\n * to the top when tapped.  Set no-tap-scroll to true to disable this behavior.\n *\n * </table><br/>\n */\nIonicModule\n.directive('ionNavBar', function() {\n  return {\n    restrict: 'E',\n    controller: '$ionicNavBar',\n    scope: true,\n    link: function($scope, $element, $attr, ctrl) {\n      ctrl.init();\n    }\n  };\n});\n\n\n/**\n * @ngdoc directive\n * @name ionNavButtons\n * @module ionic\n * @restrict E\n * @parent ionNavView\n *\n * @description\n * Use nav buttons to set the buttons on your {@link ionic.directive:ionNavBar}\n * from within an {@link ionic.directive:ionView}. This gives each\n * view template the ability to specify which buttons should show in the nav bar,\n * overriding any default buttons already placed in the nav bar.\n *\n * Any buttons you declare will be positioned on the navbar's corresponding side. Primary\n * buttons generally map to the left side of the header, and secondary buttons are\n * generally on the right side. However, their exact locations are platform-specific.\n * For example, in iOS, the primary buttons are on the far left of the header, and\n * secondary buttons are on the far right, with the header title centered between them.\n * For Android, however, both groups of buttons are on the far right of the header,\n * with the header title aligned left.\n *\n * We recommend always using `primary` and `secondary`, so the buttons correctly map\n * to the side familiar to users of each platform. However, in cases where buttons should\n * always be on an exact side, both `left` and `right` sides are still available. For\n * example, a toggle button for a left side menu should be on the left side; in this case,\n * we'd recommend using `side=\"left\"`, so it's always on the left, no matter the platform.\n *\n * ***Note*** that `ion-nav-buttons` must be immediate descendants of the `ion-view` or\n * `ion-nav-bar` element (basically, don't wrap it in another div).\n *\n * @usage\n * ```html\n * <ion-nav-bar>\n * </ion-nav-bar>\n * <ion-nav-view>\n *   <ion-view>\n *     <ion-nav-buttons side=\"primary\">\n *       <button class=\"button\" ng-click=\"doSomething()\">\n *         I'm a button on the primary of the navbar!\n *       </button>\n *     </ion-nav-buttons>\n *     <ion-content>\n *       Some super content here!\n *     </ion-content>\n *   </ion-view>\n * </ion-nav-view>\n * ```\n *\n * @param {string} side The side to place the buttons in the\n * {@link ionic.directive:ionNavBar}. Available sides: `primary`, `secondary`, `left`, and `right`.\n */\nIonicModule\n.directive('ionNavButtons', ['$document', function($document) {\n  return {\n    require: '^ionNavBar',\n    restrict: 'E',\n    compile: function(tElement, tAttrs) {\n      var side = 'left';\n\n      if (/^primary|secondary|right$/i.test(tAttrs.side || '')) {\n        side = tAttrs.side.toLowerCase();\n      }\n\n      var spanEle = $document[0].createElement('span');\n      spanEle.className = side + '-buttons';\n      spanEle.innerHTML = tElement.html();\n\n      var navElementType = side + 'Buttons';\n\n      tElement.attr('class', 'hide');\n      tElement.empty();\n\n      return {\n        pre: function($scope, $element, $attrs, navBarCtrl) {\n          // only register the plain HTML, the navBarCtrl takes care of scope/compile/link\n\n          var parentViewCtrl = $element.parent().data('$ionViewController');\n          if (parentViewCtrl) {\n            // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view\n            parentViewCtrl.navElement(navElementType, spanEle.outerHTML);\n\n          } else {\n            // these are buttons for all views that do not have their own ion-nav-buttons\n            navBarCtrl.navElement(navElementType, spanEle.outerHTML);\n          }\n\n          spanEle = null;\n        }\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name navDirection\n * @module ionic\n * @restrict A\n *\n * @description\n * The direction which the nav view transition should animate. Available options\n * are: `forward`, `back`, `enter`, `exit`, `swap`.\n *\n * @usage\n *\n * ```html\n * <a nav-direction=\"forward\" href=\"#/home\">Home</a>\n * ```\n */\nIonicModule\n.directive('navDirection', ['$ionicViewSwitcher', function($ionicViewSwitcher) {\n  return {\n    restrict: 'A',\n    priority: 1000,\n    link: function($scope, $element, $attr) {\n      $element.bind('click', function() {\n        $ionicViewSwitcher.nextDirection($attr.navDirection);\n      });\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionNavTitle\n * @module ionic\n * @restrict E\n * @parent ionNavView\n *\n * @description\n *\n * The nav title directive replaces an {@link ionic.directive:ionNavBar} title text with\n * custom HTML from within an {@link ionic.directive:ionView} template. This gives each\n * view the ability to specify its own custom title element, such as an image or any HTML,\n * rather than being text-only. Alternatively, text-only titles can be updated using the\n * `view-title` {@link ionic.directive:ionView} attribute.\n *\n * Note that `ion-nav-title` must be an immediate descendant of the `ion-view` or\n * `ion-nav-bar` element (basically don't wrap it in another div).\n *\n * @usage\n * ```html\n * <ion-nav-bar>\n * </ion-nav-bar>\n * <ion-nav-view>\n *   <ion-view>\n *     <ion-nav-title>\n *       <img src=\"logo.svg\">\n *     </ion-nav-title>\n *     <ion-content>\n *       Some super content here!\n *     </ion-content>\n *   </ion-view>\n * </ion-nav-view>\n * ```\n *\n */\nIonicModule\n.directive('ionNavTitle', ['$document', function($document) {\n  return {\n    require: '^ionNavBar',\n    restrict: 'E',\n    compile: function(tElement, tAttrs) {\n      var navElementType = 'title';\n      var spanEle = $document[0].createElement('span');\n      for (var n in tAttrs.$attr) {\n        spanEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);\n      }\n      spanEle.classList.add('nav-bar-title');\n      spanEle.innerHTML = tElement.html();\n\n      tElement.attr('class', 'hide');\n      tElement.empty();\n\n      return {\n        pre: function($scope, $element, $attrs, navBarCtrl) {\n          // only register the plain HTML, the navBarCtrl takes care of scope/compile/link\n\n          var parentViewCtrl = $element.parent().data('$ionViewController');\n          if (parentViewCtrl) {\n            // if the parent is an ion-view, then these are ion-nav-buttons for JUST this ion-view\n            parentViewCtrl.navElement(navElementType, spanEle.outerHTML);\n\n          } else {\n            // these are buttons for all views that do not have their own ion-nav-buttons\n            navBarCtrl.navElement(navElementType, spanEle.outerHTML);\n          }\n\n          spanEle = null;\n        }\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name navTransition\n * @module ionic\n * @restrict A\n *\n * @description\n * The transition type which the nav view transition should use when it animates.\n * Current, options are `ios`, `android`, and `none`. More options coming soon.\n *\n * @usage\n *\n * ```html\n * <a nav-transition=\"none\" href=\"#/home\">Home</a>\n * ```\n */\nIonicModule\n.directive('navTransition', ['$ionicViewSwitcher', function($ionicViewSwitcher) {\n  return {\n    restrict: 'A',\n    priority: 1000,\n    link: function($scope, $element, $attr) {\n      $element.bind('click', function() {\n        $ionicViewSwitcher.nextTransition($attr.navTransition);\n      });\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionNavView\n * @module ionic\n * @restrict E\n * @codepen odqCz\n *\n * @description\n * As a user navigates throughout your app, Ionic is able to keep track of their\n * navigation history. By knowing their history, transitions between views\n * correctly enter and exit using the platform's transition style. An additional\n * benefit to Ionic's navigation system is its ability to manage multiple\n * histories. For example, each tab can have it's own navigation history stack.\n *\n * Ionic uses the AngularUI Router module so app interfaces can be organized\n * into various \"states\". Like Angular's core $route service, URLs can be used\n * to control the views. However, the AngularUI Router provides a more powerful\n * state manager in that states are bound to named, nested, and parallel views,\n * allowing more than one template to be rendered on the same page.\n * Additionally, each state is not required to be bound to a URL, and data can\n * be pushed to each state which allows much flexibility.\n *\n * The ionNavView directive is used to render templates in your application. Each template\n * is part of a state. States are usually mapped to a url, and are defined programatically\n * using angular-ui-router (see [their docs](https://github.com/angular-ui/ui-router/wiki),\n * and remember to replace ui-view with ion-nav-view in examples).\n *\n * @usage\n * In this example, we will create a navigation view that contains our different states for the app.\n *\n * To do this, in our markup we use ionNavView top level directive. To display a header bar we use\n * the {@link ionic.directive:ionNavBar} directive that updates as we navigate through the\n * navigation stack.\n *\n * Next, we need to setup our states that will be rendered.\n *\n * ```js\n * var app = angular.module('myApp', ['ionic']);\n * app.config(function($stateProvider) {\n *   $stateProvider\n *   .state('index', {\n *     url: '/',\n *     templateUrl: 'home.html'\n *   })\n *   .state('music', {\n *     url: '/music',\n *     templateUrl: 'music.html'\n *   });\n * });\n * ```\n * Then on app start, $stateProvider will look at the url, see it matches the index state,\n * and then try to load home.html into the `<ion-nav-view>`.\n *\n * Pages are loaded by the URLs given. One simple way to create templates in Angular is to put\n * them directly into your HTML file and use the `<script type=\"text/ng-template\">` syntax.\n * So here is one way to put home.html into our app:\n *\n * ```html\n * <script id=\"home\" type=\"text/ng-template\">\n *   <!-- The title of the ion-view will be shown on the navbar -->\n *   <ion-view view-title=\"Home\">\n *     <ion-content ng-controller=\"HomeCtrl\">\n *       <!-- The content of the page -->\n *       <a href=\"#/music\">Go to music page!</a>\n *     </ion-content>\n *   </ion-view>\n * </script>\n * ```\n *\n * This is good to do because the template will be cached for very fast loading, instead of\n * having to fetch them from the network.\n *\n * ## Caching\n *\n * By default, views are cached to improve performance. When a view is navigated away from, its\n * element is left in the DOM, and its scope is disconnected from the `$watch` cycle. When\n * navigating to a view that is already cached, its scope is then reconnected, and the existing\n * element that was left in the DOM becomes the active view. This also allows for the scroll\n * position of previous views to be maintained.\n *\n * Caching can be disabled and enabled in multiple ways. By default, Ionic will cache a maximum of\n * 10 views, and not only can this be configured, but apps can also explicitly state which views\n * should and should not be cached.\n *\n * Note that because we are caching these views, *we aren’t destroying scopes*. Instead, scopes\n * are being disconnected from the watch cycle. Because scopes are not being destroyed and\n * recreated, controllers are not loading again on a subsequent viewing. If the app/controller\n * needs to know when a view has entered or has left, then view events emitted from the\n * {@link ionic.directive:ionView} scope, such as `$ionicView.enter`, may be useful.\n *\n * By default, when navigating back in the history, the \"forward\" views are removed from the cache.\n * If you navigate forward to the same view again, it'll create a new DOM element and controller\n * instance. Basically, any forward views are reset each time. This can be configured using the\n * {@link ionic.provider:$ionicConfigProvider}:\n *\n * ```js\n * $ionicConfigProvider.views.forwardCache(true);\n * ```\n *\n * #### Disable cache globally\n *\n * The {@link ionic.provider:$ionicConfigProvider} can be used to set the maximum allowable views\n * which can be cached, but this can also be use to disable all caching by setting it to 0.\n *\n * ```js\n * $ionicConfigProvider.views.maxCache(0);\n * ```\n *\n * #### Disable cache within state provider\n *\n * ```js\n * $stateProvider.state('myState', {\n *    cache: false,\n *    url : '/myUrl',\n *    templateUrl : 'my-template.html'\n * })\n * ```\n *\n * #### Disable cache with an attribute\n *\n * ```html\n * <ion-view cache-view=\"false\" view-title=\"My Title!\">\n *   ...\n * </ion-view>\n * ```\n *\n *\n * ## AngularUI Router\n *\n * Please visit [AngularUI Router's docs](https://github.com/angular-ui/ui-router/wiki) for\n * more info. Below is a great video by the AngularUI Router team that may help to explain\n * how it all works:\n *\n * <iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/dqJRoh8MnBo\"\n * frameborder=\"0\" allowfullscreen></iframe>\n *\n * @param {string=} name A view name. The name should be unique amongst the other views in the\n * same state. You can have views of the same name that live in different states. For more\n * information, see ui-router's\n * [ui-view documentation](http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.directive:ui-view).\n */\nIonicModule\n.directive('ionNavView', [\n  '$state',\n  '$ionicConfig',\nfunction($state, $ionicConfig) {\n  // IONIC's fork of Angular UI Router, v0.2.10\n  // the navView handles registering views in the history and how to transition between them\n  return {\n    restrict: 'E',\n    terminal: true,\n    priority: 2000,\n    transclude: true,\n    controller: '$ionicNavView',\n    compile: function(tElement, tAttrs, transclude) {\n\n      // a nav view element is a container for numerous views\n      tElement.addClass('view-container');\n      ionic.DomUtil.cachedAttr(tElement, 'nav-view-transition', $ionicConfig.views.transition());\n\n      return function($scope, $element, $attr, navViewCtrl) {\n        var latestLocals;\n\n        // Put in the compiled initial view\n        transclude($scope, function(clone) {\n          $element.append(clone);\n        });\n\n        var viewData = navViewCtrl.init();\n\n        // listen for $stateChangeSuccess\n        $scope.$on('$stateChangeSuccess', function() {\n          updateView(false);\n        });\n        $scope.$on('$viewContentLoading', function() {\n          updateView(false);\n        });\n\n        // initial load, ready go\n        updateView(true);\n\n\n        function updateView(firstTime) {\n          // get the current local according to the $state\n          var viewLocals = $state.$current && $state.$current.locals[viewData.name];\n\n          // do not update THIS nav-view if its is not the container for the given state\n          // if the viewLocals are the same as THIS latestLocals, then nothing to do\n          if (!viewLocals || (!firstTime && viewLocals === latestLocals)) return;\n\n          // update the latestLocals\n          latestLocals = viewLocals;\n          viewData.state = viewLocals.$$state;\n\n          // register, update and transition to the new view\n          navViewCtrl.register(viewLocals);\n        }\n\n      };\n    }\n  };\n}]);\n\nIonicModule\n\n.config(['$provide', function($provide) {\n  $provide.decorator('ngClickDirective', ['$delegate', function($delegate) {\n    // drop the default ngClick directive\n    $delegate.shift();\n    return $delegate;\n  }]);\n}])\n\n/**\n * @private\n */\n.factory('$ionicNgClick', ['$parse', function($parse) {\n  return function(scope, element, clickExpr) {\n    var clickHandler = angular.isFunction(clickExpr) ?\n      clickExpr :\n      $parse(clickExpr);\n\n    element.on('click', function(event) {\n      scope.$apply(function() {\n        clickHandler(scope, {$event: (event)});\n      });\n    });\n\n    // Hack for iOS Safari's benefit. It goes searching for onclick handlers and is liable to click\n    // something else nearby.\n    element.onclick = noop;\n  };\n}])\n\n.directive('ngClick', ['$ionicNgClick', function($ionicNgClick) {\n  return function(scope, element, attr) {\n    $ionicNgClick(scope, element, attr.ngClick);\n  };\n}])\n\n.directive('ionStopEvent', function() {\n  return {\n    restrict: 'A',\n    link: function(scope, element, attr) {\n      element.bind(attr.ionStopEvent, eventStopPropagation);\n    }\n  };\n});\nfunction eventStopPropagation(e) {\n  e.stopPropagation();\n}\n\n\n/**\n * @ngdoc directive\n * @name ionPane\n * @module ionic\n * @restrict E\n *\n * @description A simple container that fits content, with no side effects.  Adds the 'pane' class to the element.\n */\nIonicModule\n.directive('ionPane', function() {\n  return {\n    restrict: 'E',\n    link: function(scope, element) {\n      element.addClass('pane');\n    }\n  };\n});\n\n/*\n * We don't document the ionPopover directive, we instead document\n * the $ionicPopover service\n */\nIonicModule\n.directive('ionPopover', [function() {\n  return {\n    restrict: 'E',\n    transclude: true,\n    replace: true,\n    controller: [function() {}],\n    template: '<div class=\"popover-backdrop\">' +\n                '<div class=\"popover-wrapper\" ng-transclude></div>' +\n              '</div>'\n  };\n}]);\n\nIonicModule\n.directive('ionPopoverView', function() {\n  return {\n    restrict: 'E',\n    compile: function(element) {\n      element.append(jqLite('<div class=\"popover-arrow\">'));\n      element.addClass('popover');\n    }\n  };\n});\n\n/**\n * @ngdoc directive\n * @name ionRadio\n * @module ionic\n * @restrict E\n * @codepen saoBG\n * @description\n * The radio directive is no different than the HTML radio input, except it's styled differently.\n *\n * Radio behaves like any [AngularJS radio](http://docs.angularjs.org/api/ng/input/input[radio]).\n *\n * @usage\n * ```html\n * <ion-radio ng-model=\"choice\" ng-value=\"'A'\">Choose A</ion-radio>\n * <ion-radio ng-model=\"choice\" ng-value=\"'B'\">Choose B</ion-radio>\n * <ion-radio ng-model=\"choice\" ng-value=\"'C'\">Choose C</ion-radio>\n * ```\n *\n * @param {string=} name The name of the radio input.\n * @param {expression=} value The value of the radio input.\n * @param {boolean=} disabled The state of the radio input.\n * @param {string=} icon The icon to use when the radio input is selected.\n * @param {expression=} ng-value Angular equivalent of the value attribute.\n * @param {expression=} ng-model The angular model for the radio input.\n * @param {boolean=} ng-disabled Angular equivalent of the disabled attribute.\n * @param {expression=} ng-change Triggers given expression when radio input's model changes\n */\nIonicModule\n.directive('ionRadio', function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '?ngModel',\n    transclude: true,\n    template:\n      '<label class=\"item item-radio\">' +\n        '<input type=\"radio\" name=\"radio-group\">' +\n        '<div class=\"item-content disable-pointer-events\" ng-transclude></div>' +\n        '<i class=\"radio-icon disable-pointer-events icon ion-checkmark\"></i>' +\n      '</label>',\n\n    compile: function(element, attr) {\n      if (attr.icon) {\n        element.children().eq(2).removeClass('ion-checkmark').addClass(attr.icon);\n      }\n\n      var input = element.find('input');\n      forEach({\n          'name': attr.name,\n          'value': attr.value,\n          'disabled': attr.disabled,\n          'ng-value': attr.ngValue,\n          'ng-model': attr.ngModel,\n          'ng-disabled': attr.ngDisabled,\n          'ng-change': attr.ngChange,\n          'ng-required': attr.ngRequired,\n          'required': attr.required\n      }, function(value, name) {\n        if (isDefined(value)) {\n            input.attr(name, value);\n          }\n      });\n\n      return function(scope, element, attr) {\n        scope.getValue = function() {\n          return scope.ngValue || attr.value;\n        };\n      };\n    }\n  };\n});\n\n\n/**\n * @ngdoc directive\n * @name ionRefresher\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionContent, ionic.directive:ionScroll\n * @description\n * Allows you to add pull-to-refresh to a scrollView.\n *\n * Place it as the first child of your {@link ionic.directive:ionContent} or\n * {@link ionic.directive:ionScroll} element.\n *\n * When refreshing is complete, $broadcast the 'scroll.refreshComplete' event\n * from your controller.\n *\n * @usage\n *\n * ```html\n * <ion-content ng-controller=\"MyController\">\n *   <ion-refresher\n *     pulling-text=\"Pull to refresh...\"\n *     on-refresh=\"doRefresh()\">\n *   </ion-refresher>\n *   <ion-list>\n *     <ion-item ng-repeat=\"item in items\"></ion-item>\n *   </ion-list>\n * </ion-content>\n * ```\n * ```js\n * angular.module('testApp', ['ionic'])\n * .controller('MyController', function($scope, $http) {\n *   $scope.items = [1,2,3];\n *   $scope.doRefresh = function() {\n *     $http.get('/new-items')\n *      .success(function(newItems) {\n *        $scope.items = newItems;\n *      })\n *      .finally(function() {\n *        // Stop the ion-refresher from spinning\n *        $scope.$broadcast('scroll.refreshComplete');\n *      });\n *   };\n * });\n * ```\n *\n * @param {expression=} on-refresh Called when the user pulls down enough and lets go\n * of the refresher.\n * @param {expression=} on-pulling Called when the user starts to pull down\n * on the refresher.\n * @param {string=} pulling-text The text to display while the user is pulling down.\n * @param {string=} pulling-icon The icon to display while the user is pulling down.\n * Default: 'ion-android-arrow-down'.\n * @param {string=} spinner The {@link ionic.directive:ionSpinner} icon to display\n * after user lets go of the refresher. The SVG {@link ionic.directive:ionSpinner}\n * is now the default, replacing rotating font icons. Set to `none` to disable both the\n * spinner and the icon.\n * @param {string=} refreshing-icon The font icon to display after user lets go of the\n * refresher. This is depreicated in favor of the SVG {@link ionic.directive:ionSpinner}.\n * @param {boolean=} disable-pulling-rotation Disables the rotation animation of the pulling\n * icon when it reaches its activated threshold. To be used with a custom `pulling-icon`.\n *\n */\nIonicModule\n.directive('ionRefresher', [function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: ['?^$ionicScroll', 'ionRefresher'],\n    controller: '$ionicRefresher',\n    template:\n    '<div class=\"scroll-refresher invisible\" collection-repeat-ignore>' +\n      '<div class=\"ionic-refresher-content\" ' +\n      'ng-class=\"{\\'ionic-refresher-with-text\\': pullingText || refreshingText}\">' +\n        '<div class=\"icon-pulling\" ng-class=\"{\\'pulling-rotation-disabled\\':disablePullingRotation}\">' +\n          '<i class=\"icon {{pullingIcon}}\"></i>' +\n        '</div>' +\n        '<div class=\"text-pulling\" ng-bind-html=\"pullingText\"></div>' +\n        '<div class=\"icon-refreshing\">' +\n          '<ion-spinner ng-if=\"showSpinner\" icon=\"{{spinner}}\"></ion-spinner>' +\n          '<i ng-if=\"showIcon\" class=\"icon {{refreshingIcon}}\"></i>' +\n        '</div>' +\n        '<div class=\"text-refreshing\" ng-bind-html=\"refreshingText\"></div>' +\n      '</div>' +\n    '</div>',\n    link: function($scope, $element, $attrs, ctrls) {\n\n      // JS Scrolling uses the scroll controller\n      var scrollCtrl = ctrls[0],\n          refresherCtrl = ctrls[1];\n      if (!scrollCtrl || scrollCtrl.isNative()) {\n        // Kick off native scrolling\n        refresherCtrl.init();\n      } else {\n        $element[0].classList.add('js-scrolling');\n        scrollCtrl._setRefresher(\n          $scope,\n          $element[0],\n          refresherCtrl.getRefresherDomMethods()\n        );\n\n        $scope.$on('scroll.refreshComplete', function() {\n          $scope.$evalAsync(function() {\n            scrollCtrl.scrollView.finishPullToRefresh();\n          });\n        });\n      }\n\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionScroll\n * @module ionic\n * @delegate ionic.service:$ionicScrollDelegate\n * @codepen mwFuh\n * @restrict E\n *\n * @description\n * Creates a scrollable container for all content inside.\n *\n * @usage\n *\n * Basic usage:\n *\n * ```html\n * <ion-scroll zooming=\"true\" direction=\"xy\" style=\"width: 500px; height: 500px\">\n *   <div style=\"width: 5000px; height: 5000px; background: url('https://upload.wikimedia.org/wikipedia/commons/a/ad/Europe_geological_map-en.jpg') repeat\"></div>\n *  </ion-scroll>\n * ```\n *\n * Note that it's important to set the height of the scroll box as well as the height of the inner\n * content to enable scrolling. This makes it possible to have full control over scrollable areas.\n *\n * If you'd just like to have a center content scrolling area, use {@link ionic.directive:ionContent} instead.\n *\n * @param {string=} delegate-handle The handle used to identify this scrollView\n * with {@link ionic.service:$ionicScrollDelegate}.\n * @param {string=} direction Which way to scroll. 'x' or 'y' or 'xy'. Default 'y'.\n * @param {boolean=} locking Whether to lock scrolling in one direction at a time. Useful to set to false when zoomed in or scrolling in two directions. Default true.\n * @param {boolean=} paging Whether to scroll with paging.\n * @param {expression=} on-refresh Called on pull-to-refresh, triggered by an {@link ionic.directive:ionRefresher}.\n * @param {expression=} on-scroll Called whenever the user scrolls.\n * @param {boolean=} scrollbar-x Whether to show the horizontal scrollbar. Default true.\n * @param {boolean=} scrollbar-y Whether to show the vertical scrollbar. Default true.\n * @param {boolean=} zooming Whether to support pinch-to-zoom\n * @param {integer=} min-zoom The smallest zoom amount allowed (default is 0.5)\n * @param {integer=} max-zoom The largest zoom amount allowed (default is 3)\n * @param {boolean=} has-bouncing Whether to allow scrolling to bounce past the edges\n * of the content.  Defaults to true on iOS, false on Android.\n */\nIonicModule\n.directive('ionScroll', [\n  '$timeout',\n  '$controller',\n  '$ionicBind',\nfunction($timeout, $controller, $ionicBind) {\n  return {\n    restrict: 'E',\n    scope: true,\n    controller: function() {},\n    compile: function(element) {\n      element.addClass('scroll-view ionic-scroll');\n\n      //We cannot transclude here because it breaks element.data() inheritance on compile\n      var innerElement = jqLite('<div class=\"scroll\"></div>');\n      innerElement.append(element.contents());\n      element.append(innerElement);\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attr) {\n        $ionicBind($scope, $attr, {\n          direction: '@',\n          paging: '@',\n          $onScroll: '&onScroll',\n          scroll: '@',\n          scrollbarX: '@',\n          scrollbarY: '@',\n          zooming: '@',\n          minZoom: '@',\n          maxZoom: '@'\n        });\n        $scope.direction = $scope.direction || 'y';\n\n        if (isDefined($attr.padding)) {\n          $scope.$watch($attr.padding, function(newVal) {\n            innerElement.toggleClass('padding', !!newVal);\n          });\n        }\n        if ($scope.$eval($scope.paging) === true) {\n          innerElement.addClass('scroll-paging');\n        }\n\n        if (!$scope.direction) { $scope.direction = 'y'; }\n        var isPaging = $scope.$eval($scope.paging) === true;\n\n        var scrollViewOptions = {\n          el: $element[0],\n          delegateHandle: $attr.delegateHandle,\n          locking: ($attr.locking || 'true') === 'true',\n          bouncing: $scope.$eval($attr.hasBouncing),\n          paging: isPaging,\n          scrollbarX: $scope.$eval($scope.scrollbarX) !== false,\n          scrollbarY: $scope.$eval($scope.scrollbarY) !== false,\n          scrollingX: $scope.direction.indexOf('x') >= 0,\n          scrollingY: $scope.direction.indexOf('y') >= 0,\n          zooming: $scope.$eval($scope.zooming) === true,\n          maxZoom: $scope.$eval($scope.maxZoom) || 3,\n          minZoom: $scope.$eval($scope.minZoom) || 0.5,\n          preventDefault: true\n        };\n        if (isPaging) {\n          scrollViewOptions.speedMultiplier = 0.8;\n          scrollViewOptions.bouncing = false;\n        }\n\n        $controller('$ionicScroll', {\n          $scope: $scope,\n          scrollViewOptions: scrollViewOptions\n        });\n      }\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionSideMenu\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionSideMenus\n *\n * @description\n * A container for a side menu, sibling to an {@link ionic.directive:ionSideMenuContent} directive.\n *\n * @usage\n * ```html\n * <ion-side-menu\n *   side=\"left\"\n *   width=\"myWidthValue + 20\"\n *   is-enabled=\"shouldLeftSideMenuBeEnabled()\">\n * </ion-side-menu>\n * ```\n * For a complete side menu example, see the\n * {@link ionic.directive:ionSideMenus} documentation.\n *\n * @param {string} side Which side the side menu is currently on.  Allowed values: 'left' or 'right'.\n * @param {boolean=} is-enabled Whether this side menu is enabled.\n * @param {number=} width How many pixels wide the side menu should be.  Defaults to 275.\n */\nIonicModule\n.directive('ionSideMenu', function() {\n  return {\n    restrict: 'E',\n    require: '^ionSideMenus',\n    scope: true,\n    compile: function(element, attr) {\n      angular.isUndefined(attr.isEnabled) && attr.$set('isEnabled', 'true');\n      angular.isUndefined(attr.width) && attr.$set('width', '275');\n\n      element.addClass('menu menu-' + attr.side);\n\n      return function($scope, $element, $attr, sideMenuCtrl) {\n        $scope.side = $attr.side || 'left';\n\n        var sideMenu = sideMenuCtrl[$scope.side] = new ionic.views.SideMenu({\n          width: attr.width,\n          el: $element[0],\n          isEnabled: true\n        });\n\n        $scope.$watch($attr.width, function(val) {\n          var numberVal = +val;\n          if (numberVal && numberVal == val) {\n            sideMenu.setWidth(+val);\n          }\n        });\n        $scope.$watch($attr.isEnabled, function(val) {\n          sideMenu.setIsEnabled(!!val);\n        });\n      };\n    }\n  };\n});\n\n\n/**\n * @ngdoc directive\n * @name ionSideMenuContent\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionSideMenus\n *\n * @description\n * A container for the main visible content, sibling to one or more\n * {@link ionic.directive:ionSideMenu} directives.\n *\n * @usage\n * ```html\n * <ion-side-menu-content\n *   edge-drag-threshold=\"true\"\n *   drag-content=\"true\">\n * </ion-side-menu-content>\n * ```\n * For a complete side menu example, see the\n * {@link ionic.directive:ionSideMenus} documentation.\n *\n * @param {boolean=} drag-content Whether the content can be dragged. Default true.\n * @param {boolean|number=} edge-drag-threshold Whether the content drag can only start if it is below a certain threshold distance from the edge of the screen.  Default false. Accepts three types of values:\n   *  - If a non-zero number is given, that many pixels is used as the maximum allowed distance from the edge that starts dragging the side menu.\n   *  - If true is given, the default number of pixels (25) is used as the maximum allowed distance.\n   *  - If false or 0 is given, the edge drag threshold is disabled, and dragging from anywhere on the content is allowed.\n *\n */\nIonicModule\n.directive('ionSideMenuContent', [\n  '$timeout',\n  '$ionicGesture',\n  '$window',\nfunction($timeout, $ionicGesture, $window) {\n\n  return {\n    restrict: 'EA', //DEPRECATED 'A'\n    require: '^ionSideMenus',\n    scope: true,\n    compile: function(element, attr) {\n      element.addClass('menu-content pane');\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attr, sideMenuCtrl) {\n        var startCoord = null;\n        var primaryScrollAxis = null;\n\n        if (isDefined(attr.dragContent)) {\n          $scope.$watch(attr.dragContent, function(value) {\n            sideMenuCtrl.canDragContent(value);\n          });\n        } else {\n          sideMenuCtrl.canDragContent(true);\n        }\n\n        if (isDefined(attr.edgeDragThreshold)) {\n          $scope.$watch(attr.edgeDragThreshold, function(value) {\n            sideMenuCtrl.edgeDragThreshold(value);\n          });\n        }\n\n        // Listen for taps on the content to close the menu\n        function onContentTap(gestureEvt) {\n          if (sideMenuCtrl.getOpenAmount() !== 0) {\n            sideMenuCtrl.close();\n            gestureEvt.gesture.srcEvent.preventDefault();\n            startCoord = null;\n            primaryScrollAxis = null;\n          } else if (!startCoord) {\n            startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);\n          }\n        }\n\n        function onDragX(e) {\n          if (!sideMenuCtrl.isDraggableTarget(e)) return;\n\n          if (getPrimaryScrollAxis(e) == 'x') {\n            sideMenuCtrl._handleDrag(e);\n            e.gesture.srcEvent.preventDefault();\n          }\n        }\n\n        function onDragY(e) {\n          if (getPrimaryScrollAxis(e) == 'x') {\n            e.gesture.srcEvent.preventDefault();\n          }\n        }\n\n        function onDragRelease(e) {\n          sideMenuCtrl._endDrag(e);\n          startCoord = null;\n          primaryScrollAxis = null;\n        }\n\n        function getPrimaryScrollAxis(gestureEvt) {\n          // gets whether the user is primarily scrolling on the X or Y\n          // If a majority of the drag has been on the Y since the start of\n          // the drag, but the X has moved a little bit, it's still a Y drag\n\n          if (primaryScrollAxis) {\n            // we already figured out which way they're scrolling\n            return primaryScrollAxis;\n          }\n\n          if (gestureEvt && gestureEvt.gesture) {\n\n            if (!startCoord) {\n              // get the starting point\n              startCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);\n\n            } else {\n              // we already have a starting point, figure out which direction they're going\n              var endCoord = ionic.tap.pointerCoord(gestureEvt.gesture.srcEvent);\n\n              var xDistance = Math.abs(endCoord.x - startCoord.x);\n              var yDistance = Math.abs(endCoord.y - startCoord.y);\n\n              var scrollAxis = (xDistance < yDistance ? 'y' : 'x');\n\n              if (Math.max(xDistance, yDistance) > 30) {\n                // ok, we pretty much know which way they're going\n                // let's lock it in\n                primaryScrollAxis = scrollAxis;\n              }\n\n              return scrollAxis;\n            }\n          }\n          return 'y';\n        }\n\n        var content = {\n          element: element[0],\n          onDrag: function() {},\n          endDrag: function() {},\n          getTranslateX: function() {\n            return $scope.sideMenuContentTranslateX || 0;\n          },\n          setTranslateX: ionic.animationFrameThrottle(function(amount) {\n            var xTransform = content.offsetX + amount;\n            $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + xTransform + 'px,0,0)';\n            $timeout(function() {\n              $scope.sideMenuContentTranslateX = amount;\n            });\n          }),\n          setMarginLeft: ionic.animationFrameThrottle(function(amount) {\n            if (amount) {\n              amount = parseInt(amount, 10);\n              $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(' + amount + 'px,0,0)';\n              $element[0].style.width = ($window.innerWidth - amount) + 'px';\n              content.offsetX = amount;\n            } else {\n              $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';\n              $element[0].style.width = '';\n              content.offsetX = 0;\n            }\n          }),\n          setMarginRight: ionic.animationFrameThrottle(function(amount) {\n            if (amount) {\n              amount = parseInt(amount, 10);\n              $element[0].style.width = ($window.innerWidth - amount) + 'px';\n              content.offsetX = amount;\n            } else {\n              $element[0].style.width = '';\n              content.offsetX = 0;\n            }\n            // reset incase left gets grabby\n            $element[0].style[ionic.CSS.TRANSFORM] = 'translate3d(0,0,0)';\n          }),\n          enableAnimation: function() {\n            $scope.animationEnabled = true;\n            $element[0].classList.add('menu-animated');\n          },\n          disableAnimation: function() {\n            $scope.animationEnabled = false;\n            $element[0].classList.remove('menu-animated');\n          },\n          offsetX: 0\n        };\n\n        sideMenuCtrl.setContent(content);\n\n        // add gesture handlers\n        var gestureOpts = { stop_browser_behavior: false };\n        if (ionic.DomUtil.getParentOrSelfWithClass($element[0], 'overflow-scroll')) {\n          gestureOpts.prevent_default_directions = ['left', 'right'];\n        }\n        var contentTapGesture = $ionicGesture.on('tap', onContentTap, $element, gestureOpts);\n        var dragRightGesture = $ionicGesture.on('dragright', onDragX, $element, gestureOpts);\n        var dragLeftGesture = $ionicGesture.on('dragleft', onDragX, $element, gestureOpts);\n        var dragUpGesture = $ionicGesture.on('dragup', onDragY, $element, gestureOpts);\n        var dragDownGesture = $ionicGesture.on('dragdown', onDragY, $element, gestureOpts);\n        var releaseGesture = $ionicGesture.on('release', onDragRelease, $element, gestureOpts);\n\n        // Cleanup\n        $scope.$on('$destroy', function() {\n          if (content) {\n            content.element = null;\n            content = null;\n          }\n          $ionicGesture.off(dragLeftGesture, 'dragleft', onDragX);\n          $ionicGesture.off(dragRightGesture, 'dragright', onDragX);\n          $ionicGesture.off(dragUpGesture, 'dragup', onDragY);\n          $ionicGesture.off(dragDownGesture, 'dragdown', onDragY);\n          $ionicGesture.off(releaseGesture, 'release', onDragRelease);\n          $ionicGesture.off(contentTapGesture, 'tap', onContentTap);\n        });\n      }\n    }\n  };\n}]);\n\nIonicModule\n\n/**\n * @ngdoc directive\n * @name ionSideMenus\n * @module ionic\n * @delegate ionic.service:$ionicSideMenuDelegate\n * @restrict E\n *\n * @description\n * A container element for side menu(s) and the main content. Allows the left and/or right side menu\n * to be toggled by dragging the main content area side to side.\n *\n * To automatically close an opened menu, you can add the {@link ionic.directive:menuClose} attribute\n * directive. The `menu-close` attribute is usually added to links and buttons within\n * `ion-side-menu-content`, so that when the element is clicked, the opened side menu will\n * automatically close.\n *\n * \"Burger Icon\" toggles can be added to the header with the {@link ionic.directive:menuToggle}\n * attribute directive. Clicking the toggle will open and close the side menu like the `menu-close`\n * directive. The side menu will automatically hide on child pages, but can be overridden with the\n * enable-menu-with-back-views attribute mentioned below.\n *\n * By default, side menus are hidden underneath their side menu content and can be opened by swiping\n * the content left or right or by toggling a button to show the side menu. Additionally, by adding the\n * {@link ionic.directive:exposeAsideWhen} attribute directive to an\n * {@link ionic.directive:ionSideMenu} element directive, a side menu can be given instructions about\n * \"when\" the menu should be exposed (always viewable).\n *\n * ![Side Menu](http://ionicframework.com.s3.amazonaws.com/docs/controllers/sidemenu.gif)\n *\n * For more information on side menus, check out:\n *\n * - {@link ionic.directive:ionSideMenuContent}\n * - {@link ionic.directive:ionSideMenu}\n * - {@link ionic.directive:menuToggle}\n * - {@link ionic.directive:menuClose}\n * - {@link ionic.directive:exposeAsideWhen}\n *\n * @usage\n * To use side menus, add an `<ion-side-menus>` parent element. This will encompass all pages that have a\n * side menu, and have at least 2 child elements: 1 `<ion-side-menu-content>` for the center content,\n * and one or more `<ion-side-menu>` directives for each side menu(left/right) that you wish to place.\n *\n * ```html\n * <ion-side-menus>\n *   <!-- Center content -->\n *   <ion-side-menu-content ng-controller=\"ContentController\">\n *   </ion-side-menu-content>\n *\n *   <!-- Left menu -->\n *   <ion-side-menu side=\"left\">\n *   </ion-side-menu>\n *\n *   <!-- Right menu -->\n *   <ion-side-menu side=\"right\">\n *   </ion-side-menu>\n *\n *   <ion-side-menu-content>\n *   <!-- Main content, usually <ion-nav-view> -->\n *   </ion-side-menu-content>\n * </ion-side-menus>\n * ```\n * ```js\n * function ContentController($scope, $ionicSideMenuDelegate) {\n *   $scope.toggleLeft = function() {\n *     $ionicSideMenuDelegate.toggleLeft();\n *   };\n * }\n * ```\n *\n * @param {bool=} enable-menu-with-back-views Determines whether the side menu is enabled when the\n * back button is showing. When set to `false`, any {@link ionic.directive:menuToggle} will be hidden,\n * and the user cannot swipe to open the menu. When going back to the root page of the side menu (the\n * page without a back button visible), then any menuToggle buttons will show again, and menus will be\n * enabled again.\n * @param {string=} delegate-handle The handle used to identify this side menu\n * with {@link ionic.service:$ionicSideMenuDelegate}.\n *\n */\n.directive('ionSideMenus', ['$ionicBody', function($ionicBody) {\n  return {\n    restrict: 'ECA',\n    controller: '$ionicSideMenus',\n    compile: function(element, attr) {\n      attr.$set('class', (attr['class'] || '') + ' view');\n\n      return { pre: prelink };\n      function prelink($scope, $element, $attrs, ctrl) {\n\n        ctrl.enableMenuWithBackViews($scope.$eval($attrs.enableMenuWithBackViews));\n\n        $scope.$on('$ionicExposeAside', function(evt, isAsideExposed) {\n          if (!$scope.$exposeAside) $scope.$exposeAside = {};\n          $scope.$exposeAside.active = isAsideExposed;\n          $ionicBody.enableClass(isAsideExposed, 'aside-open');\n        });\n\n        $scope.$on('$ionicView.beforeEnter', function(ev, d) {\n          if (d.historyId) {\n            $scope.$activeHistoryId = d.historyId;\n          }\n        });\n\n        $scope.$on('$destroy', function() {\n          $ionicBody.removeClass('menu-open', 'aside-open');\n        });\n\n      }\n    }\n  };\n}]);\n\n\n/**\n * @ngdoc directive\n * @name ionSlideBox\n * @module ionic\n * @delegate ionic.service:$ionicSlideBoxDelegate\n * @restrict E\n * @description\n * The Slide Box is a multi-page container where each page can be swiped or dragged between:\n *\n * ![SlideBox](http://ionicframework.com.s3.amazonaws.com/docs/controllers/slideBox.gif)\n *\n * @usage\n * ```html\n * <ion-slide-box on-slide-changed=\"slideHasChanged($index)\">\n *   <ion-slide>\n *     <div class=\"box blue\"><h1>BLUE</h1></div>\n *   </ion-slide>\n *   <ion-slide>\n *     <div class=\"box yellow\"><h1>YELLOW</h1></div>\n *   </ion-slide>\n *   <ion-slide>\n *     <div class=\"box pink\"><h1>PINK</h1></div>\n *   </ion-slide>\n * </ion-slide-box>\n * ```\n *\n * @param {string=} delegate-handle The handle used to identify this slideBox\n * with {@link ionic.service:$ionicSlideBoxDelegate}.\n * @param {boolean=} does-continue Whether the slide box should loop.\n * @param {boolean=} auto-play Whether the slide box should automatically slide. Default true if does-continue is true.\n * @param {number=} slide-interval How many milliseconds to wait to change slides (if does-continue is true). Defaults to 4000.\n * @param {boolean=} show-pager Whether a pager should be shown for this slide box. Accepts expressions via `show-pager=\"{{shouldShow()}}\"`. Defaults to true.\n * @param {expression=} pager-click Expression to call when a pager is clicked (if show-pager is true). Is passed the 'index' variable.\n * @param {expression=} on-slide-changed Expression called whenever the slide is changed.  Is passed an '$index' variable.\n * @param {expression=} active-slide Model to bind the current slide to.\n */\nIonicModule\n.directive('ionSlideBox', [\n  '$timeout',\n  '$compile',\n  '$ionicSlideBoxDelegate',\n  '$ionicHistory',\n  '$ionicScrollDelegate',\nfunction($timeout, $compile, $ionicSlideBoxDelegate, $ionicHistory, $ionicScrollDelegate) {\n  return {\n    restrict: 'E',\n    replace: true,\n    transclude: true,\n    scope: {\n      autoPlay: '=',\n      doesContinue: '@',\n      slideInterval: '@',\n      showPager: '@',\n      pagerClick: '&',\n      disableScroll: '@',\n      onSlideChanged: '&',\n      activeSlide: '=?'\n    },\n    controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {\n      var _this = this;\n\n      var continuous = $scope.$eval($scope.doesContinue) === true;\n      var shouldAutoPlay = isDefined($attrs.autoPlay) ? !!$scope.autoPlay : false;\n      var slideInterval = shouldAutoPlay ? $scope.$eval($scope.slideInterval) || 4000 : 0;\n\n      var slider = new ionic.views.Slider({\n        el: $element[0],\n        auto: slideInterval,\n        continuous: continuous,\n        startSlide: $scope.activeSlide,\n        slidesChanged: function() {\n          $scope.currentSlide = slider.currentIndex();\n\n          // Try to trigger a digest\n          $timeout(function() {});\n        },\n        callback: function(slideIndex) {\n          $scope.currentSlide = slideIndex;\n          $scope.onSlideChanged({ index: $scope.currentSlide, $index: $scope.currentSlide});\n          $scope.$parent.$broadcast('slideBox.slideChanged', slideIndex);\n          $scope.activeSlide = slideIndex;\n          // Try to trigger a digest\n          $timeout(function() {});\n        },\n        onDrag: function() {\n          freezeAllScrolls(true);\n        },\n        onDragEnd: function() {\n          freezeAllScrolls(false);\n        }\n      });\n\n      function freezeAllScrolls(shouldFreeze) {\n        if (shouldFreeze && !_this.isScrollFreeze) {\n          $ionicScrollDelegate.freezeAllScrolls(shouldFreeze);\n\n        } else if (!shouldFreeze && _this.isScrollFreeze) {\n          $ionicScrollDelegate.freezeAllScrolls(false);\n        }\n        _this.isScrollFreeze = shouldFreeze;\n      }\n\n      slider.enableSlide($scope.$eval($attrs.disableScroll) !== true);\n\n      $scope.$watch('activeSlide', function(nv) {\n        if (isDefined(nv)) {\n          slider.slide(nv);\n        }\n      });\n\n      $scope.$on('slideBox.nextSlide', function() {\n        slider.next();\n      });\n\n      $scope.$on('slideBox.prevSlide', function() {\n        slider.prev();\n      });\n\n      $scope.$on('slideBox.setSlide', function(e, index) {\n        slider.slide(index);\n      });\n\n      //Exposed for testing\n      this.__slider = slider;\n\n      var deregisterInstance = $ionicSlideBoxDelegate._registerInstance(\n        slider, $attrs.delegateHandle, function() {\n          return $ionicHistory.isActiveScope($scope);\n        }\n      );\n      $scope.$on('$destroy', function() {\n        deregisterInstance();\n        slider.kill();\n      });\n\n      this.slidesCount = function() {\n        return slider.slidesCount();\n      };\n\n      this.onPagerClick = function(index) {\n        void 0;\n        $scope.pagerClick({index: index});\n      };\n\n      $timeout(function() {\n        slider.load();\n      });\n    }],\n    template: '<div class=\"slider\">' +\n      '<div class=\"slider-slides\" ng-transclude>' +\n      '</div>' +\n    '</div>',\n\n    link: function($scope, $element, $attr) {\n      // if showPager is undefined, show the pager\n      if (!isDefined($attr.showPager)) {\n        $scope.showPager = true;\n        getPager().toggleClass('hide', !true);\n      }\n\n      $attr.$observe('showPager', function(show) {\n        show = $scope.$eval(show);\n        getPager().toggleClass('hide', !show);\n      });\n\n      var pager;\n      function getPager() {\n        if (!pager) {\n          var childScope = $scope.$new();\n          pager = jqLite('<ion-pager></ion-pager>');\n          $element.append(pager);\n          pager = $compile(pager)(childScope);\n        }\n        return pager;\n      }\n    }\n  };\n}])\n.directive('ionSlide', function() {\n  return {\n    restrict: 'E',\n    require: '^ionSlideBox',\n    compile: function(element) {\n      element.addClass('slider-slide');\n    }\n  };\n})\n\n.directive('ionPager', function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '^ionSlideBox',\n    template: '<div class=\"slider-pager\"><span class=\"slider-pager-page\" ng-repeat=\"slide in numSlides() track by $index\" ng-class=\"{active: $index == currentSlide}\" ng-click=\"pagerClick($index)\"><i class=\"icon ion-record\"></i></span></div>',\n    link: function($scope, $element, $attr, slideBox) {\n      var selectPage = function(index) {\n        var children = $element[0].children;\n        var length = children.length;\n        for (var i = 0; i < length; i++) {\n          if (i == index) {\n            children[i].classList.add('active');\n          } else {\n            children[i].classList.remove('active');\n          }\n        }\n      };\n\n      $scope.pagerClick = function(index) {\n        slideBox.onPagerClick(index);\n      };\n\n      $scope.numSlides = function() {\n        return new Array(slideBox.slidesCount());\n      };\n\n      $scope.$watch('currentSlide', function(v) {\n        selectPage(v);\n      });\n    }\n  };\n\n});\n\n/**\n* @ngdoc directive\n* @name ionSpinner\n* @module ionic\n* @restrict E\n *\n * @description\n * The `ionSpinner` directive provides a variety of animated spinners.\n * Spinners enables you to give your users feedback that the app is\n * processing/thinking/waiting/chillin' out, or whatever you'd like it to indicate.\n * By default, the {@link ionic.directive:ionRefresher} feature uses this spinner, rather\n * than rotating font icons (previously included in [ionicons](http://ionicons.com/)).\n * While font icons are great for simple or stationary graphics, they're not suited to\n * provide great animations, which is why Ionic uses SVG instead.\n *\n * Ionic offers ten spinners out of the box, and by default, it will use the appropriate spinner\n * for the platform on which it's running. Under the hood, the `ionSpinner` directive dynamically\n * builds the required SVG element, which allows Ionic to provide all ten of the animated SVGs\n * within 3KB.\n *\n * <style>\n * .spinner-table {\n *   max-width: 280px;\n * }\n * .spinner-table tbody > tr > th, .spinner-table tbody > tr > td {\n *   vertical-align: middle;\n *   width: 42px;\n *   height: 42px;\n * }\n * .spinner {\n *   stroke: #444;\n *   fill: #444; }\n *   .spinner svg {\n *     width: 28px;\n *     height: 28px; }\n *   .spinner.spinner-inverse {\n *     stroke: #fff;\n *     fill: #fff; }\n *\n * .spinner-android {\n *   stroke: #4b8bf4; }\n *\n * .spinner-ios, .spinner-ios-small {\n *   stroke: #69717d; }\n *\n * .spinner-spiral .stop1 {\n *   stop-color: #fff;\n *   stop-opacity: 0; }\n * .spinner-spiral.spinner-inverse .stop1 {\n *   stop-color: #000; }\n * .spinner-spiral.spinner-inverse .stop2 {\n *   stop-color: #fff; }\n * </style>\n *\n * <script src=\"http://code.ionicframework.com/nightly/js/ionic.bundle.min.js\"></script>\n * <table class=\"table spinner-table\" ng-app=\"ionic\">\n *  <tr>\n *    <th>\n *      <code>android</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"android\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>ios</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"ios\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>ios-small</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"ios-small\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>bubbles</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"bubbles\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>circles</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"circles\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>crescent</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"crescent\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>dots</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"dots\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>lines</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"lines\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>ripple</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"ripple\"></ion-spinner>\n *    </td>\n *  </tr>\n *  <tr>\n *    <th>\n *      <code>spiral</code>\n *    </th>\n *    <td>\n *      <ion-spinner icon=\"spiral\"></ion-spinner>\n *    </td>\n *  </tr>\n * </table>\n *\n * Each spinner uses SVG with SMIL animations, however, the Android spinner also uses JavaScript\n * so it also works on Android 4.0-4.3. Additionally, each spinner can be styled with CSS,\n * and scaled to any size.\n *\n *\n * @usage\n * The following code would use the default spinner for the platform it's running from. If it's neither\n * iOS or Android, it'll default to use `ios`.\n *\n * ```html\n * <ion-spinner></ion-spinner>\n * ```\n *\n * By setting the `icon` attribute, you can specify which spinner to use, no matter what\n * the platform is.\n *\n * ```html\n * <ion-spinner icon=\"spiral\"></ion-spinner>\n * ```\n *\n * ## Spinner Colors\n * Like with most of Ionic's other components, spinners can also be styled using\n * Ionic's standard color naming convention. For example:\n *\n * ```html\n * <ion-spinner class=\"spinner-energized\"></ion-spinner>\n * ```\n *\n *\n * ## Styling SVG with CSS\n * One cool thing about SVG is its ability to be styled with CSS! Some of the properties\n * have different names, for example, SVG uses the term `stroke` instead of `border`, and\n * `fill` instead of `background-color`.\n *\n * ```css\n * .spinner svg {\n *   width: 28px;\n *   height: 28px;\n *   stroke: #444;\n *   fill: #444;\n * }\n * ```\n *\n*/\nIonicModule\n.directive('ionSpinner', function() {\n  return {\n    restrict: 'E',\n    controller: '$ionicSpinner',\n    link: function($scope, $element, $attrs, ctrl) {\n      var spinnerName = ctrl.init();\n      $element.addClass('spinner spinner-' + spinnerName);\n    }\n  };\n});\n\n/**\n * @ngdoc directive\n * @name ionTab\n * @module ionic\n * @restrict E\n * @parent ionic.directive:ionTabs\n *\n * @description\n * Contains a tab's content.  The content only exists while the given tab is selected.\n *\n * Each ionTab has its own view history.\n *\n * @usage\n * ```html\n * <ion-tab\n *   title=\"Tab!\"\n *   icon=\"my-icon\"\n *   href=\"#/tab/tab-link\"\n *   on-select=\"onTabSelected()\"\n *   on-deselect=\"onTabDeselected()\">\n * </ion-tab>\n * ```\n * For a complete, working tab bar example, see the {@link ionic.directive:ionTabs} documentation.\n *\n * @param {string} title The title of the tab.\n * @param {string=} href The link that this tab will navigate to when tapped.\n * @param {string=} icon The icon of the tab. If given, this will become the default for icon-on and icon-off.\n * @param {string=} icon-on The icon of the tab while it is selected.\n * @param {string=} icon-off The icon of the tab while it is not selected.\n * @param {expression=} badge The badge to put on this tab (usually a number).\n * @param {expression=} badge-style The style of badge to put on this tab (eg: badge-positive).\n * @param {expression=} on-select Called when this tab is selected.\n * @param {expression=} on-deselect Called when this tab is deselected.\n * @param {expression=} ng-click By default, the tab will be selected on click. If ngClick is set, it will not.  You can explicitly switch tabs using {@link ionic.service:$ionicTabsDelegate#select $ionicTabsDelegate.select()}.\n * @param {expression=} hidden Whether the tab is to be hidden or not.\n * @param {expression=} disabled Whether the tab is to be disabled or not.\n */\nIonicModule\n.directive('ionTab', [\n  '$compile',\n  '$ionicConfig',\n  '$ionicBind',\n  '$ionicViewSwitcher',\nfunction($compile, $ionicConfig, $ionicBind, $ionicViewSwitcher) {\n\n  //Returns ' key=\"value\"' if value exists\n  function attrStr(k, v) {\n    return isDefined(v) ? ' ' + k + '=\"' + v + '\"' : '';\n  }\n  return {\n    restrict: 'E',\n    require: ['^ionTabs', 'ionTab'],\n    controller: '$ionicTab',\n    scope: true,\n    compile: function(element, attr) {\n\n      //We create the tabNavTemplate in the compile phase so that the\n      //attributes we pass down won't be interpolated yet - we want\n      //to pass down the 'raw' versions of the attributes\n      var tabNavTemplate = '<ion-tab-nav' +\n        attrStr('ng-click', attr.ngClick) +\n        attrStr('title', attr.title) +\n        attrStr('icon', attr.icon) +\n        attrStr('icon-on', attr.iconOn) +\n        attrStr('icon-off', attr.iconOff) +\n        attrStr('badge', attr.badge) +\n        attrStr('badge-style', attr.badgeStyle) +\n        attrStr('hidden', attr.hidden) +\n        attrStr('disabled', attr.disabled) +\n        attrStr('class', attr['class']) +\n        '></ion-tab-nav>';\n\n      //Remove the contents of the element so we can compile them later, if tab is selected\n      var tabContentEle = document.createElement('div');\n      for (var x = 0; x < element[0].children.length; x++) {\n        tabContentEle.appendChild(element[0].children[x].cloneNode(true));\n      }\n      var childElementCount = tabContentEle.childElementCount;\n      element.empty();\n\n      var navViewName, isNavView;\n      if (childElementCount) {\n        if (tabContentEle.children[0].tagName === 'ION-NAV-VIEW') {\n          // get the name if it's a nav-view\n          navViewName = tabContentEle.children[0].getAttribute('name');\n          tabContentEle.children[0].classList.add('view-container');\n          isNavView = true;\n        }\n        if (childElementCount === 1) {\n          // make the 1 child element the primary tab content container\n          tabContentEle = tabContentEle.children[0];\n        }\n        if (!isNavView) tabContentEle.classList.add('pane');\n        tabContentEle.classList.add('tab-content');\n      }\n\n      return function link($scope, $element, $attr, ctrls) {\n        var childScope;\n        var childElement;\n        var tabsCtrl = ctrls[0];\n        var tabCtrl = ctrls[1];\n        var isTabContentAttached = false;\n        $scope.$tabSelected = false;\n\n        $ionicBind($scope, $attr, {\n          onSelect: '&',\n          onDeselect: '&',\n          title: '@',\n          uiSref: '@',\n          href: '@'\n        });\n\n        tabsCtrl.add($scope);\n        $scope.$on('$destroy', function() {\n          if (!$scope.$tabsDestroy) {\n            // if the containing ionTabs directive is being destroyed\n            // then don't bother going through the controllers remove\n            // method, since remove will reset the active tab as each tab\n            // is being destroyed, causing unnecessary view loads and transitions\n            tabsCtrl.remove($scope);\n          }\n          tabNavElement.isolateScope().$destroy();\n          tabNavElement.remove();\n          tabNavElement = tabContentEle = childElement = null;\n        });\n\n        //Remove title attribute so browser-tooltip does not apear\n        $element[0].removeAttribute('title');\n\n        if (navViewName) {\n          tabCtrl.navViewName = $scope.navViewName = navViewName;\n        }\n        $scope.$on('$stateChangeSuccess', selectIfMatchesState);\n        selectIfMatchesState();\n        function selectIfMatchesState() {\n          if (tabCtrl.tabMatchesState()) {\n            tabsCtrl.select($scope, false);\n          }\n        }\n\n        var tabNavElement = jqLite(tabNavTemplate);\n        tabNavElement.data('$ionTabsController', tabsCtrl);\n        tabNavElement.data('$ionTabController', tabCtrl);\n        tabsCtrl.$tabsElement.append($compile(tabNavElement)($scope));\n\n\n        function tabSelected(isSelected) {\n          if (isSelected && childElementCount) {\n            // this tab is being selected\n\n            // check if the tab is already in the DOM\n            // only do this if the tab has child elements\n            if (!isTabContentAttached) {\n              // tab should be selected and is NOT in the DOM\n              // create a new scope and append it\n              childScope = $scope.$new();\n              childElement = jqLite(tabContentEle);\n              $ionicViewSwitcher.viewEleIsActive(childElement, true);\n              tabsCtrl.$element.append(childElement);\n              $compile(childElement)(childScope);\n              isTabContentAttached = true;\n            }\n\n            // remove the hide class so the tabs content shows up\n            $ionicViewSwitcher.viewEleIsActive(childElement, true);\n\n          } else if (isTabContentAttached && childElement) {\n            // this tab should NOT be selected, and it is already in the DOM\n\n            if ($ionicConfig.views.maxCache() > 0) {\n              // keep the tabs in the DOM, only css hide it\n              $ionicViewSwitcher.viewEleIsActive(childElement, false);\n\n            } else {\n              // do not keep tabs in the DOM\n              destroyTab();\n            }\n\n          }\n        }\n\n        function destroyTab() {\n          childScope && childScope.$destroy();\n          isTabContentAttached && childElement && childElement.remove();\n          tabContentEle.innerHTML = '';\n          isTabContentAttached = childScope = childElement = null;\n        }\n\n        $scope.$watch('$tabSelected', tabSelected);\n\n        $scope.$on('$ionicView.afterEnter', function() {\n          $ionicViewSwitcher.viewEleIsActive(childElement, $scope.$tabSelected);\n        });\n\n        $scope.$on('$ionicView.clearCache', function() {\n          if (!$scope.$tabSelected) {\n            destroyTab();\n          }\n        });\n\n      };\n    }\n  };\n}]);\n\nIonicModule\n.directive('ionTabNav', [function() {\n  return {\n    restrict: 'E',\n    replace: true,\n    require: ['^ionTabs', '^ionTab'],\n    template:\n    '<a ng-class=\"{\\'tab-item-active\\': isTabActive(), \\'has-badge\\':badge, \\'tab-hidden\\':isHidden()}\" ' +\n      ' ng-disabled=\"disabled()\" class=\"tab-item\">' +\n      '<span class=\"badge {{badgeStyle}}\" ng-if=\"badge\">{{badge}}</span>' +\n      '<i class=\"icon {{getIconOn()}}\" ng-if=\"getIconOn() && isTabActive()\"></i>' +\n      '<i class=\"icon {{getIconOff()}}\" ng-if=\"getIconOff() && !isTabActive()\"></i>' +\n      '<span class=\"tab-title\" ng-bind-html=\"title\"></span>' +\n    '</a>',\n    scope: {\n      title: '@',\n      icon: '@',\n      iconOn: '@',\n      iconOff: '@',\n      badge: '=',\n      hidden: '@',\n      disabled: '&',\n      badgeStyle: '@',\n      'class': '@'\n    },\n    link: function($scope, $element, $attrs, ctrls) {\n      var tabsCtrl = ctrls[0],\n        tabCtrl = ctrls[1];\n\n      //Remove title attribute so browser-tooltip does not apear\n      $element[0].removeAttribute('title');\n\n      $scope.selectTab = function(e) {\n        e.preventDefault();\n        tabsCtrl.select(tabCtrl.$scope, true);\n      };\n      if (!$attrs.ngClick) {\n        $element.on('click', function(event) {\n          $scope.$apply(function() {\n            $scope.selectTab(event);\n          });\n        });\n      }\n\n      $scope.isHidden = function() {\n        if ($attrs.hidden === 'true' || $attrs.hidden === true) return true;\n        return false;\n      };\n\n      $scope.getIconOn = function() {\n        return $scope.iconOn || $scope.icon;\n      };\n      $scope.getIconOff = function() {\n        return $scope.iconOff || $scope.icon;\n      };\n\n      $scope.isTabActive = function() {\n        return tabsCtrl.selectedTab() === tabCtrl.$scope;\n      };\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionTabs\n * @module ionic\n * @delegate ionic.service:$ionicTabsDelegate\n * @restrict E\n * @codepen odqCz\n *\n * @description\n * Powers a multi-tabbed interface with a Tab Bar and a set of \"pages\" that can be tabbed\n * through.\n *\n * Assign any [tabs class](/docs/components#tabs) to the element to define\n * its look and feel.\n *\n * For iOS, tabs will appear at the bottom of the screen. For Android, tabs will be at the top\n * of the screen, below the nav-bar. This follows each OS's design specification, but can be\n * configured with the {@link ionic.provider:$ionicConfigProvider}.\n *\n * See the {@link ionic.directive:ionTab} directive's documentation for more details on\n * individual tabs.\n *\n * Note: do not place ion-tabs inside of an ion-content element; it has been known to cause a\n * certain CSS bug.\n *\n * @usage\n * ```html\n * <ion-tabs class=\"tabs-positive tabs-icon-only\">\n *\n *   <ion-tab title=\"Home\" icon-on=\"ion-ios-filing\" icon-off=\"ion-ios-filing-outline\">\n *     <!-- Tab 1 content -->\n *   </ion-tab>\n *\n *   <ion-tab title=\"About\" icon-on=\"ion-ios-clock\" icon-off=\"ion-ios-clock-outline\">\n *     <!-- Tab 2 content -->\n *   </ion-tab>\n *\n *   <ion-tab title=\"Settings\" icon-on=\"ion-ios-gear\" icon-off=\"ion-ios-gear-outline\">\n *     <!-- Tab 3 content -->\n *   </ion-tab>\n *\n * </ion-tabs>\n * ```\n *\n * @param {string=} delegate-handle The handle used to identify these tabs\n * with {@link ionic.service:$ionicTabsDelegate}.\n */\n\nIonicModule\n.directive('ionTabs', [\n  '$ionicTabsDelegate',\n  '$ionicConfig',\nfunction($ionicTabsDelegate, $ionicConfig) {\n  return {\n    restrict: 'E',\n    scope: true,\n    controller: '$ionicTabs',\n    compile: function(tElement) {\n      //We cannot use regular transclude here because it breaks element.data()\n      //inheritance on compile\n      var innerElement = jqLite('<div class=\"tab-nav tabs\">');\n      innerElement.append(tElement.contents());\n\n      tElement.append(innerElement)\n              .addClass('tabs-' + $ionicConfig.tabs.position() + ' tabs-' + $ionicConfig.tabs.style());\n\n      return { pre: prelink, post: postLink };\n      function prelink($scope, $element, $attr, tabsCtrl) {\n        var deregisterInstance = $ionicTabsDelegate._registerInstance(\n          tabsCtrl, $attr.delegateHandle, tabsCtrl.hasActiveScope\n        );\n\n        tabsCtrl.$scope = $scope;\n        tabsCtrl.$element = $element;\n        tabsCtrl.$tabsElement = jqLite($element[0].querySelector('.tabs'));\n\n        $scope.$watch(function() { return $element[0].className; }, function(value) {\n          var isTabsTop = value.indexOf('tabs-top') !== -1;\n          var isHidden = value.indexOf('tabs-item-hide') !== -1;\n          $scope.$hasTabs = !isTabsTop && !isHidden;\n          $scope.$hasTabsTop = isTabsTop && !isHidden;\n          $scope.$emit('$ionicTabs.top', $scope.$hasTabsTop);\n        });\n\n        function emitLifecycleEvent(ev, data) {\n          ev.stopPropagation();\n          var previousSelectedTab = tabsCtrl.previousSelectedTab();\n          if (previousSelectedTab) {\n            previousSelectedTab.$broadcast(ev.name.replace('NavView', 'Tabs'), data);\n          }\n        }\n\n        $scope.$on('$ionicNavView.beforeLeave', emitLifecycleEvent);\n        $scope.$on('$ionicNavView.afterLeave', emitLifecycleEvent);\n        $scope.$on('$ionicNavView.leave', emitLifecycleEvent);\n\n        $scope.$on('$destroy', function() {\n          // variable to inform child tabs that they're all being blown away\n          // used so that while destorying an individual tab, each one\n          // doesn't select the next tab as the active one, which causes unnecessary\n          // loading of tab views when each will eventually all go away anyway\n          $scope.$tabsDestroy = true;\n          deregisterInstance();\n          tabsCtrl.$tabsElement = tabsCtrl.$element = tabsCtrl.$scope = innerElement = null;\n          delete $scope.$hasTabs;\n          delete $scope.$hasTabsTop;\n        });\n      }\n\n      function postLink($scope, $element, $attr, tabsCtrl) {\n        if (!tabsCtrl.selectedTab()) {\n          // all the tabs have been added\n          // but one hasn't been selected yet\n          tabsCtrl.select(0);\n        }\n      }\n    }\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionToggle\n * @module ionic\n * @codepen tfAzj\n * @restrict E\n *\n * @description\n * A toggle is an animated switch which binds a given model to a boolean.\n *\n * Allows dragging of the switch's nub.\n *\n * The toggle behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]) otherwise.\n *\n * @param toggle-class {string=} Sets the CSS class on the inner `label.toggle` element created by the directive.\n *\n * @usage\n * Below is an example of a toggle directive which is wired up to the `airplaneMode` model\n * and has the `toggle-calm` CSS class assigned to the inner element.\n *\n * ```html\n * <ion-toggle ng-model=\"airplaneMode\" toggle-class=\"toggle-calm\">Airplane Mode</ion-toggle>\n * ```\n */\nIonicModule\n.directive('ionToggle', [\n  '$timeout',\n  '$ionicConfig',\nfunction($timeout, $ionicConfig) {\n\n  return {\n    restrict: 'E',\n    replace: true,\n    require: '?ngModel',\n    transclude: true,\n    template:\n      '<div class=\"item item-toggle\">' +\n        '<div ng-transclude></div>' +\n        '<label class=\"toggle\">' +\n          '<input type=\"checkbox\">' +\n          '<div class=\"track\">' +\n            '<div class=\"handle\"></div>' +\n          '</div>' +\n        '</label>' +\n      '</div>',\n\n    compile: function(element, attr) {\n      var input = element.find('input');\n      forEach({\n        'name': attr.name,\n        'ng-value': attr.ngValue,\n        'ng-model': attr.ngModel,\n        'ng-checked': attr.ngChecked,\n        'ng-disabled': attr.ngDisabled,\n        'ng-true-value': attr.ngTrueValue,\n        'ng-false-value': attr.ngFalseValue,\n        'ng-change': attr.ngChange,\n        'ng-required': attr.ngRequired,\n        'required': attr.required\n      }, function(value, name) {\n        if (isDefined(value)) {\n          input.attr(name, value);\n        }\n      });\n\n      if (attr.toggleClass) {\n        element[0].getElementsByTagName('label')[0].classList.add(attr.toggleClass);\n      }\n\n      element.addClass('toggle-' + $ionicConfig.form.toggle());\n\n      return function($scope, $element) {\n        var el = $element[0].getElementsByTagName('label')[0];\n        var checkbox = el.children[0];\n        var track = el.children[1];\n        var handle = track.children[0];\n\n        var ngModelController = jqLite(checkbox).controller('ngModel');\n\n        $scope.toggle = new ionic.views.Toggle({\n          el: el,\n          track: track,\n          checkbox: checkbox,\n          handle: handle,\n          onChange: function() {\n            if (ngModelController) {\n              ngModelController.$setViewValue(checkbox.checked);\n              $scope.$apply();\n            }\n          }\n        });\n\n        $scope.$on('$destroy', function() {\n          $scope.toggle.destroy();\n        });\n      };\n    }\n\n  };\n}]);\n\n/**\n * @ngdoc directive\n * @name ionView\n * @module ionic\n * @restrict E\n * @parent ionNavView\n *\n * @description\n * A container for view content and any navigational and header bar information. When a view\n * enters and exits its parent {@link ionic.directive:ionNavView}, the view also emits view\n * information, such as its title, whether the back button should be displayed or not, whether the\n * corresponding {@link ionic.directive:ionNavBar} should be displayed or not, which transition the view\n * should use to animate, and which direction to animate.\n *\n * *Views are cached to improve performance.* When a view is navigated away from, its element is\n * left in the DOM, and its scope is disconnected from the `$watch` cycle. When navigating to a\n * view that is already cached, its scope is reconnected, and the existing element, which was\n * left in the DOM, becomes active again. This can be disabled, or the maximum number of cached\n * views changed in {@link ionic.provider:$ionicConfigProvider}, in the view's `$state` configuration, or\n * as an attribute on the view itself (see below).\n *\n * @usage\n * Below is an example where our page will load with a {@link ionic.directive:ionNavBar} containing\n * \"My Page\" as the title.\n *\n * ```html\n * <ion-nav-bar></ion-nav-bar>\n * <ion-nav-view>\n *   <ion-view view-title=\"My Page\">\n *     <ion-content>\n *       Hello!\n *     </ion-content>\n *   </ion-view>\n * </ion-nav-view>\n * ```\n *\n * ## View LifeCycle and Events\n *\n * Views can be cached, which means ***controllers normally only load once***, which may\n * affect your controller logic. To know when a view has entered or left, events\n * have been added that are emitted from the view's scope. These events also\n * contain data about the view, such as the title and whether the back button should\n * show. Also contained is transition data, such as the transition type and\n * direction that will be or was used.\n *\n * <table class=\"table\">\n *  <tr>\n *   <td><code>$ionicView.loaded</code></td>\n *   <td>The view has loaded. This event only happens once per\n * view being created and added to the DOM. If a view leaves but is cached,\n * then this event will not fire again on a subsequent viewing. The loaded event\n * is good place to put your setup code for the view; however, it is not the\n * recommended event to listen to when a view becomes active.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.enter</code></td>\n *   <td>The view has fully entered and is now the active view.\n * This event will fire, whether it was the first load or a cached view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.leave</code></td>\n *   <td>The view has finished leaving and is no longer the\n * active view. This event will fire, whether it is cached or destroyed.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.beforeEnter</code></td>\n *   <td>The view is about to enter and become the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.beforeLeave</code></td>\n *   <td>The view is about to leave and no longer be the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.afterEnter</code></td>\n *   <td>The view has fully entered and is now the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.afterLeave</code></td>\n *   <td>The view has finished leaving and is no longer the active view.</td>\n *  </tr>\n *  <tr>\n *   <td><code>$ionicView.unloaded</code></td>\n *   <td>The view's controller has been destroyed and its element has been\n * removed from the DOM.</td>\n *  </tr>\n * </table>\n *\n * ## Caching\n *\n * Caching can be disabled and enabled in multiple ways. By default, Ionic will\n * cache a maximum of 10 views. You can optionally choose to disable caching at\n * either an individual view basis, or by global configuration. Please see the\n * _Caching_ section in {@link ionic.directive:ionNavView} for more info.\n *\n * @param {string=} view-title A text-only title to display on the parent {@link ionic.directive:ionNavBar}.\n * For an HTML title, such as an image, see {@link ionic.directive:ionNavTitle} instead.\n * @param {boolean=} cache-view If this view should be allowed to be cached or not.\n * Please see the _Caching_ section in {@link ionic.directive:ionNavView} for\n * more info. Default `true`\n * @param {boolean=} can-swipe-back If this view should be allowed to use the swipe to go back gesture or not.\n * This does not enable the swipe to go back feature if it is not available for the platform it's running\n * from, or there isn't a previous view. Default `true`\n * @param {boolean=} hide-back-button Whether to hide the back button on the parent\n * {@link ionic.directive:ionNavBar} by default.\n * @param {boolean=} hide-nav-bar Whether to hide the parent\n * {@link ionic.directive:ionNavBar} by default.\n */\nIonicModule\n.directive('ionView', function() {\n  return {\n    restrict: 'EA',\n    priority: 1000,\n    controller: '$ionicView',\n    compile: function(tElement) {\n      tElement.addClass('pane');\n      tElement[0].removeAttribute('title');\n      return function link($scope, $element, $attrs, viewCtrl) {\n        viewCtrl.init();\n      };\n    }\n  };\n});\n\n})();"
  },
  {
    "path": "examples/ionic/www/lib/ionic/js/ionic.js",
    "content": "/*!\n * Copyright 2014 Drifty Co.\n * http://drifty.com/\n *\n * Ionic, v1.0.0\n * A powerful HTML5 mobile app framework.\n * http://ionicframework.com/\n *\n * By @maxlynch, @benjsperry, @adamdbradley <3\n *\n * Licensed under the MIT license. Please see LICENSE for more information.\n *\n */\n\n(function() {\n\n// Create global ionic obj and its namespaces\n// build processes may have already created an ionic obj\nwindow.ionic = window.ionic || {};\nwindow.ionic.views = {};\nwindow.ionic.version = '1.0.0';\n\n(function (ionic) {\n\n  ionic.DelegateService = function(methodNames) {\n\n    if (methodNames.indexOf('$getByHandle') > -1) {\n      throw new Error(\"Method '$getByHandle' is implicitly added to each delegate service. Do not list it as a method.\");\n    }\n\n    function trueFn() { return true; }\n\n    return ['$log', function($log) {\n\n      /*\n       * Creates a new object that will have all the methodNames given,\n       * and call them on the given the controller instance matching given\n       * handle.\n       * The reason we don't just let $getByHandle return the controller instance\n       * itself is that the controller instance might not exist yet.\n       *\n       * We want people to be able to do\n       * `var instance = $ionicScrollDelegate.$getByHandle('foo')` on controller\n       * instantiation, but on controller instantiation a child directive\n       * may not have been compiled yet!\n       *\n       * So this is our way of solving this problem: we create an object\n       * that will only try to fetch the controller with given handle\n       * once the methods are actually called.\n       */\n      function DelegateInstance(instances, handle) {\n        this._instances = instances;\n        this.handle = handle;\n      }\n      methodNames.forEach(function(methodName) {\n        DelegateInstance.prototype[methodName] = instanceMethodCaller(methodName);\n      });\n\n\n      /**\n       * The delegate service (eg $ionicNavBarDelegate) is just an instance\n       * with a non-defined handle, a couple extra methods for registering\n       * and narrowing down to a specific handle.\n       */\n      function DelegateService() {\n        this._instances = [];\n      }\n      DelegateService.prototype = DelegateInstance.prototype;\n      DelegateService.prototype._registerInstance = function(instance, handle, filterFn) {\n        var instances = this._instances;\n        instance.$$delegateHandle = handle;\n        instance.$$filterFn = filterFn || trueFn;\n        instances.push(instance);\n\n        return function deregister() {\n          var index = instances.indexOf(instance);\n          if (index !== -1) {\n            instances.splice(index, 1);\n          }\n        };\n      };\n      DelegateService.prototype.$getByHandle = function(handle) {\n        return new DelegateInstance(this._instances, handle);\n      };\n\n      return new DelegateService();\n\n      function instanceMethodCaller(methodName) {\n        return function caller() {\n          var handle = this.handle;\n          var args = arguments;\n          var foundInstancesCount = 0;\n          var returnValue;\n\n          this._instances.forEach(function(instance) {\n            if ((!handle || handle == instance.$$delegateHandle) && instance.$$filterFn(instance)) {\n              foundInstancesCount++;\n              var ret = instance[methodName].apply(instance, args);\n              //Only return the value from the first call\n              if (foundInstancesCount === 1) {\n                returnValue = ret;\n              }\n            }\n          });\n\n          if (!foundInstancesCount && handle) {\n            return $log.warn(\n              'Delegate for handle \"' + handle + '\" could not find a ' +\n              'corresponding element with delegate-handle=\"' + handle + '\"! ' +\n              methodName + '() was not called!\\n' +\n              'Possible cause: If you are calling ' + methodName + '() immediately, and ' +\n              'your element with delegate-handle=\"' + handle + '\" is a child of your ' +\n              'controller, then your element may not be compiled yet. Put a $timeout ' +\n              'around your call to ' + methodName + '() and try again.'\n            );\n          }\n          return returnValue;\n        };\n      }\n\n    }];\n  };\n\n})(window.ionic);\n\n(function(window, document, ionic) {\n\n  var readyCallbacks = [];\n  var isDomReady = document.readyState === 'complete' || document.readyState === 'interactive';\n\n  function domReady() {\n    isDomReady = true;\n    for (var x = 0; x < readyCallbacks.length; x++) {\n      ionic.requestAnimationFrame(readyCallbacks[x]);\n    }\n    readyCallbacks = [];\n    document.removeEventListener('DOMContentLoaded', domReady);\n  }\n  if (!isDomReady) {\n    document.addEventListener('DOMContentLoaded', domReady);\n  }\n\n\n  // From the man himself, Mr. Paul Irish.\n  // The requestAnimationFrame polyfill\n  // Put it on window just to preserve its context\n  // without having to use .call\n  window._rAF = (function() {\n    return window.requestAnimationFrame ||\n           window.webkitRequestAnimationFrame ||\n           window.mozRequestAnimationFrame ||\n           function(callback) {\n             window.setTimeout(callback, 16);\n           };\n  })();\n\n  var cancelAnimationFrame = window.cancelAnimationFrame ||\n    window.webkitCancelAnimationFrame ||\n    window.mozCancelAnimationFrame ||\n    window.webkitCancelRequestAnimationFrame;\n\n  /**\n  * @ngdoc utility\n  * @name ionic.DomUtil\n  * @module ionic\n  */\n  ionic.DomUtil = {\n    //Call with proper context\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#requestAnimationFrame\n     * @alias ionic.requestAnimationFrame\n     * @description Calls [requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame), or a polyfill if not available.\n     * @param {function} callback The function to call when the next frame\n     * happens.\n     */\n    requestAnimationFrame: function(cb) {\n      return window._rAF(cb);\n    },\n\n    cancelAnimationFrame: function(requestId) {\n      cancelAnimationFrame(requestId);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#animationFrameThrottle\n     * @alias ionic.animationFrameThrottle\n     * @description\n     * When given a callback, if that callback is called 100 times between\n     * animation frames, adding Throttle will make it only run the last of\n     * the 100 calls.\n     *\n     * @param {function} callback a function which will be throttled to\n     * requestAnimationFrame\n     * @returns {function} A function which will then call the passed in callback.\n     * The passed in callback will receive the context the returned function is\n     * called with.\n     */\n    animationFrameThrottle: function(cb) {\n      var args, isQueued, context;\n      return function() {\n        args = arguments;\n        context = this;\n        if (!isQueued) {\n          isQueued = true;\n          ionic.requestAnimationFrame(function() {\n            cb.apply(context, args);\n            isQueued = false;\n          });\n        }\n      };\n    },\n\n    contains: function(parentNode, otherNode) {\n      var current = otherNode;\n      while (current) {\n        if (current === parentNode) return true;\n        current = current.parentNode;\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getPositionInParent\n     * @description\n     * Find an element's scroll offset within its container.\n     * @param {DOMElement} element The element to find the offset of.\n     * @returns {object} A position object with the following properties:\n     *   - `{number}` `left` The left offset of the element.\n     *   - `{number}` `top` The top offset of the element.\n     */\n    getPositionInParent: function(el) {\n      return {\n        left: el.offsetLeft,\n        top: el.offsetTop\n      };\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#ready\n     * @description\n     * Call a function when the DOM is ready, or if it is already ready\n     * call the function immediately.\n     * @param {function} callback The function to be called.\n     */\n    ready: function(cb) {\n      if (isDomReady) {\n        ionic.requestAnimationFrame(cb);\n      } else {\n        readyCallbacks.push(cb);\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getTextBounds\n     * @description\n     * Get a rect representing the bounds of the given textNode.\n     * @param {DOMElement} textNode The textNode to find the bounds of.\n     * @returns {object} An object representing the bounds of the node. Properties:\n     *   - `{number}` `left` The left position of the textNode.\n     *   - `{number}` `right` The right position of the textNode.\n     *   - `{number}` `top` The top position of the textNode.\n     *   - `{number}` `bottom` The bottom position of the textNode.\n     *   - `{number}` `width` The width of the textNode.\n     *   - `{number}` `height` The height of the textNode.\n     */\n    getTextBounds: function(textNode) {\n      if (document.createRange) {\n        var range = document.createRange();\n        range.selectNodeContents(textNode);\n        if (range.getBoundingClientRect) {\n          var rect = range.getBoundingClientRect();\n          if (rect) {\n            var sx = window.scrollX;\n            var sy = window.scrollY;\n\n            return {\n              top: rect.top + sy,\n              left: rect.left + sx,\n              right: rect.left + sx + rect.width,\n              bottom: rect.top + sy + rect.height,\n              width: rect.width,\n              height: rect.height\n            };\n          }\n        }\n      }\n      return null;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getChildIndex\n     * @description\n     * Get the first index of a child node within the given element of the\n     * specified type.\n     * @param {DOMElement} element The element to find the index of.\n     * @param {string} type The nodeName to match children of element against.\n     * @returns {number} The index, or -1, of a child with nodeName matching type.\n     */\n    getChildIndex: function(element, type) {\n      if (type) {\n        var ch = element.parentNode.children;\n        var c;\n        for (var i = 0, k = 0, j = ch.length; i < j; i++) {\n          c = ch[i];\n          if (c.nodeName && c.nodeName.toLowerCase() == type) {\n            if (c == element) {\n              return k;\n            }\n            k++;\n          }\n        }\n      }\n      return Array.prototype.slice.call(element.parentNode.children).indexOf(element);\n    },\n\n    /**\n     * @private\n     */\n    swapNodes: function(src, dest) {\n      dest.parentNode.insertBefore(src, dest);\n    },\n\n    elementIsDescendant: function(el, parent, stopAt) {\n      var current = el;\n      do {\n        if (current === parent) return true;\n        current = current.parentNode;\n      } while (current && current !== stopAt);\n      return false;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getParentWithClass\n     * @param {DOMElement} element\n     * @param {string} className\n     * @returns {DOMElement} The closest parent of element matching the\n     * className, or null.\n     */\n    getParentWithClass: function(e, className, depth) {\n      depth = depth || 10;\n      while (e.parentNode && depth--) {\n        if (e.parentNode.classList && e.parentNode.classList.contains(className)) {\n          return e.parentNode;\n        }\n        e = e.parentNode;\n      }\n      return null;\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#getParentOrSelfWithClass\n     * @param {DOMElement} element\n     * @param {string} className\n     * @returns {DOMElement} The closest parent or self matching the\n     * className, or null.\n     */\n    getParentOrSelfWithClass: function(e, className, depth) {\n      depth = depth || 10;\n      while (e && depth--) {\n        if (e.classList && e.classList.contains(className)) {\n          return e;\n        }\n        e = e.parentNode;\n      }\n      return null;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#rectContains\n     * @param {number} x\n     * @param {number} y\n     * @param {number} x1\n     * @param {number} y1\n     * @param {number} x2\n     * @param {number} y2\n     * @returns {boolean} Whether {x,y} fits within the rectangle defined by\n     * {x1,y1,x2,y2}.\n     */\n    rectContains: function(x, y, x1, y1, x2, y2) {\n      if (x < x1 || x > x2) return false;\n      if (y < y1 || y > y2) return false;\n      return true;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.DomUtil#blurAll\n     * @description\n     * Blurs any currently focused input element\n     * @returns {DOMElement} The element blurred or null\n     */\n    blurAll: function() {\n      if (document.activeElement && document.activeElement != document.body) {\n        document.activeElement.blur();\n        return document.activeElement;\n      }\n      return null;\n    },\n\n    cachedAttr: function(ele, key, value) {\n      ele = ele && ele.length && ele[0] || ele;\n      if (ele && ele.setAttribute) {\n        var dataKey = '$attr-' + key;\n        if (arguments.length > 2) {\n          if (ele[dataKey] !== value) {\n            ele.setAttribute(key, value);\n            ele[dataKey] = value;\n          }\n        } else if (typeof ele[dataKey] == 'undefined') {\n          ele[dataKey] = ele.getAttribute(key);\n        }\n        return ele[dataKey];\n      }\n    },\n\n    cachedStyles: function(ele, styles) {\n      ele = ele && ele.length && ele[0] || ele;\n      if (ele && ele.style) {\n        for (var prop in styles) {\n          if (ele['$style-' + prop] !== styles[prop]) {\n            ele.style[prop] = ele['$style-' + prop] = styles[prop];\n          }\n        }\n      }\n    }\n\n  };\n\n  //Shortcuts\n  ionic.requestAnimationFrame = ionic.DomUtil.requestAnimationFrame;\n  ionic.cancelAnimationFrame = ionic.DomUtil.cancelAnimationFrame;\n  ionic.animationFrameThrottle = ionic.DomUtil.animationFrameThrottle;\n\n})(window, document, ionic);\n\n/**\n * ion-events.js\n *\n * Author: Max Lynch <max@drifty.com>\n *\n * Framework events handles various mobile browser events, and\n * detects special events like tap/swipe/etc. and emits them\n * as custom events that can be used in an app.\n *\n * Portions lovingly adapted from github.com/maker/ratchet and github.com/alexgibson/tap.js - thanks guys!\n */\n\n(function(ionic) {\n\n  // Custom event polyfill\n  ionic.CustomEvent = (function() {\n    if( typeof window.CustomEvent === 'function' ) return CustomEvent;\n\n    var customEvent = function(event, params) {\n      var evt;\n      params = params || {\n        bubbles: false,\n        cancelable: false,\n        detail: undefined\n      };\n      try {\n        evt = document.createEvent(\"CustomEvent\");\n        evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);\n      } catch (error) {\n        // fallback for browsers that don't support createEvent('CustomEvent')\n        evt = document.createEvent(\"Event\");\n        for (var param in params) {\n          evt[param] = params[param];\n        }\n        evt.initEvent(event, params.bubbles, params.cancelable);\n      }\n      return evt;\n    };\n    customEvent.prototype = window.Event.prototype;\n    return customEvent;\n  })();\n\n\n  /**\n   * @ngdoc utility\n   * @name ionic.EventController\n   * @module ionic\n   */\n  ionic.EventController = {\n    VIRTUALIZED_EVENTS: ['tap', 'swipe', 'swiperight', 'swipeleft', 'drag', 'hold', 'release'],\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#trigger\n     * @alias ionic.trigger\n     * @param {string} eventType The event to trigger.\n     * @param {object} data The data for the event. Hint: pass in\n     * `{target: targetElement}`\n     * @param {boolean=} bubbles Whether the event should bubble up the DOM.\n     * @param {boolean=} cancelable Whether the event should be cancelable.\n     */\n    // Trigger a new event\n    trigger: function(eventType, data, bubbles, cancelable) {\n      var event = new ionic.CustomEvent(eventType, {\n        detail: data,\n        bubbles: !!bubbles,\n        cancelable: !!cancelable\n      });\n\n      // Make sure to trigger the event on the given target, or dispatch it from\n      // the window if we don't have an event target\n      data && data.target && data.target.dispatchEvent && data.target.dispatchEvent(event) || window.dispatchEvent(event);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#on\n     * @alias ionic.on\n     * @description Listen to an event on an element.\n     * @param {string} type The event to listen for.\n     * @param {function} callback The listener to be called.\n     * @param {DOMElement} element The element to listen for the event on.\n     */\n    on: function(type, callback, element) {\n      var e = element || window;\n\n      // Bind a gesture if it's a virtual event\n      for(var i = 0, j = this.VIRTUALIZED_EVENTS.length; i < j; i++) {\n        if(type == this.VIRTUALIZED_EVENTS[i]) {\n          var gesture = new ionic.Gesture(element);\n          gesture.on(type, callback);\n          return gesture;\n        }\n      }\n\n      // Otherwise bind a normal event\n      e.addEventListener(type, callback);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#off\n     * @alias ionic.off\n     * @description Remove an event listener.\n     * @param {string} type\n     * @param {function} callback\n     * @param {DOMElement} element\n     */\n    off: function(type, callback, element) {\n      element.removeEventListener(type, callback);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#onGesture\n     * @alias ionic.onGesture\n     * @description Add an event listener for a gesture on an element.\n     *\n     * Available eventTypes (from [hammer.js](http://eightmedia.github.io/hammer.js/)):\n     *\n     * `hold`, `tap`, `doubletap`, `drag`, `dragstart`, `dragend`, `dragup`, `dragdown`, <br/>\n     * `dragleft`, `dragright`, `swipe`, `swipeup`, `swipedown`, `swipeleft`, `swiperight`, <br/>\n     * `transform`, `transformstart`, `transformend`, `rotate`, `pinch`, `pinchin`, `pinchout`, </br>\n     * `touch`, `release`\n     *\n     * @param {string} eventType The gesture event to listen for.\n     * @param {function(e)} callback The function to call when the gesture\n     * happens.\n     * @param {DOMElement} element The angular element to listen for the event on.\n     * @param {object} options object.\n     * @returns {ionic.Gesture} The gesture object (use this to remove the gesture later on).\n     */\n    onGesture: function(type, callback, element, options) {\n      var gesture = new ionic.Gesture(element, options);\n      gesture.on(type, callback);\n      return gesture;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.EventController#offGesture\n     * @alias ionic.offGesture\n     * @description Remove an event listener for a gesture created on an element.\n     * @param {ionic.Gesture} gesture The gesture that should be removed.\n     * @param {string} eventType The gesture event to remove the listener for.\n     * @param {function(e)} callback The listener to remove.\n\n     */\n    offGesture: function(gesture, type, callback) {\n      gesture && gesture.off(type, callback);\n    },\n\n    handlePopState: function() {}\n  };\n\n\n  // Map some convenient top-level functions for event handling\n  ionic.on = function() { ionic.EventController.on.apply(ionic.EventController, arguments); };\n  ionic.off = function() { ionic.EventController.off.apply(ionic.EventController, arguments); };\n  ionic.trigger = ionic.EventController.trigger;//function() { ionic.EventController.trigger.apply(ionic.EventController.trigger, arguments); };\n  ionic.onGesture = function() { return ionic.EventController.onGesture.apply(ionic.EventController.onGesture, arguments); };\n  ionic.offGesture = function() { return ionic.EventController.offGesture.apply(ionic.EventController.offGesture, arguments); };\n\n})(window.ionic);\n\n/* eslint camelcase:0 */\n/**\n  * Simple gesture controllers with some common gestures that emit\n  * gesture events.\n  *\n  * Ported from github.com/EightMedia/hammer.js Gestures - thanks!\n  */\n(function(ionic) {\n\n  /**\n   * ionic.Gestures\n   * use this to create instances\n   * @param   {HTMLElement}   element\n   * @param   {Object}        options\n   * @returns {ionic.Gestures.Instance}\n   * @constructor\n   */\n  ionic.Gesture = function(element, options) {\n    return new ionic.Gestures.Instance(element, options || {});\n  };\n\n  ionic.Gestures = {};\n\n  // default settings\n  ionic.Gestures.defaults = {\n    // add css to the element to prevent the browser from doing\n    // its native behavior. this doesnt prevent the scrolling,\n    // but cancels the contextmenu, tap highlighting etc\n    // set to false to disable this\n    stop_browser_behavior: 'disable-user-behavior'\n  };\n\n  // detect touchevents\n  ionic.Gestures.HAS_POINTEREVENTS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled;\n  ionic.Gestures.HAS_TOUCHEVENTS = ('ontouchstart' in window);\n\n  // dont use mouseevents on mobile devices\n  ionic.Gestures.MOBILE_REGEX = /mobile|tablet|ip(ad|hone|od)|android|silk/i;\n  ionic.Gestures.NO_MOUSEEVENTS = ionic.Gestures.HAS_TOUCHEVENTS && window.navigator.userAgent.match(ionic.Gestures.MOBILE_REGEX);\n\n  // eventtypes per touchevent (start, move, end)\n  // are filled by ionic.Gestures.event.determineEventTypes on setup\n  ionic.Gestures.EVENT_TYPES = {};\n\n  // direction defines\n  ionic.Gestures.DIRECTION_DOWN = 'down';\n  ionic.Gestures.DIRECTION_LEFT = 'left';\n  ionic.Gestures.DIRECTION_UP = 'up';\n  ionic.Gestures.DIRECTION_RIGHT = 'right';\n\n  // pointer type\n  ionic.Gestures.POINTER_MOUSE = 'mouse';\n  ionic.Gestures.POINTER_TOUCH = 'touch';\n  ionic.Gestures.POINTER_PEN = 'pen';\n\n  // touch event defines\n  ionic.Gestures.EVENT_START = 'start';\n  ionic.Gestures.EVENT_MOVE = 'move';\n  ionic.Gestures.EVENT_END = 'end';\n\n  // hammer document where the base events are added at\n  ionic.Gestures.DOCUMENT = window.document;\n\n  // plugins namespace\n  ionic.Gestures.plugins = {};\n\n  // if the window events are set...\n  ionic.Gestures.READY = false;\n\n  /**\n   * setup events to detect gestures on the document\n   */\n  function setup() {\n    if(ionic.Gestures.READY) {\n      return;\n    }\n\n    // find what eventtypes we add listeners to\n    ionic.Gestures.event.determineEventTypes();\n\n    // Register all gestures inside ionic.Gestures.gestures\n    for(var name in ionic.Gestures.gestures) {\n      if(ionic.Gestures.gestures.hasOwnProperty(name)) {\n        ionic.Gestures.detection.register(ionic.Gestures.gestures[name]);\n      }\n    }\n\n    // Add touch events on the document\n    ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_MOVE, ionic.Gestures.detection.detect);\n    ionic.Gestures.event.onTouch(ionic.Gestures.DOCUMENT, ionic.Gestures.EVENT_END, ionic.Gestures.detection.detect);\n\n    // ionic.Gestures is ready...!\n    ionic.Gestures.READY = true;\n  }\n\n  /**\n   * create new hammer instance\n   * all methods should return the instance itself, so it is chainable.\n   * @param   {HTMLElement}       element\n   * @param   {Object}            [options={}]\n   * @returns {ionic.Gestures.Instance}\n   * @name Gesture.Instance\n   * @constructor\n   */\n  ionic.Gestures.Instance = function(element, options) {\n    var self = this;\n\n    // A null element was passed into the instance, which means\n    // whatever lookup was done to find this element failed to find it\n    // so we can't listen for events on it.\n    if(element === null) {\n      void 0;\n      return this;\n    }\n\n    // setup ionic.GesturesJS window events and register all gestures\n    // this also sets up the default options\n    setup();\n\n    this.element = element;\n\n    // start/stop detection option\n    this.enabled = true;\n\n    // merge options\n    this.options = ionic.Gestures.utils.extend(\n        ionic.Gestures.utils.extend({}, ionic.Gestures.defaults),\n        options || {});\n\n    // add some css to the element to prevent the browser from doing its native behavoir\n    if(this.options.stop_browser_behavior) {\n      ionic.Gestures.utils.stopDefaultBrowserBehavior(this.element, this.options.stop_browser_behavior);\n    }\n\n    // start detection on touchstart\n    ionic.Gestures.event.onTouch(element, ionic.Gestures.EVENT_START, function(ev) {\n      if(self.enabled) {\n        ionic.Gestures.detection.startDetect(self, ev);\n      }\n    });\n\n    // return instance\n    return this;\n  };\n\n\n  ionic.Gestures.Instance.prototype = {\n    /**\n     * bind events to the instance\n     * @param   {String}      gesture\n     * @param   {Function}    handler\n     * @returns {ionic.Gestures.Instance}\n     */\n    on: function onEvent(gesture, handler){\n      var gestures = gesture.split(' ');\n      for(var t = 0; t < gestures.length; t++) {\n        this.element.addEventListener(gestures[t], handler, false);\n      }\n      return this;\n    },\n\n\n    /**\n     * unbind events to the instance\n     * @param   {String}      gesture\n     * @param   {Function}    handler\n     * @returns {ionic.Gestures.Instance}\n     */\n    off: function offEvent(gesture, handler){\n      var gestures = gesture.split(' ');\n      for(var t = 0; t < gestures.length; t++) {\n        this.element.removeEventListener(gestures[t], handler, false);\n      }\n      return this;\n    },\n\n\n    /**\n     * trigger gesture event\n     * @param   {String}      gesture\n     * @param   {Object}      eventData\n     * @returns {ionic.Gestures.Instance}\n     */\n    trigger: function triggerEvent(gesture, eventData){\n      // create DOM event\n      var event = ionic.Gestures.DOCUMENT.createEvent('Event');\n      event.initEvent(gesture, true, true);\n      event.gesture = eventData;\n\n      // trigger on the target if it is in the instance element,\n      // this is for event delegation tricks\n      var element = this.element;\n      if(ionic.Gestures.utils.hasParent(eventData.target, element)) {\n        element = eventData.target;\n      }\n\n      element.dispatchEvent(event);\n      return this;\n    },\n\n\n    /**\n     * enable of disable hammer.js detection\n     * @param   {Boolean}   state\n     * @returns {ionic.Gestures.Instance}\n     */\n    enable: function enable(state) {\n      this.enabled = state;\n      return this;\n    }\n  };\n\n  /**\n   * this holds the last move event,\n   * used to fix empty touchend issue\n   * see the onTouch event for an explanation\n   * type {Object}\n   */\n  var last_move_event = null;\n\n\n  /**\n   * when the mouse is hold down, this is true\n   * type {Boolean}\n   */\n  var enable_detect = false;\n\n\n  /**\n   * when touch events have been fired, this is true\n   * type {Boolean}\n   */\n  var touch_triggered = false;\n\n\n  ionic.Gestures.event = {\n    /**\n     * simple addEventListener\n     * @param   {HTMLElement}   element\n     * @param   {String}        type\n     * @param   {Function}      handler\n     */\n    bindDom: function(element, type, handler) {\n      var types = type.split(' ');\n      for(var t = 0; t < types.length; t++) {\n        element.addEventListener(types[t], handler, false);\n      }\n    },\n\n\n    /**\n     * touch events with mouse fallback\n     * @param   {HTMLElement}   element\n     * @param   {String}        eventType        like ionic.Gestures.EVENT_MOVE\n     * @param   {Function}      handler\n     */\n    onTouch: function onTouch(element, eventType, handler) {\n      var self = this;\n\n      this.bindDom(element, ionic.Gestures.EVENT_TYPES[eventType], function bindDomOnTouch(ev) {\n        var sourceEventType = ev.type.toLowerCase();\n\n        // onmouseup, but when touchend has been fired we do nothing.\n        // this is for touchdevices which also fire a mouseup on touchend\n        if(sourceEventType.match(/mouse/) && touch_triggered) {\n          return;\n        }\n\n        // mousebutton must be down or a touch event\n        else if( sourceEventType.match(/touch/) ||   // touch events are always on screen\n          sourceEventType.match(/pointerdown/) || // pointerevents touch\n          (sourceEventType.match(/mouse/) && ev.which === 1)   // mouse is pressed\n          ){\n            enable_detect = true;\n          }\n\n        // mouse isn't pressed\n        else if(sourceEventType.match(/mouse/) && ev.which !== 1) {\n          enable_detect = false;\n        }\n\n\n        // we are in a touch event, set the touch triggered bool to true,\n        // this for the conflicts that may occur on ios and android\n        if(sourceEventType.match(/touch|pointer/)) {\n          touch_triggered = true;\n        }\n\n        // count the total touches on the screen\n        var count_touches = 0;\n\n        // when touch has been triggered in this detection session\n        // and we are now handling a mouse event, we stop that to prevent conflicts\n        if(enable_detect) {\n          // update pointerevent\n          if(ionic.Gestures.HAS_POINTEREVENTS && eventType != ionic.Gestures.EVENT_END) {\n            count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);\n          }\n          // touch\n          else if(sourceEventType.match(/touch/)) {\n            count_touches = ev.touches.length;\n          }\n          // mouse\n          else if(!touch_triggered) {\n            count_touches = sourceEventType.match(/up/) ? 0 : 1;\n          }\n\n          // if we are in a end event, but when we remove one touch and\n          // we still have enough, set eventType to move\n          if(count_touches > 0 && eventType == ionic.Gestures.EVENT_END) {\n            eventType = ionic.Gestures.EVENT_MOVE;\n          }\n          // no touches, force the end event\n          else if(!count_touches) {\n            eventType = ionic.Gestures.EVENT_END;\n          }\n\n          // store the last move event\n          if(count_touches || last_move_event === null) {\n            last_move_event = ev;\n          }\n\n          // trigger the handler\n          handler.call(ionic.Gestures.detection, self.collectEventData(element, eventType, self.getTouchList(last_move_event, eventType), ev));\n\n          // remove pointerevent from list\n          if(ionic.Gestures.HAS_POINTEREVENTS && eventType == ionic.Gestures.EVENT_END) {\n            count_touches = ionic.Gestures.PointerEvent.updatePointer(eventType, ev);\n          }\n        }\n\n        //debug(sourceEventType +\" \"+ eventType);\n\n        // on the end we reset everything\n        if(!count_touches) {\n          last_move_event = null;\n          enable_detect = false;\n          touch_triggered = false;\n          ionic.Gestures.PointerEvent.reset();\n        }\n      });\n    },\n\n\n    /**\n     * we have different events for each device/browser\n     * determine what we need and set them in the ionic.Gestures.EVENT_TYPES constant\n     */\n    determineEventTypes: function determineEventTypes() {\n      // determine the eventtype we want to set\n      var types;\n\n      // pointerEvents magic\n      if(ionic.Gestures.HAS_POINTEREVENTS) {\n        types = ionic.Gestures.PointerEvent.getEvents();\n      }\n      // on Android, iOS, blackberry, windows mobile we dont want any mouseevents\n      else if(ionic.Gestures.NO_MOUSEEVENTS) {\n        types = [\n          'touchstart',\n          'touchmove',\n          'touchend touchcancel'];\n      }\n      // for non pointer events browsers and mixed browsers,\n      // like chrome on windows8 touch laptop\n      else {\n        types = [\n          'touchstart mousedown',\n          'touchmove mousemove',\n          'touchend touchcancel mouseup'];\n      }\n\n      ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_START] = types[0];\n      ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_MOVE] = types[1];\n      ionic.Gestures.EVENT_TYPES[ionic.Gestures.EVENT_END] = types[2];\n    },\n\n\n    /**\n     * create touchlist depending on the event\n     * @param   {Object}    ev\n     * @param   {String}    eventType   used by the fakemultitouch plugin\n     */\n    getTouchList: function getTouchList(ev/*, eventType*/) {\n      // get the fake pointerEvent touchlist\n      if(ionic.Gestures.HAS_POINTEREVENTS) {\n        return ionic.Gestures.PointerEvent.getTouchList();\n      }\n      // get the touchlist\n      else if(ev.touches) {\n        return ev.touches;\n      }\n      // make fake touchlist from mouse position\n      else {\n        ev.identifier = 1;\n        return [ev];\n      }\n    },\n\n\n    /**\n     * collect event data for ionic.Gestures js\n     * @param   {HTMLElement}   element\n     * @param   {String}        eventType        like ionic.Gestures.EVENT_MOVE\n     * @param   {Object}        eventData\n     */\n    collectEventData: function collectEventData(element, eventType, touches, ev) {\n\n      // find out pointerType\n      var pointerType = ionic.Gestures.POINTER_TOUCH;\n      if(ev.type.match(/mouse/) || ionic.Gestures.PointerEvent.matchType(ionic.Gestures.POINTER_MOUSE, ev)) {\n        pointerType = ionic.Gestures.POINTER_MOUSE;\n      }\n\n      return {\n        center: ionic.Gestures.utils.getCenter(touches),\n        timeStamp: new Date().getTime(),\n        target: ev.target,\n        touches: touches,\n        eventType: eventType,\n        pointerType: pointerType,\n        srcEvent: ev,\n\n        /**\n         * prevent the browser default actions\n         * mostly used to disable scrolling of the browser\n         */\n        preventDefault: function() {\n          if(this.srcEvent.preventManipulation) {\n            this.srcEvent.preventManipulation();\n          }\n\n          if(this.srcEvent.preventDefault) {\n            // this.srcEvent.preventDefault();\n          }\n        },\n\n        /**\n         * stop bubbling the event up to its parents\n         */\n        stopPropagation: function() {\n          this.srcEvent.stopPropagation();\n        },\n\n        /**\n         * immediately stop gesture detection\n         * might be useful after a swipe was detected\n         * @return {*}\n         */\n        stopDetect: function() {\n          return ionic.Gestures.detection.stopDetect();\n        }\n      };\n    }\n  };\n\n  ionic.Gestures.PointerEvent = {\n    /**\n     * holds all pointers\n     * type {Object}\n     */\n    pointers: {},\n\n    /**\n     * get a list of pointers\n     * @returns {Array}     touchlist\n     */\n    getTouchList: function() {\n      var self = this;\n      var touchlist = [];\n\n      // we can use forEach since pointerEvents only is in IE10\n      Object.keys(self.pointers).sort().forEach(function(id) {\n        touchlist.push(self.pointers[id]);\n      });\n      return touchlist;\n    },\n\n    /**\n     * update the position of a pointer\n     * @param   {String}   type             ionic.Gestures.EVENT_END\n     * @param   {Object}   pointerEvent\n     */\n    updatePointer: function(type, pointerEvent) {\n      if(type == ionic.Gestures.EVENT_END) {\n        this.pointers = {};\n      }\n      else {\n        pointerEvent.identifier = pointerEvent.pointerId;\n        this.pointers[pointerEvent.pointerId] = pointerEvent;\n      }\n\n      return Object.keys(this.pointers).length;\n    },\n\n    /**\n     * check if ev matches pointertype\n     * @param   {String}        pointerType     ionic.Gestures.POINTER_MOUSE\n     * @param   {PointerEvent}  ev\n     */\n    matchType: function(pointerType, ev) {\n      if(!ev.pointerType) {\n        return false;\n      }\n\n      var types = {};\n      types[ionic.Gestures.POINTER_MOUSE] = (ev.pointerType == ev.MSPOINTER_TYPE_MOUSE || ev.pointerType == ionic.Gestures.POINTER_MOUSE);\n      types[ionic.Gestures.POINTER_TOUCH] = (ev.pointerType == ev.MSPOINTER_TYPE_TOUCH || ev.pointerType == ionic.Gestures.POINTER_TOUCH);\n      types[ionic.Gestures.POINTER_PEN] = (ev.pointerType == ev.MSPOINTER_TYPE_PEN || ev.pointerType == ionic.Gestures.POINTER_PEN);\n      return types[pointerType];\n    },\n\n\n    /**\n     * get events\n     */\n    getEvents: function() {\n      return [\n        'pointerdown MSPointerDown',\n      'pointermove MSPointerMove',\n      'pointerup pointercancel MSPointerUp MSPointerCancel'\n        ];\n    },\n\n    /**\n     * reset the list\n     */\n    reset: function() {\n      this.pointers = {};\n    }\n  };\n\n\n  ionic.Gestures.utils = {\n    /**\n     * extend method,\n     * also used for cloning when dest is an empty object\n     * @param   {Object}    dest\n     * @param   {Object}    src\n     * @param\t{Boolean}\tmerge\t\tdo a merge\n     * @returns {Object}    dest\n     */\n    extend: function extend(dest, src, merge) {\n      for (var key in src) {\n        if(dest[key] !== undefined && merge) {\n          continue;\n        }\n        dest[key] = src[key];\n      }\n      return dest;\n    },\n\n\n    /**\n     * find if a node is in the given parent\n     * used for event delegation tricks\n     * @param   {HTMLElement}   node\n     * @param   {HTMLElement}   parent\n     * @returns {boolean}       has_parent\n     */\n    hasParent: function(node, parent) {\n      while(node){\n        if(node == parent) {\n          return true;\n        }\n        node = node.parentNode;\n      }\n      return false;\n    },\n\n\n    /**\n     * get the center of all the touches\n     * @param   {Array}     touches\n     * @returns {Object}    center\n     */\n    getCenter: function getCenter(touches) {\n      var valuesX = [], valuesY = [];\n\n      for(var t = 0, len = touches.length; t < len; t++) {\n        valuesX.push(touches[t].pageX);\n        valuesY.push(touches[t].pageY);\n      }\n\n      return {\n        pageX: ((Math.min.apply(Math, valuesX) + Math.max.apply(Math, valuesX)) / 2),\n          pageY: ((Math.min.apply(Math, valuesY) + Math.max.apply(Math, valuesY)) / 2)\n      };\n    },\n\n\n    /**\n     * calculate the velocity between two points\n     * @param   {Number}    delta_time\n     * @param   {Number}    delta_x\n     * @param   {Number}    delta_y\n     * @returns {Object}    velocity\n     */\n    getVelocity: function getVelocity(delta_time, delta_x, delta_y) {\n      return {\n        x: Math.abs(delta_x / delta_time) || 0,\n        y: Math.abs(delta_y / delta_time) || 0\n      };\n    },\n\n\n    /**\n     * calculate the angle between two coordinates\n     * @param   {Touch}     touch1\n     * @param   {Touch}     touch2\n     * @returns {Number}    angle\n     */\n    getAngle: function getAngle(touch1, touch2) {\n      var y = touch2.pageY - touch1.pageY,\n      x = touch2.pageX - touch1.pageX;\n      return Math.atan2(y, x) * 180 / Math.PI;\n    },\n\n\n    /**\n     * angle to direction define\n     * @param   {Touch}     touch1\n     * @param   {Touch}     touch2\n     * @returns {String}    direction constant, like ionic.Gestures.DIRECTION_LEFT\n     */\n    getDirection: function getDirection(touch1, touch2) {\n      var x = Math.abs(touch1.pageX - touch2.pageX),\n      y = Math.abs(touch1.pageY - touch2.pageY);\n\n      if(x >= y) {\n        return touch1.pageX - touch2.pageX > 0 ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;\n      }\n      else {\n        return touch1.pageY - touch2.pageY > 0 ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;\n      }\n    },\n\n\n    /**\n     * calculate the distance between two touches\n     * @param   {Touch}     touch1\n     * @param   {Touch}     touch2\n     * @returns {Number}    distance\n     */\n    getDistance: function getDistance(touch1, touch2) {\n      var x = touch2.pageX - touch1.pageX,\n      y = touch2.pageY - touch1.pageY;\n      return Math.sqrt((x * x) + (y * y));\n    },\n\n\n    /**\n     * calculate the scale factor between two touchLists (fingers)\n     * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n     * @param   {Array}     start\n     * @param   {Array}     end\n     * @returns {Number}    scale\n     */\n    getScale: function getScale(start, end) {\n      // need two fingers...\n      if(start.length >= 2 && end.length >= 2) {\n        return this.getDistance(end[0], end[1]) /\n          this.getDistance(start[0], start[1]);\n      }\n      return 1;\n    },\n\n\n    /**\n     * calculate the rotation degrees between two touchLists (fingers)\n     * @param   {Array}     start\n     * @param   {Array}     end\n     * @returns {Number}    rotation\n     */\n    getRotation: function getRotation(start, end) {\n      // need two fingers\n      if(start.length >= 2 && end.length >= 2) {\n        return this.getAngle(end[1], end[0]) -\n          this.getAngle(start[1], start[0]);\n      }\n      return 0;\n    },\n\n\n    /**\n     * boolean if the direction is vertical\n     * @param    {String}    direction\n     * @returns  {Boolean}   is_vertical\n     */\n    isVertical: function isVertical(direction) {\n      return (direction == ionic.Gestures.DIRECTION_UP || direction == ionic.Gestures.DIRECTION_DOWN);\n    },\n\n\n    /**\n     * stop browser default behavior with css class\n     * @param   {HtmlElement}   element\n     * @param   {Object}        css_class\n     */\n    stopDefaultBrowserBehavior: function stopDefaultBrowserBehavior(element, css_class) {\n      // changed from making many style changes to just adding a preset classname\n      // less DOM manipulations, less code, and easier to control in the CSS side of things\n      // hammer.js doesn't come with CSS, but ionic does, which is why we prefer this method\n      if(element && element.classList) {\n        element.classList.add(css_class);\n        element.onselectstart = function() {\n          return false;\n        };\n      }\n    }\n  };\n\n\n  ionic.Gestures.detection = {\n    // contains all registred ionic.Gestures.gestures in the correct order\n    gestures: [],\n\n    // data of the current ionic.Gestures.gesture detection session\n    current: null,\n\n    // the previous ionic.Gestures.gesture session data\n    // is a full clone of the previous gesture.current object\n    previous: null,\n\n    // when this becomes true, no gestures are fired\n    stopped: false,\n\n\n    /**\n     * start ionic.Gestures.gesture detection\n     * @param   {ionic.Gestures.Instance}   inst\n     * @param   {Object}            eventData\n     */\n    startDetect: function startDetect(inst, eventData) {\n      // already busy with a ionic.Gestures.gesture detection on an element\n      if(this.current) {\n        return;\n      }\n\n      this.stopped = false;\n\n      this.current = {\n        inst: inst, // reference to ionic.GesturesInstance we're working for\n        startEvent: ionic.Gestures.utils.extend({}, eventData), // start eventData for distances, timing etc\n        lastEvent: false, // last eventData\n        name: '' // current gesture we're in/detected, can be 'tap', 'hold' etc\n      };\n\n      this.detect(eventData);\n    },\n\n\n    /**\n     * ionic.Gestures.gesture detection\n     * @param   {Object}    eventData\n     */\n    detect: function detect(eventData) {\n      if(!this.current || this.stopped) {\n        return null;\n      }\n\n      // extend event data with calculations about scale, distance etc\n      eventData = this.extendEventData(eventData);\n\n      // instance options\n      var inst_options = this.current.inst.options;\n\n      // call ionic.Gestures.gesture handlers\n      for(var g = 0, len = this.gestures.length; g < len; g++) {\n        var gesture = this.gestures[g];\n\n        // only when the instance options have enabled this gesture\n        if(!this.stopped && inst_options[gesture.name] !== false) {\n          // if a handler returns false, we stop with the detection\n          if(gesture.handler.call(gesture, eventData, this.current.inst) === false) {\n            this.stopDetect();\n            break;\n          }\n        }\n      }\n\n      // store as previous event event\n      if(this.current) {\n        this.current.lastEvent = eventData;\n      }\n\n      // endevent, but not the last touch, so dont stop\n      if(eventData.eventType == ionic.Gestures.EVENT_END && !eventData.touches.length - 1) {\n        this.stopDetect();\n      }\n\n      return eventData;\n    },\n\n\n    /**\n     * clear the ionic.Gestures.gesture vars\n     * this is called on endDetect, but can also be used when a final ionic.Gestures.gesture has been detected\n     * to stop other ionic.Gestures.gestures from being fired\n     */\n    stopDetect: function stopDetect() {\n      // clone current data to the store as the previous gesture\n      // used for the double tap gesture, since this is an other gesture detect session\n      this.previous = ionic.Gestures.utils.extend({}, this.current);\n\n      // reset the current\n      this.current = null;\n\n      // stopped!\n      this.stopped = true;\n    },\n\n\n    /**\n     * extend eventData for ionic.Gestures.gestures\n     * @param   {Object}   ev\n     * @returns {Object}   ev\n     */\n    extendEventData: function extendEventData(ev) {\n      var startEv = this.current.startEvent;\n\n      // if the touches change, set the new touches over the startEvent touches\n      // this because touchevents don't have all the touches on touchstart, or the\n      // user must place his fingers at the EXACT same time on the screen, which is not realistic\n      // but, sometimes it happens that both fingers are touching at the EXACT same time\n      if(startEv && (ev.touches.length != startEv.touches.length || ev.touches === startEv.touches)) {\n        // extend 1 level deep to get the touchlist with the touch objects\n        startEv.touches = [];\n        for(var i = 0, len = ev.touches.length; i < len; i++) {\n          startEv.touches.push(ionic.Gestures.utils.extend({}, ev.touches[i]));\n        }\n      }\n\n      var delta_time = ev.timeStamp - startEv.timeStamp,\n          delta_x = ev.center.pageX - startEv.center.pageX,\n          delta_y = ev.center.pageY - startEv.center.pageY,\n          velocity = ionic.Gestures.utils.getVelocity(delta_time, delta_x, delta_y);\n\n      ionic.Gestures.utils.extend(ev, {\n        deltaTime: delta_time,\n        deltaX: delta_x,\n        deltaY: delta_y,\n\n        velocityX: velocity.x,\n        velocityY: velocity.y,\n\n        distance: ionic.Gestures.utils.getDistance(startEv.center, ev.center),\n        angle: ionic.Gestures.utils.getAngle(startEv.center, ev.center),\n        direction: ionic.Gestures.utils.getDirection(startEv.center, ev.center),\n\n        scale: ionic.Gestures.utils.getScale(startEv.touches, ev.touches),\n        rotation: ionic.Gestures.utils.getRotation(startEv.touches, ev.touches),\n\n        startEvent: startEv\n      });\n\n      return ev;\n    },\n\n\n    /**\n     * register new gesture\n     * @param   {Object}    gesture object, see gestures.js for documentation\n     * @returns {Array}     gestures\n     */\n    register: function register(gesture) {\n      // add an enable gesture options if there is no given\n      var options = gesture.defaults || {};\n      if(options[gesture.name] === undefined) {\n        options[gesture.name] = true;\n      }\n\n      // extend ionic.Gestures default options with the ionic.Gestures.gesture options\n      ionic.Gestures.utils.extend(ionic.Gestures.defaults, options, true);\n\n      // set its index\n      gesture.index = gesture.index || 1000;\n\n      // add ionic.Gestures.gesture to the list\n      this.gestures.push(gesture);\n\n      // sort the list by index\n      this.gestures.sort(function(a, b) {\n        if (a.index < b.index) {\n          return -1;\n        }\n        if (a.index > b.index) {\n          return 1;\n        }\n        return 0;\n      });\n\n      return this.gestures;\n    }\n  };\n\n\n  ionic.Gestures.gestures = ionic.Gestures.gestures || {};\n\n  /**\n   * Custom gestures\n   * ==============================\n   *\n   * Gesture object\n   * --------------------\n   * The object structure of a gesture:\n   *\n   * { name: 'mygesture',\n   *   index: 1337,\n   *   defaults: {\n   *     mygesture_option: true\n   *   }\n   *   handler: function(type, ev, inst) {\n   *     // trigger gesture event\n   *     inst.trigger(this.name, ev);\n   *   }\n   * }\n\n   * @param   {String}    name\n   * this should be the name of the gesture, lowercase\n   * it is also being used to disable/enable the gesture per instance config.\n   *\n   * @param   {Number}    [index=1000]\n   * the index of the gesture, where it is going to be in the stack of gestures detection\n   * like when you build an gesture that depends on the drag gesture, it is a good\n   * idea to place it after the index of the drag gesture.\n   *\n   * @param   {Object}    [defaults={}]\n   * the default settings of the gesture. these are added to the instance settings,\n   * and can be overruled per instance. you can also add the name of the gesture,\n   * but this is also added by default (and set to true).\n   *\n   * @param   {Function}  handler\n   * this handles the gesture detection of your custom gesture and receives the\n   * following arguments:\n   *\n   *      @param  {Object}    eventData\n   *      event data containing the following properties:\n   *          timeStamp   {Number}        time the event occurred\n   *          target      {HTMLElement}   target element\n   *          touches     {Array}         touches (fingers, pointers, mouse) on the screen\n   *          pointerType {String}        kind of pointer that was used. matches ionic.Gestures.POINTER_MOUSE|TOUCH\n   *          center      {Object}        center position of the touches. contains pageX and pageY\n   *          deltaTime   {Number}        the total time of the touches in the screen\n   *          deltaX      {Number}        the delta on x axis we haved moved\n   *          deltaY      {Number}        the delta on y axis we haved moved\n   *          velocityX   {Number}        the velocity on the x\n   *          velocityY   {Number}        the velocity on y\n   *          angle       {Number}        the angle we are moving\n   *          direction   {String}        the direction we are moving. matches ionic.Gestures.DIRECTION_UP|DOWN|LEFT|RIGHT\n   *          distance    {Number}        the distance we haved moved\n   *          scale       {Number}        scaling of the touches, needs 2 touches\n   *          rotation    {Number}        rotation of the touches, needs 2 touches *\n   *          eventType   {String}        matches ionic.Gestures.EVENT_START|MOVE|END\n   *          srcEvent    {Object}        the source event, like TouchStart or MouseDown *\n   *          startEvent  {Object}        contains the same properties as above,\n   *                                      but from the first touch. this is used to calculate\n   *                                      distances, deltaTime, scaling etc\n   *\n   *      @param  {ionic.Gestures.Instance}    inst\n   *      the instance we are doing the detection for. you can get the options from\n   *      the inst.options object and trigger the gesture event by calling inst.trigger\n   *\n   *\n   * Handle gestures\n   * --------------------\n   * inside the handler you can get/set ionic.Gestures.detectionic.current. This is the current\n   * detection sessionic. It has the following properties\n   *      @param  {String}    name\n   *      contains the name of the gesture we have detected. it has not a real function,\n   *      only to check in other gestures if something is detected.\n   *      like in the drag gesture we set it to 'drag' and in the swipe gesture we can\n   *      check if the current gesture is 'drag' by accessing ionic.Gestures.detectionic.current.name\n   *\n   *      readonly\n   *      @param  {ionic.Gestures.Instance}    inst\n   *      the instance we do the detection for\n   *\n   *      readonly\n   *      @param  {Object}    startEvent\n   *      contains the properties of the first gesture detection in this sessionic.\n   *      Used for calculations about timing, distance, etc.\n   *\n   *      readonly\n   *      @param  {Object}    lastEvent\n   *      contains all the properties of the last gesture detect in this sessionic.\n   *\n   * after the gesture detection session has been completed (user has released the screen)\n   * the ionic.Gestures.detectionic.current object is copied into ionic.Gestures.detectionic.previous,\n   * this is usefull for gestures like doubletap, where you need to know if the\n   * previous gesture was a tap\n   *\n   * options that have been set by the instance can be received by calling inst.options\n   *\n   * You can trigger a gesture event by calling inst.trigger(\"mygesture\", event).\n   * The first param is the name of your gesture, the second the event argument\n   *\n   *\n   * Register gestures\n   * --------------------\n   * When an gesture is added to the ionic.Gestures.gestures object, it is auto registered\n   * at the setup of the first ionic.Gestures instance. You can also call ionic.Gestures.detectionic.register\n   * manually and pass your gesture object as a param\n   *\n   */\n\n  /**\n   * Hold\n   * Touch stays at the same place for x time\n   * events  hold\n   */\n  ionic.Gestures.gestures.Hold = {\n    name: 'hold',\n    index: 10,\n    defaults: {\n      hold_timeout: 500,\n      hold_threshold: 1\n    },\n    timer: null,\n    handler: function holdGesture(ev, inst) {\n      switch(ev.eventType) {\n        case ionic.Gestures.EVENT_START:\n          // clear any running timers\n          clearTimeout(this.timer);\n\n          // set the gesture so we can check in the timeout if it still is\n          ionic.Gestures.detection.current.name = this.name;\n\n          // set timer and if after the timeout it still is hold,\n          // we trigger the hold event\n          this.timer = setTimeout(function() {\n            if(ionic.Gestures.detection.current.name == 'hold') {\n              ionic.tap.cancelClick();\n              inst.trigger('hold', ev);\n            }\n          }, inst.options.hold_timeout);\n          break;\n\n          // when you move or end we clear the timer\n        case ionic.Gestures.EVENT_MOVE:\n          if(ev.distance > inst.options.hold_threshold) {\n            clearTimeout(this.timer);\n          }\n          break;\n\n        case ionic.Gestures.EVENT_END:\n          clearTimeout(this.timer);\n          break;\n      }\n    }\n  };\n\n\n  /**\n   * Tap/DoubleTap\n   * Quick touch at a place or double at the same place\n   * events  tap, doubletap\n   */\n  ionic.Gestures.gestures.Tap = {\n    name: 'tap',\n    index: 100,\n    defaults: {\n      tap_max_touchtime: 250,\n      tap_max_distance: 10,\n      tap_always: true,\n      doubletap_distance: 20,\n      doubletap_interval: 300\n    },\n    handler: function tapGesture(ev, inst) {\n      if(ev.eventType == ionic.Gestures.EVENT_END && ev.srcEvent.type != 'touchcancel') {\n        // previous gesture, for the double tap since these are two different gesture detections\n        var prev = ionic.Gestures.detection.previous,\n        did_doubletap = false;\n\n        // when the touchtime is higher then the max touch time\n        // or when the moving distance is too much\n        if(ev.deltaTime > inst.options.tap_max_touchtime ||\n            ev.distance > inst.options.tap_max_distance) {\n              return;\n            }\n\n        // check if double tap\n        if(prev && prev.name == 'tap' &&\n            (ev.timeStamp - prev.lastEvent.timeStamp) < inst.options.doubletap_interval &&\n            ev.distance < inst.options.doubletap_distance) {\n              inst.trigger('doubletap', ev);\n              did_doubletap = true;\n            }\n\n        // do a single tap\n        if(!did_doubletap || inst.options.tap_always) {\n          ionic.Gestures.detection.current.name = 'tap';\n          inst.trigger('tap', ev);\n        }\n      }\n    }\n  };\n\n\n  /**\n   * Swipe\n   * triggers swipe events when the end velocity is above the threshold\n   * events  swipe, swipeleft, swiperight, swipeup, swipedown\n   */\n  ionic.Gestures.gestures.Swipe = {\n    name: 'swipe',\n    index: 40,\n    defaults: {\n      // set 0 for unlimited, but this can conflict with transform\n      swipe_max_touches: 1,\n      swipe_velocity: 0.4\n    },\n    handler: function swipeGesture(ev, inst) {\n      if(ev.eventType == ionic.Gestures.EVENT_END) {\n        // max touches\n        if(inst.options.swipe_max_touches > 0 &&\n            ev.touches.length > inst.options.swipe_max_touches) {\n              return;\n            }\n\n        // when the distance we moved is too small we skip this gesture\n        // or we can be already in dragging\n        if(ev.velocityX > inst.options.swipe_velocity ||\n            ev.velocityY > inst.options.swipe_velocity) {\n              // trigger swipe events\n              inst.trigger(this.name, ev);\n              inst.trigger(this.name + ev.direction, ev);\n            }\n      }\n    }\n  };\n\n\n  /**\n   * Drag\n   * Move with x fingers (default 1) around on the page. Blocking the scrolling when\n   * moving left and right is a good practice. When all the drag events are blocking\n   * you disable scrolling on that area.\n   * events  drag, drapleft, dragright, dragup, dragdown\n   */\n  ionic.Gestures.gestures.Drag = {\n    name: 'drag',\n    index: 50,\n    defaults: {\n      drag_min_distance: 10,\n      // Set correct_for_drag_min_distance to true to make the starting point of the drag\n      // be calculated from where the drag was triggered, not from where the touch started.\n      // Useful to avoid a jerk-starting drag, which can make fine-adjustments\n      // through dragging difficult, and be visually unappealing.\n      correct_for_drag_min_distance: true,\n      // set 0 for unlimited, but this can conflict with transform\n      drag_max_touches: 1,\n      // prevent default browser behavior when dragging occurs\n      // be careful with it, it makes the element a blocking element\n      // when you are using the drag gesture, it is a good practice to set this true\n      drag_block_horizontal: true,\n      drag_block_vertical: true,\n      // drag_lock_to_axis keeps the drag gesture on the axis that it started on,\n      // It disallows vertical directions if the initial direction was horizontal, and vice versa.\n      drag_lock_to_axis: false,\n      // drag lock only kicks in when distance > drag_lock_min_distance\n      // This way, locking occurs only when the distance has become large enough to reliably determine the direction\n      drag_lock_min_distance: 25,\n      // prevent default if the gesture is going the given direction\n      prevent_default_directions: []\n    },\n    triggered: false,\n    handler: function dragGesture(ev, inst) {\n      if (ev.srcEvent.type == 'touchstart' || ev.srcEvent.type == 'touchend') {\n        this.preventedFirstMove = false;\n\n      } else if (!this.preventedFirstMove && ev.srcEvent.type == 'touchmove') {\n        if (inst.options.prevent_default_directions.indexOf(ev.direction) != -1) {\n          ev.srcEvent.preventDefault();\n        }\n        this.preventedFirstMove = true;\n      }\n\n      // current gesture isnt drag, but dragged is true\n      // this means an other gesture is busy. now call dragend\n      if(ionic.Gestures.detection.current.name != this.name && this.triggered) {\n        inst.trigger(this.name + 'end', ev);\n        this.triggered = false;\n        return;\n      }\n\n      // max touches\n      if(inst.options.drag_max_touches > 0 &&\n          ev.touches.length > inst.options.drag_max_touches) {\n            return;\n          }\n\n      switch(ev.eventType) {\n        case ionic.Gestures.EVENT_START:\n          this.triggered = false;\n          break;\n\n        case ionic.Gestures.EVENT_MOVE:\n          // when the distance we moved is too small we skip this gesture\n          // or we can be already in dragging\n          if(ev.distance < inst.options.drag_min_distance &&\n              ionic.Gestures.detection.current.name != this.name) {\n                return;\n              }\n\n          // we are dragging!\n          if(ionic.Gestures.detection.current.name != this.name) {\n            ionic.Gestures.detection.current.name = this.name;\n            if (inst.options.correct_for_drag_min_distance) {\n              // When a drag is triggered, set the event center to drag_min_distance pixels from the original event center.\n              // Without this correction, the dragged distance would jumpstart at drag_min_distance pixels instead of at 0.\n              // It might be useful to save the original start point somewhere\n              var factor = Math.abs(inst.options.drag_min_distance / ev.distance);\n              ionic.Gestures.detection.current.startEvent.center.pageX += ev.deltaX * factor;\n              ionic.Gestures.detection.current.startEvent.center.pageY += ev.deltaY * factor;\n\n              // recalculate event data using new start point\n              ev = ionic.Gestures.detection.extendEventData(ev);\n            }\n          }\n\n          // lock drag to axis?\n          if(ionic.Gestures.detection.current.lastEvent.drag_locked_to_axis || (inst.options.drag_lock_to_axis && inst.options.drag_lock_min_distance <= ev.distance)) {\n            ev.drag_locked_to_axis = true;\n          }\n          var last_direction = ionic.Gestures.detection.current.lastEvent.direction;\n          if(ev.drag_locked_to_axis && last_direction !== ev.direction) {\n            // keep direction on the axis that the drag gesture started on\n            if(ionic.Gestures.utils.isVertical(last_direction)) {\n              ev.direction = (ev.deltaY < 0) ? ionic.Gestures.DIRECTION_UP : ionic.Gestures.DIRECTION_DOWN;\n            }\n            else {\n              ev.direction = (ev.deltaX < 0) ? ionic.Gestures.DIRECTION_LEFT : ionic.Gestures.DIRECTION_RIGHT;\n            }\n          }\n\n          // first time, trigger dragstart event\n          if(!this.triggered) {\n            inst.trigger(this.name + 'start', ev);\n            this.triggered = true;\n          }\n\n          // trigger normal event\n          inst.trigger(this.name, ev);\n\n          // direction event, like dragdown\n          inst.trigger(this.name + ev.direction, ev);\n\n          // block the browser events\n          if( (inst.options.drag_block_vertical && ionic.Gestures.utils.isVertical(ev.direction)) ||\n              (inst.options.drag_block_horizontal && !ionic.Gestures.utils.isVertical(ev.direction))) {\n                ev.preventDefault();\n              }\n          break;\n\n        case ionic.Gestures.EVENT_END:\n          // trigger dragend\n          if(this.triggered) {\n            inst.trigger(this.name + 'end', ev);\n          }\n\n          this.triggered = false;\n          break;\n      }\n    }\n  };\n\n\n  /**\n   * Transform\n   * User want to scale or rotate with 2 fingers\n   * events  transform, pinch, pinchin, pinchout, rotate\n   */\n  ionic.Gestures.gestures.Transform = {\n    name: 'transform',\n    index: 45,\n    defaults: {\n      // factor, no scale is 1, zoomin is to 0 and zoomout until higher then 1\n      transform_min_scale: 0.01,\n      // rotation in degrees\n      transform_min_rotation: 1,\n      // prevent default browser behavior when two touches are on the screen\n      // but it makes the element a blocking element\n      // when you are using the transform gesture, it is a good practice to set this true\n      transform_always_block: false\n    },\n    triggered: false,\n    handler: function transformGesture(ev, inst) {\n      // current gesture isnt drag, but dragged is true\n      // this means an other gesture is busy. now call dragend\n      if(ionic.Gestures.detection.current.name != this.name && this.triggered) {\n        inst.trigger(this.name + 'end', ev);\n        this.triggered = false;\n        return;\n      }\n\n      // atleast multitouch\n      if(ev.touches.length < 2) {\n        return;\n      }\n\n      // prevent default when two fingers are on the screen\n      if(inst.options.transform_always_block) {\n        ev.preventDefault();\n      }\n\n      switch(ev.eventType) {\n        case ionic.Gestures.EVENT_START:\n          this.triggered = false;\n          break;\n\n        case ionic.Gestures.EVENT_MOVE:\n          var scale_threshold = Math.abs(1 - ev.scale);\n          var rotation_threshold = Math.abs(ev.rotation);\n\n          // when the distance we moved is too small we skip this gesture\n          // or we can be already in dragging\n          if(scale_threshold < inst.options.transform_min_scale &&\n              rotation_threshold < inst.options.transform_min_rotation) {\n                return;\n              }\n\n          // we are transforming!\n          ionic.Gestures.detection.current.name = this.name;\n\n          // first time, trigger dragstart event\n          if(!this.triggered) {\n            inst.trigger(this.name + 'start', ev);\n            this.triggered = true;\n          }\n\n          inst.trigger(this.name, ev); // basic transform event\n\n          // trigger rotate event\n          if(rotation_threshold > inst.options.transform_min_rotation) {\n            inst.trigger('rotate', ev);\n          }\n\n          // trigger pinch event\n          if(scale_threshold > inst.options.transform_min_scale) {\n            inst.trigger('pinch', ev);\n            inst.trigger('pinch' + ((ev.scale < 1) ? 'in' : 'out'), ev);\n          }\n          break;\n\n        case ionic.Gestures.EVENT_END:\n          // trigger dragend\n          if(this.triggered) {\n            inst.trigger(this.name + 'end', ev);\n          }\n\n          this.triggered = false;\n          break;\n      }\n    }\n  };\n\n\n  /**\n   * Touch\n   * Called as first, tells the user has touched the screen\n   * events  touch\n   */\n  ionic.Gestures.gestures.Touch = {\n    name: 'touch',\n    index: -Infinity,\n    defaults: {\n      // call preventDefault at touchstart, and makes the element blocking by\n      // disabling the scrolling of the page, but it improves gestures like\n      // transforming and dragging.\n      // be careful with using this, it can be very annoying for users to be stuck\n      // on the page\n      prevent_default: false,\n\n      // disable mouse events, so only touch (or pen!) input triggers events\n      prevent_mouseevents: false\n    },\n    handler: function touchGesture(ev, inst) {\n      if(inst.options.prevent_mouseevents && ev.pointerType == ionic.Gestures.POINTER_MOUSE) {\n        ev.stopDetect();\n        return;\n      }\n\n      if(inst.options.prevent_default) {\n        ev.preventDefault();\n      }\n\n      if(ev.eventType == ionic.Gestures.EVENT_START) {\n        inst.trigger(this.name, ev);\n      }\n    }\n  };\n\n\n  /**\n   * Release\n   * Called as last, tells the user has released the screen\n   * events  release\n   */\n  ionic.Gestures.gestures.Release = {\n    name: 'release',\n    index: Infinity,\n    handler: function releaseGesture(ev, inst) {\n      if(ev.eventType == ionic.Gestures.EVENT_END) {\n        inst.trigger(this.name, ev);\n      }\n    }\n  };\n})(window.ionic);\n\n(function(window, document, ionic) {\n\n  function getParameterByName(name) {\n    name = name.replace(/[\\[]/, \"\\\\[\").replace(/[\\]]/, \"\\\\]\");\n    var regex = new RegExp(\"[\\\\?&]\" + name + \"=([^&#]*)\"),\n    results = regex.exec(location.search);\n    return results === null ? \"\" : decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n  }\n\n  var IOS = 'ios';\n  var ANDROID = 'android';\n  var WINDOWS_PHONE = 'windowsphone';\n  var requestAnimationFrame = ionic.requestAnimationFrame;\n\n  /**\n   * @ngdoc utility\n   * @name ionic.Platform\n   * @module ionic\n   * @description\n   * A set of utility methods that can be used to retrieve the device ready state and\n   * various other information such as what kind of platform the app is currently installed on.\n   *\n   * @usage\n   * ```js\n   * angular.module('PlatformApp', ['ionic'])\n   * .controller('PlatformCtrl', function($scope) {\n   *\n   *   ionic.Platform.ready(function(){\n   *     // will execute when device is ready, or immediately if the device is already ready.\n   *   });\n   *\n   *   var deviceInformation = ionic.Platform.device();\n   *\n   *   var isWebView = ionic.Platform.isWebView();\n   *   var isIPad = ionic.Platform.isIPad();\n   *   var isIOS = ionic.Platform.isIOS();\n   *   var isAndroid = ionic.Platform.isAndroid();\n   *   var isWindowsPhone = ionic.Platform.isWindowsPhone();\n   *\n   *   var currentPlatform = ionic.Platform.platform();\n   *   var currentPlatformVersion = ionic.Platform.version();\n   *\n   *   ionic.Platform.exitApp(); // stops the app\n   * });\n   * ```\n   */\n  var self = ionic.Platform = {\n\n    // Put navigator on platform so it can be mocked and set\n    // the browser does not allow window.navigator to be set\n    navigator: window.navigator,\n\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#isReady\n     * @returns {boolean} Whether the device is ready.\n     */\n    isReady: false,\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#isFullScreen\n     * @returns {boolean} Whether the device is fullscreen.\n     */\n    isFullScreen: false,\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#platforms\n     * @returns {Array(string)} An array of all platforms found.\n     */\n    platforms: null,\n    /**\n     * @ngdoc property\n     * @name ionic.Platform#grade\n     * @returns {string} What grade the current platform is.\n     */\n    grade: null,\n    ua: navigator.userAgent,\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#ready\n     * @description\n     * Trigger a callback once the device is ready, or immediately\n     * if the device is already ready. This method can be run from\n     * anywhere and does not need to be wrapped by any additonal methods.\n     * When the app is within a WebView (Cordova), it'll fire\n     * the callback once the device is ready. If the app is within\n     * a web browser, it'll fire the callback after `window.load`.\n     * Please remember that Cordova features (Camera, FileSystem, etc) still\n     * will not work in a web browser.\n     * @param {function} callback The function to call.\n     */\n    ready: function(cb) {\n      // run through tasks to complete now that the device is ready\n      if (self.isReady) {\n        cb();\n      } else {\n        // the platform isn't ready yet, add it to this array\n        // which will be called once the platform is ready\n        readyCallbacks.push(cb);\n      }\n    },\n\n    /**\n     * @private\n     */\n    detect: function() {\n      self._checkPlatforms();\n\n      requestAnimationFrame(function() {\n        // only add to the body class if we got platform info\n        for (var i = 0; i < self.platforms.length; i++) {\n          document.body.classList.add('platform-' + self.platforms[i]);\n        }\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#setGrade\n     * @description Set the grade of the device: 'a', 'b', or 'c'. 'a' is the best\n     * (most css features enabled), 'c' is the worst.  By default, sets the grade\n     * depending on the current device.\n     * @param {string} grade The new grade to set.\n     */\n    setGrade: function(grade) {\n      var oldGrade = self.grade;\n      self.grade = grade;\n      requestAnimationFrame(function() {\n        if (oldGrade) {\n          document.body.classList.remove('grade-' + oldGrade);\n        }\n        document.body.classList.add('grade-' + grade);\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#device\n     * @description Return the current device (given by cordova).\n     * @returns {object} The device object.\n     */\n    device: function() {\n      return window.device || {};\n    },\n\n    _checkPlatforms: function() {\n      self.platforms = [];\n      var grade = 'a';\n\n      if (self.isWebView()) {\n        self.platforms.push('webview');\n        if (!(!window.cordova && !window.PhoneGap && !window.phonegap)) {\n          self.platforms.push('cordova');\n        } else if (window.forge) {\n          self.platforms.push('trigger');\n        }\n      } else {\n        self.platforms.push('browser');\n      }\n      if (self.isIPad()) self.platforms.push('ipad');\n\n      var platform = self.platform();\n      if (platform) {\n        self.platforms.push(platform);\n\n        var version = self.version();\n        if (version) {\n          var v = version.toString();\n          if (v.indexOf('.') > 0) {\n            v = v.replace('.', '_');\n          } else {\n            v += '_0';\n          }\n          self.platforms.push(platform + v.split('_')[0]);\n          self.platforms.push(platform + v);\n\n          if (self.isAndroid() && version < 4.4) {\n            grade = (version < 4 ? 'c' : 'b');\n          } else if (self.isWindowsPhone()) {\n            grade = 'b';\n          }\n        }\n      }\n\n      self.setGrade(grade);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isWebView\n     * @returns {boolean} Check if we are running within a WebView (such as Cordova).\n     */\n    isWebView: function() {\n      return !(!window.cordova && !window.PhoneGap && !window.phonegap && !window.forge);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isIPad\n     * @returns {boolean} Whether we are running on iPad.\n     */\n    isIPad: function() {\n      if (/iPad/i.test(self.navigator.platform)) {\n        return true;\n      }\n      return /iPad/i.test(self.ua);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isIOS\n     * @returns {boolean} Whether we are running on iOS.\n     */\n    isIOS: function() {\n      return self.is(IOS);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isAndroid\n     * @returns {boolean} Whether we are running on Android.\n     */\n    isAndroid: function() {\n      return self.is(ANDROID);\n    },\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#isWindowsPhone\n     * @returns {boolean} Whether we are running on Windows Phone.\n     */\n    isWindowsPhone: function() {\n      return self.is(WINDOWS_PHONE);\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#platform\n     * @returns {string} The name of the current platform.\n     */\n    platform: function() {\n      // singleton to get the platform name\n      if (platformName === null) self.setPlatform(self.device().platform);\n      return platformName;\n    },\n\n    /**\n     * @private\n     */\n    setPlatform: function(n) {\n      if (typeof n != 'undefined' && n !== null && n.length) {\n        platformName = n.toLowerCase();\n      } else if (getParameterByName('ionicplatform')) {\n        platformName = getParameterByName('ionicplatform');\n      } else if (self.ua.indexOf('Android') > 0) {\n        platformName = ANDROID;\n      } else if (/iPhone|iPad|iPod/.test(self.ua)) {\n        platformName = IOS;\n      } else if (self.ua.indexOf('Windows Phone') > -1) {\n        platformName = WINDOWS_PHONE;\n      } else {\n        platformName = self.navigator.platform && navigator.platform.toLowerCase().split(' ')[0] || '';\n      }\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#version\n     * @returns {number} The version of the current device platform.\n     */\n    version: function() {\n      // singleton to get the platform version\n      if (platformVersion === null) self.setVersion(self.device().version);\n      return platformVersion;\n    },\n\n    /**\n     * @private\n     */\n    setVersion: function(v) {\n      if (typeof v != 'undefined' && v !== null) {\n        v = v.split('.');\n        v = parseFloat(v[0] + '.' + (v.length > 1 ? v[1] : 0));\n        if (!isNaN(v)) {\n          platformVersion = v;\n          return;\n        }\n      }\n\n      platformVersion = 0;\n\n      // fallback to user-agent checking\n      var pName = self.platform();\n      var versionMatch = {\n        'android': /Android (\\d+).(\\d+)?/,\n        'ios': /OS (\\d+)_(\\d+)?/,\n        'windowsphone': /Windows Phone (\\d+).(\\d+)?/\n      };\n      if (versionMatch[pName]) {\n        v = self.ua.match(versionMatch[pName]);\n        if (v && v.length > 2) {\n          platformVersion = parseFloat(v[1] + '.' + v[2]);\n        }\n      }\n    },\n\n    // Check if the platform is the one detected by cordova\n    is: function(type) {\n      type = type.toLowerCase();\n      // check if it has an array of platforms\n      if (self.platforms) {\n        for (var x = 0; x < self.platforms.length; x++) {\n          if (self.platforms[x] === type) return true;\n        }\n      }\n      // exact match\n      var pName = self.platform();\n      if (pName) {\n        return pName === type.toLowerCase();\n      }\n\n      // A quick hack for to check userAgent\n      return self.ua.toLowerCase().indexOf(type) >= 0;\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#exitApp\n     * @description Exit the app.\n     */\n    exitApp: function() {\n      self.ready(function() {\n        navigator.app && navigator.app.exitApp && navigator.app.exitApp();\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#showStatusBar\n     * @description Shows or hides the device status bar (in Cordova). Requires `cordova plugin add org.apache.cordova.statusbar`\n     * @param {boolean} shouldShow Whether or not to show the status bar.\n     */\n    showStatusBar: function(val) {\n      // Only useful when run within cordova\n      self._showStatusBar = val;\n      self.ready(function() {\n        // run this only when or if the platform (cordova) is ready\n        requestAnimationFrame(function() {\n          if (self._showStatusBar) {\n            // they do not want it to be full screen\n            window.StatusBar && window.StatusBar.show();\n            document.body.classList.remove('status-bar-hide');\n          } else {\n            // it should be full screen\n            window.StatusBar && window.StatusBar.hide();\n            document.body.classList.add('status-bar-hide');\n          }\n        });\n      });\n    },\n\n    /**\n     * @ngdoc method\n     * @name ionic.Platform#fullScreen\n     * @description\n     * Sets whether the app is fullscreen or not (in Cordova).\n     * @param {boolean=} showFullScreen Whether or not to set the app to fullscreen. Defaults to true. Requires `cordova plugin add org.apache.cordova.statusbar`\n     * @param {boolean=} showStatusBar Whether or not to show the device's status bar. Defaults to false.\n     */\n    fullScreen: function(showFullScreen, showStatusBar) {\n      // showFullScreen: default is true if no param provided\n      self.isFullScreen = (showFullScreen !== false);\n\n      // add/remove the fullscreen classname to the body\n      ionic.DomUtil.ready(function() {\n        // run this only when or if the DOM is ready\n        requestAnimationFrame(function() {\n          if (self.isFullScreen) {\n            document.body.classList.add('fullscreen');\n          } else {\n            document.body.classList.remove('fullscreen');\n          }\n        });\n        // showStatusBar: default is false if no param provided\n        self.showStatusBar((showStatusBar === true));\n      });\n    }\n\n  };\n\n  var platformName = null, // just the name, like iOS or Android\n  platformVersion = null, // a float of the major and minor, like 7.1\n  readyCallbacks = [],\n  windowLoadListenderAttached;\n\n  // setup listeners to know when the device is ready to go\n  function onWindowLoad() {\n    if (self.isWebView()) {\n      // the window and scripts are fully loaded, and a cordova/phonegap\n      // object exists then let's listen for the deviceready\n      document.addEventListener(\"deviceready\", onPlatformReady, false);\n    } else {\n      // the window and scripts are fully loaded, but the window object doesn't have the\n      // cordova/phonegap object, so its just a browser, not a webview wrapped w/ cordova\n      onPlatformReady();\n    }\n    if (windowLoadListenderAttached) {\n      window.removeEventListener(\"load\", onWindowLoad, false);\n    }\n  }\n  if (document.readyState === 'complete') {\n    onWindowLoad();\n  } else {\n    windowLoadListenderAttached = true;\n    window.addEventListener(\"load\", onWindowLoad, false);\n  }\n\n  function onPlatformReady() {\n    // the device is all set to go, init our own stuff then fire off our event\n    self.isReady = true;\n    self.detect();\n    for (var x = 0; x < readyCallbacks.length; x++) {\n      // fire off all the callbacks that were added before the platform was ready\n      readyCallbacks[x]();\n    }\n    readyCallbacks = [];\n    ionic.trigger('platformready', { target: document });\n\n    requestAnimationFrame(function() {\n      document.body.classList.add('platform-ready');\n    });\n  }\n\n})(this, document, ionic);\n\n(function(document, ionic) {\n  'use strict';\n\n  // Ionic CSS polyfills\n  ionic.CSS = {};\n\n  (function() {\n\n    // transform\n    var i, keys = ['webkitTransform', 'transform', '-webkit-transform', 'webkit-transform',\n                   '-moz-transform', 'moz-transform', 'MozTransform', 'mozTransform', 'msTransform'];\n\n    for (i = 0; i < keys.length; i++) {\n      if (document.documentElement.style[keys[i]] !== undefined) {\n        ionic.CSS.TRANSFORM = keys[i];\n        break;\n      }\n    }\n\n    // transition\n    keys = ['webkitTransition', 'mozTransition', 'msTransition', 'transition'];\n    for (i = 0; i < keys.length; i++) {\n      if (document.documentElement.style[keys[i]] !== undefined) {\n        ionic.CSS.TRANSITION = keys[i];\n        break;\n      }\n    }\n\n    // The only prefix we care about is webkit for transitions.\n    var isWebkit = ionic.CSS.TRANSITION.indexOf('webkit') > -1;\n\n    // transition duration\n    ionic.CSS.TRANSITION_DURATION = (isWebkit ? '-webkit-' : '') + 'transition-duration';\n\n    // To be sure transitionend works everywhere, include *both* the webkit and non-webkit events\n    ionic.CSS.TRANSITIONEND = (isWebkit ? 'webkitTransitionEnd ' : '') + 'transitionend';\n  })();\n\n  // classList polyfill for them older Androids\n  // https://gist.github.com/devongovett/1381839\n  if (!(\"classList\" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {\n    Object.defineProperty(HTMLElement.prototype, 'classList', {\n      get: function() {\n        var self = this;\n        function update(fn) {\n          return function() {\n            var x, classes = self.className.split(/\\s+/);\n\n            for (x = 0; x < arguments.length; x++) {\n              fn(classes, classes.indexOf(arguments[x]), arguments[x]);\n            }\n\n            self.className = classes.join(\" \");\n          };\n        }\n\n        return {\n          add: update(function(classes, index, value) {\n            ~index || classes.push(value);\n          }),\n\n          remove: update(function(classes, index) {\n            ~index && classes.splice(index, 1);\n          }),\n\n          toggle: update(function(classes, index, value) {\n            ~index ? classes.splice(index, 1) : classes.push(value);\n          }),\n\n          contains: function(value) {\n            return !!~self.className.split(/\\s+/).indexOf(value);\n          },\n\n          item: function(i) {\n            return self.className.split(/\\s+/)[i] || null;\n          }\n        };\n\n      }\n    });\n  }\n\n})(document, ionic);\n\n\n/**\n * @ngdoc page\n * @name tap\n * @module ionic\n * @description\n * On touch devices such as a phone or tablet, some browsers implement a 300ms delay between\n * the time the user stops touching the display and the moment the browser executes the\n * click. This delay was initially introduced so the browser can know whether the user wants to\n * double-tap to zoom in on the webpage.  Basically, the browser waits roughly 300ms to see if\n * the user is double-tapping, or just tapping on the display once.\n *\n * Out of the box, Ionic automatically removes the 300ms delay in order to make Ionic apps\n * feel more \"native\" like. Resultingly, other solutions such as\n * [fastclick](https://github.com/ftlabs/fastclick) and Angular's\n * [ngTouch](https://docs.angularjs.org/api/ngTouch) should not be included, to avoid conflicts.\n *\n * Some browsers already remove the delay with certain settings, such as the CSS property\n * `touch-events: none` or with specific meta tag viewport values. However, each of these\n * browsers still handle clicks differently, such as when to fire off or cancel the event\n * (like scrolling when the target is a button, or holding a button down).\n * For browsers that already remove the 300ms delay, consider Ionic's tap system as a way to\n * normalize how clicks are handled across the various devices so there's an expected response\n * no matter what the device, platform or version. Additionally, Ionic will prevent\n * ghostclicks which even browsers that remove the delay still experience.\n *\n * In some cases, third-party libraries may also be working with touch events which can interfere\n * with the tap system. For example, mapping libraries like Google or Leaflet Maps often implement\n * a touch detection system which conflicts with Ionic's tap system.\n *\n * ### Disabling the tap system\n *\n * To disable the tap for an element and all of its children elements,\n * add the attribute `data-tap-disabled=\"true\"`.\n *\n * ```html\n * <div data-tap-disabled=\"true\">\n *     <div id=\"google-map\"></div>\n * </div>\n * ```\n *\n * ### Additional Notes:\n *\n * - Ionic tap  works with Ionic's JavaScript scrolling\n * - Elements can come and go from the DOM and Ionic tap doesn't keep adding and removing\n *   listeners\n * - No \"tap delay\" after the first \"tap\" (you can tap as fast as you want, they all click)\n * - Minimal events listeners, only being added to document\n * - Correct focus in/out on each input type (select, textearea, range) on each platform/device\n * - Shows and hides virtual keyboard correctly for each platform/device\n * - Works with labels surrounding inputs\n * - Does not fire off a click if the user moves the pointer too far\n * - Adds and removes an 'activated' css class\n * - Multiple [unit tests](https://github.com/driftyco/ionic/blob/master/test/unit/utils/tap.unit.js) for each scenario\n *\n */\n/*\n\n IONIC TAP\n ---------------\n - Both touch and mouse events are added to the document.body on DOM ready\n - If a touch event happens, it does not use mouse event listeners\n - On touchend, if the distance between start and end was small, trigger a click\n - In the triggered click event, add a 'isIonicTap' property\n - The triggered click receives the same x,y coordinates as as the end event\n - On document.body click listener (with useCapture=true), only allow clicks with 'isIonicTap'\n - Triggering clicks with mouse events work the same as touch, except with mousedown/mouseup\n - Tapping inputs is disabled during scrolling\n*/\n\nvar tapDoc; // the element which the listeners are on (document.body)\nvar tapActiveEle; // the element which is active (probably has focus)\nvar tapEnabledTouchEvents;\nvar tapMouseResetTimer;\nvar tapPointerMoved;\nvar tapPointerStart;\nvar tapTouchFocusedInput;\nvar tapLastTouchTarget;\nvar tapTouchMoveListener = 'touchmove';\n\n// how much the coordinates can be off between start/end, but still a click\nvar TAP_RELEASE_TOLERANCE = 12; // default tolerance\nvar TAP_RELEASE_BUTTON_TOLERANCE = 50; // button elements should have a larger tolerance\n\nvar tapEventListeners = {\n  'click': tapClickGateKeeper,\n\n  'mousedown': tapMouseDown,\n  'mouseup': tapMouseUp,\n  'mousemove': tapMouseMove,\n\n  'touchstart': tapTouchStart,\n  'touchend': tapTouchEnd,\n  'touchcancel': tapTouchCancel,\n  'touchmove': tapTouchMove,\n\n  'pointerdown': tapTouchStart,\n  'pointerup': tapTouchEnd,\n  'pointercancel': tapTouchCancel,\n  'pointermove': tapTouchMove,\n\n  'MSPointerDown': tapTouchStart,\n  'MSPointerUp': tapTouchEnd,\n  'MSPointerCancel': tapTouchCancel,\n  'MSPointerMove': tapTouchMove,\n\n  'focusin': tapFocusIn,\n  'focusout': tapFocusOut\n};\n\nionic.tap = {\n\n  register: function(ele) {\n    tapDoc = ele;\n\n    tapEventListener('click', true, true);\n    tapEventListener('mouseup');\n    tapEventListener('mousedown');\n\n    if (window.navigator.pointerEnabled) {\n      tapEventListener('pointerdown');\n      tapEventListener('pointerup');\n      tapEventListener('pointcancel');\n      tapTouchMoveListener = 'pointermove';\n\n    } else if (window.navigator.msPointerEnabled) {\n      tapEventListener('MSPointerDown');\n      tapEventListener('MSPointerUp');\n      tapEventListener('MSPointerCancel');\n      tapTouchMoveListener = 'MSPointerMove';\n\n    } else {\n      tapEventListener('touchstart');\n      tapEventListener('touchend');\n      tapEventListener('touchcancel');\n    }\n\n    tapEventListener('focusin');\n    tapEventListener('focusout');\n\n    return function() {\n      for (var type in tapEventListeners) {\n        tapEventListener(type, false);\n      }\n      tapDoc = null;\n      tapActiveEle = null;\n      tapEnabledTouchEvents = false;\n      tapPointerMoved = false;\n      tapPointerStart = null;\n    };\n  },\n\n  ignoreScrollStart: function(e) {\n    return (e.defaultPrevented) ||  // defaultPrevented has been assigned by another component handling the event\n           (/^(file|range)$/i).test(e.target.type) ||\n           (e.target.dataset ? e.target.dataset.preventScroll : e.target.getAttribute('data-prevent-scroll')) == 'true' || // manually set within an elements attributes\n           (!!(/^(object|embed)$/i).test(e.target.tagName)) ||  // flash/movie/object touches should not try to scroll\n           ionic.tap.isElementTapDisabled(e.target); // check if this element, or an ancestor, has `data-tap-disabled` attribute\n  },\n\n  isTextInput: function(ele) {\n    return !!ele &&\n           (ele.tagName == 'TEXTAREA' ||\n            ele.contentEditable === 'true' ||\n            (ele.tagName == 'INPUT' && !(/^(radio|checkbox|range|file|submit|reset|color|image|button)$/i).test(ele.type)));\n  },\n\n  isDateInput: function(ele) {\n    return !!ele &&\n            (ele.tagName == 'INPUT' && (/^(date|time|datetime-local|month|week)$/i).test(ele.type));\n  },\n\n  isKeyboardElement: function(ele) {\n    if ( !ionic.Platform.isIOS() || ionic.Platform.isIPad() ) {\n      return ionic.tap.isTextInput(ele) && !ionic.tap.isDateInput(ele);\n    } else {\n      return ionic.tap.isTextInput(ele) || ( !!ele && ele.tagName == \"SELECT\");\n    }\n  },\n\n  isLabelWithTextInput: function(ele) {\n    var container = tapContainingElement(ele, false);\n\n    return !!container &&\n           ionic.tap.isTextInput(tapTargetElement(container));\n  },\n\n  containsOrIsTextInput: function(ele) {\n    return ionic.tap.isTextInput(ele) || ionic.tap.isLabelWithTextInput(ele);\n  },\n\n  cloneFocusedInput: function(container) {\n    if (ionic.tap.hasCheckedClone) return;\n    ionic.tap.hasCheckedClone = true;\n\n    ionic.requestAnimationFrame(function() {\n      var focusInput = container.querySelector(':focus');\n      if (ionic.tap.isTextInput(focusInput)) {\n        var clonedInput = focusInput.cloneNode(true);\n\n        clonedInput.value = focusInput.value;\n        clonedInput.classList.add('cloned-text-input');\n        clonedInput.readOnly = true;\n        if (focusInput.isContentEditable) {\n          clonedInput.contentEditable = focusInput.contentEditable;\n          clonedInput.innerHTML = focusInput.innerHTML;\n        }\n        focusInput.parentElement.insertBefore(clonedInput, focusInput);\n        focusInput.classList.add('previous-input-focus');\n\n        clonedInput.scrollTop = focusInput.scrollTop;\n      }\n    });\n  },\n\n  hasCheckedClone: false,\n\n  removeClonedInputs: function(container) {\n    ionic.tap.hasCheckedClone = false;\n\n    ionic.requestAnimationFrame(function() {\n      var clonedInputs = container.querySelectorAll('.cloned-text-input');\n      var previousInputFocus = container.querySelectorAll('.previous-input-focus');\n      var x;\n\n      for (x = 0; x < clonedInputs.length; x++) {\n        clonedInputs[x].parentElement.removeChild(clonedInputs[x]);\n      }\n\n      for (x = 0; x < previousInputFocus.length; x++) {\n        previousInputFocus[x].classList.remove('previous-input-focus');\n        previousInputFocus[x].style.top = '';\n        if ( ionic.keyboard.isOpen && !ionic.keyboard.isClosing ) previousInputFocus[x].focus();\n      }\n    });\n  },\n\n  requiresNativeClick: function(ele) {\n    if (!ele || ele.disabled || (/^(file|range)$/i).test(ele.type) || (/^(object|video)$/i).test(ele.tagName) || ionic.tap.isLabelContainingFileInput(ele)) {\n      return true;\n    }\n    return ionic.tap.isElementTapDisabled(ele);\n  },\n\n  isLabelContainingFileInput: function(ele) {\n    var lbl = tapContainingElement(ele);\n    if (lbl.tagName !== 'LABEL') return false;\n    var fileInput = lbl.querySelector('input[type=file]');\n    if (fileInput && fileInput.disabled === false) return true;\n    return false;\n  },\n\n  isElementTapDisabled: function(ele) {\n    if (ele && ele.nodeType === 1) {\n      var element = ele;\n      while (element) {\n        if ((element.dataset ? element.dataset.tapDisabled : element.getAttribute('data-tap-disabled')) == 'true') {\n          return true;\n        }\n        element = element.parentElement;\n      }\n    }\n    return false;\n  },\n\n  setTolerance: function(releaseTolerance, releaseButtonTolerance) {\n    TAP_RELEASE_TOLERANCE = releaseTolerance;\n    TAP_RELEASE_BUTTON_TOLERANCE = releaseButtonTolerance;\n  },\n\n  cancelClick: function() {\n    // used to cancel any simulated clicks which may happen on a touchend/mouseup\n    // gestures uses this method within its tap and hold events\n    tapPointerMoved = true;\n  },\n\n  pointerCoord: function(event) {\n    // This method can get coordinates for both a mouse click\n    // or a touch depending on the given event\n    var c = { x: 0, y: 0 };\n    if (event) {\n      var touches = event.touches && event.touches.length ? event.touches : [event];\n      var e = (event.changedTouches && event.changedTouches[0]) || touches[0];\n      if (e) {\n        c.x = e.clientX || e.pageX || 0;\n        c.y = e.clientY || e.pageY || 0;\n      }\n    }\n    return c;\n  }\n\n};\n\nfunction tapEventListener(type, enable, useCapture) {\n  if (enable !== false) {\n    tapDoc.addEventListener(type, tapEventListeners[type], useCapture);\n  } else {\n    tapDoc.removeEventListener(type, tapEventListeners[type]);\n  }\n}\n\nfunction tapClick(e) {\n  // simulate a normal click by running the element's click method then focus on it\n  var container = tapContainingElement(e.target);\n  var ele = tapTargetElement(container);\n\n  if (ionic.tap.requiresNativeClick(ele) || tapPointerMoved) return false;\n\n  var c = ionic.tap.pointerCoord(e);\n\n  //console.log('tapClick', e.type, ele.tagName, '('+c.x+','+c.y+')');\n  triggerMouseEvent('click', ele, c.x, c.y);\n\n  // if it's an input, focus in on the target, otherwise blur\n  tapHandleFocus(ele);\n}\n\nfunction triggerMouseEvent(type, ele, x, y) {\n  // using initMouseEvent instead of MouseEvent for our Android friends\n  var clickEvent = document.createEvent(\"MouseEvents\");\n  clickEvent.initMouseEvent(type, true, true, window, 1, 0, 0, x, y, false, false, false, false, 0, null);\n  clickEvent.isIonicTap = true;\n  ele.dispatchEvent(clickEvent);\n}\n\nfunction tapClickGateKeeper(e) {\n  //console.log('click ' + Date.now() + ' isIonicTap: ' + (e.isIonicTap ? true : false));\n  if (e.target.type == 'submit' && e.detail === 0) {\n    // do not prevent click if it came from an \"Enter\" or \"Go\" keypress submit\n    return null;\n  }\n\n  // do not allow through any click events that were not created by ionic.tap\n  if ((ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) ||\n      (!e.isIonicTap && !ionic.tap.requiresNativeClick(e.target))) {\n    //console.log('clickPrevent', e.target.tagName);\n    e.stopPropagation();\n\n    if (!ionic.tap.isLabelWithTextInput(e.target)) {\n      // labels clicks from native should not preventDefault othersize keyboard will not show on input focus\n      e.preventDefault();\n    }\n    return false;\n  }\n}\n\n// MOUSE\nfunction tapMouseDown(e) {\n  //console.log('mousedown ' + Date.now());\n  if (e.isIonicTap || tapIgnoreEvent(e)) return null;\n\n  if (tapEnabledTouchEvents) {\n    void 0;\n    e.stopPropagation();\n\n    if ((!ionic.tap.isTextInput(e.target) || tapLastTouchTarget !== e.target) && !(/^(select|option)$/i).test(e.target.tagName)) {\n      // If you preventDefault on a text input then you cannot move its text caret/cursor.\n      // Allow through only the text input default. However, without preventDefault on an\n      // input the 300ms delay can change focus on inputs after the keyboard shows up.\n      // The focusin event handles the chance of focus changing after the keyboard shows.\n      e.preventDefault();\n    }\n\n    return false;\n  }\n\n  tapPointerMoved = false;\n  tapPointerStart = ionic.tap.pointerCoord(e);\n\n  tapEventListener('mousemove');\n  ionic.activator.start(e);\n}\n\nfunction tapMouseUp(e) {\n  //console.log(\"mouseup \" + Date.now());\n  if (tapEnabledTouchEvents) {\n    e.stopPropagation();\n    e.preventDefault();\n    return false;\n  }\n\n  if (tapIgnoreEvent(e) || (/^(select|option)$/i).test(e.target.tagName)) return false;\n\n  if (!tapHasPointerMoved(e)) {\n    tapClick(e);\n  }\n  tapEventListener('mousemove', false);\n  ionic.activator.end();\n  tapPointerMoved = false;\n}\n\nfunction tapMouseMove(e) {\n  if (tapHasPointerMoved(e)) {\n    tapEventListener('mousemove', false);\n    ionic.activator.end();\n    tapPointerMoved = true;\n    return false;\n  }\n}\n\n\n// TOUCH\nfunction tapTouchStart(e) {\n  //console.log(\"touchstart \" + Date.now());\n  if (tapIgnoreEvent(e)) return;\n\n  tapPointerMoved = false;\n\n  tapEnableTouchEvents();\n  tapPointerStart = ionic.tap.pointerCoord(e);\n\n  tapEventListener(tapTouchMoveListener);\n  ionic.activator.start(e);\n\n  if (ionic.Platform.isIOS() && ionic.tap.isLabelWithTextInput(e.target)) {\n    // if the tapped element is a label, which has a child input\n    // then preventDefault so iOS doesn't ugly auto scroll to the input\n    // but do not prevent default on Android or else you cannot move the text caret\n    // and do not prevent default on Android or else no virtual keyboard shows up\n\n    var textInput = tapTargetElement(tapContainingElement(e.target));\n    if (textInput !== tapActiveEle) {\n      // don't preventDefault on an already focused input or else iOS's text caret isn't usable\n      e.preventDefault();\n    }\n  }\n}\n\nfunction tapTouchEnd(e) {\n  //console.log('touchend ' + Date.now());\n  if (tapIgnoreEvent(e)) return;\n\n  tapEnableTouchEvents();\n  if (!tapHasPointerMoved(e)) {\n    tapClick(e);\n\n    if ((/^(select|option)$/i).test(e.target.tagName)) {\n      e.preventDefault();\n    }\n  }\n\n  tapLastTouchTarget = e.target;\n  tapTouchCancel();\n}\n\nfunction tapTouchMove(e) {\n  if (tapHasPointerMoved(e)) {\n    tapPointerMoved = true;\n    tapEventListener(tapTouchMoveListener, false);\n    ionic.activator.end();\n    return false;\n  }\n}\n\nfunction tapTouchCancel() {\n  tapEventListener(tapTouchMoveListener, false);\n  ionic.activator.end();\n  tapPointerMoved = false;\n}\n\nfunction tapEnableTouchEvents() {\n  tapEnabledTouchEvents = true;\n  clearTimeout(tapMouseResetTimer);\n  tapMouseResetTimer = setTimeout(function() {\n    tapEnabledTouchEvents = false;\n  }, 600);\n}\n\nfunction tapIgnoreEvent(e) {\n  if (e.isTapHandled) return true;\n  e.isTapHandled = true;\n\n  if (ionic.scroll.isScrolling && ionic.tap.containsOrIsTextInput(e.target)) {\n    e.preventDefault();\n    return true;\n  }\n}\n\nfunction tapHandleFocus(ele) {\n  tapTouchFocusedInput = null;\n\n  var triggerFocusIn = false;\n\n  if (ele.tagName == 'SELECT') {\n    // trick to force Android options to show up\n    triggerMouseEvent('mousedown', ele, 0, 0);\n    ele.focus && ele.focus();\n    triggerFocusIn = true;\n\n  } else if (tapActiveElement() === ele) {\n    // already is the active element and has focus\n    triggerFocusIn = true;\n\n  } else if ((/^(input|textarea)$/i).test(ele.tagName) || ele.isContentEditable) {\n    triggerFocusIn = true;\n    ele.focus && ele.focus();\n    ele.value = ele.value;\n    if (tapEnabledTouchEvents) {\n      tapTouchFocusedInput = ele;\n    }\n\n  } else {\n    tapFocusOutActive();\n  }\n\n  if (triggerFocusIn) {\n    tapActiveElement(ele);\n    ionic.trigger('ionic.focusin', {\n      target: ele\n    }, true);\n  }\n}\n\nfunction tapFocusOutActive() {\n  var ele = tapActiveElement();\n  if (ele && ((/^(input|textarea|select)$/i).test(ele.tagName) || ele.isContentEditable)) {\n    void 0;\n    ele.blur();\n  }\n  tapActiveElement(null);\n}\n\nfunction tapFocusIn(e) {\n  //console.log('focusin ' + Date.now());\n  // Because a text input doesn't preventDefault (so the caret still works) there's a chance\n  // that its mousedown event 300ms later will change the focus to another element after\n  // the keyboard shows up.\n\n  if (tapEnabledTouchEvents &&\n      ionic.tap.isTextInput(tapActiveElement()) &&\n      ionic.tap.isTextInput(tapTouchFocusedInput) &&\n      tapTouchFocusedInput !== e.target) {\n\n    // 1) The pointer is from touch events\n    // 2) There is an active element which is a text input\n    // 3) A text input was just set to be focused on by a touch event\n    // 4) A new focus has been set, however the target isn't the one the touch event wanted\n    void 0;\n    tapTouchFocusedInput.focus();\n    tapTouchFocusedInput = null;\n  }\n  ionic.scroll.isScrolling = false;\n}\n\nfunction tapFocusOut() {\n  //console.log(\"focusout\");\n  tapActiveElement(null);\n}\n\nfunction tapActiveElement(ele) {\n  if (arguments.length) {\n    tapActiveEle = ele;\n  }\n  return tapActiveEle || document.activeElement;\n}\n\nfunction tapHasPointerMoved(endEvent) {\n  if (!endEvent || endEvent.target.nodeType !== 1 || !tapPointerStart || (tapPointerStart.x === 0 && tapPointerStart.y === 0)) {\n    return false;\n  }\n  var endCoordinates = ionic.tap.pointerCoord(endEvent);\n\n  var hasClassList = !!(endEvent.target.classList && endEvent.target.classList.contains &&\n    typeof endEvent.target.classList.contains === 'function');\n  var releaseTolerance = hasClassList && endEvent.target.classList.contains('button') ?\n    TAP_RELEASE_BUTTON_TOLERANCE :\n    TAP_RELEASE_TOLERANCE;\n\n  return Math.abs(tapPointerStart.x - endCoordinates.x) > releaseTolerance ||\n         Math.abs(tapPointerStart.y - endCoordinates.y) > releaseTolerance;\n}\n\nfunction tapContainingElement(ele, allowSelf) {\n  var climbEle = ele;\n  for (var x = 0; x < 6; x++) {\n    if (!climbEle) break;\n    if (climbEle.tagName === 'LABEL') return climbEle;\n    climbEle = climbEle.parentElement;\n  }\n  if (allowSelf !== false) return ele;\n}\n\nfunction tapTargetElement(ele) {\n  if (ele && ele.tagName === 'LABEL') {\n    if (ele.control) return ele.control;\n\n    // older devices do not support the \"control\" property\n    if (ele.querySelector) {\n      var control = ele.querySelector('input,textarea,select');\n      if (control) return control;\n    }\n  }\n  return ele;\n}\n\nionic.DomUtil.ready(function() {\n  var ng = typeof angular !== 'undefined' ? angular : null;\n  //do nothing for e2e tests\n  if (!ng || (ng && !ng.scenario)) {\n    ionic.tap.register(document);\n  }\n});\n\n(function(document, ionic) {\n  'use strict';\n\n  var queueElements = {};   // elements that should get an active state in XX milliseconds\n  var activeElements = {};  // elements that are currently active\n  var keyId = 0;            // a counter for unique keys for the above ojects\n  var ACTIVATED_CLASS = 'activated';\n\n  ionic.activator = {\n\n    start: function(e) {\n      var hitX = ionic.tap.pointerCoord(e).x;\n      if (hitX > 0 && hitX < 30) {\n        return;\n      }\n\n      // when an element is touched/clicked, it climbs up a few\n      // parents to see if it is an .item or .button element\n      ionic.requestAnimationFrame(function() {\n        if ((ionic.scroll && ionic.scroll.isScrolling) || ionic.tap.requiresNativeClick(e.target)) return;\n        var ele = e.target;\n        var eleToActivate;\n\n        for (var x = 0; x < 6; x++) {\n          if (!ele || ele.nodeType !== 1) break;\n          if (eleToActivate && ele.classList && ele.classList.contains('item')) {\n            eleToActivate = ele;\n            break;\n          }\n          if (ele.tagName == 'A' || ele.tagName == 'BUTTON' || ele.hasAttribute('ng-click')) {\n            eleToActivate = ele;\n            break;\n          }\n          if (ele.classList.contains('button')) {\n            eleToActivate = ele;\n            break;\n          }\n          // no sense climbing past these\n          if (ele.tagName == 'ION-CONTENT' || (ele.classList && ele.classList.contains('pane')) || ele.tagName == 'BODY') {\n            break;\n          }\n          ele = ele.parentElement;\n        }\n\n        if (eleToActivate) {\n          // queue that this element should be set to active\n          queueElements[keyId] = eleToActivate;\n\n          // on the next frame, set the queued elements to active\n          ionic.requestAnimationFrame(activateElements);\n\n          keyId = (keyId > 29 ? 0 : keyId + 1);\n        }\n\n      });\n    },\n\n    end: function() {\n      // clear out any active/queued elements after XX milliseconds\n      setTimeout(clear, 200);\n    }\n\n  };\n\n  function clear() {\n    // clear out any elements that are queued to be set to active\n    queueElements = {};\n\n    // in the next frame, remove the active class from all active elements\n    ionic.requestAnimationFrame(deactivateElements);\n  }\n\n  function activateElements() {\n    // activate all elements in the queue\n    for (var key in queueElements) {\n      if (queueElements[key]) {\n        queueElements[key].classList.add(ACTIVATED_CLASS);\n        activeElements[key] = queueElements[key];\n      }\n    }\n    queueElements = {};\n  }\n\n  function deactivateElements() {\n    if (ionic.transition && ionic.transition.isActive) {\n      setTimeout(deactivateElements, 400);\n      return;\n    }\n\n    for (var key in activeElements) {\n      if (activeElements[key]) {\n        activeElements[key].classList.remove(ACTIVATED_CLASS);\n        delete activeElements[key];\n      }\n    }\n  }\n\n})(document, ionic);\n\n(function(ionic) {\n  /* for nextUid function below */\n  var nextId = 0;\n\n  /**\n   * Various utilities used throughout Ionic\n   *\n   * Some of these are adopted from underscore.js and backbone.js, both also MIT licensed.\n   */\n  ionic.Utils = {\n\n    arrayMove: function(arr, oldIndex, newIndex) {\n      if (newIndex >= arr.length) {\n        var k = newIndex - arr.length;\n        while ((k--) + 1) {\n          arr.push(undefined);\n        }\n      }\n      arr.splice(newIndex, 0, arr.splice(oldIndex, 1)[0]);\n      return arr;\n    },\n\n    /**\n     * Return a function that will be called with the given context\n     */\n    proxy: function(func, context) {\n      var args = Array.prototype.slice.call(arguments, 2);\n      return function() {\n        return func.apply(context, args.concat(Array.prototype.slice.call(arguments)));\n      };\n    },\n\n    /**\n     * Only call a function once in the given interval.\n     *\n     * @param func {Function} the function to call\n     * @param wait {int} how long to wait before/after to allow function calls\n     * @param immediate {boolean} whether to call immediately or after the wait interval\n     */\n     debounce: function(func, wait, immediate) {\n      var timeout, args, context, timestamp, result;\n      return function() {\n        context = this;\n        args = arguments;\n        timestamp = new Date();\n        var later = function() {\n          var last = (new Date()) - timestamp;\n          if (last < wait) {\n            timeout = setTimeout(later, wait - last);\n          } else {\n            timeout = null;\n            if (!immediate) result = func.apply(context, args);\n          }\n        };\n        var callNow = immediate && !timeout;\n        if (!timeout) {\n          timeout = setTimeout(later, wait);\n        }\n        if (callNow) result = func.apply(context, args);\n        return result;\n      };\n    },\n\n    /**\n     * Throttle the given fun, only allowing it to be\n     * called at most every `wait` ms.\n     */\n    throttle: function(func, wait, options) {\n      var context, args, result;\n      var timeout = null;\n      var previous = 0;\n      options || (options = {});\n      var later = function() {\n        previous = options.leading === false ? 0 : Date.now();\n        timeout = null;\n        result = func.apply(context, args);\n      };\n      return function() {\n        var now = Date.now();\n        if (!previous && options.leading === false) previous = now;\n        var remaining = wait - (now - previous);\n        context = this;\n        args = arguments;\n        if (remaining <= 0) {\n          clearTimeout(timeout);\n          timeout = null;\n          previous = now;\n          result = func.apply(context, args);\n        } else if (!timeout && options.trailing !== false) {\n          timeout = setTimeout(later, remaining);\n        }\n        return result;\n      };\n    },\n     // Borrowed from Backbone.js's extend\n     // Helper function to correctly set up the prototype chain, for subclasses.\n     // Similar to `goog.inherits`, but uses a hash of prototype properties and\n     // class properties to be extended.\n    inherit: function(protoProps, staticProps) {\n      var parent = this;\n      var child;\n\n      // The constructor function for the new subclass is either defined by you\n      // (the \"constructor\" property in your `extend` definition), or defaulted\n      // by us to simply call the parent's constructor.\n      if (protoProps && protoProps.hasOwnProperty('constructor')) {\n        child = protoProps.constructor;\n      } else {\n        child = function() { return parent.apply(this, arguments); };\n      }\n\n      // Add static properties to the constructor function, if supplied.\n      ionic.extend(child, parent, staticProps);\n\n      // Set the prototype chain to inherit from `parent`, without calling\n      // `parent`'s constructor function.\n      var Surrogate = function() { this.constructor = child; };\n      Surrogate.prototype = parent.prototype;\n      child.prototype = new Surrogate();\n\n      // Add prototype properties (instance properties) to the subclass,\n      // if supplied.\n      if (protoProps) ionic.extend(child.prototype, protoProps);\n\n      // Set a convenience property in case the parent's prototype is needed\n      // later.\n      child.__super__ = parent.prototype;\n\n      return child;\n    },\n\n    // Extend adapted from Underscore.js\n    extend: function(obj) {\n       var args = Array.prototype.slice.call(arguments, 1);\n       for (var i = 0; i < args.length; i++) {\n         var source = args[i];\n         if (source) {\n           for (var prop in source) {\n             obj[prop] = source[prop];\n           }\n         }\n       }\n       return obj;\n    },\n\n    nextUid: function() {\n      return 'ion' + (nextId++);\n    },\n\n    disconnectScope: function disconnectScope(scope) {\n      if (!scope) return;\n\n      if (scope.$root === scope) {\n        return; // we can't disconnect the root node;\n      }\n      var parent = scope.$parent;\n      scope.$$disconnected = true;\n      scope.$broadcast('$ionic.disconnectScope', scope);\n\n      // See Scope.$destroy\n      if (parent.$$childHead === scope) {\n        parent.$$childHead = scope.$$nextSibling;\n      }\n      if (parent.$$childTail === scope) {\n        parent.$$childTail = scope.$$prevSibling;\n      }\n      if (scope.$$prevSibling) {\n        scope.$$prevSibling.$$nextSibling = scope.$$nextSibling;\n      }\n      if (scope.$$nextSibling) {\n        scope.$$nextSibling.$$prevSibling = scope.$$prevSibling;\n      }\n      scope.$$nextSibling = scope.$$prevSibling = null;\n    },\n\n    reconnectScope: function reconnectScope(scope) {\n      if (!scope) return;\n\n      if (scope.$root === scope) {\n        return; // we can't disconnect the root node;\n      }\n      if (!scope.$$disconnected) {\n        return;\n      }\n      var parent = scope.$parent;\n      scope.$$disconnected = false;\n      scope.$broadcast('$ionic.reconnectScope', scope);\n      // See Scope.$new for this logic...\n      scope.$$prevSibling = parent.$$childTail;\n      if (parent.$$childHead) {\n        parent.$$childTail.$$nextSibling = scope;\n        parent.$$childTail = scope;\n      } else {\n        parent.$$childHead = parent.$$childTail = scope;\n      }\n    },\n\n    isScopeDisconnected: function(scope) {\n      var climbScope = scope;\n      while (climbScope) {\n        if (climbScope.$$disconnected) return true;\n        climbScope = climbScope.$parent;\n      }\n      return false;\n    }\n  };\n\n  // Bind a few of the most useful functions to the ionic scope\n  ionic.inherit = ionic.Utils.inherit;\n  ionic.extend = ionic.Utils.extend;\n  ionic.throttle = ionic.Utils.throttle;\n  ionic.proxy = ionic.Utils.proxy;\n  ionic.debounce = ionic.Utils.debounce;\n\n})(window.ionic);\n\n/**\n * @ngdoc page\n * @name keyboard\n * @module ionic\n * @description\n * On both Android and iOS, Ionic will attempt to prevent the keyboard from\n * obscuring inputs and focusable elements when it appears by scrolling them\n * into view.  In order for this to work, any focusable elements must be within\n * a [Scroll View](http://ionicframework.com/docs/api/directive/ionScroll/)\n * or a directive such as [Content](http://ionicframework.com/docs/api/directive/ionContent/)\n * that has a Scroll View.\n *\n * It will also attempt to prevent the native overflow scrolling on focus,\n * which can cause layout issues such as pushing headers up and out of view.\n *\n * The keyboard fixes work best in conjunction with the\n * [Ionic Keyboard Plugin](https://github.com/driftyco/ionic-plugins-keyboard),\n * although it will perform reasonably well without.  However, if you are using\n * Cordova there is no reason not to use the plugin.\n *\n * ### Hide when keyboard shows\n *\n * To hide an element when the keyboard is open, add the class `hide-on-keyboard-open`.\n *\n * ```html\n * <div class=\"hide-on-keyboard-open\">\n *   <div id=\"google-map\"></div>\n * </div>\n * ```\n * ----------\n *\n * ### Plugin Usage\n * Information on using the plugin can be found at\n * [https://github.com/driftyco/ionic-plugins-keyboard](https://github.com/driftyco/ionic-plugins-keyboard).\n *\n * ----------\n *\n * ### Android Notes\n * - If your app is running in fullscreen, i.e. you have\n *   `<preference name=\"Fullscreen\" value=\"true\" />` in your `config.xml` file\n *   you will need to set `ionic.Platform.isFullScreen = true` manually.\n *\n * - You can configure the behavior of the web view when the keyboard shows by setting\n *   [android:windowSoftInputMode](http://developer.android.com/reference/android/R.attr.html#windowSoftInputMode)\n *   to either `adjustPan`, `adjustResize` or `adjustNothing` in your app's\n *   activity in `AndroidManifest.xml`. `adjustResize` is the recommended setting\n *   for Ionic, but if for some reason you do use `adjustPan` you will need to\n *   set `ionic.Platform.isFullScreen = true`.\n *\n *   ```xml\n *   <activity android:windowSoftInputMode=\"adjustResize\">\n *\n *   ```\n *\n * ### iOS Notes\n * - If the content of your app (including the header) is being pushed up and\n *   out of view on input focus, try setting `cordova.plugins.Keyboard.disableScroll(true)`.\n *   This does **not** disable scrolling in the Ionic scroll view, rather it\n *   disables the native overflow scrolling that happens automatically as a\n *   result of focusing on inputs below the keyboard.\n *\n */\n\n/**\n * The current viewport height.\n */\nvar keyboardCurrentViewportHeight = 0;\n\n/**\n * The viewport height when in portrait orientation.\n */\nvar keyboardPortraitViewportHeight = 0;\n\n/**\n * The viewport height when in landscape orientation.\n */\nvar keyboardLandscapeViewportHeight = 0;\n\n/**\n * The currently focused input.\n */\nvar keyboardActiveElement;\n\n/**\n * The scroll view containing the currently focused input.\n */\nvar scrollView;\n\n/**\n * Timer for the setInterval that polls window.innerHeight to determine whether\n * the layout has updated for the keyboard showing/hiding.\n */\nvar waitForResizeTimer;\n\n/**\n * Sometimes when switching inputs or orientations, focusout will fire before\n * focusin, so this timer is for the small setTimeout to determine if we should\n * really focusout/hide the keyboard.\n */\nvar keyboardFocusOutTimer;\n\n/**\n * on Android, orientationchange will fire before the keyboard plugin notifies\n * the browser that the keyboard will show/is showing, so this flag indicates\n * to nativeShow that there was an orientationChange and we should update\n * the viewport height with an accurate keyboard height value\n */\nvar wasOrientationChange = false;\n\n/**\n * CSS class added to the body indicating the keyboard is open.\n */\nvar KEYBOARD_OPEN_CSS = 'keyboard-open';\n\n/**\n * CSS class that indicates a scroll container.\n */\nvar SCROLL_CONTAINER_CSS = 'scroll-content';\n\n/**\n * Debounced keyboardFocusIn function\n */\nvar debouncedKeyboardFocusIn = ionic.debounce(keyboardFocusIn, 200, true);\n\n/**\n * Debounced keyboardNativeShow function\n */\nvar debouncedKeyboardNativeShow = ionic.debounce(keyboardNativeShow, 100, true);\n\n/**\n * Ionic keyboard namespace.\n * @namespace keyboard\n */\nionic.keyboard = {\n\n  /**\n   * Whether the keyboard is open or not.\n   */\n  isOpen: false,\n\n  /**\n   * Whether the keyboard is closing or not.\n   */\n  isClosing: false,\n\n  /**\n   * Whether the keyboard is opening or not.\n   */\n  isOpening: false,\n\n  /**\n   * The height of the keyboard in pixels, as reported by the keyboard plugin.\n   * If the plugin is not available, calculated as the difference in\n   * window.innerHeight after the keyboard has shown.\n   */\n  height: 0,\n\n  /**\n   * Whether the device is in landscape orientation or not.\n   */\n  isLandscape: false,\n\n  /**\n   * Whether the keyboard event listeners have been added or not\n   */\n  isInitialized: false,\n\n  /**\n   * Hide the keyboard, if it is open.\n   */\n  hide: function() {\n    if (keyboardHasPlugin()) {\n      cordova.plugins.Keyboard.close();\n    }\n    keyboardActiveElement && keyboardActiveElement.blur();\n  },\n\n  /**\n   * An alias for cordova.plugins.Keyboard.show(). If the keyboard plugin\n   * is installed, show the keyboard.\n   */\n  show: function() {\n    if (keyboardHasPlugin()) {\n      cordova.plugins.Keyboard.show();\n    }\n  },\n\n  /**\n   * Remove all keyboard related event listeners, effectively disabling Ionic's\n   * keyboard adjustments.\n   */\n  disable: function() {\n    if (keyboardHasPlugin()) {\n      window.removeEventListener('native.keyboardshow', debouncedKeyboardNativeShow );\n      window.removeEventListener('native.keyboardhide', keyboardFocusOut);\n    } else {\n      document.body.removeEventListener('focusout', keyboardFocusOut);\n    }\n\n    document.body.removeEventListener('ionic.focusin', debouncedKeyboardFocusIn);\n    document.body.removeEventListener('focusin', debouncedKeyboardFocusIn);\n\n    window.removeEventListener('orientationchange', keyboardOrientationChange);\n\n    if ( window.navigator.msPointerEnabled ) {\n      document.removeEventListener(\"MSPointerDown\", keyboardInit);\n    } else {\n      document.removeEventListener('touchstart', keyboardInit);\n    }\n    ionic.keyboard.isInitialized = false;\n  },\n\n  /**\n   * Alias for keyboardInit, initialize all keyboard related event listeners.\n   */\n  enable: function() {\n    keyboardInit();\n  }\n};\n\n// Initialize the viewport height (after ionic.keyboard.height has been\n// defined).\nkeyboardCurrentViewportHeight = getViewportHeight();\n\n\n                             /* Event handlers */\n/* ------------------------------------------------------------------------- */\n\n/**\n * Event handler for first touch event, initializes all event listeners\n * for keyboard related events. Also aliased by ionic.keyboard.enable.\n */\nfunction keyboardInit() {\n\n  if (ionic.keyboard.isInitialized) return;\n\n  if (keyboardHasPlugin()) {\n    window.addEventListener('native.keyboardshow', debouncedKeyboardNativeShow);\n    window.addEventListener('native.keyboardhide', keyboardFocusOut);\n  } else {\n    document.body.addEventListener('focusout', keyboardFocusOut);\n  }\n\n  document.body.addEventListener('ionic.focusin', debouncedKeyboardFocusIn);\n  document.body.addEventListener('focusin', debouncedKeyboardFocusIn);\n\n  if (window.navigator.msPointerEnabled) {\n    document.removeEventListener(\"MSPointerDown\", keyboardInit);\n  } else {\n    document.removeEventListener('touchstart', keyboardInit);\n  }\n\n  ionic.keyboard.isInitialized = true;\n}\n\n/**\n * Event handler for 'native.keyboardshow' event, sets keyboard.height to the\n * reported height and keyboard.isOpening to true. Then calls\n * keyboardWaitForResize with keyboardShow or keyboardUpdateViewportHeight as\n * the callback depending on whether the event was triggered by a focusin or\n * an orientationchange.\n */\nfunction keyboardNativeShow(e) {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardNativeShow fired at: \" + Date.now());\n  //console.log(\"keyboardNativeshow window.innerHeight: \" + window.innerHeight);\n\n  if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {\n    ionic.keyboard.isOpening = true;\n    ionic.keyboard.isClosing = false;\n  }\n\n  ionic.keyboard.height = e.keyboardHeight;\n  //console.log('nativeshow keyboard height:' + e.keyboardHeight);\n\n  if (wasOrientationChange) {\n    keyboardWaitForResize(keyboardUpdateViewportHeight, true);\n  } else {\n    keyboardWaitForResize(keyboardShow, true);\n  }\n}\n\n/**\n * Event handler for 'focusin' and 'ionic.focusin' events. Initializes\n * keyboard state (keyboardActiveElement and keyboard.isOpening) for the\n * appropriate adjustments once the window has resized.  If not using the\n * keyboard plugin, calls keyboardWaitForResize with keyboardShow as the\n * callback or keyboardShow right away if the keyboard is already open.  If\n * using the keyboard plugin does nothing and lets keyboardNativeShow handle\n * adjustments with a more accurate keyboard height.\n */\nfunction keyboardFocusIn(e) {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardFocusIn from: \" + e.type + \" at: \" + Date.now());\n\n  if (!e.target ||\n      e.target.readOnly ||\n      !ionic.tap.isKeyboardElement(e.target) ||\n      !(scrollView = inputScrollView(e.target))) {\n    keyboardActiveElement = null;\n    return;\n  }\n\n  keyboardActiveElement = e.target;\n\n  // if using JS scrolling, undo the effects of native overflow scroll so the\n  // scroll view is positioned correctly\n  document.body.scrollTop = 0;\n  scrollView.scrollTop = 0;\n  ionic.requestAnimationFrame(function(){\n    document.body.scrollTop = 0;\n    scrollView.scrollTop = 0;\n  });\n\n  if (!ionic.keyboard.isOpen || ionic.keyboard.isClosing) {\n    ionic.keyboard.isOpening = true;\n    ionic.keyboard.isClosing = false;\n  }\n\n  // attempt to prevent browser from natively scrolling input into view while\n  // we are trying to do the same (while we are scrolling) if the user taps the\n  // keyboard\n  document.addEventListener('keydown', keyboardOnKeyDown, false);\n\n  // any showing part of the document that isn't within the scroll the user\n  // could touchmove and cause some ugly changes to the app, so disable\n  // any touchmove events while the keyboard is open using e.preventDefault()\n  if (window.navigator.msPointerEnabled) {\n    document.addEventListener(\"MSPointerMove\", keyboardPreventDefault, false);\n  } else {\n    document.addEventListener('touchmove', keyboardPreventDefault, false);\n  }\n\n  // if we aren't using the plugin and the keyboard isn't open yet, wait for the\n  // window to resize so we can get an accurate estimate of the keyboard size,\n  // otherwise we do nothing and let nativeShow call keyboardShow once we have\n  // an exact keyboard height\n  // if the keyboard is already open, go ahead and scroll the input into view\n  // if necessary\n  if (!ionic.keyboard.isOpen && !keyboardHasPlugin()) {\n    keyboardWaitForResize(keyboardShow, true);\n\n  } else if (ionic.keyboard.isOpen) {\n    keyboardShow();\n  }\n}\n\n/**\n * Event handler for 'focusout' events. Sets keyboard.isClosing to true and\n * calls keyboardWaitForResize with keyboardHide as the callback after a small\n * timeout.\n */\nfunction keyboardFocusOut() {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardFocusOut fired at: \" + Date.now());\n  //console.log(\"keyboardFocusOut event type: \" + e.type);\n\n  if (ionic.keyboard.isOpen || ionic.keyboard.isOpening) {\n    ionic.keyboard.isClosing = true;\n    ionic.keyboard.isOpening = false;\n  }\n\n  // Call keyboardHide with a slight delay because sometimes on focus or\n  // orientation change focusin is called immediately after, so we give it time\n  // to cancel keyboardHide\n  keyboardFocusOutTimer = setTimeout(function() {\n    ionic.requestAnimationFrame(function() {\n      // focusOut during or right after an orientationchange, so we didn't get\n      // a chance to update the viewport height yet, do it and keyboardHide\n      //console.log(\"focusOut, wasOrientationChange: \" + wasOrientationChange);\n      if (wasOrientationChange) {\n        keyboardWaitForResize(function(){\n          keyboardUpdateViewportHeight();\n          keyboardHide();\n        }, false);\n      } else {\n        keyboardWaitForResize(keyboardHide, false);\n      }\n    });\n  }, 50);\n}\n\n/**\n * Event handler for 'orientationchange' events. If using the keyboard plugin\n * and the keyboard is open on Android, sets wasOrientationChange to true so\n * nativeShow can update the viewport height with an accurate keyboard height.\n * If the keyboard isn't open or keyboard plugin isn't being used,\n * waits for the window to resize before updating the viewport height.\n *\n * On iOS, where orientationchange fires after the keyboard has already shown,\n * updates the viewport immediately, regardless of if the keyboard is already\n * open.\n */\nfunction keyboardOrientationChange() {\n  //console.log(\"orientationchange fired at: \" + Date.now());\n  //console.log(\"orientation was: \" + (ionic.keyboard.isLandscape ? \"landscape\" : \"portrait\"));\n\n  // toggle orientation\n  ionic.keyboard.isLandscape = !ionic.keyboard.isLandscape;\n  // //console.log(\"now orientation is: \" + (ionic.keyboard.isLandscape ? \"landscape\" : \"portrait\"));\n\n  // no need to wait for resizing on iOS, and orientationchange always fires\n  // after the keyboard has opened, so it doesn't matter if it's open or not\n  if (ionic.Platform.isIOS()) {\n    keyboardUpdateViewportHeight();\n  }\n\n  // On Android, if the keyboard isn't open or we aren't using the keyboard\n  // plugin, update the viewport height once everything has resized. If the\n  // keyboard is open and we are using the keyboard plugin do nothing and let\n  // nativeShow handle it using an accurate keyboard height.\n  if ( ionic.Platform.isAndroid()) {\n    if (!ionic.keyboard.isOpen || !keyboardHasPlugin()) {\n      keyboardWaitForResize(keyboardUpdateViewportHeight, false);\n    } else {\n      wasOrientationChange = true;\n    }\n  }\n}\n\n/**\n * Event handler for 'keydown' event. Tries to prevent browser from natively\n * scrolling an input into view when a user taps the keyboard while we are\n * scrolling the input into view ourselves with JS.\n */\nfunction keyboardOnKeyDown(e) {\n  if (ionic.scroll.isScrolling) {\n    keyboardPreventDefault(e);\n  }\n}\n\n/**\n * Event for 'touchmove' or 'MSPointerMove'. Prevents native scrolling on\n * elements outside the scroll view while the keyboard is open.\n */\nfunction keyboardPreventDefault(e) {\n  if (e.target.tagName !== 'TEXTAREA') {\n    e.preventDefault();\n  }\n}\n\n                              /* Private API */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Polls window.innerHeight until it has updated to an expected value (or\n * sufficient time has passed) before calling the specified callback function.\n * Only necessary for non-fullscreen Android which sometimes reports multiple\n * window.innerHeight values during interim layouts while it is resizing.\n *\n * On iOS, the window.innerHeight will already be updated, but we use the 50ms\n * delay as essentially a timeout so that scroll view adjustments happen after\n * the keyboard has shown so there isn't a white flash from us resizing too\n * quickly.\n *\n * @param {Function} callback the function to call once the window has resized\n * @param {boolean} isOpening whether the resize is from the keyboard opening\n * or not\n */\nfunction keyboardWaitForResize(callback, isOpening) {\n  clearInterval(waitForResizeTimer);\n  var count = 0;\n  var maxCount;\n  var initialHeight = getViewportHeight();\n  var viewportHeight = initialHeight;\n\n  //console.log(\"waitForResize initial viewport height: \" + viewportHeight);\n  //var start = Date.now();\n  //console.log(\"start: \" + start);\n\n  // want to fail relatively quickly on modern android devices, since it's much\n  // more likely we just have a bad keyboard height\n  if (ionic.Platform.isAndroid() && ionic.Platform.version() < 4.4) {\n    maxCount = 30;\n  } else if (ionic.Platform.isAndroid()) {\n    maxCount = 10;\n  } else {\n    maxCount = 1;\n  }\n\n  // poll timer\n  waitForResizeTimer = setInterval(function(){\n    viewportHeight = getViewportHeight();\n\n    // height hasn't updated yet, try again in 50ms\n    // if not using plugin, wait for maxCount to ensure we have waited long enough\n    // to get an accurate keyboard height\n    if (++count < maxCount &&\n        ((!isPortraitViewportHeight(viewportHeight) &&\n         !isLandscapeViewportHeight(viewportHeight)) ||\n         !ionic.keyboard.height)) {\n      return;\n    }\n\n    // infer the keyboard height from the resize if not using the keyboard plugin\n    if (!keyboardHasPlugin()) {\n      ionic.keyboard.height = Math.abs(initialHeight - window.innerHeight);\n    }\n\n    // set to true if we were waiting for the keyboard to open\n    ionic.keyboard.isOpen = isOpening;\n\n    clearInterval(waitForResizeTimer);\n    //var end = Date.now();\n    //console.log(\"waitForResize count: \" + count);\n    //console.log(\"end: \" + end);\n    //console.log(\"difference: \" + ( end - start ) + \"ms\");\n\n    //console.log(\"callback: \" + callback.name);\n    callback();\n\n  }, 50);\n\n  return maxCount; //for tests\n}\n\n/**\n * On keyboard close sets keyboard state to closed, resets the scroll view,\n * removes CSS from body indicating keyboard was open, removes any event\n * listeners for when the keyboard is open and on Android blurs the active\n * element (which in some cases will still have focus even if the keyboard\n * is closed and can cause it to reappear on subsequent taps).\n */\nfunction keyboardHide() {\n  clearTimeout(keyboardFocusOutTimer);\n  //console.log(\"keyboardHide\");\n\n  ionic.keyboard.isOpen = false;\n  ionic.keyboard.isClosing = false;\n\n  if (keyboardActiveElement) {\n    ionic.trigger('resetScrollView', {\n      target: keyboardActiveElement\n    }, true);\n  }\n\n  ionic.requestAnimationFrame(function(){\n    document.body.classList.remove(KEYBOARD_OPEN_CSS);\n  });\n\n  // the keyboard is gone now, remove the touchmove that disables native scroll\n  if (window.navigator.msPointerEnabled) {\n    document.removeEventListener(\"MSPointerMove\", keyboardPreventDefault);\n  } else {\n    document.removeEventListener('touchmove', keyboardPreventDefault);\n  }\n  document.removeEventListener('keydown', keyboardOnKeyDown);\n\n  if (ionic.Platform.isAndroid()) {\n    // on android closing the keyboard with the back/dismiss button won't remove\n    // focus and keyboard can re-appear on subsequent taps (like scrolling)\n    if (keyboardHasPlugin()) cordova.plugins.Keyboard.close();\n    keyboardActiveElement && keyboardActiveElement.blur();\n  }\n\n  keyboardActiveElement = null;\n}\n\n/**\n * On keyboard open sets keyboard state to open, adds CSS to the body\n * indicating the keyboard is open and tells the scroll view to resize and\n * the currently focused input into view if necessary.\n */\nfunction keyboardShow() {\n\n  ionic.keyboard.isOpen = true;\n  ionic.keyboard.isOpening = false;\n\n  var details = {\n    keyboardHeight: keyboardGetHeight(),\n    viewportHeight: keyboardCurrentViewportHeight\n  };\n\n  if (keyboardActiveElement) {\n    details.target = keyboardActiveElement;\n\n    var elementBounds = keyboardActiveElement.getBoundingClientRect();\n\n    details.elementTop = Math.round(elementBounds.top);\n    details.elementBottom = Math.round(elementBounds.bottom);\n\n    details.windowHeight = details.viewportHeight - details.keyboardHeight;\n    //console.log(\"keyboardShow viewportHeight: \" + details.viewportHeight +\n    //\", windowHeight: \" + details.windowHeight +\n    //\", keyboardHeight: \" + details.keyboardHeight);\n\n    // figure out if the element is under the keyboard\n    details.isElementUnderKeyboard = (details.elementBottom > details.windowHeight);\n    //console.log(\"isUnderKeyboard: \" + details.isElementUnderKeyboard);\n    //console.log(\"elementBottom: \" + details.elementBottom);\n\n    // send event so the scroll view adjusts\n    ionic.trigger('scrollChildIntoView', details, true);\n  }\n\n  setTimeout(function(){\n    document.body.classList.add(KEYBOARD_OPEN_CSS);\n  }, 400);\n\n  return details; //for testing\n}\n\n/* eslint no-unused-vars:0 */\nfunction keyboardGetHeight() {\n  // check if we already have a keyboard height from the plugin or resize calculations\n  if (ionic.keyboard.height) {\n    return ionic.keyboard.height;\n  }\n\n  if (ionic.Platform.isAndroid()) {\n    // should be using the plugin, no way to know how big the keyboard is, so guess\n    if ( ionic.Platform.isFullScreen ) {\n      return 275;\n    }\n    // otherwise just calculate it\n    var contentHeight = window.innerHeight;\n    if (contentHeight < keyboardCurrentViewportHeight) {\n      return keyboardCurrentViewportHeight - contentHeight;\n    } else {\n      return 0;\n    }\n  }\n\n  // fallback for when it's the webview without the plugin\n  // or for just the standard web browser\n  // TODO: have these be based on device\n  if (ionic.Platform.isIOS()) {\n    if (ionic.keyboard.isLandscape) {\n      return 206;\n    }\n\n    if (!ionic.Platform.isWebView()) {\n      return 216;\n    }\n\n    return 260;\n  }\n\n  // safe guess\n  return 275;\n}\n\nfunction isPortraitViewportHeight(viewportHeight) {\n  return !!(!ionic.keyboard.isLandscape &&\n         keyboardPortraitViewportHeight &&\n         (Math.abs(keyboardPortraitViewportHeight - viewportHeight) < 2));\n}\n\nfunction isLandscapeViewportHeight(viewportHeight) {\n  return !!(ionic.keyboard.isLandscape &&\n         keyboardLandscapeViewportHeight &&\n         (Math.abs(keyboardLandscapeViewportHeight - viewportHeight) < 2));\n}\n\nfunction keyboardUpdateViewportHeight() {\n  wasOrientationChange = false;\n  keyboardCurrentViewportHeight = getViewportHeight();\n\n  if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {\n    //console.log(\"saved landscape: \" + keyboardCurrentViewportHeight);\n    keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;\n\n  } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {\n    //console.log(\"saved portrait: \" + keyboardCurrentViewportHeight);\n    keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;\n  }\n\n  if (keyboardActiveElement) {\n    ionic.trigger('resetScrollView', {\n      target: keyboardActiveElement\n    }, true);\n  }\n\n  if (ionic.keyboard.isOpen && ionic.tap.isTextInput(keyboardActiveElement)) {\n    keyboardShow();\n  }\n}\n\nfunction keyboardInitViewportHeight() {\n  var viewportHeight = getViewportHeight();\n  //console.log(\"Keyboard init VP: \" + viewportHeight + \" \" + window.innerWidth);\n  // can't just use window.innerHeight in case the keyboard is opened immediately\n  if ((viewportHeight / window.innerWidth) < 1) {\n    ionic.keyboard.isLandscape = true;\n  }\n  //console.log(\"ionic.keyboard.isLandscape is: \" + ionic.keyboard.isLandscape);\n\n  // initialize or update the current viewport height values\n  keyboardCurrentViewportHeight = viewportHeight;\n  if (ionic.keyboard.isLandscape && !keyboardLandscapeViewportHeight) {\n    keyboardLandscapeViewportHeight = keyboardCurrentViewportHeight;\n  } else if (!ionic.keyboard.isLandscape && !keyboardPortraitViewportHeight) {\n    keyboardPortraitViewportHeight = keyboardCurrentViewportHeight;\n  }\n}\n\nfunction getViewportHeight() {\n  var windowHeight = window.innerHeight;\n  //console.log('window.innerHeight is: ' + windowHeight);\n  //console.log('kb height is: ' + ionic.keyboard.height);\n  //console.log('kb isOpen: ' + ionic.keyboard.isOpen);\n\n  //TODO: add iPad undocked/split kb once kb plugin supports it\n  // the keyboard overlays the window on Android fullscreen\n  if (!(ionic.Platform.isAndroid() && ionic.Platform.isFullScreen) &&\n      (ionic.keyboard.isOpen || ionic.keyboard.isOpening) &&\n      !ionic.keyboard.isClosing) {\n\n     return windowHeight + keyboardGetHeight();\n  }\n  return windowHeight;\n}\n\nfunction inputScrollView(ele) {\n  while(ele) {\n    if (ele.classList.contains(SCROLL_CONTAINER_CSS)) {\n      return ele;\n    }\n    ele = ele.parentElement;\n  }\n  return null;\n}\n\nfunction keyboardHasPlugin() {\n  return !!(window.cordova && cordova.plugins && cordova.plugins.Keyboard);\n}\n\nionic.Platform.ready(function() {\n  keyboardInitViewportHeight();\n\n  window.addEventListener('orientationchange', keyboardOrientationChange);\n\n  // if orientation changes while app is in background, update on resuming\n  /*\n  if ( ionic.Platform.isWebView() ) {\n    document.addEventListener('resume', keyboardInitViewportHeight);\n\n    if (ionic.Platform.isAndroid()) {\n      //TODO: onbackpressed to detect keyboard close without focusout or plugin\n    }\n  }\n  */\n\n  // if orientation changes while app is in background, update on resuming\n/*  if ( ionic.Platform.isWebView() ) {\n    document.addEventListener('pause', function() {\n      window.removeEventListener('orientationchange', keyboardOrientationChange);\n    })\n    document.addEventListener('resume', function() {\n      keyboardInitViewportHeight();\n      window.addEventListener('orientationchange', keyboardOrientationChange)\n    });\n  }*/\n\n  // Android sometimes reports bad innerHeight on window.load\n  // try it again in a lil bit to play it safe\n  setTimeout(keyboardInitViewportHeight, 999);\n\n  // only initialize the adjustments for the virtual keyboard\n  // if a touchstart event happens\n  if (window.navigator.msPointerEnabled) {\n    document.addEventListener(\"MSPointerDown\", keyboardInit, false);\n  } else {\n    document.addEventListener('touchstart', keyboardInit, false);\n  }\n});\n\n\n\nvar viewportTag;\nvar viewportProperties = {};\n\nionic.viewport = {\n  orientation: function() {\n    // 0 = Portrait\n    // 90 = Landscape\n    // not using window.orientation because each device has a different implementation\n    return (window.innerWidth > window.innerHeight ? 90 : 0);\n  }\n};\n\nfunction viewportLoadTag() {\n  var x;\n\n  for (x = 0; x < document.head.children.length; x++) {\n    if (document.head.children[x].name == 'viewport') {\n      viewportTag = document.head.children[x];\n      break;\n    }\n  }\n\n  if (viewportTag) {\n    var props = viewportTag.content.toLowerCase().replace(/\\s+/g, '').split(',');\n    var keyValue;\n    for (x = 0; x < props.length; x++) {\n      if (props[x]) {\n        keyValue = props[x].split('=');\n        viewportProperties[ keyValue[0] ] = (keyValue.length > 1 ? keyValue[1] : '_');\n      }\n    }\n    viewportUpdate();\n  }\n}\n\nfunction viewportUpdate() {\n  // unit tests in viewport.unit.js\n\n  var initWidth = viewportProperties.width;\n  var initHeight = viewportProperties.height;\n  var p = ionic.Platform;\n  var version = p.version();\n  var DEVICE_WIDTH = 'device-width';\n  var DEVICE_HEIGHT = 'device-height';\n  var orientation = ionic.viewport.orientation();\n\n  // Most times we're removing the height and adding the width\n  // So this is the default to start with, then modify per platform/version/oreintation\n  delete viewportProperties.height;\n  viewportProperties.width = DEVICE_WIDTH;\n\n  if (p.isIPad()) {\n    // iPad\n\n    if (version > 7) {\n      // iPad >= 7.1\n      // https://issues.apache.org/jira/browse/CB-4323\n      delete viewportProperties.width;\n\n    } else {\n      // iPad <= 7.0\n\n      if (p.isWebView()) {\n        // iPad <= 7.0 WebView\n\n        if (orientation == 90) {\n          // iPad <= 7.0 WebView Landscape\n          viewportProperties.height = '0';\n\n        } else if (version == 7) {\n          // iPad <= 7.0 WebView Portait\n          viewportProperties.height = DEVICE_HEIGHT;\n        }\n      } else {\n        // iPad <= 6.1 Browser\n        if (version < 7) {\n          viewportProperties.height = '0';\n        }\n      }\n    }\n\n  } else if (p.isIOS()) {\n    // iPhone\n\n    if (p.isWebView()) {\n      // iPhone WebView\n\n      if (version > 7) {\n        // iPhone >= 7.1 WebView\n        delete viewportProperties.width;\n\n      } else if (version < 7) {\n        // iPhone <= 6.1 WebView\n        // if height was set it needs to get removed with this hack for <= 6.1\n        if (initHeight) viewportProperties.height = '0';\n\n      } else if (version == 7) {\n        //iPhone == 7.0 WebView\n        viewportProperties.height = DEVICE_HEIGHT;\n      }\n\n    } else {\n      // iPhone Browser\n\n      if (version < 7) {\n        // iPhone <= 6.1 Browser\n        // if height was set it needs to get removed with this hack for <= 6.1\n        if (initHeight) viewportProperties.height = '0';\n      }\n    }\n\n  }\n\n  // only update the viewport tag if there was a change\n  if (initWidth !== viewportProperties.width || initHeight !== viewportProperties.height) {\n    viewportTagUpdate();\n  }\n}\n\nfunction viewportTagUpdate() {\n  var key, props = [];\n  for (key in viewportProperties) {\n    if (viewportProperties[key]) {\n      props.push(key + (viewportProperties[key] == '_' ? '' : '=' + viewportProperties[key]));\n    }\n  }\n\n  viewportTag.content = props.join(', ');\n}\n\nionic.Platform.ready(function() {\n  viewportLoadTag();\n\n  window.addEventListener(\"orientationchange\", function() {\n    setTimeout(viewportUpdate, 1000);\n  }, false);\n});\n\n(function(ionic) {\n'use strict';\n  ionic.views.View = function() {\n    this.initialize.apply(this, arguments);\n  };\n\n  ionic.views.View.inherit = ionic.inherit;\n\n  ionic.extend(ionic.views.View.prototype, {\n    initialize: function() {}\n  });\n\n})(window.ionic);\n\n/*\n * Scroller\n * http://github.com/zynga/scroller\n *\n * Copyright 2011, Zynga Inc.\n * Licensed under the MIT License.\n * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt\n *\n * Based on the work of: Unify Project (unify-project.org)\n * http://unify-project.org\n * Copyright 2011, Deutsche Telekom AG\n * License: MIT + Apache (V2)\n */\n\n/* jshint eqnull: true */\n\n/**\n * Generic animation class with support for dropped frames both optional easing and duration.\n *\n * Optional duration is useful when the lifetime is defined by another condition than time\n * e.g. speed of an animating object, etc.\n *\n * Dropped frame logic allows to keep using the same updater logic independent from the actual\n * rendering. This eases a lot of cases where it might be pretty complex to break down a state\n * based on the pure time difference.\n */\nvar zyngaCore = { effect: {} };\n(function(global) {\n  var time = Date.now || function() {\n    return +new Date();\n  };\n  var desiredFrames = 60;\n  var millisecondsPerSecond = 1000;\n  var running = {};\n  var counter = 1;\n\n  zyngaCore.effect.Animate = {\n\n    /**\n     * A requestAnimationFrame wrapper / polyfill.\n     *\n     * @param callback {Function} The callback to be invoked before the next repaint.\n     * @param root {HTMLElement} The root element for the repaint\n     */\n    requestAnimationFrame: (function() {\n\n      // Check for request animation Frame support\n      var requestFrame = global.requestAnimationFrame || global.webkitRequestAnimationFrame || global.mozRequestAnimationFrame || global.oRequestAnimationFrame;\n      var isNative = !!requestFrame;\n\n      if (requestFrame && !/requestAnimationFrame\\(\\)\\s*\\{\\s*\\[native code\\]\\s*\\}/i.test(requestFrame.toString())) {\n        isNative = false;\n      }\n\n      if (isNative) {\n        return function(callback, root) {\n          requestFrame(callback, root);\n        };\n      }\n\n      var TARGET_FPS = 60;\n      var requests = {};\n      var requestCount = 0;\n      var rafHandle = 1;\n      var intervalHandle = null;\n      var lastActive = +new Date();\n\n      return function(callback) {\n        var callbackHandle = rafHandle++;\n\n        // Store callback\n        requests[callbackHandle] = callback;\n        requestCount++;\n\n        // Create timeout at first request\n        if (intervalHandle === null) {\n\n          intervalHandle = setInterval(function() {\n\n            var time = +new Date();\n            var currentRequests = requests;\n\n            // Reset data structure before executing callbacks\n            requests = {};\n            requestCount = 0;\n\n            for(var key in currentRequests) {\n              if (currentRequests.hasOwnProperty(key)) {\n                currentRequests[key](time);\n                lastActive = time;\n              }\n            }\n\n            // Disable the timeout when nothing happens for a certain\n            // period of time\n            if (time - lastActive > 2500) {\n              clearInterval(intervalHandle);\n              intervalHandle = null;\n            }\n\n          }, 1000 / TARGET_FPS);\n        }\n\n        return callbackHandle;\n      };\n\n    })(),\n\n\n    /**\n     * Stops the given animation.\n     *\n     * @param id {Integer} Unique animation ID\n     * @return {Boolean} Whether the animation was stopped (aka, was running before)\n     */\n    stop: function(id) {\n      var cleared = running[id] != null;\n      if (cleared) {\n        running[id] = null;\n      }\n\n      return cleared;\n    },\n\n\n    /**\n     * Whether the given animation is still running.\n     *\n     * @param id {Integer} Unique animation ID\n     * @return {Boolean} Whether the animation is still running\n     */\n    isRunning: function(id) {\n      return running[id] != null;\n    },\n\n\n    /**\n     * Start the animation.\n     *\n     * @param stepCallback {Function} Pointer to function which is executed on every step.\n     *   Signature of the method should be `function(percent, now, virtual) { return continueWithAnimation; }`\n     * @param verifyCallback {Function} Executed before every animation step.\n     *   Signature of the method should be `function() { return continueWithAnimation; }`\n     * @param completedCallback {Function}\n     *   Signature of the method should be `function(droppedFrames, finishedAnimation) {}`\n     * @param duration {Integer} Milliseconds to run the animation\n     * @param easingMethod {Function} Pointer to easing function\n     *   Signature of the method should be `function(percent) { return modifiedValue; }`\n     * @param root {Element} Render root, when available. Used for internal\n     *   usage of requestAnimationFrame.\n     * @return {Integer} Identifier of animation. Can be used to stop it any time.\n     */\n    start: function(stepCallback, verifyCallback, completedCallback, duration, easingMethod, root) {\n\n      var start = time();\n      var lastFrame = start;\n      var percent = 0;\n      var dropCounter = 0;\n      var id = counter++;\n\n      if (!root) {\n        root = document.body;\n      }\n\n      // Compacting running db automatically every few new animations\n      if (id % 20 === 0) {\n        var newRunning = {};\n        for (var usedId in running) {\n          newRunning[usedId] = true;\n        }\n        running = newRunning;\n      }\n\n      // This is the internal step method which is called every few milliseconds\n      var step = function(virtual) {\n\n        // Normalize virtual value\n        var render = virtual !== true;\n\n        // Get current time\n        var now = time();\n\n        // Verification is executed before next animation step\n        if (!running[id] || (verifyCallback && !verifyCallback(id))) {\n\n          running[id] = null;\n          completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, false);\n          return;\n\n        }\n\n        // For the current rendering to apply let's update omitted steps in memory.\n        // This is important to bring internal state variables up-to-date with progress in time.\n        if (render) {\n\n          var droppedFrames = Math.round((now - lastFrame) / (millisecondsPerSecond / desiredFrames)) - 1;\n          for (var j = 0; j < Math.min(droppedFrames, 4); j++) {\n            step(true);\n            dropCounter++;\n          }\n\n        }\n\n        // Compute percent value\n        if (duration) {\n          percent = (now - start) / duration;\n          if (percent > 1) {\n            percent = 1;\n          }\n        }\n\n        // Execute step callback, then...\n        var value = easingMethod ? easingMethod(percent) : percent;\n        if ((stepCallback(value, now, render) === false || percent === 1) && render) {\n          running[id] = null;\n          completedCallback && completedCallback(desiredFrames - (dropCounter / ((now - start) / millisecondsPerSecond)), id, percent === 1 || duration == null);\n        } else if (render) {\n          lastFrame = now;\n          zyngaCore.effect.Animate.requestAnimationFrame(step, root);\n        }\n      };\n\n      // Mark as running\n      running[id] = true;\n\n      // Init first step\n      zyngaCore.effect.Animate.requestAnimationFrame(step, root);\n\n      // Return unique animation ID\n      return id;\n    }\n  };\n})(this);\n\n/*\n * Scroller\n * http://github.com/zynga/scroller\n *\n * Copyright 2011, Zynga Inc.\n * Licensed under the MIT License.\n * https://raw.github.com/zynga/scroller/master/MIT-LICENSE.txt\n *\n * Based on the work of: Unify Project (unify-project.org)\n * http://unify-project.org\n * Copyright 2011, Deutsche Telekom AG\n * License: MIT + Apache (V2)\n */\n\n(function(ionic) {\n  var NOOP = function(){};\n\n  // Easing Equations (c) 2003 Robert Penner, all rights reserved.\n  // Open source under the BSD License.\n\n  /**\n   * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)\n  **/\n  var easeOutCubic = function(pos) {\n    return (Math.pow((pos - 1), 3) + 1);\n  };\n\n  /**\n   * @param pos {Number} position between 0 (start of effect) and 1 (end of effect)\n  **/\n  var easeInOutCubic = function(pos) {\n    if ((pos /= 0.5) < 1) {\n      return 0.5 * Math.pow(pos, 3);\n    }\n\n    return 0.5 * (Math.pow((pos - 2), 3) + 2);\n  };\n\n\n/**\n * ionic.views.Scroll\n * A powerful scroll view with support for bouncing, pull to refresh, and paging.\n * @param   {Object}        options options for the scroll view\n * @class A scroll view system\n * @memberof ionic.views\n */\nionic.views.Scroll = ionic.views.View.inherit({\n  initialize: function(options) {\n    var self = this;\n\n    self.__container = options.el;\n    self.__content = options.el.firstElementChild;\n\n    //Remove any scrollTop attached to these elements; they are virtual scroll now\n    //This also stops on-load-scroll-to-window.location.hash that the browser does\n    setTimeout(function() {\n      if (self.__container && self.__content) {\n        self.__container.scrollTop = 0;\n        self.__content.scrollTop = 0;\n      }\n    });\n\n    self.options = {\n\n      /** Disable scrolling on x-axis by default */\n      scrollingX: false,\n      scrollbarX: true,\n\n      /** Enable scrolling on y-axis */\n      scrollingY: true,\n      scrollbarY: true,\n\n      startX: 0,\n      startY: 0,\n\n      /** The amount to dampen mousewheel events */\n      wheelDampen: 6,\n\n      /** The minimum size the scrollbars scale to while scrolling */\n      minScrollbarSizeX: 5,\n      minScrollbarSizeY: 5,\n\n      /** Scrollbar fading after scrolling */\n      scrollbarsFade: true,\n      scrollbarFadeDelay: 300,\n      /** The initial fade delay when the pane is resized or initialized */\n      scrollbarResizeFadeDelay: 1000,\n\n      /** Enable animations for deceleration, snap back, zooming and scrolling */\n      animating: true,\n\n      /** duration for animations triggered by scrollTo/zoomTo */\n      animationDuration: 250,\n\n      /** The velocity required to make the scroll view \"slide\" after touchend */\n      decelVelocityThreshold: 4,\n\n      /** The velocity required to make the scroll view \"slide\" after touchend when using paging */\n      decelVelocityThresholdPaging: 4,\n\n      /** Enable bouncing (content can be slowly moved outside and jumps back after releasing) */\n      bouncing: true,\n\n      /** Enable locking to the main axis if user moves only slightly on one of them at start */\n      locking: true,\n\n      /** Enable pagination mode (switching between full page content panes) */\n      paging: false,\n\n      /** Enable snapping of content to a configured pixel grid */\n      snapping: false,\n\n      /** Enable zooming of content via API, fingers and mouse wheel */\n      zooming: false,\n\n      /** Minimum zoom level */\n      minZoom: 0.5,\n\n      /** Maximum zoom level */\n      maxZoom: 3,\n\n      /** Multiply or decrease scrolling speed **/\n      speedMultiplier: 1,\n\n      deceleration: 0.97,\n\n      /** Whether to prevent default on a scroll operation to capture drag events **/\n      preventDefault: false,\n\n      /** Callback that is fired on the later of touch end or deceleration end,\n        provided that another scrolling action has not begun. Used to know\n        when to fade out a scrollbar. */\n      scrollingComplete: NOOP,\n\n      /** This configures the amount of change applied to deceleration when reaching boundaries  **/\n      penetrationDeceleration: 0.03,\n\n      /** This configures the amount of change applied to acceleration when reaching boundaries  **/\n      penetrationAcceleration: 0.08,\n\n      // The ms interval for triggering scroll events\n      scrollEventInterval: 10,\n\n      freeze: false,\n\n      getContentWidth: function() {\n        return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);\n      },\n      getContentHeight: function() {\n        return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));\n      }\n    };\n\n    for (var key in options) {\n      self.options[key] = options[key];\n    }\n\n    self.hintResize = ionic.debounce(function() {\n      self.resize();\n    }, 1000, true);\n\n    self.onScroll = function() {\n\n      if (!ionic.scroll.isScrolling) {\n        setTimeout(self.setScrollStart, 50);\n      } else {\n        clearTimeout(self.scrollTimer);\n        self.scrollTimer = setTimeout(self.setScrollStop, 80);\n      }\n\n    };\n\n    self.freeze = function(shouldFreeze) {\n      if (arguments.length) {\n        self.options.freeze = shouldFreeze;\n      }\n      return self.options.freeze;\n    };\n\n    self.setScrollStart = function() {\n      ionic.scroll.isScrolling = Math.abs(ionic.scroll.lastTop - self.__scrollTop) > 1;\n      clearTimeout(self.scrollTimer);\n      self.scrollTimer = setTimeout(self.setScrollStop, 80);\n    };\n\n    self.setScrollStop = function() {\n      ionic.scroll.isScrolling = false;\n      ionic.scroll.lastTop = self.__scrollTop;\n    };\n\n    self.triggerScrollEvent = ionic.throttle(function() {\n      self.onScroll();\n      ionic.trigger('scroll', {\n        scrollTop: self.__scrollTop,\n        scrollLeft: self.__scrollLeft,\n        target: self.__container\n      });\n    }, self.options.scrollEventInterval);\n\n    self.triggerScrollEndEvent = function() {\n      ionic.trigger('scrollend', {\n        scrollTop: self.__scrollTop,\n        scrollLeft: self.__scrollLeft,\n        target: self.__container\n      });\n    };\n\n    self.__scrollLeft = self.options.startX;\n    self.__scrollTop = self.options.startY;\n\n    // Get the render update function, initialize event handlers,\n    // and calculate the size of the scroll container\n    self.__callback = self.getRenderFn();\n    self.__initEventHandlers();\n    self.__createScrollbars();\n\n  },\n\n  run: function() {\n    this.resize();\n\n    // Fade them out\n    this.__fadeScrollbars('out', this.options.scrollbarResizeFadeDelay);\n  },\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: STATUS\n  ---------------------------------------------------------------------------\n  */\n\n  /** Whether only a single finger is used in touch handling */\n  __isSingleTouch: false,\n\n  /** Whether a touch event sequence is in progress */\n  __isTracking: false,\n\n  /** Whether a deceleration animation went to completion. */\n  __didDecelerationComplete: false,\n\n  /**\n   * Whether a gesture zoom/rotate event is in progress. Activates when\n   * a gesturestart event happens. This has higher priority than dragging.\n   */\n  __isGesturing: false,\n\n  /**\n   * Whether the user has moved by such a distance that we have enabled\n   * dragging mode. Hint: It's only enabled after some pixels of movement to\n   * not interrupt with clicks etc.\n   */\n  __isDragging: false,\n\n  /**\n   * Not touching and dragging anymore, and smoothly animating the\n   * touch sequence using deceleration.\n   */\n  __isDecelerating: false,\n\n  /**\n   * Smoothly animating the currently configured change\n   */\n  __isAnimating: false,\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: DIMENSIONS\n  ---------------------------------------------------------------------------\n  */\n\n  /** Available outer left position (from document perspective) */\n  __clientLeft: 0,\n\n  /** Available outer top position (from document perspective) */\n  __clientTop: 0,\n\n  /** Available outer width */\n  __clientWidth: 0,\n\n  /** Available outer height */\n  __clientHeight: 0,\n\n  /** Outer width of content */\n  __contentWidth: 0,\n\n  /** Outer height of content */\n  __contentHeight: 0,\n\n  /** Snapping width for content */\n  __snapWidth: 100,\n\n  /** Snapping height for content */\n  __snapHeight: 100,\n\n  /** Height to assign to refresh area */\n  __refreshHeight: null,\n\n  /** Whether the refresh process is enabled when the event is released now */\n  __refreshActive: false,\n\n  /** Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release */\n  __refreshActivate: null,\n\n  /** Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled */\n  __refreshDeactivate: null,\n\n  /** Callback to execute to start the actual refresh. Call {@link #refreshFinish} when done */\n  __refreshStart: null,\n\n  /** Zoom level */\n  __zoomLevel: 1,\n\n  /** Scroll position on x-axis */\n  __scrollLeft: 0,\n\n  /** Scroll position on y-axis */\n  __scrollTop: 0,\n\n  /** Maximum allowed scroll position on x-axis */\n  __maxScrollLeft: 0,\n\n  /** Maximum allowed scroll position on y-axis */\n  __maxScrollTop: 0,\n\n  /* Scheduled left position (final position when animating) */\n  __scheduledLeft: 0,\n\n  /* Scheduled top position (final position when animating) */\n  __scheduledTop: 0,\n\n  /* Scheduled zoom level (final scale when animating) */\n  __scheduledZoom: 0,\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: LAST POSITIONS\n  ---------------------------------------------------------------------------\n  */\n\n  /** Left position of finger at start */\n  __lastTouchLeft: null,\n\n  /** Top position of finger at start */\n  __lastTouchTop: null,\n\n  /** Timestamp of last move of finger. Used to limit tracking range for deceleration speed. */\n  __lastTouchMove: null,\n\n  /** List of positions, uses three indexes for each state: left, top, timestamp */\n  __positions: null,\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    INTERNAL FIELDS :: DECELERATION SUPPORT\n  ---------------------------------------------------------------------------\n  */\n\n  /** Minimum left scroll position during deceleration */\n  __minDecelerationScrollLeft: null,\n\n  /** Minimum top scroll position during deceleration */\n  __minDecelerationScrollTop: null,\n\n  /** Maximum left scroll position during deceleration */\n  __maxDecelerationScrollLeft: null,\n\n  /** Maximum top scroll position during deceleration */\n  __maxDecelerationScrollTop: null,\n\n  /** Current factor to modify horizontal scroll position with on every step */\n  __decelerationVelocityX: null,\n\n  /** Current factor to modify vertical scroll position with on every step */\n  __decelerationVelocityY: null,\n\n\n  /** the browser-specific property to use for transforms */\n  __transformProperty: null,\n  __perspectiveProperty: null,\n\n  /** scrollbar indicators */\n  __indicatorX: null,\n  __indicatorY: null,\n\n  /** Timeout for scrollbar fading */\n  __scrollbarFadeTimeout: null,\n\n  /** whether we've tried to wait for size already */\n  __didWaitForSize: null,\n  __sizerTimeout: null,\n\n  __initEventHandlers: function() {\n    var self = this;\n\n    // Event Handler\n    var container = self.__container;\n\n    // save height when scroll view is shrunk so we don't need to reflow\n    var scrollViewOffsetHeight;\n\n    /**\n     * Shrink the scroll view when the keyboard is up if necessary and if the\n     * focused input is below the bottom of the shrunk scroll view, scroll it\n     * into view.\n     */\n    self.scrollChildIntoView = function(e) {\n      //console.log(\"scrollChildIntoView at: \" + Date.now());\n\n      // D\n      var scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;\n      // D - A\n      scrollViewOffsetHeight = container.offsetHeight;\n      var alreadyShrunk = self.isShrunkForKeyboard;\n\n      var isModal = container.parentNode.classList.contains('modal');\n      // 680px is when the media query for 60% modal width kicks in\n      var isInsetModal = isModal && window.innerWidth >= 680;\n\n     /*\n      *  _______\n      * |---A---| <- top of scroll view\n      * |       |\n      * |---B---| <- keyboard\n      * |   C   | <- input\n      * |---D---| <- initial bottom of scroll view\n      * |___E___| <- bottom of viewport\n      *\n      *  All commented calculations relative to the top of the viewport (ie E\n      *  is the viewport height, not 0)\n      */\n      if (!alreadyShrunk) {\n        // shrink scrollview so we can actually scroll if the input is hidden\n        // if it isn't shrink so we can scroll to inputs under the keyboard\n        // inset modals won't shrink on Android on their own when the keyboard appears\n        if ( ionic.Platform.isIOS() || ionic.Platform.isFullScreen || isInsetModal ) {\n          // if there are things below the scroll view account for them and\n          // subtract them from the keyboard height when resizing\n          // E - D                         E                         D\n          var scrollBottomOffsetToBottom = e.detail.viewportHeight - scrollBottomOffsetToTop;\n\n          // 0 or D - B if D > B           E - B                     E - D\n          var keyboardOffset = Math.max(0, e.detail.keyboardHeight - scrollBottomOffsetToBottom);\n\n          ionic.requestAnimationFrame(function(){\n            // D - A or B - A if D > B       D - A             max(0, D - B)\n            scrollViewOffsetHeight = scrollViewOffsetHeight - keyboardOffset;\n            container.style.height = scrollViewOffsetHeight + \"px\";\n            container.style.overflow = \"visible\";\n\n            //update scroll view\n            self.resize();\n          });\n        }\n\n        self.isShrunkForKeyboard = true;\n      }\n\n      /*\n       *  _______\n       * |---A---| <- top of scroll view\n       * |   *   | <- where we want to scroll to\n       * |--B-D--| <- keyboard, bottom of scroll view\n       * |   C   | <- input\n       * |       |\n       * |___E___| <- bottom of viewport\n       *\n       *  All commented calculations relative to the top of the viewport (ie E\n       *  is the viewport height, not 0)\n       */\n      // if the element is positioned under the keyboard scroll it into view\n      if (e.detail.isElementUnderKeyboard) {\n\n        ionic.requestAnimationFrame(function(){\n          container.scrollTop = 0;\n          // update D if we shrunk\n          if (self.isShrunkForKeyboard && !alreadyShrunk) {\n            scrollBottomOffsetToTop = container.getBoundingClientRect().bottom;\n          }\n\n          // middle of the scrollview, this is where we want to scroll to\n          // (D - A) / 2\n          var scrollMidpointOffset = scrollViewOffsetHeight * 0.5;\n          //console.log(\"container.offsetHeight: \" + scrollViewOffsetHeight);\n\n          // middle of the input we want to scroll into view\n          // C\n          var inputMidpoint = ((e.detail.elementBottom + e.detail.elementTop) / 2);\n\n          // distance from middle of input to the bottom of the scroll view\n          // C - D                                C               D\n          var inputMidpointOffsetToScrollBottom = inputMidpoint - scrollBottomOffsetToTop;\n\n          //C - D + (D - A)/2          C - D                     (D - A)/ 2\n          var scrollTop = inputMidpointOffsetToScrollBottom + scrollMidpointOffset;\n\n          if ( scrollTop > 0) {\n            if (ionic.Platform.isIOS()) ionic.tap.cloneFocusedInput(container, self);\n            self.scrollBy(0, scrollTop, true);\n            self.onScroll();\n          }\n        });\n      }\n\n      // Only the first scrollView parent of the element that broadcasted this event\n      // (the active element that needs to be shown) should receive this event\n      e.stopPropagation();\n    };\n\n    self.resetScrollView = function() {\n      //return scrollview to original height once keyboard has hidden\n      if ( self.isShrunkForKeyboard ) {\n        self.isShrunkForKeyboard = false;\n        container.style.height = \"\";\n        container.style.overflow = \"\";\n      }\n      self.resize();\n    };\n\n    //Broadcasted when keyboard is shown on some platforms.\n    //See js/utils/keyboard.js\n    container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);\n\n    // Listen on document because container may not have had the last\n    // keyboardActiveElement, for example after closing a modal with a focused\n    // input and returning to a previously resized scroll view in an ion-content.\n    // Since we can only resize scroll views that are currently visible, just resize\n    // the current scroll view when the keyboard is closed.\n    document.addEventListener('resetScrollView', self.resetScrollView);\n\n    function getEventTouches(e) {\n      return e.touches && e.touches.length ? e.touches : [{\n        pageX: e.pageX,\n        pageY: e.pageY\n      }];\n    }\n\n    self.touchStart = function(e) {\n      self.startCoordinates = ionic.tap.pointerCoord(e);\n\n      if ( ionic.tap.ignoreScrollStart(e) ) {\n        return;\n      }\n\n      self.__isDown = true;\n\n      if ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) {\n        // do not start if the target is a text input\n        // if there is a touchmove on this input, then we can start the scroll\n        self.__hasStarted = false;\n        return;\n      }\n\n      self.__isSelectable = true;\n      self.__enableScrollY = true;\n      self.__hasStarted = true;\n      self.doTouchStart(getEventTouches(e), e.timeStamp);\n      e.preventDefault();\n    };\n\n    self.touchMove = function(e) {\n      if (self.options.freeze || !self.__isDown ||\n        (!self.__isDown && e.defaultPrevented) ||\n        (e.target.tagName === 'TEXTAREA' && e.target.parentElement.querySelector(':focus')) ) {\n        return;\n      }\n\n      if ( !self.__hasStarted && ( ionic.tap.containsOrIsTextInput(e.target) || e.target.tagName === 'SELECT' ) ) {\n        // the target is a text input and scroll has started\n        // since the text input doesn't start on touchStart, do it here\n        self.__hasStarted = true;\n        self.doTouchStart(getEventTouches(e), e.timeStamp);\n        e.preventDefault();\n        return;\n      }\n\n      if (self.startCoordinates) {\n        // we have start coordinates, so get this touch move's current coordinates\n        var currentCoordinates = ionic.tap.pointerCoord(e);\n\n        if ( self.__isSelectable &&\n            ionic.tap.isTextInput(e.target) &&\n            Math.abs(self.startCoordinates.x - currentCoordinates.x) > 20 ) {\n          // user slid the text input's caret on its x axis, disable any future y scrolling\n          self.__enableScrollY = false;\n          self.__isSelectable = true;\n        }\n\n        if ( self.__enableScrollY && Math.abs(self.startCoordinates.y - currentCoordinates.y) > 10 ) {\n          // user scrolled the entire view on the y axis\n          // disabled being able to select text on an input\n          // hide the input which has focus, and show a cloned one that doesn't have focus\n          self.__isSelectable = false;\n          ionic.tap.cloneFocusedInput(container, self);\n        }\n      }\n\n      self.doTouchMove(getEventTouches(e), e.timeStamp, e.scale);\n      self.__isDown = true;\n    };\n\n    self.touchMoveBubble = function(e) {\n      if(self.__isDown && self.options.preventDefault) {\n        e.preventDefault();\n      }\n    };\n\n    self.touchEnd = function(e) {\n      if (!self.__isDown) return;\n\n      self.doTouchEnd(e, e.timeStamp);\n      self.__isDown = false;\n      self.__hasStarted = false;\n      self.__isSelectable = true;\n      self.__enableScrollY = true;\n\n      if ( !self.__isDragging && !self.__isDecelerating && !self.__isAnimating ) {\n        ionic.tap.removeClonedInputs(container, self);\n      }\n    };\n\n    self.mouseWheel = ionic.animationFrameThrottle(function(e) {\n      var scrollParent = ionic.DomUtil.getParentOrSelfWithClass(e.target, 'ionic-scroll');\n      if (!self.options.freeze && scrollParent === self.__container) {\n\n        self.hintResize();\n        self.scrollBy(\n          (e.wheelDeltaX || e.deltaX || 0) / self.options.wheelDampen,\n          (-e.wheelDeltaY || e.deltaY || 0) / self.options.wheelDampen\n        );\n\n        self.__fadeScrollbars('in');\n        clearTimeout(self.__wheelHideBarTimeout);\n        self.__wheelHideBarTimeout = setTimeout(function() {\n          self.__fadeScrollbars('out');\n        }, 100);\n      }\n    });\n\n    if ('ontouchstart' in window) {\n      // Touch Events\n      container.addEventListener(\"touchstart\", self.touchStart, false);\n      if(self.options.preventDefault) container.addEventListener(\"touchmove\", self.touchMoveBubble, false);\n      document.addEventListener(\"touchmove\", self.touchMove, false);\n      document.addEventListener(\"touchend\", self.touchEnd, false);\n      document.addEventListener(\"touchcancel\", self.touchEnd, false);\n\n    } else if (window.navigator.pointerEnabled) {\n      // Pointer Events\n      container.addEventListener(\"pointerdown\", self.touchStart, false);\n      if(self.options.preventDefault) container.addEventListener(\"pointermove\", self.touchMoveBubble, false);\n      document.addEventListener(\"pointermove\", self.touchMove, false);\n      document.addEventListener(\"pointerup\", self.touchEnd, false);\n      document.addEventListener(\"pointercancel\", self.touchEnd, false);\n      document.addEventListener(\"wheel\", self.mouseWheel, false);\n\n    } else if (window.navigator.msPointerEnabled) {\n      // IE10, WP8 (Pointer Events)\n      container.addEventListener(\"MSPointerDown\", self.touchStart, false);\n      if(self.options.preventDefault) container.addEventListener(\"MSPointerMove\", self.touchMoveBubble, false);\n      document.addEventListener(\"MSPointerMove\", self.touchMove, false);\n      document.addEventListener(\"MSPointerUp\", self.touchEnd, false);\n      document.addEventListener(\"MSPointerCancel\", self.touchEnd, false);\n      document.addEventListener(\"wheel\", self.mouseWheel, false);\n\n    } else {\n      // Mouse Events\n      var mousedown = false;\n\n      self.mouseDown = function(e) {\n        if ( ionic.tap.ignoreScrollStart(e) || e.target.tagName === 'SELECT' ) {\n          return;\n        }\n        self.doTouchStart(getEventTouches(e), e.timeStamp);\n\n        if ( !ionic.tap.isTextInput(e.target) ) {\n          e.preventDefault();\n        }\n        mousedown = true;\n      };\n\n      self.mouseMove = function(e) {\n        if (self.options.freeze || !mousedown || (!mousedown && e.defaultPrevented)) {\n          return;\n        }\n\n        self.doTouchMove(getEventTouches(e), e.timeStamp);\n\n        mousedown = true;\n      };\n\n      self.mouseMoveBubble = function(e) {\n        if (mousedown && self.options.preventDefault) {\n          e.preventDefault();\n        }\n      };\n\n      self.mouseUp = function(e) {\n        if (!mousedown) {\n          return;\n        }\n\n        self.doTouchEnd(e, e.timeStamp);\n\n        mousedown = false;\n      };\n\n      container.addEventListener(\"mousedown\", self.mouseDown, false);\n      if(self.options.preventDefault) container.addEventListener(\"mousemove\", self.mouseMoveBubble, false);\n      document.addEventListener(\"mousemove\", self.mouseMove, false);\n      document.addEventListener(\"mouseup\", self.mouseUp, false);\n      document.addEventListener('mousewheel', self.mouseWheel, false);\n      document.addEventListener('wheel', self.mouseWheel, false);\n    }\n  },\n\n  __cleanup: function() {\n    var self = this;\n    var container = self.__container;\n\n    container.removeEventListener('touchstart', self.touchStart);\n    container.removeEventListener('touchmove', self.touchMoveBubble);\n    document.removeEventListener('touchmove', self.touchMove);\n    document.removeEventListener('touchend', self.touchEnd);\n    document.removeEventListener('touchcancel', self.touchCancel);\n\n    container.removeEventListener(\"pointerdown\", self.touchStart);\n    container.removeEventListener(\"pointermove\", self.touchMoveBubble);\n    document.removeEventListener(\"pointermove\", self.touchMove);\n    document.removeEventListener(\"pointerup\", self.touchEnd);\n    document.removeEventListener(\"pointercancel\", self.touchEnd);\n\n    container.removeEventListener(\"MSPointerDown\", self.touchStart);\n    container.removeEventListener(\"MSPointerMove\", self.touchMoveBubble);\n    document.removeEventListener(\"MSPointerMove\", self.touchMove);\n    document.removeEventListener(\"MSPointerUp\", self.touchEnd);\n    document.removeEventListener(\"MSPointerCancel\", self.touchEnd);\n\n    container.removeEventListener(\"mousedown\", self.mouseDown);\n    container.removeEventListener(\"mousemove\", self.mouseMoveBubble);\n    document.removeEventListener(\"mousemove\", self.mouseMove);\n    document.removeEventListener(\"mouseup\", self.mouseUp);\n    document.removeEventListener('mousewheel', self.mouseWheel);\n    document.removeEventListener('wheel', self.mouseWheel);\n\n    container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);\n    document.removeEventListener('resetScrollView', self.resetScrollView);\n\n    ionic.tap.removeClonedInputs(container, self);\n\n    delete self.__container;\n    delete self.__content;\n    delete self.__indicatorX;\n    delete self.__indicatorY;\n    delete self.options.el;\n\n    self.__callback = self.scrollChildIntoView = self.resetScrollView = NOOP;\n\n    self.mouseMove = self.mouseDown = self.mouseUp = self.mouseWheel =\n      self.touchStart = self.touchMove = self.touchEnd = self.touchCancel = NOOP;\n\n    self.resize = self.scrollTo = self.zoomTo =\n      self.__scrollingComplete = NOOP;\n    container = null;\n  },\n\n  /** Create a scroll bar div with the given direction **/\n  __createScrollbar: function(direction) {\n    var bar = document.createElement('div'),\n      indicator = document.createElement('div');\n\n    indicator.className = 'scroll-bar-indicator scroll-bar-fade-out';\n\n    if (direction == 'h') {\n      bar.className = 'scroll-bar scroll-bar-h';\n    } else {\n      bar.className = 'scroll-bar scroll-bar-v';\n    }\n\n    bar.appendChild(indicator);\n    return bar;\n  },\n\n  __createScrollbars: function() {\n    var self = this;\n    var indicatorX, indicatorY;\n\n    if (self.options.scrollingX) {\n      indicatorX = {\n        el: self.__createScrollbar('h'),\n        sizeRatio: 1\n      };\n      indicatorX.indicator = indicatorX.el.children[0];\n\n      if (self.options.scrollbarX) {\n        self.__container.appendChild(indicatorX.el);\n      }\n      self.__indicatorX = indicatorX;\n    }\n\n    if (self.options.scrollingY) {\n      indicatorY = {\n        el: self.__createScrollbar('v'),\n        sizeRatio: 1\n      };\n      indicatorY.indicator = indicatorY.el.children[0];\n\n      if (self.options.scrollbarY) {\n        self.__container.appendChild(indicatorY.el);\n      }\n      self.__indicatorY = indicatorY;\n    }\n  },\n\n  __resizeScrollbars: function() {\n    var self = this;\n\n    // Update horiz bar\n    if (self.__indicatorX) {\n      var width = Math.max(Math.round(self.__clientWidth * self.__clientWidth / (self.__contentWidth)), 20);\n      if (width > self.__contentWidth) {\n        width = 0;\n      }\n      if (width !== self.__indicatorX.size) {\n        ionic.requestAnimationFrame(function(){\n          self.__indicatorX.indicator.style.width = width + 'px';\n        });\n      }\n      self.__indicatorX.size = width;\n      self.__indicatorX.minScale = self.options.minScrollbarSizeX / width;\n      self.__indicatorX.maxPos = self.__clientWidth - width;\n      self.__indicatorX.sizeRatio = self.__maxScrollLeft ? self.__indicatorX.maxPos / self.__maxScrollLeft : 1;\n    }\n\n    // Update vert bar\n    if (self.__indicatorY) {\n      var height = Math.max(Math.round(self.__clientHeight * self.__clientHeight / (self.__contentHeight)), 20);\n      if (height > self.__contentHeight) {\n        height = 0;\n      }\n      if (height !== self.__indicatorY.size) {\n        ionic.requestAnimationFrame(function(){\n          self.__indicatorY && (self.__indicatorY.indicator.style.height = height + 'px');\n        });\n      }\n      self.__indicatorY.size = height;\n      self.__indicatorY.minScale = self.options.minScrollbarSizeY / height;\n      self.__indicatorY.maxPos = self.__clientHeight - height;\n      self.__indicatorY.sizeRatio = self.__maxScrollTop ? self.__indicatorY.maxPos / self.__maxScrollTop : 1;\n    }\n  },\n\n  /**\n   * Move and scale the scrollbars as the page scrolls.\n   */\n  __repositionScrollbars: function() {\n    var self = this,\n        heightScale, widthScale,\n        widthDiff, heightDiff,\n        x, y,\n        xstop = 0, ystop = 0;\n\n    if (self.__indicatorX) {\n      // Handle the X scrollbar\n\n      // Don't go all the way to the right if we have a vertical scrollbar as well\n      if (self.__indicatorY) xstop = 10;\n\n      x = Math.round(self.__indicatorX.sizeRatio * self.__scrollLeft) || 0;\n\n      // The the difference between the last content X position, and our overscrolled one\n      widthDiff = self.__scrollLeft - (self.__maxScrollLeft - xstop);\n\n      if (self.__scrollLeft < 0) {\n\n        widthScale = Math.max(self.__indicatorX.minScale,\n            (self.__indicatorX.size - Math.abs(self.__scrollLeft)) / self.__indicatorX.size);\n\n        // Stay at left\n        x = 0;\n\n        // Make sure scale is transformed from the left/center origin point\n        self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'left center';\n      } else if (widthDiff > 0) {\n\n        widthScale = Math.max(self.__indicatorX.minScale,\n            (self.__indicatorX.size - widthDiff) / self.__indicatorX.size);\n\n        // Stay at the furthest x for the scrollable viewport\n        x = self.__indicatorX.maxPos - xstop;\n\n        // Make sure scale is transformed from the right/center origin point\n        self.__indicatorX.indicator.style[self.__transformOriginProperty] = 'right center';\n\n      } else {\n\n        // Normal motion\n        x = Math.min(self.__maxScrollLeft, Math.max(0, x));\n        widthScale = 1;\n\n      }\n\n      var translate3dX = 'translate3d(' + x + 'px, 0, 0) scaleX(' + widthScale + ')';\n      if (self.__indicatorX.transformProp !== translate3dX) {\n        self.__indicatorX.indicator.style[self.__transformProperty] = translate3dX;\n        self.__indicatorX.transformProp = translate3dX;\n      }\n    }\n\n    if (self.__indicatorY) {\n\n      y = Math.round(self.__indicatorY.sizeRatio * self.__scrollTop) || 0;\n\n      // Don't go all the way to the right if we have a vertical scrollbar as well\n      if (self.__indicatorX) ystop = 10;\n\n      heightDiff = self.__scrollTop - (self.__maxScrollTop - ystop);\n\n      if (self.__scrollTop < 0) {\n\n        heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - Math.abs(self.__scrollTop)) / self.__indicatorY.size);\n\n        // Stay at top\n        y = 0;\n\n        // Make sure scale is transformed from the center/top origin point\n        if (self.__indicatorY.originProp !== 'center top') {\n          self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center top';\n          self.__indicatorY.originProp = 'center top';\n        }\n\n      } else if (heightDiff > 0) {\n\n        heightScale = Math.max(self.__indicatorY.minScale, (self.__indicatorY.size - heightDiff) / self.__indicatorY.size);\n\n        // Stay at bottom of scrollable viewport\n        y = self.__indicatorY.maxPos - ystop;\n\n        // Make sure scale is transformed from the center/bottom origin point\n        if (self.__indicatorY.originProp !== 'center bottom') {\n          self.__indicatorY.indicator.style[self.__transformOriginProperty] = 'center bottom';\n          self.__indicatorY.originProp = 'center bottom';\n        }\n\n      } else {\n\n        // Normal motion\n        y = Math.min(self.__maxScrollTop, Math.max(0, y));\n        heightScale = 1;\n\n      }\n\n      var translate3dY = 'translate3d(0,' + y + 'px, 0) scaleY(' + heightScale + ')';\n      if (self.__indicatorY.transformProp !== translate3dY) {\n        self.__indicatorY.indicator.style[self.__transformProperty] = translate3dY;\n        self.__indicatorY.transformProp = translate3dY;\n      }\n    }\n  },\n\n  __fadeScrollbars: function(direction, delay) {\n    var self = this;\n\n    if (!self.options.scrollbarsFade) {\n      return;\n    }\n\n    var className = 'scroll-bar-fade-out';\n\n    if (self.options.scrollbarsFade === true) {\n      clearTimeout(self.__scrollbarFadeTimeout);\n\n      if (direction == 'in') {\n        if (self.__indicatorX) { self.__indicatorX.indicator.classList.remove(className); }\n        if (self.__indicatorY) { self.__indicatorY.indicator.classList.remove(className); }\n      } else {\n        self.__scrollbarFadeTimeout = setTimeout(function() {\n          if (self.__indicatorX) { self.__indicatorX.indicator.classList.add(className); }\n          if (self.__indicatorY) { self.__indicatorY.indicator.classList.add(className); }\n        }, delay || self.options.scrollbarFadeDelay);\n      }\n    }\n  },\n\n  __scrollingComplete: function() {\n    this.options.scrollingComplete();\n    ionic.tap.removeClonedInputs(this.__container, this);\n    this.__fadeScrollbars('out');\n  },\n\n  resize: function(continueScrolling) {\n    var self = this;\n    if (!self.__container || !self.options) return;\n\n    // Update Scroller dimensions for changed content\n    // Add padding to bottom of content\n    self.setDimensions(\n      self.__container.clientWidth,\n      self.__container.clientHeight,\n      self.options.getContentWidth(),\n      self.options.getContentHeight(),\n      continueScrolling\n    );\n  },\n  /*\n  ---------------------------------------------------------------------------\n    PUBLIC API\n  ---------------------------------------------------------------------------\n  */\n\n  getRenderFn: function() {\n    var self = this;\n\n    var content = self.__content;\n\n    var docStyle = document.documentElement.style;\n\n    var engine;\n    if ('MozAppearance' in docStyle) {\n      engine = 'gecko';\n    } else if ('WebkitAppearance' in docStyle) {\n      engine = 'webkit';\n    } else if (typeof navigator.cpuClass === 'string') {\n      engine = 'trident';\n    }\n\n    var vendorPrefix = {\n      trident: 'ms',\n      gecko: 'Moz',\n      webkit: 'Webkit',\n      presto: 'O'\n    }[engine];\n\n    var helperElem = document.createElement(\"div\");\n    var undef;\n\n    var perspectiveProperty = vendorPrefix + \"Perspective\";\n    var transformProperty = vendorPrefix + \"Transform\";\n    var transformOriginProperty = vendorPrefix + 'TransformOrigin';\n\n    self.__perspectiveProperty = transformProperty;\n    self.__transformProperty = transformProperty;\n    self.__transformOriginProperty = transformOriginProperty;\n\n    if (helperElem.style[perspectiveProperty] !== undef) {\n\n      return function(left, top, zoom, wasResize) {\n        var translate3d = 'translate3d(' + (-left) + 'px,' + (-top) + 'px,0) scale(' + zoom + ')';\n        if (translate3d !== self.contentTransform) {\n          content.style[transformProperty] = translate3d;\n          self.contentTransform = translate3d;\n        }\n        self.__repositionScrollbars();\n        if (!wasResize) {\n          self.triggerScrollEvent();\n        }\n      };\n\n    } else if (helperElem.style[transformProperty] !== undef) {\n\n      return function(left, top, zoom, wasResize) {\n        content.style[transformProperty] = 'translate(' + (-left) + 'px,' + (-top) + 'px) scale(' + zoom + ')';\n        self.__repositionScrollbars();\n        if (!wasResize) {\n          self.triggerScrollEvent();\n        }\n      };\n\n    } else {\n\n      return function(left, top, zoom, wasResize) {\n        content.style.marginLeft = left ? (-left / zoom) + 'px' : '';\n        content.style.marginTop = top ? (-top / zoom) + 'px' : '';\n        content.style.zoom = zoom || '';\n        self.__repositionScrollbars();\n        if (!wasResize) {\n          self.triggerScrollEvent();\n        }\n      };\n\n    }\n  },\n\n\n  /**\n   * Configures the dimensions of the client (outer) and content (inner) elements.\n   * Requires the available space for the outer element and the outer size of the inner element.\n   * All values which are falsy (null or zero etc.) are ignored and the old value is kept.\n   *\n   * @param clientWidth {Integer} Inner width of outer element\n   * @param clientHeight {Integer} Inner height of outer element\n   * @param contentWidth {Integer} Outer width of inner element\n   * @param contentHeight {Integer} Outer height of inner element\n   */\n  setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight, continueScrolling) {\n    var self = this;\n\n    if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {\n      // this scrollview isn't rendered, don't bother\n      return;\n    }\n\n    // Only update values which are defined\n    if (clientWidth === +clientWidth) {\n      self.__clientWidth = clientWidth;\n    }\n\n    if (clientHeight === +clientHeight) {\n      self.__clientHeight = clientHeight;\n    }\n\n    if (contentWidth === +contentWidth) {\n      self.__contentWidth = contentWidth;\n    }\n\n    if (contentHeight === +contentHeight) {\n      self.__contentHeight = contentHeight;\n    }\n\n    // Refresh maximums\n    self.__computeScrollMax();\n    self.__resizeScrollbars();\n\n    // Refresh scroll position\n    if (!continueScrolling) {\n      self.scrollTo(self.__scrollLeft, self.__scrollTop, true, null, true);\n    }\n\n  },\n\n\n  /**\n   * Sets the client coordinates in relation to the document.\n   *\n   * @param left {Integer} Left position of outer element\n   * @param top {Integer} Top position of outer element\n   */\n  setPosition: function(left, top) {\n    this.__clientLeft = left || 0;\n    this.__clientTop = top || 0;\n  },\n\n\n  /**\n   * Configures the snapping (when snapping is active)\n   *\n   * @param width {Integer} Snapping width\n   * @param height {Integer} Snapping height\n   */\n  setSnapSize: function(width, height) {\n    this.__snapWidth = width;\n    this.__snapHeight = height;\n  },\n\n\n  /**\n   * Activates pull-to-refresh. A special zone on the top of the list to start a list refresh whenever\n   * the user event is released during visibility of this zone. This was introduced by some apps on iOS like\n   * the official Twitter client.\n   *\n   * @param height {Integer} Height of pull-to-refresh zone on top of rendered list\n   * @param activateCallback {Function} Callback to execute on activation. This is for signalling the user about a refresh is about to happen when he release.\n   * @param deactivateCallback {Function} Callback to execute on deactivation. This is for signalling the user about the refresh being cancelled.\n   * @param startCallback {Function} Callback to execute to start the real async refresh action. Call {@link #finishPullToRefresh} after finish of refresh.\n   * @param showCallback {Function} Callback to execute when the refresher should be shown. This is for showing the refresher during a negative scrollTop.\n   * @param hideCallback {Function} Callback to execute when the refresher should be hidden. This is for hiding the refresher when it's behind the nav bar.\n   * @param tailCallback {Function} Callback to execute just before the refresher returns to it's original state. This is for zooming out the refresher.\n   * @param pullProgressCallback Callback to state the progress while pulling to refresh\n   */\n  activatePullToRefresh: function(height, refresherMethods) {\n    var self = this;\n\n    self.__refreshHeight = height;\n    self.__refreshActivate = function() { ionic.requestAnimationFrame(refresherMethods.activate); };\n    self.__refreshDeactivate = function() { ionic.requestAnimationFrame(refresherMethods.deactivate); };\n    self.__refreshStart = function() { ionic.requestAnimationFrame(refresherMethods.start); };\n    self.__refreshShow = function() { ionic.requestAnimationFrame(refresherMethods.show); };\n    self.__refreshHide = function() { ionic.requestAnimationFrame(refresherMethods.hide); };\n    self.__refreshTail = function() { ionic.requestAnimationFrame(refresherMethods.tail); };\n    self.__refreshTailTime = 100;\n    self.__minSpinTime = 600;\n  },\n\n\n  /**\n   * Starts pull-to-refresh manually.\n   */\n  triggerPullToRefresh: function() {\n    // Use publish instead of scrollTo to allow scrolling to out of boundary position\n    // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled\n    this.__publish(this.__scrollLeft, -this.__refreshHeight, this.__zoomLevel, true);\n\n    var d = new Date();\n    this.refreshStartTime = d.getTime();\n\n    if (this.__refreshStart) {\n      this.__refreshStart();\n    }\n  },\n\n\n  /**\n   * Signalizes that pull-to-refresh is finished.\n   */\n  finishPullToRefresh: function() {\n    var self = this;\n    // delay to make sure the spinner has a chance to spin for a split second before it's dismissed\n    var d = new Date();\n    var delay = 0;\n    if (self.refreshStartTime + self.__minSpinTime > d.getTime()) {\n      delay = self.refreshStartTime + self.__minSpinTime - d.getTime();\n    }\n    setTimeout(function() {\n      if (self.__refreshTail) {\n        self.__refreshTail();\n      }\n      setTimeout(function() {\n        self.__refreshActive = false;\n        if (self.__refreshDeactivate) {\n          self.__refreshDeactivate();\n        }\n        if (self.__refreshHide) {\n          self.__refreshHide();\n        }\n\n        self.scrollTo(self.__scrollLeft, self.__scrollTop, true);\n      }, self.__refreshTailTime);\n    }, delay);\n  },\n\n\n  /**\n   * Returns the scroll position and zooming values\n   *\n   * @return {Map} `left` and `top` scroll position and `zoom` level\n   */\n  getValues: function() {\n    return {\n      left: this.__scrollLeft,\n      top: this.__scrollTop,\n      zoom: this.__zoomLevel\n    };\n  },\n\n\n  /**\n   * Returns the maximum scroll values\n   *\n   * @return {Map} `left` and `top` maximum scroll values\n   */\n  getScrollMax: function() {\n    return {\n      left: this.__maxScrollLeft,\n      top: this.__maxScrollTop\n    };\n  },\n\n\n  /**\n   * Zooms to the given level. Supports optional animation. Zooms\n   * the center when no coordinates are given.\n   *\n   * @param level {Number} Level to zoom to\n   * @param animate {Boolean} Whether to use animation\n   * @param originLeft {Number} Zoom in at given left coordinate\n   * @param originTop {Number} Zoom in at given top coordinate\n   */\n  zoomTo: function(level, animate, originLeft, originTop) {\n    var self = this;\n\n    if (!self.options.zooming) {\n      throw new Error(\"Zooming is not enabled!\");\n    }\n\n    // Stop deceleration\n    if (self.__isDecelerating) {\n      zyngaCore.effect.Animate.stop(self.__isDecelerating);\n      self.__isDecelerating = false;\n    }\n\n    var oldLevel = self.__zoomLevel;\n\n    // Normalize input origin to center of viewport if not defined\n    if (originLeft == null) {\n      originLeft = self.__clientWidth / 2;\n    }\n\n    if (originTop == null) {\n      originTop = self.__clientHeight / 2;\n    }\n\n    // Limit level according to configuration\n    level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);\n\n    // Recompute maximum values while temporary tweaking maximum scroll ranges\n    self.__computeScrollMax(level);\n\n    // Recompute left and top coordinates based on new zoom level\n    var left = ((originLeft + self.__scrollLeft) * level / oldLevel) - originLeft;\n    var top = ((originTop + self.__scrollTop) * level / oldLevel) - originTop;\n\n    // Limit x-axis\n    if (left > self.__maxScrollLeft) {\n      left = self.__maxScrollLeft;\n    } else if (left < 0) {\n      left = 0;\n    }\n\n    // Limit y-axis\n    if (top > self.__maxScrollTop) {\n      top = self.__maxScrollTop;\n    } else if (top < 0) {\n      top = 0;\n    }\n\n    // Push values out\n    self.__publish(left, top, level, animate);\n\n  },\n\n\n  /**\n   * Zooms the content by the given factor.\n   *\n   * @param factor {Number} Zoom by given factor\n   * @param animate {Boolean} Whether to use animation\n   * @param originLeft {Number} Zoom in at given left coordinate\n   * @param originTop {Number} Zoom in at given top coordinate\n   */\n  zoomBy: function(factor, animate, originLeft, originTop) {\n    this.zoomTo(this.__zoomLevel * factor, animate, originLeft, originTop);\n  },\n\n\n  /**\n   * Scrolls to the given position. Respect limitations and snapping automatically.\n   *\n   * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>\n   * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>\n   * @param animate {Boolean} Whether the scrolling should happen using an animation\n   * @param zoom {Number} Zoom level to go to\n   */\n  scrollTo: function(left, top, animate, zoom, wasResize) {\n    var self = this;\n\n    // Stop deceleration\n    if (self.__isDecelerating) {\n      zyngaCore.effect.Animate.stop(self.__isDecelerating);\n      self.__isDecelerating = false;\n    }\n\n    // Correct coordinates based on new zoom level\n    if (zoom != null && zoom !== self.__zoomLevel) {\n\n      if (!self.options.zooming) {\n        throw new Error(\"Zooming is not enabled!\");\n      }\n\n      left *= zoom;\n      top *= zoom;\n\n      // Recompute maximum values while temporary tweaking maximum scroll ranges\n      self.__computeScrollMax(zoom);\n\n    } else {\n\n      // Keep zoom when not defined\n      zoom = self.__zoomLevel;\n\n    }\n\n    if (!self.options.scrollingX) {\n\n      left = self.__scrollLeft;\n\n    } else {\n\n      if (self.options.paging) {\n        left = Math.round(left / self.__clientWidth) * self.__clientWidth;\n      } else if (self.options.snapping) {\n        left = Math.round(left / self.__snapWidth) * self.__snapWidth;\n      }\n\n    }\n\n    if (!self.options.scrollingY) {\n\n      top = self.__scrollTop;\n\n    } else {\n\n      if (self.options.paging) {\n        top = Math.round(top / self.__clientHeight) * self.__clientHeight;\n      } else if (self.options.snapping) {\n        top = Math.round(top / self.__snapHeight) * self.__snapHeight;\n      }\n\n    }\n\n    // Limit for allowed ranges\n    left = Math.max(Math.min(self.__maxScrollLeft, left), 0);\n    top = Math.max(Math.min(self.__maxScrollTop, top), 0);\n\n    // Don't animate when no change detected, still call publish to make sure\n    // that rendered position is really in-sync with internal data\n    if (left === self.__scrollLeft && top === self.__scrollTop) {\n      animate = false;\n    }\n\n    // Publish new values\n    self.__publish(left, top, zoom, animate, wasResize);\n\n  },\n\n\n  /**\n   * Scroll by the given offset\n   *\n   * @param left {Number} Scroll x-axis by given offset\n   * @param top {Number} Scroll y-axis by given offset\n   * @param animate {Boolean} Whether to animate the given change\n   */\n  scrollBy: function(left, top, animate) {\n    var self = this;\n\n    var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;\n    var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;\n\n    self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);\n  },\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    EVENT CALLBACKS\n  ---------------------------------------------------------------------------\n  */\n\n  /**\n   * Mouse wheel handler for zooming support\n   */\n  doMouseZoom: function(wheelDelta, timeStamp, pageX, pageY) {\n    var change = wheelDelta > 0 ? 0.97 : 1.03;\n    return this.zoomTo(this.__zoomLevel * change, false, pageX - this.__clientLeft, pageY - this.__clientTop);\n  },\n\n  /**\n   * Touch start handler for scrolling support\n   */\n  doTouchStart: function(touches, timeStamp) {\n    var self = this;\n\n    // remember if the deceleration was just stopped\n    self.__decStopped = !!(self.__isDecelerating || self.__isAnimating);\n\n    self.hintResize();\n\n    if (timeStamp instanceof Date) {\n      timeStamp = timeStamp.valueOf();\n    }\n    if (typeof timeStamp !== \"number\") {\n      timeStamp = Date.now();\n    }\n\n    // Reset interruptedAnimation flag\n    self.__interruptedAnimation = true;\n\n    // Stop deceleration\n    if (self.__isDecelerating) {\n      zyngaCore.effect.Animate.stop(self.__isDecelerating);\n      self.__isDecelerating = false;\n      self.__interruptedAnimation = true;\n    }\n\n    // Stop animation\n    if (self.__isAnimating) {\n      zyngaCore.effect.Animate.stop(self.__isAnimating);\n      self.__isAnimating = false;\n      self.__interruptedAnimation = true;\n    }\n\n    // Use center point when dealing with two fingers\n    var currentTouchLeft, currentTouchTop;\n    var isSingleTouch = touches.length === 1;\n    if (isSingleTouch) {\n      currentTouchLeft = touches[0].pageX;\n      currentTouchTop = touches[0].pageY;\n    } else {\n      currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;\n      currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;\n    }\n\n    // Store initial positions\n    self.__initialTouchLeft = currentTouchLeft;\n    self.__initialTouchTop = currentTouchTop;\n\n    // Store initial touchList for scale calculation\n    self.__initialTouches = touches;\n\n    // Store current zoom level\n    self.__zoomLevelStart = self.__zoomLevel;\n\n    // Store initial touch positions\n    self.__lastTouchLeft = currentTouchLeft;\n    self.__lastTouchTop = currentTouchTop;\n\n    // Store initial move time stamp\n    self.__lastTouchMove = timeStamp;\n\n    // Reset initial scale\n    self.__lastScale = 1;\n\n    // Reset locking flags\n    self.__enableScrollX = !isSingleTouch && self.options.scrollingX;\n    self.__enableScrollY = !isSingleTouch && self.options.scrollingY;\n\n    // Reset tracking flag\n    self.__isTracking = true;\n\n    // Reset deceleration complete flag\n    self.__didDecelerationComplete = false;\n\n    // Dragging starts directly with two fingers, otherwise lazy with an offset\n    self.__isDragging = !isSingleTouch;\n\n    // Some features are disabled in multi touch scenarios\n    self.__isSingleTouch = isSingleTouch;\n\n    // Clearing data structure\n    self.__positions = [];\n\n  },\n\n\n  /**\n   * Touch move handler for scrolling support\n   */\n  doTouchMove: function(touches, timeStamp, scale) {\n    if (timeStamp instanceof Date) {\n      timeStamp = timeStamp.valueOf();\n    }\n    if (typeof timeStamp !== \"number\") {\n      timeStamp = Date.now();\n    }\n\n    var self = this;\n\n    // Ignore event when tracking is not enabled (event might be outside of element)\n    if (!self.__isTracking) {\n      return;\n    }\n\n    var currentTouchLeft, currentTouchTop;\n\n    // Compute move based around of center of fingers\n    if (touches.length === 2) {\n      currentTouchLeft = Math.abs(touches[0].pageX + touches[1].pageX) / 2;\n      currentTouchTop = Math.abs(touches[0].pageY + touches[1].pageY) / 2;\n\n      // Calculate scale when not present and only when touches are used\n      if (!scale && self.options.zooming) {\n        scale = self.__getScale(self.__initialTouches, touches);\n      }\n    } else {\n      currentTouchLeft = touches[0].pageX;\n      currentTouchTop = touches[0].pageY;\n    }\n\n    var positions = self.__positions;\n\n    // Are we already is dragging mode?\n    if (self.__isDragging) {\n        self.__decStopped = false;\n\n      // Compute move distance\n      var moveX = currentTouchLeft - self.__lastTouchLeft;\n      var moveY = currentTouchTop - self.__lastTouchTop;\n\n      // Read previous scroll position and zooming\n      var scrollLeft = self.__scrollLeft;\n      var scrollTop = self.__scrollTop;\n      var level = self.__zoomLevel;\n\n      // Work with scaling\n      if (scale != null && self.options.zooming) {\n\n        var oldLevel = level;\n\n        // Recompute level based on previous scale and new scale\n        level = level / self.__lastScale * scale;\n\n        // Limit level according to configuration\n        level = Math.max(Math.min(level, self.options.maxZoom), self.options.minZoom);\n\n        // Only do further compution when change happened\n        if (oldLevel !== level) {\n\n          // Compute relative event position to container\n          var currentTouchLeftRel = currentTouchLeft - self.__clientLeft;\n          var currentTouchTopRel = currentTouchTop - self.__clientTop;\n\n          // Recompute left and top coordinates based on new zoom level\n          scrollLeft = ((currentTouchLeftRel + scrollLeft) * level / oldLevel) - currentTouchLeftRel;\n          scrollTop = ((currentTouchTopRel + scrollTop) * level / oldLevel) - currentTouchTopRel;\n\n          // Recompute max scroll values\n          self.__computeScrollMax(level);\n\n        }\n      }\n\n      if (self.__enableScrollX) {\n\n        scrollLeft -= moveX * self.options.speedMultiplier;\n        var maxScrollLeft = self.__maxScrollLeft;\n\n        if (scrollLeft > maxScrollLeft || scrollLeft < 0) {\n\n          // Slow down on the edges\n          if (self.options.bouncing) {\n\n            scrollLeft += (moveX / 2 * self.options.speedMultiplier);\n\n          } else if (scrollLeft > maxScrollLeft) {\n\n            scrollLeft = maxScrollLeft;\n\n          } else {\n\n            scrollLeft = 0;\n\n          }\n        }\n      }\n\n      // Compute new vertical scroll position\n      if (self.__enableScrollY) {\n\n        scrollTop -= moveY * self.options.speedMultiplier;\n        var maxScrollTop = self.__maxScrollTop;\n\n        if (scrollTop > maxScrollTop || scrollTop < 0) {\n\n          // Slow down on the edges\n          if (self.options.bouncing || (self.__refreshHeight && scrollTop < 0)) {\n\n            scrollTop += (moveY / 2 * self.options.speedMultiplier);\n\n            // Support pull-to-refresh (only when only y is scrollable)\n            if (!self.__enableScrollX && self.__refreshHeight != null) {\n\n              // hide the refresher when it's behind the header bar in case of header transparency\n              if (scrollTop < 0) {\n                self.__refreshHidden = false;\n                self.__refreshShow();\n              } else {\n                self.__refreshHide();\n                self.__refreshHidden = true;\n              }\n\n              if (!self.__refreshActive && scrollTop <= -self.__refreshHeight) {\n\n                self.__refreshActive = true;\n                if (self.__refreshActivate) {\n                  self.__refreshActivate();\n                }\n\n              } else if (self.__refreshActive && scrollTop > -self.__refreshHeight) {\n\n                self.__refreshActive = false;\n                if (self.__refreshDeactivate) {\n                  self.__refreshDeactivate();\n                }\n\n              }\n            }\n\n          } else if (scrollTop > maxScrollTop) {\n\n            scrollTop = maxScrollTop;\n\n          } else {\n\n            scrollTop = 0;\n\n          }\n        } else if (self.__refreshHeight && !self.__refreshHidden) {\n          // if a positive scroll value and the refresher is still not hidden, hide it\n          self.__refreshHide();\n          self.__refreshHidden = true;\n        }\n      }\n\n      // Keep list from growing infinitely (holding min 10, max 20 measure points)\n      if (positions.length > 60) {\n        positions.splice(0, 30);\n      }\n\n      // Track scroll movement for decleration\n      positions.push(scrollLeft, scrollTop, timeStamp);\n\n      // Sync scroll position\n      self.__publish(scrollLeft, scrollTop, level);\n\n    // Otherwise figure out whether we are switching into dragging mode now.\n    } else {\n\n      var minimumTrackingForScroll = self.options.locking ? 3 : 0;\n      var minimumTrackingForDrag = 5;\n\n      var distanceX = Math.abs(currentTouchLeft - self.__initialTouchLeft);\n      var distanceY = Math.abs(currentTouchTop - self.__initialTouchTop);\n\n      self.__enableScrollX = self.options.scrollingX && distanceX >= minimumTrackingForScroll;\n      self.__enableScrollY = self.options.scrollingY && distanceY >= minimumTrackingForScroll;\n\n      positions.push(self.__scrollLeft, self.__scrollTop, timeStamp);\n\n      self.__isDragging = (self.__enableScrollX || self.__enableScrollY) && (distanceX >= minimumTrackingForDrag || distanceY >= minimumTrackingForDrag);\n      if (self.__isDragging) {\n        self.__interruptedAnimation = false;\n        self.__fadeScrollbars('in');\n      }\n\n    }\n\n    // Update last touch positions and time stamp for next event\n    self.__lastTouchLeft = currentTouchLeft;\n    self.__lastTouchTop = currentTouchTop;\n    self.__lastTouchMove = timeStamp;\n    self.__lastScale = scale;\n\n  },\n\n\n  /**\n   * Touch end handler for scrolling support\n   */\n  doTouchEnd: function(e, timeStamp) {\n    if (timeStamp instanceof Date) {\n      timeStamp = timeStamp.valueOf();\n    }\n    if (typeof timeStamp !== \"number\") {\n      timeStamp = Date.now();\n    }\n\n    var self = this;\n\n    // Ignore event when tracking is not enabled (no touchstart event on element)\n    // This is required as this listener ('touchmove') sits on the document and not on the element itself.\n    if (!self.__isTracking) {\n      return;\n    }\n\n    // Not touching anymore (when two finger hit the screen there are two touch end events)\n    self.__isTracking = false;\n\n    // Be sure to reset the dragging flag now. Here we also detect whether\n    // the finger has moved fast enough to switch into a deceleration animation.\n    if (self.__isDragging) {\n\n      // Reset dragging flag\n      self.__isDragging = false;\n\n      // Start deceleration\n      // Verify that the last move detected was in some relevant time frame\n      if (self.__isSingleTouch && self.options.animating && (timeStamp - self.__lastTouchMove) <= 100) {\n\n        // Then figure out what the scroll position was about 100ms ago\n        var positions = self.__positions;\n        var endPos = positions.length - 1;\n        var startPos = endPos;\n\n        // Move pointer to position measured 100ms ago\n        for (var i = endPos; i > 0 && positions[i] > (self.__lastTouchMove - 100); i -= 3) {\n          startPos = i;\n        }\n\n        // If start and stop position is identical in a 100ms timeframe,\n        // we cannot compute any useful deceleration.\n        if (startPos !== endPos) {\n\n          // Compute relative movement between these two points\n          var timeOffset = positions[endPos] - positions[startPos];\n          var movedLeft = self.__scrollLeft - positions[startPos - 2];\n          var movedTop = self.__scrollTop - positions[startPos - 1];\n\n          // Based on 50ms compute the movement to apply for each render step\n          self.__decelerationVelocityX = movedLeft / timeOffset * (1000 / 60);\n          self.__decelerationVelocityY = movedTop / timeOffset * (1000 / 60);\n\n          // How much velocity is required to start the deceleration\n          var minVelocityToStartDeceleration = self.options.paging || self.options.snapping ? self.options.decelVelocityThresholdPaging : self.options.decelVelocityThreshold;\n\n          // Verify that we have enough velocity to start deceleration\n          if (Math.abs(self.__decelerationVelocityX) > minVelocityToStartDeceleration || Math.abs(self.__decelerationVelocityY) > minVelocityToStartDeceleration) {\n\n            // Deactivate pull-to-refresh when decelerating\n            if (!self.__refreshActive) {\n              self.__startDeceleration(timeStamp);\n            }\n          }\n        } else {\n          self.__scrollingComplete();\n        }\n      } else if ((timeStamp - self.__lastTouchMove) > 100) {\n        self.__scrollingComplete();\n      }\n\n    } else if (self.__decStopped) {\n      // the deceleration was stopped\n      // user flicked the scroll fast, and stop dragging, then did a touchstart to stop the srolling\n      // tell the touchend event code to do nothing, we don't want to actually send a click\n      e.isTapHandled = true;\n      self.__decStopped = false;\n    }\n\n    // If this was a slower move it is per default non decelerated, but this\n    // still means that we want snap back to the bounds which is done here.\n    // This is placed outside the condition above to improve edge case stability\n    // e.g. touchend fired without enabled dragging. This should normally do not\n    // have modified the scroll positions or even showed the scrollbars though.\n    if (!self.__isDecelerating) {\n\n      if (self.__refreshActive && self.__refreshStart) {\n\n        // Use publish instead of scrollTo to allow scrolling to out of boundary position\n        // We don't need to normalize scrollLeft, zoomLevel, etc. here because we only y-scrolling when pull-to-refresh is enabled\n        self.__publish(self.__scrollLeft, -self.__refreshHeight, self.__zoomLevel, true);\n\n        var d = new Date();\n        self.refreshStartTime = d.getTime();\n\n        if (self.__refreshStart) {\n          self.__refreshStart();\n        }\n        // for iOS-ey style scrolling\n        if (!ionic.Platform.isAndroid())self.__startDeceleration();\n      } else {\n\n        if (self.__interruptedAnimation || self.__isDragging) {\n          self.__scrollingComplete();\n        }\n        self.scrollTo(self.__scrollLeft, self.__scrollTop, true, self.__zoomLevel);\n\n        // Directly signalize deactivation (nothing todo on refresh?)\n        if (self.__refreshActive) {\n\n          self.__refreshActive = false;\n          if (self.__refreshDeactivate) {\n            self.__refreshDeactivate();\n          }\n\n        }\n      }\n    }\n\n    // Fully cleanup list\n    self.__positions.length = 0;\n\n  },\n\n\n\n  /*\n  ---------------------------------------------------------------------------\n    PRIVATE API\n  ---------------------------------------------------------------------------\n  */\n\n  /**\n   * Applies the scroll position to the content element\n   *\n   * @param left {Number} Left scroll position\n   * @param top {Number} Top scroll position\n   * @param animate {Boolean} Whether animation should be used to move to the new coordinates\n   */\n  __publish: function(left, top, zoom, animate, wasResize) {\n\n    var self = this;\n\n    // Remember whether we had an animation, then we try to continue based on the current \"drive\" of the animation\n    var wasAnimating = self.__isAnimating;\n    if (wasAnimating) {\n      zyngaCore.effect.Animate.stop(wasAnimating);\n      self.__isAnimating = false;\n    }\n\n    if (animate && self.options.animating) {\n\n      // Keep scheduled positions for scrollBy/zoomBy functionality\n      self.__scheduledLeft = left;\n      self.__scheduledTop = top;\n      self.__scheduledZoom = zoom;\n\n      var oldLeft = self.__scrollLeft;\n      var oldTop = self.__scrollTop;\n      var oldZoom = self.__zoomLevel;\n\n      var diffLeft = left - oldLeft;\n      var diffTop = top - oldTop;\n      var diffZoom = zoom - oldZoom;\n\n      var step = function(percent, now, render) {\n\n        if (render) {\n\n          self.__scrollLeft = oldLeft + (diffLeft * percent);\n          self.__scrollTop = oldTop + (diffTop * percent);\n          self.__zoomLevel = oldZoom + (diffZoom * percent);\n\n          // Push values out\n          if (self.__callback) {\n            self.__callback(self.__scrollLeft, self.__scrollTop, self.__zoomLevel, wasResize);\n          }\n\n        }\n      };\n\n      var verify = function(id) {\n        return self.__isAnimating === id;\n      };\n\n      var completed = function(renderedFramesPerSecond, animationId, wasFinished) {\n        if (animationId === self.__isAnimating) {\n          self.__isAnimating = false;\n        }\n        if (self.__didDecelerationComplete || wasFinished) {\n          self.__scrollingComplete();\n        }\n\n        if (self.options.zooming) {\n          self.__computeScrollMax();\n        }\n      };\n\n      // When continuing based on previous animation we choose an ease-out animation instead of ease-in-out\n      self.__isAnimating = zyngaCore.effect.Animate.start(step, verify, completed, self.options.animationDuration, wasAnimating ? easeOutCubic : easeInOutCubic);\n\n    } else {\n\n      self.__scheduledLeft = self.__scrollLeft = left;\n      self.__scheduledTop = self.__scrollTop = top;\n      self.__scheduledZoom = self.__zoomLevel = zoom;\n\n      // Push values out\n      if (self.__callback) {\n        self.__callback(left, top, zoom, wasResize);\n      }\n\n      // Fix max scroll ranges\n      if (self.options.zooming) {\n        self.__computeScrollMax();\n      }\n    }\n  },\n\n\n  /**\n   * Recomputes scroll minimum values based on client dimensions and content dimensions.\n   */\n  __computeScrollMax: function(zoomLevel) {\n    var self = this;\n\n    if (zoomLevel == null) {\n      zoomLevel = self.__zoomLevel;\n    }\n\n    self.__maxScrollLeft = Math.max((self.__contentWidth * zoomLevel) - self.__clientWidth, 0);\n    self.__maxScrollTop = Math.max((self.__contentHeight * zoomLevel) - self.__clientHeight, 0);\n\n    if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {\n      self.__didWaitForSize = true;\n      self.__waitForSize();\n    }\n  },\n\n\n  /**\n   * If the scroll view isn't sized correctly on start, wait until we have at least some size\n   */\n  __waitForSize: function() {\n    var self = this;\n\n    clearTimeout(self.__sizerTimeout);\n\n    var sizer = function() {\n      self.resize(true);\n    };\n\n    sizer();\n    self.__sizerTimeout = setTimeout(sizer, 500);\n  },\n\n  /*\n  ---------------------------------------------------------------------------\n    ANIMATION (DECELERATION) SUPPORT\n  ---------------------------------------------------------------------------\n  */\n\n  /**\n   * Called when a touch sequence end and the speed of the finger was high enough\n   * to switch into deceleration mode.\n   */\n  __startDeceleration: function() {\n    var self = this;\n\n    if (self.options.paging) {\n\n      var scrollLeft = Math.max(Math.min(self.__scrollLeft, self.__maxScrollLeft), 0);\n      var scrollTop = Math.max(Math.min(self.__scrollTop, self.__maxScrollTop), 0);\n      var clientWidth = self.__clientWidth;\n      var clientHeight = self.__clientHeight;\n\n      // We limit deceleration not to the min/max values of the allowed range, but to the size of the visible client area.\n      // Each page should have exactly the size of the client area.\n      self.__minDecelerationScrollLeft = Math.floor(scrollLeft / clientWidth) * clientWidth;\n      self.__minDecelerationScrollTop = Math.floor(scrollTop / clientHeight) * clientHeight;\n      self.__maxDecelerationScrollLeft = Math.ceil(scrollLeft / clientWidth) * clientWidth;\n      self.__maxDecelerationScrollTop = Math.ceil(scrollTop / clientHeight) * clientHeight;\n\n    } else {\n\n      self.__minDecelerationScrollLeft = 0;\n      self.__minDecelerationScrollTop = 0;\n      self.__maxDecelerationScrollLeft = self.__maxScrollLeft;\n      self.__maxDecelerationScrollTop = self.__maxScrollTop;\n      if (self.__refreshActive) self.__minDecelerationScrollTop = self.__refreshHeight * -1;\n    }\n\n    // Wrap class method\n    var step = function(percent, now, render) {\n      self.__stepThroughDeceleration(render);\n    };\n\n    // How much velocity is required to keep the deceleration running\n    self.__minVelocityToKeepDecelerating = self.options.snapping ? 4 : 0.1;\n\n    // Detect whether it's still worth to continue animating steps\n    // If we are already slow enough to not being user perceivable anymore, we stop the whole process here.\n    var verify = function() {\n      var shouldContinue = Math.abs(self.__decelerationVelocityX) >= self.__minVelocityToKeepDecelerating ||\n        Math.abs(self.__decelerationVelocityY) >= self.__minVelocityToKeepDecelerating;\n      if (!shouldContinue) {\n        self.__didDecelerationComplete = true;\n\n        //Make sure the scroll values are within the boundaries after a bounce,\n        //not below 0 or above maximum\n        if (self.options.bouncing && !self.__refreshActive) {\n          self.scrollTo(\n            Math.min( Math.max(self.__scrollLeft, 0), self.__maxScrollLeft ),\n            Math.min( Math.max(self.__scrollTop, 0), self.__maxScrollTop ),\n            self.__refreshActive\n          );\n        }\n      }\n      return shouldContinue;\n    };\n\n    var completed = function() {\n      self.__isDecelerating = false;\n      if (self.__didDecelerationComplete) {\n        self.__scrollingComplete();\n      }\n\n      // Animate to grid when snapping is active, otherwise just fix out-of-boundary positions\n      if (self.options.paging) {\n        self.scrollTo(self.__scrollLeft, self.__scrollTop, self.options.snapping);\n      }\n    };\n\n    // Start animation and switch on flag\n    self.__isDecelerating = zyngaCore.effect.Animate.start(step, verify, completed);\n\n  },\n\n\n  /**\n   * Called on every step of the animation\n   *\n   * @param inMemory {Boolean} Whether to not render the current step, but keep it in memory only. Used internally only!\n   */\n  __stepThroughDeceleration: function(render) {\n    var self = this;\n\n\n    //\n    // COMPUTE NEXT SCROLL POSITION\n    //\n\n    // Add deceleration to scroll position\n    var scrollLeft = self.__scrollLeft + self.__decelerationVelocityX;// * self.options.deceleration);\n    var scrollTop = self.__scrollTop + self.__decelerationVelocityY;// * self.options.deceleration);\n\n\n    //\n    // HARD LIMIT SCROLL POSITION FOR NON BOUNCING MODE\n    //\n\n    if (!self.options.bouncing) {\n\n      var scrollLeftFixed = Math.max(Math.min(self.__maxDecelerationScrollLeft, scrollLeft), self.__minDecelerationScrollLeft);\n      if (scrollLeftFixed !== scrollLeft) {\n        scrollLeft = scrollLeftFixed;\n        self.__decelerationVelocityX = 0;\n      }\n\n      var scrollTopFixed = Math.max(Math.min(self.__maxDecelerationScrollTop, scrollTop), self.__minDecelerationScrollTop);\n      if (scrollTopFixed !== scrollTop) {\n        scrollTop = scrollTopFixed;\n        self.__decelerationVelocityY = 0;\n      }\n\n    }\n\n\n    //\n    // UPDATE SCROLL POSITION\n    //\n\n    if (render) {\n\n      self.__publish(scrollLeft, scrollTop, self.__zoomLevel);\n\n    } else {\n\n      self.__scrollLeft = scrollLeft;\n      self.__scrollTop = scrollTop;\n\n    }\n\n\n    //\n    // SLOW DOWN\n    //\n\n    // Slow down velocity on every iteration\n    if (!self.options.paging) {\n\n      // This is the factor applied to every iteration of the animation\n      // to slow down the process. This should emulate natural behavior where\n      // objects slow down when the initiator of the movement is removed\n      var frictionFactor = self.options.deceleration;\n\n      self.__decelerationVelocityX *= frictionFactor;\n      self.__decelerationVelocityY *= frictionFactor;\n\n    }\n\n\n    //\n    // BOUNCING SUPPORT\n    //\n\n    if (self.options.bouncing) {\n\n      var scrollOutsideX = 0;\n      var scrollOutsideY = 0;\n\n      // This configures the amount of change applied to deceleration/acceleration when reaching boundaries\n      var penetrationDeceleration = self.options.penetrationDeceleration;\n      var penetrationAcceleration = self.options.penetrationAcceleration;\n\n      // Check limits\n      if (scrollLeft < self.__minDecelerationScrollLeft) {\n        scrollOutsideX = self.__minDecelerationScrollLeft - scrollLeft;\n      } else if (scrollLeft > self.__maxDecelerationScrollLeft) {\n        scrollOutsideX = self.__maxDecelerationScrollLeft - scrollLeft;\n      }\n\n      if (scrollTop < self.__minDecelerationScrollTop) {\n        scrollOutsideY = self.__minDecelerationScrollTop - scrollTop;\n      } else if (scrollTop > self.__maxDecelerationScrollTop) {\n        scrollOutsideY = self.__maxDecelerationScrollTop - scrollTop;\n      }\n\n      // Slow down until slow enough, then flip back to snap position\n      if (scrollOutsideX !== 0) {\n        var isHeadingOutwardsX = scrollOutsideX * self.__decelerationVelocityX <= self.__minDecelerationScrollLeft;\n        if (isHeadingOutwardsX) {\n          self.__decelerationVelocityX += scrollOutsideX * penetrationDeceleration;\n        }\n        var isStoppedX = Math.abs(self.__decelerationVelocityX) <= self.__minVelocityToKeepDecelerating;\n        //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds\n        if (!isHeadingOutwardsX || isStoppedX) {\n          self.__decelerationVelocityX = scrollOutsideX * penetrationAcceleration;\n        }\n      }\n\n      if (scrollOutsideY !== 0) {\n        var isHeadingOutwardsY = scrollOutsideY * self.__decelerationVelocityY <= self.__minDecelerationScrollTop;\n        if (isHeadingOutwardsY) {\n          self.__decelerationVelocityY += scrollOutsideY * penetrationDeceleration;\n        }\n        var isStoppedY = Math.abs(self.__decelerationVelocityY) <= self.__minVelocityToKeepDecelerating;\n        //If we're not heading outwards, or if the above statement got us below minDeceleration, go back towards bounds\n        if (!isHeadingOutwardsY || isStoppedY) {\n          self.__decelerationVelocityY = scrollOutsideY * penetrationAcceleration;\n        }\n      }\n    }\n  },\n\n\n  /**\n   * calculate the distance between two touches\n   * @param   {Touch}     touch1\n   * @param   {Touch}     touch2\n   * @returns {Number}    distance\n   */\n  __getDistance: function getDistance(touch1, touch2) {\n    var x = touch2.pageX - touch1.pageX,\n    y = touch2.pageY - touch1.pageY;\n    return Math.sqrt((x * x) + (y * y));\n  },\n\n\n  /**\n   * calculate the scale factor between two touchLists (fingers)\n   * no scale is 1, and goes down to 0 when pinched together, and bigger when pinched out\n   * @param   {Array}     start\n   * @param   {Array}     end\n   * @returns {Number}    scale\n   */\n  __getScale: function getScale(start, end) {\n    // need two fingers...\n    if (start.length >= 2 && end.length >= 2) {\n      return this.__getDistance(end[0], end[1]) /\n        this.__getDistance(start[0], start[1]);\n    }\n    return 1;\n  }\n});\n\nionic.scroll = {\n  isScrolling: false,\n  lastTop: 0\n};\n\n})(ionic);\n\n(function(ionic) {\n  var NOOP = function() {};\n  var depreciated = function(name) {\n    void 0;\n  };\n  ionic.views.ScrollNative = ionic.views.View.inherit({\n\n    initialize: function(options) {\n      var self = this;\n      self.__container = self.el = options.el;\n      self.__content = options.el.firstElementChild;\n      self.isNative = true;\n\n      self.__scrollTop = self.el.scrollTop;\n      self.__scrollLeft = self.el.scrollLeft;\n      self.__clientHeight = self.__content.clientHeight;\n      self.__clientWidth = self.__content.clientWidth;\n      self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);\n      self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);\n\n      self.options = {\n\n        freeze: false,\n\n        getContentWidth: function() {\n          return Math.max(self.__content.scrollWidth, self.__content.offsetWidth);\n        },\n\n        getContentHeight: function() {\n          return Math.max(self.__content.scrollHeight, self.__content.offsetHeight + (self.__content.offsetTop * 2));\n        }\n\n      };\n\n      for (var key in options) {\n        self.options[key] = options[key];\n      }\n\n      /**\n       * Sets isScrolling to true, and automatically deactivates if not called again in 80ms.\n       */\n      self.onScroll = function() {\n        if (!ionic.scroll.isScrolling) {\n          ionic.scroll.isScrolling = true;\n        }\n\n        clearTimeout(self.scrollTimer);\n        self.scrollTimer = setTimeout(function() {\n          ionic.scroll.isScrolling = false;\n        }, 80);\n      };\n\n      self.freeze = NOOP;\n\n      self.__initEventHandlers();\n    },\n\n    /**  Methods not used in native scrolling */\n    __callback: function() { depreciated('__callback'); },\n    zoomTo: function() { depreciated('zoomTo'); },\n    zoomBy: function() { depreciated('zoomBy'); },\n    activatePullToRefresh: function() { depreciated('activatePullToRefresh'); },\n\n    /**\n     * Returns the scroll position and zooming values\n     *\n     * @return {Map} `left` and `top` scroll position and `zoom` level\n     */\n    resize: function(continueScrolling) {\n      var self = this;\n      if (!self.__container || !self.options) return;\n\n      // Update Scroller dimensions for changed content\n      // Add padding to bottom of content\n      self.setDimensions(\n        self.__container.clientWidth,\n        self.__container.clientHeight,\n        self.options.getContentWidth(),\n        self.options.getContentHeight(),\n        continueScrolling\n      );\n    },\n\n    /**\n     * Initialize the scrollview\n     * In native scrolling, this only means we need to gather size information\n     */\n    run: function() {\n      this.resize();\n    },\n\n    /**\n     * Returns the scroll position and zooming values\n     *\n     * @return {Map} `left` and `top` scroll position and `zoom` level\n     */\n    getValues: function() {\n      var self = this;\n      self.update();\n      return {\n        left: self.__scrollLeft,\n        top: self.__scrollTop,\n        zoom: 1\n      };\n    },\n\n    /**\n     * Updates the __scrollLeft and __scrollTop values to el's current value\n     */\n    update: function() {\n      var self = this;\n      self.__scrollLeft = self.el.scrollLeft;\n      self.__scrollTop = self.el.scrollTop;\n    },\n\n    /**\n     * Configures the dimensions of the client (outer) and content (inner) elements.\n     * Requires the available space for the outer element and the outer size of the inner element.\n     * All values which are falsy (null or zero etc.) are ignored and the old value is kept.\n     *\n     * @param clientWidth {Integer} Inner width of outer element\n     * @param clientHeight {Integer} Inner height of outer element\n     * @param contentWidth {Integer} Outer width of inner element\n     * @param contentHeight {Integer} Outer height of inner element\n     */\n    setDimensions: function(clientWidth, clientHeight, contentWidth, contentHeight) {\n      var self = this;\n\n      if (!clientWidth && !clientHeight && !contentWidth && !contentHeight) {\n        // this scrollview isn't rendered, don't bother\n        return;\n      }\n\n      // Only update values which are defined\n      if (clientWidth === +clientWidth) {\n        self.__clientWidth = clientWidth;\n      }\n\n      if (clientHeight === +clientHeight) {\n        self.__clientHeight = clientHeight;\n      }\n\n      if (contentWidth === +contentWidth) {\n        self.__contentWidth = contentWidth;\n      }\n\n      if (contentHeight === +contentHeight) {\n        self.__contentHeight = contentHeight;\n      }\n\n      // Refresh maximums\n      self.__computeScrollMax();\n    },\n\n    /**\n     * Returns the maximum scroll values\n     *\n     * @return {Map} `left` and `top` maximum scroll values\n     */\n    getScrollMax: function() {\n      return {\n        left: this.__maxScrollLeft,\n        top: this.__maxScrollTop\n      };\n    },\n\n    /**\n     * Scrolls by the given amount in px.\n     *\n     * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>\n     * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>\n     * @param animate {Boolean} Whether the scrolling should happen using an animation\n     */\n\n    scrollBy: function(left, top, animate) {\n      var self = this;\n\n      // update scroll vars before refferencing them\n      self.update();\n\n      var startLeft = self.__isAnimating ? self.__scheduledLeft : self.__scrollLeft;\n      var startTop = self.__isAnimating ? self.__scheduledTop : self.__scrollTop;\n\n      self.scrollTo(startLeft + (left || 0), startTop + (top || 0), animate);\n    },\n\n    /**\n     * Scrolls to the given position in px.\n     *\n     * @param left {Number} Horizontal scroll position, keeps current if value is <code>null</code>\n     * @param top {Number} Vertical scroll position, keeps current if value is <code>null</code>\n     * @param animate {Boolean} Whether the scrolling should happen using an animation\n     */\n    scrollTo: function(left, top, animate) {\n      var self = this;\n      if (!animate) {\n        self.el.scrollTop = top;\n        self.el.scrollLeft = left;\n        self.resize();\n        return;\n      }\n      animateScroll(top, left);\n\n      function animateScroll(Y, X) {\n        // scroll animation loop w/ easing\n        // credit https://gist.github.com/dezinezync/5487119\n        var start = Date.now(),\n          duration = 1000, //milliseconds\n          fromY = self.el.scrollTop,\n          fromX = self.el.scrollLeft;\n\n        if (fromY === Y && fromX === X) {\n          self.resize();\n          return; /* Prevent scrolling to the Y point if already there */\n        }\n\n        // decelerating to zero velocity\n        function easeOutCubic(t) {\n          return (--t) * t * t + 1;\n        }\n\n        // scroll loop\n        function animateScrollStep() {\n          var currentTime = Date.now(),\n            time = Math.min(1, ((currentTime - start) / duration)),\n          // where .5 would be 50% of time on a linear scale easedT gives a\n          // fraction based on the easing method\n            easedT = easeOutCubic(time);\n\n          if (fromY != Y) {\n            self.el.scrollTop = parseInt((easedT * (Y - fromY)) + fromY, 10);\n          }\n          if (fromX != X) {\n            self.el.scrollLeft = parseInt((easedT * (X - fromX)) + fromX, 10);\n          }\n\n          if (time < 1) {\n            ionic.requestAnimationFrame(animateScrollStep);\n\n          } else {\n            // done\n            self.resize();\n          }\n        }\n\n        // start scroll loop\n        ionic.requestAnimationFrame(animateScrollStep);\n      }\n    },\n\n\n\n    /*\n     ---------------------------------------------------------------------------\n     PRIVATE API\n     ---------------------------------------------------------------------------\n     */\n\n    /**\n     * If the scroll view isn't sized correctly on start, wait until we have at least some size\n     */\n    __waitForSize: function() {\n      var self = this;\n\n      clearTimeout(self.__sizerTimeout);\n\n      var sizer = function() {\n        self.resize(true);\n      };\n\n      sizer();\n      self.__sizerTimeout = setTimeout(sizer, 500);\n    },\n\n\n    /**\n     * Recomputes scroll minimum values based on client dimensions and content dimensions.\n     */\n    __computeScrollMax: function() {\n      var self = this;\n\n      self.__maxScrollLeft = Math.max((self.__contentWidth) - self.__clientWidth, 0);\n      self.__maxScrollTop = Math.max((self.__contentHeight) - self.__clientHeight, 0);\n\n      if (!self.__didWaitForSize && !self.__maxScrollLeft && !self.__maxScrollTop) {\n        self.__didWaitForSize = true;\n        self.__waitForSize();\n      }\n    },\n\n    __initEventHandlers: function() {\n      var self = this;\n\n      // Event Handler\n      var container = self.__container;\n\n      // should be unnecessary in native scrolling, but keep in case bugs show up\n      self.scrollChildIntoView = NOOP;\n\n      self.resetScrollView = function() {\n        //return scrollview to original height once keyboard has hidden\n        if (self.isScrolledIntoView) {\n          self.isScrolledIntoView = false;\n          container.style.height = \"\";\n          container.style.overflow = \"\";\n          self.resize();\n          ionic.scroll.isScrolling = false;\n        }\n      };\n\n      container.addEventListener('resetScrollView', self.resetScrollView);\n      container.addEventListener('scroll', self.onScroll);\n\n      //Broadcasted when keyboard is shown on some platforms.\n      //See js/utils/keyboard.js\n      container.addEventListener('scrollChildIntoView', self.scrollChildIntoView);\n      container.addEventListener('resetScrollView', self.resetScrollView);\n    },\n\n    __cleanup: function() {\n      var self = this;\n      var container = self.__container;\n\n      container.removeEventListener('resetScrollView', self.resetScrollView);\n      container.removeEventListener('scroll', self.onScroll);\n\n      container.removeEventListener('scrollChildIntoView', self.scrollChildIntoView);\n      container.removeEventListener('resetScrollView', self.resetScrollView);\n\n      ionic.tap.removeClonedInputs(container, self);\n\n      delete self.__container;\n      delete self.__content;\n      delete self.__indicatorX;\n      delete self.__indicatorY;\n      delete self.options.el;\n\n      self.resize = self.scrollTo = self.onScroll = self.resetScrollView = NOOP;\n      container = null;\n    }\n  });\n\n})(ionic);\n\n\n(function(ionic) {\n'use strict';\n\n  var ITEM_CLASS = 'item';\n  var ITEM_CONTENT_CLASS = 'item-content';\n  var ITEM_SLIDING_CLASS = 'item-sliding';\n  var ITEM_OPTIONS_CLASS = 'item-options';\n  var ITEM_PLACEHOLDER_CLASS = 'item-placeholder';\n  var ITEM_REORDERING_CLASS = 'item-reordering';\n  var ITEM_REORDER_BTN_CLASS = 'item-reorder';\n\n  var DragOp = function() {};\n  DragOp.prototype = {\n    start: function(){},\n    drag: function(){},\n    end: function(){},\n    isSameItem: function() {\n      return false;\n    }\n  };\n\n  var SlideDrag = function(opts) {\n    this.dragThresholdX = opts.dragThresholdX || 10;\n    this.el = opts.el;\n    this.item = opts.item;\n    this.canSwipe = opts.canSwipe;\n  };\n\n  SlideDrag.prototype = new DragOp();\n\n  SlideDrag.prototype.start = function(e) {\n    var content, buttons, offsetX, buttonsWidth;\n\n    if (!this.canSwipe()) {\n      return;\n    }\n\n    if (e.target.classList.contains(ITEM_CONTENT_CLASS)) {\n      content = e.target;\n    } else if (e.target.classList.contains(ITEM_CLASS)) {\n      content = e.target.querySelector('.' + ITEM_CONTENT_CLASS);\n    } else {\n      content = ionic.DomUtil.getParentWithClass(e.target, ITEM_CONTENT_CLASS);\n    }\n\n    // If we don't have a content area as one of our children (or ourselves), skip\n    if (!content) {\n      return;\n    }\n\n    // Make sure we aren't animating as we slide\n    content.classList.remove(ITEM_SLIDING_CLASS);\n\n    // Grab the starting X point for the item (for example, so we can tell whether it is open or closed to start)\n    offsetX = parseFloat(content.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]) || 0;\n\n    // Grab the buttons\n    buttons = content.parentNode.querySelector('.' + ITEM_OPTIONS_CLASS);\n    if (!buttons) {\n      return;\n    }\n    buttons.classList.remove('invisible');\n\n    buttonsWidth = buttons.offsetWidth;\n\n    this._currentDrag = {\n      buttons: buttons,\n      buttonsWidth: buttonsWidth,\n      content: content,\n      startOffsetX: offsetX\n    };\n  };\n\n  /**\n   * Check if this is the same item that was previously dragged.\n   */\n  SlideDrag.prototype.isSameItem = function(op) {\n    if (op._lastDrag && this._currentDrag) {\n      return this._currentDrag.content == op._lastDrag.content;\n    }\n    return false;\n  };\n\n  SlideDrag.prototype.clean = function(isInstant) {\n    var lastDrag = this._lastDrag;\n\n    if (!lastDrag || !lastDrag.content) return;\n\n    lastDrag.content.style[ionic.CSS.TRANSITION] = '';\n    lastDrag.content.style[ionic.CSS.TRANSFORM] = '';\n    if (isInstant) {\n      lastDrag.content.style[ionic.CSS.TRANSITION] = 'none';\n      makeInvisible();\n      ionic.requestAnimationFrame(function() {\n        lastDrag.content.style[ionic.CSS.TRANSITION] = '';\n      });\n    } else {\n      ionic.requestAnimationFrame(function() {\n        setTimeout(makeInvisible, 250);\n      });\n    }\n    function makeInvisible() {\n      lastDrag.buttons && lastDrag.buttons.classList.add('invisible');\n    }\n  };\n\n  SlideDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {\n    var buttonsWidth;\n\n    // We really aren't dragging\n    if (!this._currentDrag) {\n      return;\n    }\n\n    // Check if we should start dragging. Check if we've dragged past the threshold,\n    // or we are starting from the open state.\n    if (!this._isDragging &&\n        ((Math.abs(e.gesture.deltaX) > this.dragThresholdX) ||\n        (Math.abs(this._currentDrag.startOffsetX) > 0))) {\n      this._isDragging = true;\n    }\n\n    if (this._isDragging) {\n      buttonsWidth = this._currentDrag.buttonsWidth;\n\n      // Grab the new X point, capping it at zero\n      var newX = Math.min(0, this._currentDrag.startOffsetX + e.gesture.deltaX);\n\n      // If the new X position is past the buttons, we need to slow down the drag (rubber band style)\n      if (newX < -buttonsWidth) {\n        // Calculate the new X position, capped at the top of the buttons\n        newX = Math.min(-buttonsWidth, -buttonsWidth + (((e.gesture.deltaX + buttonsWidth) * 0.4)));\n      }\n\n      this._currentDrag.content.$$ionicOptionsOpen = newX !== 0;\n\n      this._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + newX + 'px, 0, 0)';\n      this._currentDrag.content.style[ionic.CSS.TRANSITION] = 'none';\n    }\n  });\n\n  SlideDrag.prototype.end = function(e, doneCallback) {\n    var self = this;\n\n    // There is no drag, just end immediately\n    if (!self._currentDrag) {\n      doneCallback && doneCallback();\n      return;\n    }\n\n    // If we are currently dragging, we want to snap back into place\n    // The final resting point X will be the width of the exposed buttons\n    var restingPoint = -self._currentDrag.buttonsWidth;\n\n    // Check if the drag didn't clear the buttons mid-point\n    // and we aren't moving fast enough to swipe open\n    if (e.gesture.deltaX > -(self._currentDrag.buttonsWidth / 2)) {\n\n      // If we are going left but too slow, or going right, go back to resting\n      if (e.gesture.direction == \"left\" && Math.abs(e.gesture.velocityX) < 0.3) {\n        restingPoint = 0;\n\n      } else if (e.gesture.direction == \"right\") {\n        restingPoint = 0;\n      }\n\n    }\n\n    ionic.requestAnimationFrame(function() {\n      if (restingPoint === 0) {\n        self._currentDrag.content.style[ionic.CSS.TRANSFORM] = '';\n        var buttons = self._currentDrag.buttons;\n        setTimeout(function() {\n          buttons && buttons.classList.add('invisible');\n        }, 250);\n      } else {\n        self._currentDrag.content.style[ionic.CSS.TRANSFORM] = 'translate3d(' + restingPoint + 'px,0,0)';\n      }\n      self._currentDrag.content.style[ionic.CSS.TRANSITION] = '';\n\n\n      // Kill the current drag\n      if (!self._lastDrag) {\n        self._lastDrag = {};\n      }\n      ionic.extend(self._lastDrag, self._currentDrag);\n      if (self._currentDrag) {\n        self._currentDrag.buttons = null;\n        self._currentDrag.content = null;\n      }\n      self._currentDrag = null;\n\n      // We are done, notify caller\n      doneCallback && doneCallback();\n    });\n  };\n\n  var ReorderDrag = function(opts) {\n    var self = this;\n\n    self.dragThresholdY = opts.dragThresholdY || 0;\n    self.onReorder = opts.onReorder;\n    self.listEl = opts.listEl;\n    self.el = self.item = opts.el;\n    self.scrollEl = opts.scrollEl;\n    self.scrollView = opts.scrollView;\n    // Get the True Top of the list el http://www.quirksmode.org/js/findpos.html\n    self.listElTrueTop = 0;\n    if (self.listEl.offsetParent) {\n      var obj = self.listEl;\n      do {\n        self.listElTrueTop += obj.offsetTop;\n        obj = obj.offsetParent;\n      } while (obj);\n    }\n  };\n\n  ReorderDrag.prototype = new DragOp();\n\n  ReorderDrag.prototype._moveElement = function(e) {\n    var y = e.gesture.center.pageY +\n      this.scrollView.getValues().top -\n      (this._currentDrag.elementHeight / 2) -\n      this.listElTrueTop;\n    this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(0, ' + y + 'px, 0)';\n  };\n\n  ReorderDrag.prototype.deregister = function() {\n    this.listEl = this.el = this.scrollEl = this.scrollView = null;\n  };\n\n  ReorderDrag.prototype.start = function(e) {\n\n    var startIndex = ionic.DomUtil.getChildIndex(this.el, this.el.nodeName.toLowerCase());\n    var elementHeight = this.el.scrollHeight;\n    var placeholder = this.el.cloneNode(true);\n\n    placeholder.classList.add(ITEM_PLACEHOLDER_CLASS);\n\n    this.el.parentNode.insertBefore(placeholder, this.el);\n    this.el.classList.add(ITEM_REORDERING_CLASS);\n\n    this._currentDrag = {\n      elementHeight: elementHeight,\n      startIndex: startIndex,\n      placeholder: placeholder,\n      scrollHeight: scroll,\n      list: placeholder.parentNode\n    };\n\n    this._moveElement(e);\n  };\n\n  ReorderDrag.prototype.drag = ionic.animationFrameThrottle(function(e) {\n    // We really aren't dragging\n    var self = this;\n    if (!this._currentDrag) {\n      return;\n    }\n\n    var scrollY = 0;\n    var pageY = e.gesture.center.pageY;\n    var offset = this.listElTrueTop;\n\n    //If we have a scrollView, check scroll boundaries for dragged element and scroll if necessary\n    if (this.scrollView) {\n\n      var container = this.scrollView.__container;\n      scrollY = this.scrollView.getValues().top;\n\n      var containerTop = container.offsetTop;\n      var pixelsPastTop = containerTop - pageY + this._currentDrag.elementHeight / 2;\n      var pixelsPastBottom = pageY + this._currentDrag.elementHeight / 2 - containerTop - container.offsetHeight;\n\n      if (e.gesture.deltaY < 0 && pixelsPastTop > 0 && scrollY > 0) {\n        this.scrollView.scrollBy(null, -pixelsPastTop);\n        //Trigger another drag so the scrolling keeps going\n        ionic.requestAnimationFrame(function() {\n          self.drag(e);\n        });\n      }\n      if (e.gesture.deltaY > 0 && pixelsPastBottom > 0) {\n        if (scrollY < this.scrollView.getScrollMax().top) {\n          this.scrollView.scrollBy(null, pixelsPastBottom);\n          //Trigger another drag so the scrolling keeps going\n          ionic.requestAnimationFrame(function() {\n            self.drag(e);\n          });\n        }\n      }\n    }\n\n    // Check if we should start dragging. Check if we've dragged past the threshold,\n    // or we are starting from the open state.\n    if (!this._isDragging && Math.abs(e.gesture.deltaY) > this.dragThresholdY) {\n      this._isDragging = true;\n    }\n\n    if (this._isDragging) {\n      this._moveElement(e);\n\n      this._currentDrag.currentY = scrollY + pageY - offset;\n\n      // this._reorderItems();\n    }\n  });\n\n  // When an item is dragged, we need to reorder any items for sorting purposes\n  ReorderDrag.prototype._getReorderIndex = function() {\n    var self = this;\n\n    var siblings = Array.prototype.slice.call(self._currentDrag.placeholder.parentNode.children)\n      .filter(function(el) {\n        return el.nodeName === self.el.nodeName && el !== self.el;\n      });\n\n    var dragOffsetTop = self._currentDrag.currentY;\n    var el;\n    for (var i = 0, len = siblings.length; i < len; i++) {\n      el = siblings[i];\n      if (i === len - 1) {\n        if (dragOffsetTop > el.offsetTop) {\n          return i;\n        }\n      } else if (i === 0) {\n        if (dragOffsetTop < el.offsetTop + el.offsetHeight) {\n          return i;\n        }\n      } else if (dragOffsetTop > el.offsetTop - el.offsetHeight / 2 &&\n                 dragOffsetTop < el.offsetTop + el.offsetHeight) {\n        return i;\n      }\n    }\n    return self._currentDrag.startIndex;\n  };\n\n  ReorderDrag.prototype.end = function(e, doneCallback) {\n    if (!this._currentDrag) {\n      doneCallback && doneCallback();\n      return;\n    }\n\n    var placeholder = this._currentDrag.placeholder;\n    var finalIndex = this._getReorderIndex();\n\n    // Reposition the element\n    this.el.classList.remove(ITEM_REORDERING_CLASS);\n    this.el.style[ionic.CSS.TRANSFORM] = '';\n\n    placeholder.parentNode.insertBefore(this.el, placeholder);\n    placeholder.parentNode.removeChild(placeholder);\n\n    this.onReorder && this.onReorder(this.el, this._currentDrag.startIndex, finalIndex);\n\n    this._currentDrag = {\n      placeholder: null,\n      content: null\n    };\n    this._currentDrag = null;\n    doneCallback && doneCallback();\n  };\n\n\n\n  /**\n   * The ListView handles a list of items. It will process drag animations, edit mode,\n   * and other operations that are common on mobile lists or table views.\n   */\n  ionic.views.ListView = ionic.views.View.inherit({\n    initialize: function(opts) {\n      var self = this;\n\n      opts = ionic.extend({\n        onReorder: function() {},\n        virtualRemoveThreshold: -200,\n        virtualAddThreshold: 200,\n        canSwipe: function() {\n          return true;\n        }\n      }, opts);\n\n      ionic.extend(self, opts);\n\n      if (!self.itemHeight && self.listEl) {\n        self.itemHeight = self.listEl.children[0] && parseInt(self.listEl.children[0].style.height, 10);\n      }\n\n      self.onRefresh = opts.onRefresh || function() {};\n      self.onRefreshOpening = opts.onRefreshOpening || function() {};\n      self.onRefreshHolding = opts.onRefreshHolding || function() {};\n\n      var gestureOpts = {};\n      // don't prevent native scrolling\n      if (ionic.DomUtil.getParentOrSelfWithClass(self.el, 'overflow-scroll')) {\n        gestureOpts.prevent_default_directions = ['left', 'right'];\n      }\n\n      window.ionic.onGesture('release', function(e) {\n        self._handleEndDrag(e);\n      }, self.el, gestureOpts);\n\n      window.ionic.onGesture('drag', function(e) {\n        self._handleDrag(e);\n      }, self.el, gestureOpts);\n      // Start the drag states\n      self._initDrag();\n    },\n\n    /**\n     * Be sure to cleanup references.\n     */\n    deregister: function() {\n      this.el = this.listEl = this.scrollEl = this.scrollView = null;\n\n      // ensure no scrolls have been left frozen\n      if (this.isScrollFreeze) {\n        self.scrollView.freeze(false);\n      }\n    },\n\n    /**\n     * Called to tell the list to stop refreshing. This is useful\n     * if you are refreshing the list and are done with refreshing.\n     */\n    stopRefreshing: function() {\n      var refresher = this.el.querySelector('.list-refresher');\n      refresher.style.height = '0';\n    },\n\n    /**\n     * If we scrolled and have virtual mode enabled, compute the window\n     * of active elements in order to figure out the viewport to render.\n     */\n    didScroll: function(e) {\n      var self = this;\n\n      if (self.isVirtual) {\n        var itemHeight = self.itemHeight;\n\n        // Grab the total height of the list\n        var scrollHeight = e.target.scrollHeight;\n\n        // Get the viewport height\n        var viewportHeight = self.el.parentNode.offsetHeight;\n\n        // High water is the pixel position of the first element to include (everything before\n        // that will be removed)\n        var highWater = Math.max(0, e.scrollTop + self.virtualRemoveThreshold);\n\n        // Low water is the pixel position of the last element to include (everything after\n        // that will be removed)\n        var lowWater = Math.min(scrollHeight, Math.abs(e.scrollTop) + viewportHeight + self.virtualAddThreshold);\n\n        // Get the first and last elements in the list based on how many can fit\n        // between the pixel range of lowWater and highWater\n        var first = parseInt(Math.abs(highWater / itemHeight), 10);\n        var last = parseInt(Math.abs(lowWater / itemHeight), 10);\n\n        // Get the items we need to remove\n        self._virtualItemsToRemove = Array.prototype.slice.call(self.listEl.children, 0, first);\n\n        self.renderViewport && self.renderViewport(highWater, lowWater, first, last);\n      }\n    },\n\n    didStopScrolling: function() {\n      if (this.isVirtual) {\n        for (var i = 0; i < this._virtualItemsToRemove.length; i++) {\n          //el.parentNode.removeChild(el);\n          this.didHideItem && this.didHideItem(i);\n        }\n        // Once scrolling stops, check if we need to remove old items\n\n      }\n    },\n\n    /**\n     * Clear any active drag effects on the list.\n     */\n    clearDragEffects: function(isInstant) {\n      if (this._lastDragOp) {\n        this._lastDragOp.clean && this._lastDragOp.clean(isInstant);\n        this._lastDragOp.deregister && this._lastDragOp.deregister();\n        this._lastDragOp = null;\n      }\n    },\n\n    _initDrag: function() {\n      // Store the last one\n      if (this._lastDragOp) {\n        this._lastDragOp.deregister && this._lastDragOp.deregister();\n      }\n      this._lastDragOp = this._dragOp;\n\n      this._dragOp = null;\n    },\n\n    // Return the list item from the given target\n    _getItem: function(target) {\n      while (target) {\n        if (target.classList && target.classList.contains(ITEM_CLASS)) {\n          return target;\n        }\n        target = target.parentNode;\n      }\n      return null;\n    },\n\n\n    _startDrag: function(e) {\n      var self = this;\n\n      self._isDragging = false;\n\n      var lastDragOp = self._lastDragOp;\n      var item;\n\n      // If we have an open SlideDrag and we're scrolling the list. Clear it.\n      if (self._didDragUpOrDown && lastDragOp instanceof SlideDrag) {\n          lastDragOp.clean && lastDragOp.clean();\n      }\n\n      // Check if this is a reorder drag\n      if (ionic.DomUtil.getParentOrSelfWithClass(e.target, ITEM_REORDER_BTN_CLASS) && (e.gesture.direction == 'up' || e.gesture.direction == 'down')) {\n        item = self._getItem(e.target);\n\n        if (item) {\n          self._dragOp = new ReorderDrag({\n            listEl: self.el,\n            el: item,\n            scrollEl: self.scrollEl,\n            scrollView: self.scrollView,\n            onReorder: function(el, start, end) {\n              self.onReorder && self.onReorder(el, start, end);\n            }\n          });\n          self._dragOp.start(e);\n          e.preventDefault();\n        }\n      }\n\n      // Or check if this is a swipe to the side drag\n      else if (!self._didDragUpOrDown && (e.gesture.direction == 'left' || e.gesture.direction == 'right') && Math.abs(e.gesture.deltaX) > 5) {\n\n        // Make sure this is an item with buttons\n        item = self._getItem(e.target);\n        if (item && item.querySelector('.item-options')) {\n          self._dragOp = new SlideDrag({\n            el: self.el,\n            item: item,\n            canSwipe: self.canSwipe\n          });\n          self._dragOp.start(e);\n          e.preventDefault();\n          self.isScrollFreeze = self.scrollView.freeze(true);\n        }\n      }\n\n      // If we had a last drag operation and this is a new one on a different item, clean that last one\n      if (lastDragOp && self._dragOp && !self._dragOp.isSameItem(lastDragOp) && e.defaultPrevented) {\n        lastDragOp.clean && lastDragOp.clean();\n      }\n    },\n\n\n    _handleEndDrag: function(e) {\n      var self = this;\n\n      if (self.scrollView) {\n        self.isScrollFreeze = self.scrollView.freeze(false);\n      }\n\n      self._didDragUpOrDown = false;\n\n      if (!self._dragOp) {\n        return;\n      }\n\n      self._dragOp.end(e, function() {\n        self._initDrag();\n      });\n    },\n\n    /**\n     * Process the drag event to move the item to the left or right.\n     */\n    _handleDrag: function(e) {\n      var self = this;\n\n      if (Math.abs(e.gesture.deltaY) > 5) {\n        self._didDragUpOrDown = true;\n      }\n\n      // If we get a drag event, make sure we aren't in another drag, then check if we should\n      // start one\n      if (!self.isDragging && !self._dragOp) {\n        self._startDrag(e);\n      }\n\n      // No drag still, pass it up\n      if (!self._dragOp) {\n        return;\n      }\n\n      e.gesture.srcEvent.preventDefault();\n      self._dragOp.drag(e);\n    }\n\n  });\n\n})(ionic);\n\n(function(ionic) {\n'use strict';\n\n  ionic.views.Modal = ionic.views.View.inherit({\n    initialize: function(opts) {\n      opts = ionic.extend({\n        focusFirstInput: false,\n        unfocusOnHide: true,\n        focusFirstDelay: 600,\n        backdropClickToClose: true,\n        hardwareBackButtonClose: true,\n      }, opts);\n\n      ionic.extend(this, opts);\n\n      this.el = opts.el;\n    },\n    show: function() {\n      var self = this;\n\n      if(self.focusFirstInput) {\n        // Let any animations run first\n        window.setTimeout(function() {\n          var input = self.el.querySelector('input, textarea');\n          input && input.focus && input.focus();\n        }, self.focusFirstDelay);\n      }\n    },\n    hide: function() {\n      // Unfocus all elements\n      if(this.unfocusOnHide) {\n        var inputs = this.el.querySelectorAll('input, textarea');\n        // Let any animations run first\n        window.setTimeout(function() {\n          for(var i = 0; i < inputs.length; i++) {\n            inputs[i].blur && inputs[i].blur();\n          }\n        });\n      }\n    }\n  });\n\n})(ionic);\n\n(function(ionic) {\n'use strict';\n\n  /**\n   * The side menu view handles one of the side menu's in a Side Menu Controller\n   * configuration.\n   * It takes a DOM reference to that side menu element.\n   */\n  ionic.views.SideMenu = ionic.views.View.inherit({\n    initialize: function(opts) {\n      this.el = opts.el;\n      this.isEnabled = (typeof opts.isEnabled === 'undefined') ? true : opts.isEnabled;\n      this.setWidth(opts.width);\n    },\n    getFullWidth: function() {\n      return this.width;\n    },\n    setWidth: function(width) {\n      this.width = width;\n      this.el.style.width = width + 'px';\n    },\n    setIsEnabled: function(isEnabled) {\n      this.isEnabled = isEnabled;\n    },\n    bringUp: function() {\n      if(this.el.style.zIndex !== '0') {\n        this.el.style.zIndex = '0';\n      }\n    },\n    pushDown: function() {\n      if(this.el.style.zIndex !== '-1') {\n        this.el.style.zIndex = '-1';\n      }\n    }\n  });\n\n  ionic.views.SideMenuContent = ionic.views.View.inherit({\n    initialize: function(opts) {\n      ionic.extend(this, {\n        animationClass: 'menu-animated',\n        onDrag: function() {},\n        onEndDrag: function() {}\n      }, opts);\n\n      ionic.onGesture('drag', ionic.proxy(this._onDrag, this), this.el);\n      ionic.onGesture('release', ionic.proxy(this._onEndDrag, this), this.el);\n    },\n    _onDrag: function(e) {\n      this.onDrag && this.onDrag(e);\n    },\n    _onEndDrag: function(e) {\n      this.onEndDrag && this.onEndDrag(e);\n    },\n    disableAnimation: function() {\n      this.el.classList.remove(this.animationClass);\n    },\n    enableAnimation: function() {\n      this.el.classList.add(this.animationClass);\n    },\n    getTranslateX: function() {\n      return parseFloat(this.el.style[ionic.CSS.TRANSFORM].replace('translate3d(', '').split(',')[0]);\n    },\n    setTranslateX: ionic.animationFrameThrottle(function(x) {\n      this.el.style[ionic.CSS.TRANSFORM] = 'translate3d(' + x + 'px, 0, 0)';\n    })\n  });\n\n})(ionic);\n\n/*\n * Adapted from Swipe.js 2.0\n *\n * Brad Birdsall\n * Copyright 2013, MIT License\n *\n*/\n\n(function(ionic) {\n'use strict';\n\nionic.views.Slider = ionic.views.View.inherit({\n  initialize: function (options) {\n    var slider = this;\n\n    // utilities\n    var noop = function() {}; // simple no operation function\n    var offloadFn = function(fn) { setTimeout(fn || noop, 0); }; // offload a functions execution\n\n    // check browser capabilities\n    var browser = {\n      addEventListener: !!window.addEventListener,\n      touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,\n      transitions: (function(temp) {\n        var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];\n        for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;\n        return false;\n      })(document.createElement('swipe'))\n    };\n\n\n    var container = options.el;\n\n    // quit if no root element\n    if (!container) return;\n    var element = container.children[0];\n    var slides, slidePos, width, length;\n    options = options || {};\n    var index = parseInt(options.startSlide, 10) || 0;\n    var speed = options.speed || 300;\n    options.continuous = options.continuous !== undefined ? options.continuous : true;\n\n    function setup() {\n\n      // do not setup if the container has no width\n      if (!container.offsetWidth) {\n        return;\n      }\n\n      // cache slides\n      slides = element.children;\n      length = slides.length;\n\n      // set continuous to false if only one slide\n      if (slides.length < 2) options.continuous = false;\n\n      //special case if two slides\n      if (browser.transitions && options.continuous && slides.length < 3) {\n        element.appendChild(slides[0].cloneNode(true));\n        element.appendChild(element.children[1].cloneNode(true));\n        slides = element.children;\n      }\n\n      // create an array to store current positions of each slide\n      slidePos = new Array(slides.length);\n\n      // determine width of each slide\n      width = container.offsetWidth || container.getBoundingClientRect().width;\n\n      element.style.width = (slides.length * width) + 'px';\n\n      // stack elements\n      var pos = slides.length;\n      while(pos--) {\n\n        var slide = slides[pos];\n\n        slide.style.width = width + 'px';\n        slide.setAttribute('data-index', pos);\n\n        if (browser.transitions) {\n          slide.style.left = (pos * -width) + 'px';\n          move(pos, index > pos ? -width : (index < pos ? width : 0), 0);\n        }\n\n      }\n\n      // reposition elements before and after index\n      if (options.continuous && browser.transitions) {\n        move(circle(index - 1), -width, 0);\n        move(circle(index + 1), width, 0);\n      }\n\n      if (!browser.transitions) element.style.left = (index * -width) + 'px';\n\n      container.style.visibility = 'visible';\n\n      options.slidesChanged && options.slidesChanged();\n    }\n\n    function prev(slideSpeed) {\n\n      if (options.continuous) slide(index - 1, slideSpeed);\n      else if (index) slide(index - 1, slideSpeed);\n\n    }\n\n    function next(slideSpeed) {\n\n      if (options.continuous) slide(index + 1, slideSpeed);\n      else if (index < slides.length - 1) slide(index + 1, slideSpeed);\n\n    }\n\n    function circle(index) {\n\n      // a simple positive modulo using slides.length\n      return (slides.length + (index % slides.length)) % slides.length;\n\n    }\n\n    function slide(to, slideSpeed) {\n\n      // do nothing if already on requested slide\n      if (index == to) return;\n\n      if (browser.transitions) {\n\n        var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward\n\n        // get the actual position of the slide\n        if (options.continuous) {\n          var naturalDirection = direction;\n          direction = -slidePos[circle(to)] / width;\n\n          // if going forward but to < index, use to = slides.length + to\n          // if going backward but to > index, use to = -slides.length + to\n          if (direction !== naturalDirection) to = -direction * slides.length + to;\n\n        }\n\n        var diff = Math.abs(index - to) - 1;\n\n        // move all the slides between index and to in the right direction\n        while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);\n\n        to = circle(to);\n\n        move(index, width * direction, slideSpeed || speed);\n        move(to, 0, slideSpeed || speed);\n\n        if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place\n\n      } else {\n\n        to = circle(to);\n        animate(index * -width, to * -width, slideSpeed || speed);\n        //no fallback for a circular continuous if the browser does not accept transitions\n      }\n\n      index = to;\n      offloadFn(options.callback && options.callback(index, slides[index]));\n    }\n\n    function move(index, dist, speed) {\n\n      translate(index, dist, speed);\n      slidePos[index] = dist;\n\n    }\n\n    function translate(index, dist, speed) {\n\n      var slide = slides[index];\n      var style = slide && slide.style;\n\n      if (!style) return;\n\n      style.webkitTransitionDuration =\n      style.MozTransitionDuration =\n      style.msTransitionDuration =\n      style.OTransitionDuration =\n      style.transitionDuration = speed + 'ms';\n\n      style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';\n      style.msTransform =\n      style.MozTransform =\n      style.OTransform = 'translateX(' + dist + 'px)';\n\n    }\n\n    function animate(from, to, speed) {\n\n      // if not an animation, just reposition\n      if (!speed) {\n\n        element.style.left = to + 'px';\n        return;\n\n      }\n\n      var start = +new Date();\n\n      var timer = setInterval(function() {\n\n        var timeElap = +new Date() - start;\n\n        if (timeElap > speed) {\n\n          element.style.left = to + 'px';\n\n          if (delay) begin();\n\n          options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);\n\n          clearInterval(timer);\n          return;\n\n        }\n\n        element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';\n\n      }, 4);\n\n    }\n\n    // setup auto slideshow\n    var delay = options.auto || 0;\n    var interval;\n\n    function begin() {\n\n      interval = setTimeout(next, delay);\n\n    }\n\n    function stop() {\n\n      delay = options.auto || 0;\n      clearTimeout(interval);\n\n    }\n\n\n    // setup initial vars\n    var start = {};\n    var delta = {};\n    var isScrolling;\n\n    // setup event capturing\n    var events = {\n\n      handleEvent: function(event) {\n        if(event.type == 'mousedown' || event.type == 'mouseup' || event.type == 'mousemove') {\n          event.touches = [{\n            pageX: event.pageX,\n            pageY: event.pageY\n          }];\n        }\n\n        switch (event.type) {\n          case 'mousedown': this.start(event); break;\n          case 'touchstart': this.start(event); break;\n          case 'touchmove': this.touchmove(event); break;\n          case 'mousemove': this.touchmove(event); break;\n          case 'touchend': offloadFn(this.end(event)); break;\n          case 'mouseup': offloadFn(this.end(event)); break;\n          case 'webkitTransitionEnd':\n          case 'msTransitionEnd':\n          case 'oTransitionEnd':\n          case 'otransitionend':\n          case 'transitionend': offloadFn(this.transitionEnd(event)); break;\n          case 'resize': offloadFn(setup); break;\n        }\n\n        if (options.stopPropagation) event.stopPropagation();\n\n      },\n      start: function(event) {\n\n        var touches = event.touches[0];\n\n        // measure start values\n        start = {\n\n          // get initial touch coords\n          x: touches.pageX,\n          y: touches.pageY,\n\n          // store time to determine touch duration\n          time: +new Date()\n\n        };\n\n        // used for testing first move event\n        isScrolling = undefined;\n\n        // reset delta and end measurements\n        delta = {};\n\n        // attach touchmove and touchend listeners\n        if(browser.touch) {\n          element.addEventListener('touchmove', this, false);\n          element.addEventListener('touchend', this, false);\n        } else {\n          element.addEventListener('mousemove', this, false);\n          element.addEventListener('mouseup', this, false);\n          document.addEventListener('mouseup', this, false);\n        }\n      },\n      touchmove: function(event) {\n\n        // ensure swiping with one touch and not pinching\n        // ensure sliding is enabled\n        if (event.touches.length > 1 ||\n            event.scale && event.scale !== 1 ||\n            slider.slideIsDisabled) {\n          return;\n        }\n\n        if (options.disableScroll) event.preventDefault();\n\n        var touches = event.touches[0];\n\n        // measure change in x and y\n        delta = {\n          x: touches.pageX - start.x,\n          y: touches.pageY - start.y\n        };\n\n        // determine if scrolling test has run - one time test\n        if ( typeof isScrolling == 'undefined') {\n          isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );\n        }\n\n        // if user is not trying to scroll vertically\n        if (!isScrolling) {\n\n          // prevent native scrolling\n          event.preventDefault();\n\n          // stop slideshow\n          stop();\n\n          // increase resistance if first or last slide\n          if (options.continuous) { // we don't add resistance at the end\n\n            translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);\n            translate(index, delta.x + slidePos[index], 0);\n            translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);\n\n          } else {\n\n            delta.x =\n              delta.x /\n                ( (!index && delta.x > 0 ||         // if first slide and sliding left\n                  index == slides.length - 1 &&     // or if last slide and sliding right\n                  delta.x < 0                       // and if sliding at all\n                ) ?\n                ( Math.abs(delta.x) / width + 1 )      // determine resistance level\n                : 1 );                                 // no resistance if false\n\n            // translate 1:1\n            translate(index - 1, delta.x + slidePos[index - 1], 0);\n            translate(index, delta.x + slidePos[index], 0);\n            translate(index + 1, delta.x + slidePos[index + 1], 0);\n          }\n\n          options.onDrag && options.onDrag();\n        }\n\n      },\n      end: function() {\n\n        // measure duration\n        var duration = +new Date() - start.time;\n\n        // determine if slide attempt triggers next/prev slide\n        var isValidSlide =\n              Number(duration) < 250 &&         // if slide duration is less than 250ms\n              Math.abs(delta.x) > 20 ||         // and if slide amt is greater than 20px\n              Math.abs(delta.x) > width / 2;      // or if slide amt is greater than half the width\n\n        // determine if slide attempt is past start and end\n        var isPastBounds = (!index && delta.x > 0) ||      // if first slide and slide amt is greater than 0\n              (index == slides.length - 1 && delta.x < 0); // or if last slide and slide amt is less than 0\n\n        if (options.continuous) isPastBounds = false;\n\n        // determine direction of swipe (true:right, false:left)\n        var direction = delta.x < 0;\n\n        // if not scrolling vertically\n        if (!isScrolling) {\n\n          if (isValidSlide && !isPastBounds) {\n\n            if (direction) {\n\n              if (options.continuous) { // we need to get the next in this direction in place\n\n                move(circle(index - 1), -width, 0);\n                move(circle(index + 2), width, 0);\n\n              } else {\n                move(index - 1, -width, 0);\n              }\n\n              move(index, slidePos[index] - width, speed);\n              move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);\n              index = circle(index + 1);\n\n            } else {\n              if (options.continuous) { // we need to get the next in this direction in place\n\n                move(circle(index + 1), width, 0);\n                move(circle(index - 2), -width, 0);\n\n              } else {\n                move(index + 1, width, 0);\n              }\n\n              move(index, slidePos[index] + width, speed);\n              move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);\n              index = circle(index - 1);\n\n            }\n\n            options.callback && options.callback(index, slides[index]);\n\n          } else {\n\n            if (options.continuous) {\n\n              move(circle(index - 1), -width, speed);\n              move(index, 0, speed);\n              move(circle(index + 1), width, speed);\n\n            } else {\n\n              move(index - 1, -width, speed);\n              move(index, 0, speed);\n              move(index + 1, width, speed);\n            }\n\n          }\n\n        }\n\n        // kill touchmove and touchend event listeners until touchstart called again\n        if(browser.touch) {\n          element.removeEventListener('touchmove', events, false);\n          element.removeEventListener('touchend', events, false);\n        } else {\n          element.removeEventListener('mousemove', events, false);\n          element.removeEventListener('mouseup', events, false);\n          document.removeEventListener('mouseup', events, false);\n        }\n\n        options.onDragEnd && options.onDragEnd();\n      },\n      transitionEnd: function(event) {\n\n        if (parseInt(event.target.getAttribute('data-index'), 10) == index) {\n\n          if (delay) begin();\n\n          options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);\n\n        }\n\n      }\n\n    };\n\n    // Public API\n    this.update = function() {\n      setTimeout(setup);\n    };\n    this.setup = function() {\n      setup();\n    };\n\n    this.loop = function(value) {\n      if (arguments.length) options.continuous = !!value;\n      return options.continuous;\n    };\n\n    this.enableSlide = function(shouldEnable) {\n      if (arguments.length) {\n        this.slideIsDisabled = !shouldEnable;\n      }\n      return !this.slideIsDisabled;\n    };\n\n    this.slide = this.select = function(to, speed) {\n      // cancel slideshow\n      stop();\n\n      slide(to, speed);\n    };\n\n    this.prev = this.previous = function() {\n      // cancel slideshow\n      stop();\n\n      prev();\n    };\n\n    this.next = function() {\n      // cancel slideshow\n      stop();\n\n      next();\n    };\n\n    this.stop = function() {\n      // cancel slideshow\n      stop();\n    };\n\n    this.start = function() {\n      begin();\n    };\n\n    this.autoPlay = function(newDelay) {\n      if (!delay || delay < 0) {\n        stop();\n      } else {\n        delay = newDelay;\n        begin();\n      }\n    };\n\n    this.currentIndex = this.selected = function() {\n      // return current index position\n      return index;\n    };\n\n    this.slidesCount = this.count = function() {\n      // return total number of slides\n      return length;\n    };\n\n    this.kill = function() {\n      // cancel slideshow\n      stop();\n\n      // reset element\n      element.style.width = '';\n      element.style.left = '';\n\n      // reset slides so no refs are held on to\n      slides && (slides = []);\n\n      // removed event listeners\n      if (browser.addEventListener) {\n\n        // remove current event listeners\n        element.removeEventListener('touchstart', events, false);\n        element.removeEventListener('webkitTransitionEnd', events, false);\n        element.removeEventListener('msTransitionEnd', events, false);\n        element.removeEventListener('oTransitionEnd', events, false);\n        element.removeEventListener('otransitionend', events, false);\n        element.removeEventListener('transitionend', events, false);\n        window.removeEventListener('resize', events, false);\n\n      }\n      else {\n\n        window.onresize = null;\n\n      }\n    };\n\n    this.load = function() {\n      // trigger setup\n      setup();\n\n      // start auto slideshow if applicable\n      if (delay) begin();\n\n\n      // add event listeners\n      if (browser.addEventListener) {\n\n        // set touchstart event on element\n        if (browser.touch) {\n          element.addEventListener('touchstart', events, false);\n        } else {\n          element.addEventListener('mousedown', events, false);\n        }\n\n        if (browser.transitions) {\n          element.addEventListener('webkitTransitionEnd', events, false);\n          element.addEventListener('msTransitionEnd', events, false);\n          element.addEventListener('oTransitionEnd', events, false);\n          element.addEventListener('otransitionend', events, false);\n          element.addEventListener('transitionend', events, false);\n        }\n\n        // set resize event on window\n        window.addEventListener('resize', events, false);\n\n      } else {\n\n        window.onresize = function () { setup(); }; // to play nice with old IE\n\n      }\n    };\n\n  }\n});\n\n})(ionic);\n\n(function(ionic) {\n'use strict';\n\n  ionic.views.Toggle = ionic.views.View.inherit({\n    initialize: function(opts) {\n      var self = this;\n\n      this.el = opts.el;\n      this.checkbox = opts.checkbox;\n      this.track = opts.track;\n      this.handle = opts.handle;\n      this.openPercent = -1;\n      this.onChange = opts.onChange || function() {};\n\n      this.triggerThreshold = opts.triggerThreshold || 20;\n\n      this.dragStartHandler = function(e) {\n        self.dragStart(e);\n      };\n      this.dragHandler = function(e) {\n        self.drag(e);\n      };\n      this.holdHandler = function(e) {\n        self.hold(e);\n      };\n      this.releaseHandler = function(e) {\n        self.release(e);\n      };\n\n      this.dragStartGesture = ionic.onGesture('dragstart', this.dragStartHandler, this.el);\n      this.dragGesture = ionic.onGesture('drag', this.dragHandler, this.el);\n      this.dragHoldGesture = ionic.onGesture('hold', this.holdHandler, this.el);\n      this.dragReleaseGesture = ionic.onGesture('release', this.releaseHandler, this.el);\n    },\n\n    destroy: function() {\n      ionic.offGesture(this.dragStartGesture, 'dragstart', this.dragStartGesture);\n      ionic.offGesture(this.dragGesture, 'drag', this.dragGesture);\n      ionic.offGesture(this.dragHoldGesture, 'hold', this.holdHandler);\n      ionic.offGesture(this.dragReleaseGesture, 'release', this.releaseHandler);\n    },\n\n    tap: function() {\n      if(this.el.getAttribute('disabled') !== 'disabled') {\n        this.val( !this.checkbox.checked );\n      }\n    },\n\n    dragStart: function(e) {\n      if(this.checkbox.disabled) return;\n\n      this._dragInfo = {\n        width: this.el.offsetWidth,\n        left: this.el.offsetLeft,\n        right: this.el.offsetLeft + this.el.offsetWidth,\n        triggerX: this.el.offsetWidth / 2,\n        initialState: this.checkbox.checked\n      };\n\n      // Stop any parent dragging\n      e.gesture.srcEvent.preventDefault();\n\n      // Trigger hold styles\n      this.hold(e);\n    },\n\n    drag: function(e) {\n      var self = this;\n      if(!this._dragInfo) { return; }\n\n      // Stop any parent dragging\n      e.gesture.srcEvent.preventDefault();\n\n      ionic.requestAnimationFrame(function () {\n        if (!self._dragInfo) { return; }\n\n        var px = e.gesture.touches[0].pageX - self._dragInfo.left;\n        var mx = self._dragInfo.width - self.triggerThreshold;\n\n        // The initial state was on, so \"tend towards\" on\n        if(self._dragInfo.initialState) {\n          if(px < self.triggerThreshold) {\n            self.setOpenPercent(0);\n          } else if(px > self._dragInfo.triggerX) {\n            self.setOpenPercent(100);\n          }\n        } else {\n          // The initial state was off, so \"tend towards\" off\n          if(px < self._dragInfo.triggerX) {\n            self.setOpenPercent(0);\n          } else if(px > mx) {\n            self.setOpenPercent(100);\n          }\n        }\n      });\n    },\n\n    endDrag: function() {\n      this._dragInfo = null;\n    },\n\n    hold: function() {\n      this.el.classList.add('dragging');\n    },\n    release: function(e) {\n      this.el.classList.remove('dragging');\n      this.endDrag(e);\n    },\n\n\n    setOpenPercent: function(openPercent) {\n      // only make a change if the new open percent has changed\n      if(this.openPercent < 0 || (openPercent < (this.openPercent - 3) || openPercent > (this.openPercent + 3) ) ) {\n        this.openPercent = openPercent;\n\n        if(openPercent === 0) {\n          this.val(false);\n        } else if(openPercent === 100) {\n          this.val(true);\n        } else {\n          var openPixel = Math.round( (openPercent / 100) * this.track.offsetWidth - (this.handle.offsetWidth) );\n          openPixel = (openPixel < 1 ? 0 : openPixel);\n          this.handle.style[ionic.CSS.TRANSFORM] = 'translate3d(' + openPixel + 'px,0,0)';\n        }\n      }\n    },\n\n    val: function(value) {\n      if(value === true || value === false) {\n        if(this.handle.style[ionic.CSS.TRANSFORM] !== \"\") {\n          this.handle.style[ionic.CSS.TRANSFORM] = \"\";\n        }\n        this.checkbox.checked = value;\n        this.openPercent = (value ? 100 : 0);\n        this.onChange && this.onChange();\n      }\n      return this.checkbox.checked;\n    }\n\n  });\n\n})(ionic);\n\n})();"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_action-sheet.scss",
    "content": "/**\n * Action Sheets\n * --------------------------------------------------\n */\n\n.action-sheet-backdrop {\n  @include transition(background-color 150ms ease-in-out);\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: $z-index-action-sheet;\n  width: 100%;\n  height: 100%;\n  background-color: rgba(0,0,0,0);\n\n  &.active {\n    background-color: rgba(0,0,0,0.4);\n  }\n}\n\n.action-sheet-wrapper {\n  @include translate3d(0, 100%, 0);\n  @include transition(all cubic-bezier(.36, .66, .04, 1) 500ms);\n  position: absolute;\n  bottom: 0;\n  left: 0;\n  right: 0;\n  width: 100%;\n  max-width: 500px;\n  margin: auto;\n}\n\n.action-sheet-up {\n  @include translate3d(0, 0, 0);\n}\n\n.action-sheet {\n  margin-left: $sheet-margin;\n  margin-right: $sheet-margin;\n  width: auto;\n  z-index: $z-index-action-sheet;\n  overflow: hidden;\n\n  .button {\n    display: block;\n    padding: 1px;\n    width: 100%;\n    border-radius: 0;\n    border-color: $sheet-options-border-color;\n    background-color: transparent;\n\n    color: $sheet-options-text-color;\n    font-size: 21px;\n\n    &:hover {\n      color: $sheet-options-text-color;\n    }\n    &.destructive {\n      color: #ff3b30;\n      &:hover {\n        color: #ff3b30;\n      }\n    }\n  }\n\n  .button.active, .button.activated {\n    box-shadow: none;\n    border-color: $sheet-options-border-color;\n    color: $sheet-options-text-color;\n    background: $sheet-options-bg-active-color;\n  }\n}\n\n.action-sheet-has-icons .icon {\n  position: absolute;\n  left: 16px;\n}\n\n.action-sheet-title {\n  padding: $sheet-margin * 2;\n  color: #8f8f8f;\n  text-align: center;\n  font-size: 13px;\n}\n\n.action-sheet-group {\n  margin-bottom: $sheet-margin;\n  border-radius: $sheet-border-radius;\n  background-color: #fff;\n  overflow: hidden;\n\n  .button {\n    border-width: 1px 0px 0px 0px;\n  }\n  .button:first-child:last-child {\n    border-width: 0;\n  }\n}\n\n.action-sheet-options {\n  background: $sheet-options-bg-color;\n}\n\n.action-sheet-cancel {\n  .button {\n    font-weight: 500;\n  }\n}\n\n.action-sheet-open {\n  pointer-events: none;\n\n  &.modal-open .modal {\n    pointer-events: none;\n  }\n\n  .action-sheet-backdrop {\n    pointer-events: auto;\n  }\n}\n\n\n.platform-android {\n\n  .action-sheet-backdrop.active {\n    background-color: rgba(0,0,0,0.2);\n  }\n\n  .action-sheet {\n    margin: 0;\n\n    .action-sheet-title,\n    .button {\n      text-align: left;\n      border-color: transparent;\n      font-size: 16px;\n      color: inherit;\n    }\n\n    .action-sheet-title {\n      font-size: 14px;\n      padding: 16px;\n      color: #666;\n    }\n\n    .button.active,\n    .button.activated {\n      background: #e8e8e8;\n    }\n  }\n\n  .action-sheet-group {\n    margin: 0;\n    border-radius: 0;\n    background-color: #fafafa;\n  }\n\n  .action-sheet-cancel {\n    display: none;\n  }\n\n  .action-sheet-has-icons {\n\n    .button {\n      padding-left: 56px;\n    }\n\n  }\n\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_animations.scss",
    "content": "\n// Slide up from the bottom, used for modals\n// -------------------------------\n\n.slide-in-up {\n  @include translate3d(0, 100%, 0);\n}\n.slide-in-up.ng-enter,\n.slide-in-up > .ng-enter {\n  @include transition(all cubic-bezier(.1, .7, .1, 1) 400ms);\n}\n.slide-in-up.ng-enter-active,\n.slide-in-up > .ng-enter-active {\n  @include translate3d(0, 0, 0);\n}\n\n.slide-in-up.ng-leave,\n.slide-in-up > .ng-leave {\n  @include transition(all ease-in-out 250ms);\n}\n\n\n// Scale Out\n// Scale from hero (1 in this case) to zero\n// -------------------------------\n\n@-webkit-keyframes scaleOut {\n  from { -webkit-transform: scale(1); opacity: 1; }\n  to { -webkit-transform: scale(0.8); opacity: 0; }\n}\n@keyframes scaleOut {\n  from { transform: scale(1); opacity: 1; }\n  to { transform: scale(0.8); opacity: 0; }\n}\n\n\n// Super Scale In\n// Scale from super (1.x) to duper (1 in this case)\n// -------------------------------\n\n@-webkit-keyframes superScaleIn {\n  from { -webkit-transform: scale(1.2); opacity: 0; }\n  to { -webkit-transform: scale(1); opacity: 1 }\n}\n@keyframes superScaleIn {\n  from { transform: scale(1.2); opacity: 0; }\n  to { transform: scale(1); opacity: 1; }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_backdrop.scss",
    "content": "\n.backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: $z-index-backdrop;\n\n  width: 100%;\n  height: 100%;\n\n  background-color: $loading-backdrop-bg-color;\n\n  visibility: hidden;\n  opacity: 0;\n\n  &.visible {\n    visibility: visible;\n  }\n  &.active {\n    opacity: 1;\n  }\n\n  @include transition($loading-backdrop-fadein-duration opacity linear);\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_badge.scss",
    "content": "\n/**\n * Badges\n * --------------------------------------------------\n */\n\n.badge {\n  @include badge-style($badge-default-bg, $badge-default-text);\n  z-index: $z-index-badge;\n  display: inline-block;\n  padding: 3px 8px;\n  min-width: 10px;\n  border-radius: $badge-border-radius;\n  vertical-align: baseline;\n  text-align: center;\n  white-space: nowrap;\n  font-weight: $badge-font-weight;\n  font-size: $badge-font-size;\n  line-height: $badge-line-height;\n\n  &:empty {\n    display: none;\n  }\n}\n\n//Be sure to override specificity of rule that 'badge color matches tab color by default'\n.tabs .tab-item .badge,\n.badge {\n  &.badge-light {\n    @include badge-style($badge-light-bg, $badge-light-text);\n  }\n  &.badge-stable {\n    @include badge-style($badge-stable-bg, $badge-stable-text);\n  }\n  &.badge-positive {\n    @include badge-style($badge-positive-bg, $badge-positive-text);\n  }\n  &.badge-calm {\n    @include badge-style($badge-calm-bg, $badge-calm-text);\n  }\n  &.badge-assertive {\n    @include badge-style($badge-assertive-bg, $badge-assertive-text);\n  }\n  &.badge-balanced {\n    @include badge-style($badge-balanced-bg, $badge-balanced-text);\n  }\n  &.badge-energized {\n    @include badge-style($badge-energized-bg, $badge-energized-text);\n  }\n  &.badge-royal {\n    @include badge-style($badge-royal-bg, $badge-royal-text);\n  }\n  &.badge-dark {\n    @include badge-style($badge-dark-bg, $badge-dark-text);\n  }\n}\n\n// Quick fix for labels/badges in buttons\n.button .badge {\n  position: relative;\n  top: -1px;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_bar.scss",
    "content": "\n/**\n * Bar (Headers and Footers)\n * --------------------------------------------------\n */\n\n.bar {\n  @include display-flex();\n  @include translate3d(0,0,0);\n  @include user-select(none);\n  position: absolute;\n  right: 0;\n  left: 0;\n  z-index: $z-index-bar;\n\n  box-sizing: border-box;\n  padding: $bar-padding-portrait;\n\n  width: 100%;\n  height: $bar-height;\n  border-width: 0;\n  border-style: solid;\n  border-top: 1px solid transparent;\n  border-bottom: 1px solid $bar-default-border;\n\n  background-color: $bar-default-bg;\n\n  /* border-width: 1px will actually create 2 device pixels on retina */\n  /* this nifty trick sets an actual 1px border on hi-res displays */\n  background-size: 0;\n  @media (min--moz-device-pixel-ratio: 1.5),\n         (-webkit-min-device-pixel-ratio: 1.5),\n         (min-device-pixel-ratio: 1.5),\n         (min-resolution: 144dpi),\n         (min-resolution: 1.5dppx) {\n    border: none;\n    background-image: linear-gradient(0deg, $bar-default-border, $bar-default-border 50%, transparent 50%);\n    background-position: bottom;\n    background-size: 100% 1px;\n    background-repeat: no-repeat;\n  }\n\n  &.bar-clear {\n    border: none;\n    background: none;\n    color: #fff;\n\n    .button {\n      color: #fff;\n    }\n    .title {\n      color: #fff;\n    }\n  }\n\n  &.item-input-inset {\n    .item-input-wrapper {\n      margin-top: -1px;\n\n      input {\n        padding-left: 8px;\n        width: 94%;\n        height: 28px;\n        background: transparent;\n      }\n    }\n  }\n\n  &.bar-light {\n    @include bar-style($bar-light-bg, $bar-light-border, $bar-light-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-light-border, $bar-light-border 50%, transparent 50%);\n    }\n  }\n  &.bar-stable {\n    @include bar-style($bar-stable-bg, $bar-stable-border, $bar-stable-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-stable-border, $bar-stable-border 50%, transparent 50%);\n    }\n  }\n  &.bar-positive {\n    @include bar-style($bar-positive-bg, $bar-positive-border, $bar-positive-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-positive-border, $bar-positive-border 50%, transparent 50%);\n    }\n  }\n  &.bar-calm {\n    @include bar-style($bar-calm-bg, $bar-calm-border, $bar-calm-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-calm-border, $bar-calm-border 50%, transparent 50%);\n    }\n  }\n  &.bar-assertive {\n    @include bar-style($bar-assertive-bg, $bar-assertive-border, $bar-assertive-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-assertive-border, $bar-assertive-border 50%, transparent 50%);\n    }\n  }\n  &.bar-balanced {\n    @include bar-style($bar-balanced-bg, $bar-balanced-border, $bar-balanced-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-balanced-border, $bar-positive-border 50%, transparent 50%);\n    }\n  }\n  &.bar-energized {\n    @include bar-style($bar-energized-bg, $bar-energized-border, $bar-energized-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-energized-border, $bar-energized-border 50%, transparent 50%);\n    }\n  }\n  &.bar-royal {\n    @include bar-style($bar-royal-bg, $bar-royal-border, $bar-royal-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-royal-border, $bar-royal-border 50%, transparent 50%);\n    }\n  }\n  &.bar-dark {\n    @include bar-style($bar-dark-bg, $bar-dark-border, $bar-dark-text);\n    &.bar-footer{\n      background-image: linear-gradient(180deg, $bar-dark-border, $bar-dark-border 50%, transparent 50%);\n    }\n  }\n\n  // Title inside of a bar is centered\n  .title {\n    position: absolute;\n\n    top: 0;\n    right: 0;\n    left: 0;\n    z-index: $z-index-bar-title;\n    overflow: hidden;\n\n    margin: 0 10px;\n\n    min-width: 30px;\n    height: $bar-height - 1;\n\n    text-align: center;\n\n    // Go into ellipsis if too small\n    text-overflow: ellipsis;\n    white-space: nowrap;\n\n    font-size: $bar-title-font-size;\n    font-weight: $headings-font-weight;\n\n    line-height: $bar-height;\n\n    &.title-left {\n      text-align: left;\n    }\n    &.title-right {\n      text-align: right;\n    }\n  }\n\n  .title a {\n    color: inherit;\n  }\n\n  .button {\n    z-index: $z-index-bar-button;\n    padding: 0 $button-bar-button-padding;\n    min-width: initial;\n    min-height: $button-bar-button-height - 1;\n    font-weight: 400;\n    font-size: $button-bar-button-font-size;\n    line-height: $button-bar-button-height;\n\n    &.button-icon:before,\n    .icon:before,\n    &.icon:before,\n    &.icon-left:before,\n    &.icon-right:before {\n      padding-right: 2px;\n      padding-left: 2px;\n      font-size: $button-bar-button-icon-size;\n      line-height: $button-bar-button-height;\n    }\n\n    &.button-icon {\n      font-size: $bar-title-font-size;\n      .icon:before,\n      &:before,\n      &.icon-left:before,\n      &.icon-right:before {\n        vertical-align: top;\n        font-size: $button-large-icon-size;\n        line-height: $button-bar-button-height;\n      }\n    }\n    &.button-clear {\n      padding-right: 2px;\n      padding-left: 2px;\n      font-weight: 300;\n      font-size: $bar-title-font-size;\n\n      .icon:before,\n      &.icon:before,\n      &.icon-left:before,\n      &.icon-right:before {\n        font-size: $button-large-icon-size;\n        line-height: $button-bar-button-height;\n      }\n    }\n\n    &.back-button {\n      display: block;\n      margin-right: 5px;\n      padding: 0;\n      white-space: nowrap;\n      font-weight: 400;\n    }\n\n    &.back-button.active,\n    &.back-button.activated {\n      opacity: 0.2;\n    }\n  }\n\n  .button-bar > .button,\n  .buttons > .button {\n    min-height: $button-bar-button-height - 1;\n    line-height: $button-bar-button-height;\n  }\n\n  .button-bar + .button,\n  .button + .button-bar {\n    margin-left: 5px;\n  }\n\n  // Android 4.4 messes with the display property\n  .buttons,\n  .buttons.primary-buttons,\n  .buttons.secondary-buttons {\n    display: inherit;\n  }\n  .buttons span {\n    display: inline-block;\n  }\n  .buttons-left span {\n    margin-right: 5px;\n    display: inherit;\n  }\n  .buttons-right span {\n    margin-left: 5px;\n    display: inherit;\n  }\n\n  // Place the last button in a bar on the right of the bar\n  .title + .button:last-child,\n  > .button + .button:last-child,\n  > .button.pull-right,\n  .buttons.pull-right,\n  .title + .buttons {\n    position: absolute;\n    top: 5px;\n    right: 5px;\n    bottom: 5px;\n  }\n\n}\n\n.platform-android {\n\n  .nav-bar-has-subheader .bar {\n    background-image: none;\n  }\n\n  .bar {\n\n    .back-button .icon:before {\n      font-size: 24px;\n    }\n\n    .title {\n      font-size: 19px;\n      line-height: $bar-height;\n    }\n  }\n\n}\n\n// Default styles for buttons inside of styled bars\n.bar-light {\n  .button {\n    @include button-style($bar-light-bg, $bar-light-border, $bar-light-active-bg, $bar-light-active-border, $bar-light-text);\n    @include button-clear($bar-light-text, $bar-title-font-size);\n  }\n}\n.bar-stable {\n  .button {\n    @include button-style($bar-stable-bg, $bar-stable-border, $bar-stable-active-bg, $bar-stable-active-border, $bar-stable-text);\n    @include button-clear($bar-stable-text, $bar-title-font-size);\n  }\n}\n.bar-positive {\n  .button {\n    @include button-style($bar-positive-bg, $bar-positive-border, $bar-positive-active-bg, $bar-positive-active-border, $bar-positive-text);\n    @include button-clear(#fff, $bar-title-font-size);\n  }\n}\n.bar-calm {\n  .button {\n    @include button-style($bar-calm-bg, $bar-calm-border, $bar-calm-active-bg, $bar-calm-active-border, $bar-calm-text);\n    @include button-clear(#fff, $bar-title-font-size);\n  }\n}\n.bar-assertive {\n  .button {\n    @include button-style($bar-assertive-bg, $bar-assertive-border, $bar-assertive-active-bg, $bar-assertive-active-border, $bar-assertive-text);\n    @include button-clear(#fff, $bar-title-font-size);\n  }\n}\n.bar-balanced {\n  .button {\n    @include button-style($bar-balanced-bg, $bar-balanced-border, $bar-balanced-active-bg, $bar-balanced-active-border, $bar-balanced-text);\n    @include button-clear(#fff, $bar-title-font-size);\n  }\n}\n.bar-energized {\n  .button {\n    @include button-style($bar-energized-bg, $bar-energized-border, $bar-energized-active-bg, $bar-energized-active-border, $bar-energized-text);\n    @include button-clear(#fff, $bar-title-font-size);\n  }\n}\n.bar-royal {\n  .button {\n    @include button-style($bar-royal-bg, $bar-royal-border, $bar-royal-active-bg, $bar-royal-active-border, $bar-royal-text);\n    @include button-clear(#fff, $bar-title-font-size);\n  }\n}\n.bar-dark {\n  .button {\n    @include button-style($bar-dark-bg, $bar-dark-border, $bar-dark-active-bg, $bar-dark-active-border, $bar-dark-text);\n    @include button-clear(#fff, $bar-title-font-size);\n  }\n}\n\n// Header at top\n.bar-header {\n  top: 0;\n  border-top-width: 0;\n  border-bottom-width: 1px;\n  &.has-tabs-top{\n    border-bottom-width: 0px;\n    background-image: none;\n  }\n}\n.tabs-top .bar-header{\n  border-bottom-width: 0px;\n  background-image: none;\n}\n\n// Footer at bottom\n.bar-footer {\n  bottom: 0;\n  border-top-width: 1px;\n  border-bottom-width: 0;\n  background-position: top;\n\n  height: $bar-footer-height;\n\n  &.item-input-inset {\n    position: absolute;\n  }\n}\n\n// Don't render padding if the bar is just for tabs\n.bar-tabs {\n  padding: 0;\n}\n\n.bar-subheader {\n  top: $bar-height;\n  display: block;\n\n  height: $bar-subheader-height;\n}\n.bar-subfooter {\n  bottom: $bar-footer-height;\n  display: block;\n\n  height: $bar-subfooter-height;\n}\n\n.nav-bar-block {\n  position: absolute;\n  top: 0;\n  right: 0;\n  left: 0;\n  z-index: $z-index-bar;\n}\n\n.bar .back-button.hide,\n.bar .buttons .hide {\n  display: none;\n}\n\n.nav-bar-tabs-top .bar {\n  background-image: none;\n}\n\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_button-bar.scss",
    "content": "\n/**\n * Button Bar\n * --------------------------------------------------\n */\n\n.button-bar {\n  @include display-flex();\n  @include flex(1);\n  width: 100%;\n\n  &.button-bar-inline {\n    display: block;\n    width: auto;\n\n    @include clearfix();\n\n    > .button {\n      width: auto;\n      display: inline-block;\n      float: left;\n    }\n  }\n}\n\n.button-bar > .button {\n  @include flex(1);\n  display: block;\n  \n  overflow: hidden;\n\n  padding: 0 16px;\n\n  width: 0;\n\n  border-width: 1px 0px 1px 1px;\n  border-radius: 0;\n  text-align: center;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n\n  &:before,\n  .icon:before {\n    line-height: 44px;\n  }\n\n  &:first-child {\n    border-radius: $button-border-radius 0px 0px $button-border-radius;\n  }\n  &:last-child {\n    border-right-width: 1px;\n    border-radius: 0px $button-border-radius $button-border-radius 0px;\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_button.scss",
    "content": "\n/**\n * Buttons\n * --------------------------------------------------\n */\n\n.button {\n  // set the color defaults\n  @include button-style($button-default-bg, $button-default-border, $button-default-active-bg, $button-default-active-border, $button-default-text);\n\n  position: relative;\n  display: inline-block;\n  margin: 0;\n  padding: 0 $button-padding;\n\n  min-width: ($button-padding * 3) + $button-font-size;\n  min-height: $button-height + 5px;\n\n  border-width: $button-border-width;\n  border-style: solid;\n  border-radius: $button-border-radius;\n\n  vertical-align: top;\n  text-align: center;\n\n  text-overflow: ellipsis;\n  font-size: $button-font-size;\n  line-height: $button-height - $button-border-width + 1px;\n\n  cursor: pointer;\n\n  &:after {\n    // used to create a larger button \"hit\" area\n    position: absolute;\n    top: -6px;\n    right: -6px;\n    bottom: -6px;\n    left: -6px;\n    content: ' ';\n  }\n\n  .icon {\n    vertical-align: top;\n    pointer-events: none;\n  }\n\n  .icon:before,\n  &.icon:before,\n  &.icon-left:before,\n  &.icon-right:before {\n    display: inline-block;\n    padding: 0 0 $button-border-width 0;\n    vertical-align: inherit;\n    font-size: $button-icon-size;\n    line-height: $button-height - $button-border-width;\n    pointer-events: none;\n  }\n  &.icon-left:before {\n    float: left;\n    padding-right: .2em;\n    padding-left: 0;\n  }\n  &.icon-right:before {\n    float: right;\n    padding-right: 0;\n    padding-left: .2em;\n  }\n\n  &.button-block, &.button-full {\n    margin-top: $button-block-margin;\n    margin-bottom: $button-block-margin;\n  }\n\n  &.button-light {\n    @include button-style($button-light-bg, $button-light-border, $button-light-active-bg, $button-light-active-border, $button-light-text);\n    @include button-clear($button-light-border);\n    @include button-outline($button-light-border);\n  }\n\n  &.button-stable {\n    @include button-style($button-stable-bg, $button-stable-border, $button-stable-active-bg, $button-stable-active-border, $button-stable-text);\n    @include button-clear($button-stable-border);\n    @include button-outline($button-stable-border);\n  }\n\n  &.button-positive {\n    @include button-style($button-positive-bg, $button-positive-border, $button-positive-active-bg, $button-positive-active-border, $button-positive-text);\n    @include button-clear($button-positive-bg);\n    @include button-outline($button-positive-bg);\n  }\n\n  &.button-calm {\n    @include button-style($button-calm-bg, $button-calm-border, $button-calm-active-bg, $button-calm-active-border, $button-calm-text);\n    @include button-clear($button-calm-bg);\n    @include button-outline($button-calm-bg);\n  }\n\n  &.button-assertive {\n    @include button-style($button-assertive-bg, $button-assertive-border, $button-assertive-active-bg, $button-assertive-active-border, $button-assertive-text);\n    @include button-clear($button-assertive-bg);\n    @include button-outline($button-assertive-bg);\n  }\n\n  &.button-balanced {\n    @include button-style($button-balanced-bg, $button-balanced-border, $button-balanced-active-bg, $button-balanced-active-border, $button-balanced-text);\n    @include button-clear($button-balanced-bg);\n    @include button-outline($button-balanced-bg);\n  }\n\n  &.button-energized {\n    @include button-style($button-energized-bg, $button-energized-border, $button-energized-active-bg, $button-energized-active-border, $button-energized-text);\n    @include button-clear($button-energized-bg);\n    @include button-outline($button-energized-bg);\n  }\n\n  &.button-royal {\n    @include button-style($button-royal-bg, $button-royal-border, $button-royal-active-bg, $button-royal-active-border, $button-royal-text);\n    @include button-clear($button-royal-bg);\n    @include button-outline($button-royal-bg);\n  }\n\n  &.button-dark {\n    @include button-style($button-dark-bg, $button-dark-border, $button-dark-active-bg, $button-dark-active-border, $button-dark-text);\n    @include button-clear($button-dark-bg);\n    @include button-outline($button-dark-bg);\n  }\n}\n\n.button-small {\n  padding: 2px $button-small-padding 1px;\n  min-width: $button-small-height;\n  min-height: $button-small-height + 2;\n  font-size: $button-small-font-size;\n  line-height: $button-small-height - $button-border-width - 1;\n\n  .icon:before,\n  &.icon:before,\n  &.icon-left:before,\n  &.icon-right:before {\n    font-size: $button-small-icon-size;\n    line-height: $button-small-icon-size + 3;\n    margin-top: 3px;\n  }\n}\n\n.button-large {\n  padding: 0 $button-large-padding;\n  min-width: ($button-large-padding * 3) + $button-large-font-size;\n  min-height: $button-large-height + 5;\n  font-size: $button-large-font-size;\n  line-height: $button-large-height - $button-border-width;\n\n  .icon:before,\n  &.icon:before,\n  &.icon-left:before,\n  &.icon-right:before {\n    padding-bottom: ($button-border-width * 2);\n    font-size: $button-large-icon-size;\n    line-height: $button-large-height - ($button-border-width * 2) - 1;\n  }\n}\n\n.button-icon {\n  @include transition(opacity .1s);\n  padding: 0 6px;\n  min-width: initial;\n  border-color: transparent;\n  background: none;\n\n  &.button.active,\n  &.button.activated {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    opacity: 0.3;\n  }\n\n  .icon:before,\n  &.icon:before {\n    font-size: $button-large-icon-size;\n  }\n}\n\n.button-clear {\n  @include button-clear($button-default-border);\n  @include transition(opacity .1s);\n  padding: 0 $button-clear-padding;\n  max-height: $button-height;\n  border-color: transparent;\n  background: none;\n  box-shadow: none;\n\n  &.active,\n  &.activated {\n    opacity: 0.3;\n  }\n}\n\n.button-outline {\n  @include button-outline($button-default-border);\n  @include transition(opacity .1s);\n  background: none;\n  box-shadow: none;\n}\n\n.padding > .button.button-block:first-child {\n  margin-top: 0;\n}\n\n.button-block {\n  display: block;\n  clear: both;\n\n  &:after {\n    clear: both;\n  }\n}\n\n.button-full,\n.button-full > .button {\n  display: block;\n  margin-right: 0;\n  margin-left: 0;\n  border-right-width: 0;\n  border-left-width: 0;\n  border-radius: 0;\n}\n\nbutton.button-block,\nbutton.button-full,\n.button-full > button.button,\ninput.button.button-block  {\n  width: 100%;\n}\n\na.button {\n  text-decoration: none;\n\n  .icon:before,\n  &.icon:before,\n  &.icon-left:before,\n  &.icon-right:before {\n    margin-top: 2px;\n  }\n}\n\n.button.disabled,\n.button[disabled] {\n  opacity: .4;\n  cursor: default !important;\n  pointer-events: none;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_checkbox.scss",
    "content": "\n/**\n * Checkbox\n * --------------------------------------------------\n */\n\n.checkbox {\n  // set the color defaults\n  @include checkbox-style($checkbox-off-border-default, $checkbox-on-bg-default, $checkbox-on-border-default);\n\n  position: relative;\n  display: inline-block;\n  padding: ($checkbox-height / 4) ($checkbox-width / 4);\n  cursor: pointer;\n}\n.checkbox-light  {\n  @include checkbox-style($checkbox-off-border-light, $checkbox-on-bg-light, $checkbox-off-border-light);\n}\n.checkbox-stable  {\n  @include checkbox-style($checkbox-off-border-stable, $checkbox-on-bg-stable, $checkbox-off-border-stable);\n}\n.checkbox-positive  {\n  @include checkbox-style($checkbox-off-border-positive, $checkbox-on-bg-positive, $checkbox-off-border-positive);\n}\n.checkbox-calm  {\n  @include checkbox-style($checkbox-off-border-calm, $checkbox-on-bg-calm, $checkbox-off-border-calm);\n}\n.checkbox-assertive  {\n  @include checkbox-style($checkbox-off-border-assertive, $checkbox-on-bg-assertive, $checkbox-off-border-assertive);\n}\n.checkbox-balanced  {\n  @include checkbox-style($checkbox-off-border-balanced, $checkbox-on-bg-balanced, $checkbox-off-border-balanced);\n}\n.checkbox-energized{\n  @include checkbox-style($checkbox-off-border-energized, $checkbox-on-bg-energized, $checkbox-off-border-energized);\n}\n.checkbox-royal  {\n  @include checkbox-style($checkbox-off-border-royal, $checkbox-on-bg-royal, $checkbox-off-border-royal);\n}\n.checkbox-dark  {\n  @include checkbox-style($checkbox-off-border-dark, $checkbox-on-bg-dark, $checkbox-off-border-dark);\n}\n\n.checkbox input:disabled:before,\n.checkbox input:disabled + .checkbox-icon:before {\n  border-color: $checkbox-off-border-light;\n}\n\n.checkbox input:disabled:checked:before,\n.checkbox input:disabled:checked + .checkbox-icon:before {\n  background: $checkbox-on-bg-light;\n}\n\n\n.checkbox.checkbox-input-hidden input {\n  display: none !important;\n}\n\n.checkbox input,\n.checkbox-icon {\n  position: relative;\n  width: $checkbox-width;\n  height: $checkbox-height;\n  display: block;\n  border: 0;\n  background: transparent;\n  cursor: pointer;\n  -webkit-appearance: none;\n\n  &:before {\n    // what the checkbox looks like when its not checked\n    display: table;\n    width: 100%;\n    height: 100%;\n    border-width: $checkbox-border-width;\n    border-style: solid;\n    border-radius: $checkbox-border-radius;\n    background: $checkbox-off-bg-color;\n    content: ' ';\n    @include transition(background-color 20ms ease-in-out);\n  }\n}\n\n.checkbox input:checked:before,\ninput:checked + .checkbox-icon:before {\n  border-width: $checkbox-border-width + 1;\n}\n\n// the checkmark within the box\n.checkbox input:after,\n.checkbox-icon:after {\n  @include transition(opacity .05s ease-in-out);\n  @include rotate(-45deg);\n  position: absolute;\n  top: 33%;\n  left: 25%;\n  display: table;\n  width: ($checkbox-width / 2);\n  height: ($checkbox-width / 4) - 1;\n  border: $checkbox-check-width solid $checkbox-check-color;\n  border-top: 0;\n  border-right: 0;\n  content: ' ';\n  opacity: 0;\n}\n\n.platform-android .checkbox-platform input:before,\n.platform-android .checkbox-platform .checkbox-icon:before,\n.checkbox-square input:before,\n.checkbox-square .checkbox-icon:before {\n  border-radius: 2px;\n  width: 72%;\n  height: 72%;\n  margin-top: 14%;\n  margin-left: 14%;\n  border-width: 2px;\n}\n\n.platform-android .checkbox-platform input:after,\n.platform-android .checkbox-platform .checkbox-icon:after,\n.checkbox-square input:after,\n.checkbox-square .checkbox-icon:after {\n  border-width: 2px;\n  top: 19%;\n  left: 25%;\n  width: ($checkbox-width / 2) - 1;\n  height: 7px;\n}\n\n.grade-c .checkbox input:after,\n.grade-c .checkbox-icon:after {\n  @include rotate(0);\n  top: 3px;\n  left: 4px;\n  border: none;\n  color: $checkbox-check-color;\n  content: '\\2713';\n  font-weight: bold;\n  font-size: 20px;\n}\n\n// what the checkmark looks like when its checked\n.checkbox input:checked:after,\ninput:checked + .checkbox-icon:after {\n  opacity: 1;\n}\n\n// make sure item content have enough padding on left to fit the checkbox\n.item-checkbox {\n  padding-left: ($item-padding * 2) + $checkbox-width;\n\n  &.active {\n    box-shadow: none;\n  }\n}\n\n// position the checkbox to the left within an item\n.item-checkbox .checkbox {\n  position: absolute;\n  top: 50%;\n  right: $item-padding / 2;\n  left: $item-padding / 2;\n  z-index: $z-index-item-checkbox;\n  margin-top: (($checkbox-height + ($checkbox-height / 2)) / 2) * -1;\n}\n\n\n.item-checkbox.item-checkbox-right {\n  padding-right: ($item-padding * 2) + $checkbox-width;\n  padding-left: $item-padding;\n}\n\n.item-checkbox-right .checkbox input,\n.item-checkbox-right .checkbox-icon {\n  float: right;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_form.scss",
    "content": "/**\n * Forms\n * --------------------------------------------------\n */\n\n// Make all forms have space below them\nform {\n  margin: 0 0 $line-height-base;\n}\n\n// Groups of fields with labels on top (legends)\nlegend {\n  display: block;\n  margin-bottom: $line-height-base;\n  padding: 0;\n  width: 100%;\n  border: $input-border-width solid $input-border;\n  color: $dark;\n  font-size: $font-size-base * 1.5;\n  line-height: $line-height-base * 2;\n\n  small {\n    color: $stable;\n    font-size: $line-height-base * .75;\n  }\n}\n\n// Set font for forms\nlabel,\ninput,\nbutton,\nselect,\ntextarea {\n  @include font-shorthand($font-size-base, normal, $line-height-base); // Set size, weight, line-height here\n}\ninput,\nbutton,\nselect,\ntextarea {\n  font-family: $font-family-base; // And only set font-family here for those that need it (note the missing label element)\n}\n\n\n// Input List\n// -------------------------------\n\n.item-input {\n  @include display-flex();\n  @include align-items(center);\n  position: relative;\n  overflow: hidden;\n  padding: 6px 0 5px 16px;\n\n  input {\n    @include border-radius(0);\n    @include flex(1, 220px);\n    @include appearance(none);\n    margin: 0;\n    padding-right: 24px;\n    background-color: transparent;\n  }\n\n  .button .icon {\n    @include flex(0, 0, 24px);\n    position: static;\n    display: inline-block;\n    height: auto;\n    text-align: center;\n    font-size: 16px;\n  }\n\n  .button-bar {\n    @include border-radius(0);\n    @include flex(1, 0, 220px);\n    @include appearance(none);\n  }\n\n  .icon {\n    min-width: 14px;\n  }\n}\n// prevent flex-shrink on WP\n.platform-windowsphone .item-input input{\n  flex-shrink: 1;\n}\n\n.item-input-inset {\n  @include display-flex();\n  @include align-items(center);\n  position: relative;\n  overflow: hidden;\n  padding: ($item-padding / 3) * 2;\n}\n\n.item-input-wrapper {\n  @include display-flex();\n  @include flex(1, 0);\n  @include align-items(center);\n  @include border-radius(4px);\n  padding-right: 8px;\n  padding-left: 8px;\n  background: #eee;\n}\n\n.item-input-inset .item-input-wrapper input {\n  padding-left: 4px;\n  height: 29px;\n  background: transparent;\n  line-height: 18px;\n}\n\n.item-input-wrapper ~ .button {\n  margin-left: ($item-padding / 3) * 2;\n}\n\n.input-label {\n  display: table;\n  padding: 7px 10px 7px 0px;\n  max-width: 200px;\n  width: 35%;\n  color: $input-label-color;\n  font-size: 16px;\n}\n\n.placeholder-icon {\n  color: #aaa;\n  &:first-child {\n    padding-right: 6px;\n  }\n  &:last-child {\n    padding-left: 6px;\n  }\n}\n\n.item-stacked-label {\n  display: block;\n  background-color: transparent;\n  box-shadow: none;\n\n  .input-label, .icon {\n    display: inline-block;\n    padding: 4px 0 0 0px;\n    vertical-align: middle;\n  }\n}\n\n.item-stacked-label input,\n.item-stacked-label textarea {\n  @include border-radius(2px);\n  padding: 4px 8px 3px 0;\n  border: none;\n  background-color: $input-bg;\n}\n.item-stacked-label input {\n  overflow: hidden;\n  height: $line-height-computed + $font-size-base + 12px;\n}\n\n.item-floating-label {\n  display: block;\n  background-color: transparent;\n  box-shadow: none;\n\n  .input-label {\n    position: relative;\n    padding: 5px 0 0 0;\n    opacity: 0;\n    top: 10px;\n    @include transition(opacity .15s ease-in, top .2s linear);\n\n    &.has-input {\n      opacity: 1;\n      top: 0;\n      @include transition(opacity .15s ease-in, top .2s linear);\n    }\n  }\n}\n\n\n// Form Controls\n// -------------------------------\n\n// Shared size and type resets\ntextarea,\ninput[type=\"text\"],\ninput[type=\"password\"],\ninput[type=\"datetime\"],\ninput[type=\"datetime-local\"],\ninput[type=\"date\"],\ninput[type=\"month\"],\ninput[type=\"time\"],\ninput[type=\"week\"],\ninput[type=\"number\"],\ninput[type=\"email\"],\ninput[type=\"url\"],\ninput[type=\"search\"],\ninput[type=\"tel\"],\ninput[type=\"color\"] {\n  display: block;\n  padding-top: 2px;\n  padding-left: 0;\n  height: $line-height-computed + $font-size-base;\n  color: $input-color;\n  vertical-align: middle;\n  font-size: $font-size-base;\n  line-height: $font-size-base + 2;\n}\n\n.platform-ios,\n.platform-android {\n  input[type=\"datetime-local\"],\n  input[type=\"date\"],\n  input[type=\"month\"],\n  input[type=\"time\"],\n  input[type=\"week\"] {\n    padding-top: 8px;\n  }\n}\n\n.item-input {\n  input,\n  textarea {\n    width: 100%;\n  }\n}\n\ntextarea {\n  padding-left: 0;\n  @include placeholder($input-color-placeholder, -3px);\n}\n\n// Reset height since textareas have rows\ntextarea {\n  height: auto;\n}\n\n// Everything else\ntextarea,\ninput[type=\"text\"],\ninput[type=\"password\"],\ninput[type=\"datetime\"],\ninput[type=\"datetime-local\"],\ninput[type=\"date\"],\ninput[type=\"month\"],\ninput[type=\"time\"],\ninput[type=\"week\"],\ninput[type=\"number\"],\ninput[type=\"email\"],\ninput[type=\"url\"],\ninput[type=\"search\"],\ninput[type=\"tel\"],\ninput[type=\"color\"] {\n  border: 0;\n}\n\n// Position radios and checkboxes better\ninput[type=\"radio\"],\ninput[type=\"checkbox\"] {\n  margin: 0;\n  line-height: normal;\n}\n\n// Reset width of input images, buttons, radios, checkboxes\n.item-input {\n  input[type=\"file\"],\n  input[type=\"image\"],\n  input[type=\"submit\"],\n  input[type=\"reset\"],\n  input[type=\"button\"],\n  input[type=\"radio\"],\n  input[type=\"checkbox\"] {\n    width: auto; // Override of generic input selector\n  }\n}\n\n// Set the height of file to match text inputs\ninput[type=\"file\"] {\n  line-height: $input-height-base;\n}\n\n// Text input classes to hide text caret during scroll\n.previous-input-focus,\n.cloned-text-input + input,\n.cloned-text-input + textarea {\n  position: absolute !important;\n  left: -9999px;\n  width: 200px;\n}\n\n\n// Placeholder\n// -------------------------------\ninput,\ntextarea {\n  @include placeholder();\n}\n\n\n// DISABLED STATE\n// -------------------------------\n\n// Disabled and read-only inputs\ninput[disabled],\nselect[disabled],\ntextarea[disabled],\ninput[readonly]:not(.cloned-text-input),\ntextarea[readonly]:not(.cloned-text-input),\nselect[readonly] {\n  background-color: $input-bg-disabled;\n  cursor: not-allowed;\n}\n// Explicitly reset the colors here\ninput[type=\"radio\"][disabled],\ninput[type=\"checkbox\"][disabled],\ninput[type=\"radio\"][readonly],\ninput[type=\"checkbox\"][readonly] {\n  background-color: transparent;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_grid.scss",
    "content": "/**\n * Grid\n * --------------------------------------------------\n * Using flexbox for the grid, inspired by Philip Walton:\n * http://philipwalton.github.io/solved-by-flexbox/demos/grids/\n * By default each .col within a .row will evenly take up\n * available width, and the height of each .col with take\n * up the height of the tallest .col in the same .row.\n */\n\n.row {\n  @include display-flex();\n  padding: ($grid-padding-width / 2);\n  width: 100%;\n}\n\n.row-wrap {\n  @include flex-wrap(wrap);\n}\n\n.row-no-padding {\n  padding: 0;\n\n  > .col {\n    padding: 0;\n  }\n}\n\n.row + .row {\n  margin-top: ($grid-padding-width / 2) * -1;\n  padding-top: 0;\n}\n\n.col {\n  @include flex(1);\n  display: block;\n  padding: ($grid-padding-width / 2);\n  width: 100%;\n}\n\n\n/* Vertically Align Columns */\n/* .row-* vertically aligns every .col in the .row */\n.row-top {\n  @include align-items(flex-start);\n}\n.row-bottom {\n  @include align-items(flex-end);\n}\n.row-center {\n  @include align-items(center);\n}\n.row-stretch {\n  @include align-items(stretch);\n}\n.row-baseline {\n  @include align-items(baseline);\n}\n\n/* .col-* vertically aligns an individual .col */\n.col-top {\n  @include align-self(flex-start);\n}\n.col-bottom {\n  @include align-self(flex-end);\n}\n.col-center {\n  @include align-self(center);\n}\n\n/* Column Offsets */\n.col-offset-10 {\n  margin-left: 10%;\n}\n.col-offset-20 {\n  margin-left: 20%;\n}\n.col-offset-25 {\n  margin-left: 25%;\n}\n.col-offset-33, .col-offset-34 {\n  margin-left: 33.3333%;\n}\n.col-offset-50 {\n  margin-left: 50%;\n}\n.col-offset-66, .col-offset-67 {\n  margin-left: 66.6666%;\n}\n.col-offset-75 {\n  margin-left: 75%;\n}\n.col-offset-80 {\n  margin-left: 80%;\n}\n.col-offset-90 {\n  margin-left: 90%;\n}\n\n\n/* Explicit Column Percent Sizes */\n/* By default each grid column will evenly distribute */\n/* across the grid. However, you can specify individual */\n/* columns to take up a certain size of the available area */\n.col-10 {\n  @include flex(0, 0, 10%);\n  max-width: 10%;\n}\n.col-20 {\n  @include flex(0, 0, 20%);\n  max-width: 20%;\n}\n.col-25 {\n  @include flex(0, 0, 25%);\n  max-width: 25%;\n}\n.col-33, .col-34 {\n  @include flex(0, 0, 33.3333%);\n  max-width: 33.3333%;\n}\n.col-50 {\n  @include flex(0, 0, 50%);\n  max-width: 50%;\n}\n.col-66, .col-67 {\n  @include flex(0, 0, 66.6666%);\n  max-width: 66.6666%;\n}\n.col-75 {\n  @include flex(0, 0, 75%);\n  max-width: 75%;\n}\n.col-80 {\n  @include flex(0, 0, 80%);\n  max-width: 80%;\n}\n.col-90 {\n  @include flex(0, 0, 90%);\n  max-width: 90%;\n}\n\n\n/* Responsive Grid Classes */\n/* Adding a class of responsive-X to a row */\n/* will trigger the flex-direction to */\n/* change to column and add some margin */\n/* to any columns in the row for clearity */\n\n@include responsive-grid-break('.responsive-sm', $grid-responsive-sm-break);\n@include responsive-grid-break('.responsive-md', $grid-responsive-md-break);\n@include responsive-grid-break('.responsive-lg', $grid-responsive-lg-break);\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_items.scss",
    "content": "/**\n * Items\n * --------------------------------------------------\n */\n\n.item {\n  @include item-style($item-default-bg, $item-default-border, $item-default-text);\n\n  position: relative;\n  z-index: $z-index-item; // Make sure the borders and stuff don't get hidden by children\n  display: block;\n\n  margin: $item-border-width * -1;\n  padding: $item-padding;\n\n  border-width: $item-border-width;\n  border-style: solid;\n  font-size: $item-font-size;\n\n  h2 {\n    margin: 0 0 2px 0;\n    font-size: 16px;\n    font-weight: normal;\n  }\n  h3 {\n    margin: 0 0 4px 0;\n    font-size: 14px;\n  }\n  h4 {\n    margin: 0 0 4px 0;\n    font-size: 12px;\n  }\n  h5, h6 {\n    margin: 0 0 3px 0;\n    font-size: 10px;\n  }\n  p {\n    color: #666;\n    font-size: 14px;\n    margin-bottom: 2px;\n  }\n\n  h1:last-child,\n  h2:last-child,\n  h3:last-child,\n  h4:last-child,\n  h5:last-child,\n  h6:last-child,\n  p:last-child {\n    margin-bottom: 0;\n  }\n\n  // Align badges within items\n  .badge {\n    @include display-flex();\n    position: absolute;\n    top: $item-padding;\n    right: ($item-padding * 2);\n  }\n  &.item-button-right .badge {\n    right: ($item-padding * 2) + 35;\n  }\n  &.item-divider .badge {\n    top: ceil($item-padding / 2);\n  }\n  .badge + .badge {\n    margin-right: 5px;\n  }\n\n  // Different themes for items\n  &.item-light {\n    @include item-style($item-light-bg, $item-light-border, $item-light-text);\n  }\n  &.item-stable {\n    @include item-style($item-stable-bg, $item-stable-border, $item-stable-text);\n  }\n  &.item-positive {\n    @include item-style($item-positive-bg, $item-positive-border, $item-positive-text);\n  }\n  &.item-calm {\n    @include item-style($item-calm-bg, $item-calm-border, $item-calm-text);\n  }\n  &.item-assertive {\n    @include item-style($item-assertive-bg, $item-assertive-border, $item-assertive-text);\n  }\n  &.item-balanced {\n    @include item-style($item-balanced-bg, $item-balanced-border, $item-balanced-text);\n  }\n  &.item-energized {\n    @include item-style($item-energized-bg, $item-energized-border, $item-energized-text);\n  }\n  &.item-royal {\n    @include item-style($item-royal-bg, $item-royal-border, $item-royal-text);\n  }\n  &.item-dark {\n    @include item-style($item-dark-bg, $item-dark-border, $item-dark-text);\n  }\n\n  &[ng-click]:hover {\n    cursor: pointer;\n  }\n\n}\n\n.list-borderless .item,\n.item-borderless {\n  border-width: 0;\n}\n\n// Link and Button Active States\n.item.active,\n.item.activated,\n.item-complex.active .item-content,\n.item-complex.activated .item-content,\n.item .item-content.active,\n.item .item-content.activated {\n  @include item-active-style($item-default-active-bg, $item-default-active-border);\n\n  // Different active themes for <a> and <button> items\n  &.item-light {\n    @include item-active-style($item-light-active-bg, $item-light-active-border);\n  }\n  &.item-stable {\n    @include item-active-style($item-stable-active-bg, $item-stable-active-border);\n  }\n  &.item-positive {\n    @include item-active-style($item-positive-active-bg, $item-positive-active-border);\n  }\n  &.item-calm {\n    @include item-active-style($item-calm-active-bg, $item-calm-active-border);\n  }\n  &.item-assertive {\n    @include item-active-style($item-assertive-active-bg, $item-assertive-active-border);\n  }\n  &.item-balanced {\n    @include item-active-style($item-balanced-active-bg, $item-balanced-active-border);\n  }\n  &.item-energized {\n    @include item-active-style($item-energized-active-bg, $item-energized-active-border);\n  }\n  &.item-royal {\n    @include item-active-style($item-royal-active-bg, $item-royal-active-border);\n  }\n  &.item-dark {\n    @include item-active-style($item-dark-active-bg, $item-dark-active-border);\n  }\n}\n\n// Handle text overflow\n.item,\n.item h1,\n.item h2,\n.item h3,\n.item h4,\n.item h5,\n.item h6,\n.item p,\n.item-content,\n.item-content h1,\n.item-content h2,\n.item-content h3,\n.item-content h4,\n.item-content h5,\n.item-content h6,\n.item-content p {\n  overflow: hidden;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n}\n\n// Linked list items\na.item {\n  color: inherit;\n  text-decoration: none;\n\n  &:hover,\n  &:focus {\n    text-decoration: none;\n  }\n}\n\n\n/**\n * Complex Items\n * --------------------------------------------------\n * Adding .item-complex allows the .item to be slidable and\n * have options underneath the button, but also requires an\n * additional .item-content element inside .item.\n * Basically .item-complex removes any default settings which\n * .item added, so that .item-content looks them as just .item.\n */\n\n.item-complex,\na.item.item-complex,\nbutton.item.item-complex {\n  padding: 0;\n}\n.item-complex .item-content,\n.item-radio .item-content {\n  position: relative;\n  z-index: $z-index-item;\n  padding: $item-padding (ceil( ($item-padding * 3) + ($item-padding / 3) ) - 5) $item-padding $item-padding;\n  border: none;\n  background-color: white;\n}\n\na.item-content {\n  display: block;\n  color: inherit;\n  text-decoration: none;\n}\n\n.item-text-wrap .item,\n.item-text-wrap .item-content,\n.item-text-wrap,\n.item-text-wrap h1,\n.item-text-wrap h2,\n.item-text-wrap h3,\n.item-text-wrap h4,\n.item-text-wrap h5,\n.item-text-wrap h6,\n.item-text-wrap p,\n.item-complex.item-text-wrap .item-content,\n.item-body h1,\n.item-body h2,\n.item-body h3,\n.item-body h4,\n.item-body h5,\n.item-body h6,\n.item-body p {\n  overflow: visible;\n  white-space: normal;\n}\n.item-complex.item-text-wrap,\n.item-complex.item-text-wrap h1,\n.item-complex.item-text-wrap h2,\n.item-complex.item-text-wrap h3,\n.item-complex.item-text-wrap h4,\n.item-complex.item-text-wrap h5,\n.item-complex.item-text-wrap h6,\n.item-complex.item-text-wrap p {\n  overflow: visible;\n  white-space: normal;\n}\n\n// Link and Button Active States\n\n.item-complex{\n  // Stylized items\n  &.item-light > .item-content{\n    @include item-style($item-light-bg, $item-light-border, $item-light-text);\n    &.active, &:active {\n      @include item-active-style($item-light-active-bg, $item-light-active-border);\n    }\n  }\n  &.item-stable > .item-content{\n    @include item-style($item-stable-bg, $item-stable-border, $item-stable-text);\n    &.active, &:active {\n      @include item-active-style($item-stable-active-bg, $item-stable-active-border);\n    }\n  }\n  &.item-positive > .item-content{\n    @include item-style($item-positive-bg, $item-positive-border, $item-positive-text);\n    &.active, &:active {\n      @include item-active-style($item-positive-active-bg, $item-positive-active-border);\n    }\n  }\n  &.item-calm > .item-content{\n    @include item-style($item-calm-bg, $item-calm-border, $item-calm-text);\n    &.active, &:active {\n      @include item-active-style($item-calm-active-bg, $item-calm-active-border);\n    }\n  }\n  &.item-assertive > .item-content{\n    @include item-style($item-assertive-bg, $item-assertive-border, $item-assertive-text);\n    &.active, &:active {\n      @include item-active-style($item-assertive-active-bg, $item-assertive-active-border);\n    }\n  }\n  &.item-balanced > .item-content{\n    @include item-style($item-balanced-bg, $item-balanced-border, $item-balanced-text);\n    &.active, &:active {\n      @include item-active-style($item-balanced-active-bg, $item-balanced-active-border);\n    }\n  }\n  &.item-energized > .item-content{\n    @include item-style($item-energized-bg, $item-energized-border, $item-energized-text);\n    &.active, &:active {\n      @include item-active-style($item-energized-active-bg, $item-energized-active-border);\n    }\n  }\n  &.item-royal > .item-content{\n    @include item-style($item-royal-bg, $item-royal-border, $item-royal-text);\n    &.active, &:active {\n      @include item-active-style($item-royal-active-bg, $item-royal-active-border);\n    }\n  }\n  &.item-dark > .item-content{\n    @include item-style($item-dark-bg, $item-dark-border, $item-dark-text);\n    &.active, &:active {\n      @include item-active-style($item-dark-active-bg, $item-dark-active-border);\n    }\n  }\n}\n\n\n/**\n * Item Icons\n * --------------------------------------------------\n */\n\n.item-icon-left .icon,\n.item-icon-right .icon {\n  @include display-flex();\n  @include align-items(center);\n  position: absolute;\n  top: 0;\n  height: 100%;\n  font-size: $item-icon-font-size;\n\n  &:before {\n    display: block;\n    width: $item-icon-font-size;\n    text-align: center;\n  }\n}\n\n.item .fill-icon {\n  min-width: $item-icon-fill-font-size + 2;\n  min-height: $item-icon-fill-font-size + 2;\n  font-size: $item-icon-fill-font-size;\n}\n\n.item-icon-left {\n  padding-left: ceil( ($item-padding * 3) + ($item-padding / 3) );\n\n  .icon {\n    left: ceil( ($item-padding / 3) * 2);\n  }\n}\n.item-complex.item-icon-left {\n  padding-left: 0;\n\n  .item-content {\n    padding-left: ceil( ($item-padding * 3) + ($item-padding / 3) );\n  }\n}\n\n.item-icon-right {\n  padding-right: ceil( ($item-padding * 3) + ($item-padding / 3) );\n\n  .icon {\n    right: ceil( ($item-padding / 3) * 2);\n  }\n}\n.item-complex.item-icon-right {\n  padding-right: 0;\n\n  .item-content {\n    padding-right: ceil( ($item-padding * 3) + ($item-padding / 3) );\n  }\n}\n\n.item-icon-left.item-icon-right .icon:first-child {\n  right: auto;\n}\n.item-icon-left.item-icon-right .icon:last-child,\n.item-icon-left .item-delete .icon {\n  left: auto;\n}\n\n.item-icon-left .icon-accessory,\n.item-icon-right .icon-accessory {\n  color: $item-icon-accessory-color;\n  font-size: $item-icon-accessory-font-size;\n}\n.item-icon-left .icon-accessory {\n  left: floor($item-padding / 5);\n}\n.item-icon-right .icon-accessory {\n  right: floor($item-padding / 5);\n}\n\n\n/**\n * Item Button\n * --------------------------------------------------\n * An item button is a child button inside an .item (not the entire .item)\n */\n\n.item-button-left {\n  padding-left: ceil($item-padding * 4.5);\n}\n\n.item-button-left > .button,\n.item-button-left .item-content > .button {\n  @include display-flex();\n  @include align-items(center);\n  position: absolute;\n  top: ceil($item-padding / 2);\n  left: ceil( ($item-padding / 3) * 2);\n  min-width: $item-icon-font-size + ($button-border-width * 2);\n  min-height: $item-icon-font-size + ($button-border-width * 2);\n  font-size: $item-button-font-size;\n  line-height: $item-button-line-height;\n\n  .icon:before {\n    position: relative;\n    left: auto;\n    width: auto;\n    line-height: $item-icon-font-size - 1;\n  }\n\n  > .button {\n    margin: 0px 2px;\n    min-height: $item-icon-font-size + ($button-border-width * 2);\n    font-size: $item-button-font-size;\n    line-height: $item-button-line-height;\n  }\n}\n\n.item-button-right,\na.item.item-button-right,\nbutton.item.item-button-right {\n  padding-right: $item-padding * 5;\n}\n\n.item-button-right > .button,\n.item-button-right .item-content > .button,\n.item-button-right > .buttons,\n.item-button-right .item-content > .buttons {\n  @include display-flex();\n  @include align-items(center);\n  position: absolute;\n  top: ceil($item-padding / 2);\n  right: $item-padding;\n  min-width: $item-icon-font-size + ($button-border-width * 2);\n  min-height: $item-icon-font-size + ($button-border-width * 2);\n  font-size: $item-button-font-size;\n  line-height: $item-button-line-height;\n\n  .icon:before {\n    position: relative;\n    left: auto;\n    width: auto;\n    line-height: $item-icon-font-size - 1;\n  }\n\n  > .button {\n    margin: 0px 2px;\n    min-width: $item-icon-font-size + ($button-border-width * 2);\n    min-height: $item-icon-font-size + ($button-border-width * 2);\n    font-size: $item-button-font-size;\n    line-height: $item-button-line-height;\n  }\n}\n\n\n// Item Avatar\n// -------------------------------\n\n.item-avatar,\n.item-avatar .item-content,\n.item-avatar-left,\n.item-avatar-left .item-content {\n  padding-left: $item-avatar-width + ($item-padding * 2);\n  min-height: $item-avatar-width + ($item-padding * 2);\n\n  > img:first-child,\n  .item-image {\n    position: absolute;\n    top: $item-padding;\n    left: $item-padding;\n    max-width: $item-avatar-width;\n    max-height: $item-avatar-height;\n    width: 100%;\n    height: 100%;\n    border-radius: $item-avatar-border-radius;\n  }\n}\n\n.item-avatar-right,\n.item-avatar-right .item-content {\n  padding-right: $item-avatar-width + ($item-padding * 2);\n  min-height: $item-avatar-width + ($item-padding * 2);\n\n  > img:first-child,\n  .item-image {\n    position: absolute;\n    top: $item-padding;\n    right: $item-padding;\n    max-width: $item-avatar-width;\n    max-height: $item-avatar-height;\n    width: 100%;\n    height: 100%;\n    border-radius: $item-avatar-border-radius;\n  }\n}\n\n\n// Item Thumbnails\n// -------------------------------\n\n.item-thumbnail-left,\n.item-thumbnail-left .item-content {\n  padding-top: $item-padding / 2;\n  padding-left: $item-thumbnail-width + $item-thumbnail-margin + $item-padding;\n  min-height: $item-thumbnail-height + ($item-thumbnail-margin * 2);\n\n  > img:first-child,\n  .item-image {\n    position: absolute;\n    top: $item-thumbnail-margin;\n    left: $item-thumbnail-margin;\n    max-width: $item-thumbnail-width;\n    max-height: $item-thumbnail-height;\n    width: 100%;\n    height: 100%;\n  }\n}\n.item-avatar.item-complex,\n.item-avatar-left.item-complex,\n.item-thumbnail-left.item-complex {\n  padding-top: 0;\n  padding-left: 0;\n}\n\n.item-thumbnail-right,\n.item-thumbnail-right .item-content {\n  padding-top: $item-padding / 2;\n  padding-right: $item-thumbnail-width + $item-thumbnail-margin + $item-padding;\n  min-height: $item-thumbnail-height + ($item-thumbnail-margin * 2);\n\n  > img:first-child,\n  .item-image {\n    position: absolute;\n    top: $item-thumbnail-margin;\n    right: $item-thumbnail-margin;\n    max-width: $item-thumbnail-width;\n    max-height: $item-thumbnail-height;\n    width: 100%;\n    height: 100%;\n  }\n}\n.item-avatar-right.item-complex,\n.item-thumbnail-right.item-complex {\n  padding-top: 0;\n  padding-right: 0;\n}\n\n\n// Item Image\n// -------------------------------\n\n.item-image {\n  padding: 0;\n  text-align: center;\n\n  img:first-child, .list-img {\n    width: 100%;\n    vertical-align: middle;\n  }\n}\n\n\n// Item Body\n// -------------------------------\n\n.item-body {\n  overflow: auto;\n  padding: $item-padding;\n  text-overflow: inherit;\n  white-space: normal;\n\n  h1, h2, h3, h4, h5, h6, p {\n    margin-top: $item-padding;\n    margin-bottom: $item-padding;\n  }\n}\n\n\n// Item Divider\n// -------------------------------\n\n.item-divider {\n  padding-top: ceil($item-padding / 2);\n  padding-bottom: ceil($item-padding / 2);\n  min-height: 30px;\n  background-color: $item-divider-bg;\n  color: $item-divider-color;\n  font-weight: 500;\n}\n\n.platform-ios .item-divider-platform,\n.item-divider-ios {\n  padding-top: 26px;\n  text-transform: uppercase;\n  font-weight: 300;\n  font-size: 13px;\n  background-color: #efeff4;\n  color: #555;\n}\n\n.platform-android .item-divider-platform,\n.item-divider-android {\n  font-weight: 300;\n  font-size: 13px;\n}\n\n\n// Item Note\n// -------------------------------\n\n.item-note {\n  float: right;\n  color: #aaa;\n  font-size: 14px;\n}\n\n\n// Item Editing\n// -------------------------------\n\n.item-left-editable .item-content,\n.item-right-editable .item-content {\n  // setup standard transition settings\n  @include transition-duration( $item-edit-transition-duration );\n  @include transition-timing-function( $item-edit-transition-function );\n  -webkit-transition-property: -webkit-transform;\n     -moz-transition-property: -moz-transform;\n          transition-property: transform;\n}\n\n.list-left-editing .item-left-editable .item-content,\n.item-left-editing.item-left-editable .item-content {\n  // actively editing the left side of the item\n  @include translate3d($item-left-edit-open-width, 0, 0);\n}\n\n.item-remove-animate {\n  &.ng-leave {\n    @include transition-duration( $item-remove-transition-duration );\n  }\n  &.ng-leave .item-content,\n  &.ng-leave:last-of-type {\n    @include transition-duration( $item-remove-transition-duration );\n    @include transition-timing-function( $item-remove-transition-function );\n    @include transition-property( all );\n  }\n\n  &.ng-leave.ng-leave-active .item-content {\n    opacity:0;\n    -webkit-transform: translate3d(-100%, 0, 0) !important;\n    transform: translate3d(-100%, 0, 0) !important;\n  }\n  &.ng-leave.ng-leave-active:last-of-type {\n    opacity: 0;\n  }\n\n  &.ng-leave.ng-leave-active ~ ion-item:not(.ng-leave) {\n    -webkit-transform: translate3d(0, unquote('-webkit-calc(-100% + 1px)'), 0);\n    transform: translate3d(0, calc(-100% + 1px), 0);\n    @include transition-duration( $item-remove-transition-duration );\n    @include transition-timing-function( $item-remove-descendents-transition-function );\n    @include transition-property( all );\n  }\n}\n\n\n\n// Item Left Edit Button\n// -------------------------------\n\n.item-left-edit {\n  @include transition(all $item-edit-transition-function $item-edit-transition-duration / 2);\n  position: absolute;\n  top: 0;\n  left: 0;\n  z-index: $z-index-item-edit;\n  width: $item-left-edit-open-width;\n  height: 100%;\n  line-height: 100%;\n\n  .button {\n    height: 100%;\n\n    &.icon {\n      @include display-flex();\n      @include align-items(center);\n      position: absolute;\n      top: 0;\n      height: 100%;\n    }\n  }\n\n  display: none;\n  opacity: 0;\n  @include translate3d( ($item-left-edit-left - $item-left-edit-open-width) / 2, 0, 0);\n  &.visible {\n    display: block;\n    &.active {\n      opacity: 1;\n      @include translate3d($item-left-edit-left, 0, 0);\n    }\n  }\n}\n.list-left-editing .item-left-edit {\n  @include transition-delay($item-edit-transition-duration / 2);\n}\n\n// Item Delete (Left side edit button)\n// -------------------------------\n\n.item-delete .button.icon {\n  color: $item-delete-icon-color;\n  font-size: $item-delete-icon-size;\n\n  &:hover {\n    opacity: .7;\n  }\n}\n\n\n// Item Right Edit Button\n// -------------------------------\n\n.item-right-edit {\n  @include transition(all $item-edit-transition-function $item-edit-transition-duration);\n  position: absolute;\n  top: 0;\n  right: 0;\n  z-index: $z-index-item-reorder;\n  width: $item-right-edit-open-width *  1.5;\n  height: 100%;\n  background: inherit;\n  padding-left: 20px;\n\n  .button {\n    min-width: $item-right-edit-open-width;\n    height: 100%;\n\n    &.icon {\n      @include display-flex();\n      @include align-items(center);\n      position: absolute;\n      top: 0;\n      height: 100%;\n      font-size: $item-reorder-icon-size;\n    }\n  }\n\n  display: block;\n  opacity: 0;\n  @include translate3d($item-right-edit-open-width *  1.5, 0, 0);\n  &.visible {\n    display: block;\n    &.active {\n      opacity: 1;\n      @include translate3d(0, 0, 0);\n    }\n  }\n}\n\n\n// Item Reordering (Right side edit button)\n// -------------------------------\n\n.item-reorder .button.icon {\n  color: $item-reorder-icon-color;\n  font-size: $item-reorder-icon-size;\n}\n\n.item-reordering {\n  // item is actively being reordered\n  position: absolute;\n  left: 0;\n  top: 0;\n  z-index: $z-index-item-reordering;\n  width: 100%;\n  box-shadow: 0px 0px 10px 0px #aaa;\n\n  .item-reorder {\n    z-index: $z-index-item-reordering;\n  }\n}\n\n.item-placeholder {\n  // placeholder for the item that's being reordered\n  opacity: 0.7;\n}\n\n\n/**\n * The hidden right-side buttons that can be exposed under a list item\n * with dragging.\n */\n.item-options {\n  position: absolute;\n  top: 0;\n  right: 0;\n  z-index: $z-index-item-options;\n  height: 100%;\n\n  .button {\n    height: 100%;\n    border: none;\n    border-radius: 0;\n    @include display-inline-flex();\n    @include align-items(center);\n\n    &:before{\n      margin: 0 auto;\n    }\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_list.scss",
    "content": "\n/**\n * Lists\n * --------------------------------------------------\n */\n\n.list {\n  position: relative;\n  padding-top: $item-border-width;\n  padding-bottom: $item-border-width;\n  padding-left: 0; // reset padding because ul and ol\n  margin-bottom: 20px;\n}\n.list:last-child {\n  margin-bottom: 0px;\n  &.card{\n    margin-bottom:40px;\n  }\n}\n\n\n/**\n * List Header\n * --------------------------------------------------\n */\n\n.list-header {\n  margin-top: $list-header-margin-top;\n  padding: $list-header-padding;\n  background-color: $list-header-bg;\n  color: $list-header-color;\n  font-weight: bold;\n}\n\n// when its a card make sure it doesn't duplicate top and bottom borders\n.card.list .list-item {\n  padding-right: 1px;\n  padding-left: 1px;\n}\n\n\n/**\n * Cards and Inset Lists\n * --------------------------------------------------\n * A card and list-inset are close to the same thing, except a card as a box shadow.\n */\n\n.card,\n.list-inset {\n  overflow: hidden;\n  margin: ($content-padding * 2) $content-padding;\n  border-radius: $card-border-radius;\n  background-color: $card-body-bg;\n}\n\n.card {\n  padding-top: $item-border-width;\n  padding-bottom: $item-border-width;\n  box-shadow: $card-box-shadow;\n\n  .item {\n    border-left: 0;\n    border-right: 0;\n  }\n  .item:first-child {\n    border-top: 0;\n  }\n  .item:last-child {\n    border-bottom: 0;\n  }\n}\n\n.padding {\n  .card, .list-inset {\n    margin-left: 0;\n    margin-right: 0;\n  }\n}\n\n.card .item,\n.list-inset .item,\n.padding > .list .item\n{\n  &:first-child {\n    border-top-left-radius: $card-border-radius;\n    border-top-right-radius: $card-border-radius;\n\n    .item-content {\n      border-top-left-radius: $card-border-radius;\n      border-top-right-radius: $card-border-radius;\n    }\n  }\n  &:last-child {\n    border-bottom-right-radius: $card-border-radius;\n    border-bottom-left-radius: $card-border-radius;\n\n    .item-content {\n      border-bottom-right-radius: $card-border-radius;\n      border-bottom-left-radius: $card-border-radius;\n    }\n  }\n}\n\n.card .item:last-child,\n.list-inset .item:last-child {\n  margin-bottom: $item-border-width * -1;\n}\n\n.card .item,\n.list-inset .item,\n.padding > .list .item,\n.padding-horizontal > .list .item {\n  margin-right: 0;\n  margin-left: 0;\n\n  &.item-input input {\n    padding-right: 44px;\n  }\n}\n.padding-left > .list .item {\n  margin-left: 0;\n}\n.padding-right > .list .item {\n  margin-right: 0;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_loading.scss",
    "content": "\n/**\n * Loading\n * --------------------------------------------------\n */\n\n.loading-container {\n  position: absolute;\n  left: 0;\n  top: 0;\n  right: 0;\n  bottom: 0;\n\n  z-index: $z-index-loading;\n\n  @include display-flex();\n  @include justify-content(center);\n  @include align-items(center);\n\n  @include transition(0.2s opacity linear);\n  visibility: hidden;\n  opacity: 0;\n\n  &:not(.visible) .icon {\n    display: none;\n  }\n  &.visible {\n    visibility: visible;\n  }\n  &.active {\n    opacity: 1;\n  }\n\n  .loading {\n    padding: $loading-padding;\n\n    border-radius: $loading-border-radius;\n    background-color: $loading-bg-color;\n\n    color: $loading-text-color;\n\n    text-align: center;\n    text-overflow: ellipsis;\n    font-size: $loading-font-size;\n\n    h1, h2, h3, h4, h5, h6 {\n      color: $loading-text-color;\n    }\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_menu.scss",
    "content": "\n/**\n * Menus\n * --------------------------------------------------\n * Side panel structure\n */\n\n.menu {\n  position: absolute;\n  top: 0;\n  bottom: 0;\n  z-index: $z-index-menu;\n  overflow: hidden;\n\n  min-height: 100%;\n  max-height: 100%;\n  width: $menu-width;\n\n  background-color: $menu-bg;\n\n  .scroll-content {\n    z-index: $z-index-menu-scroll-content;\n  }\n\n  .bar-header {\n    z-index: $z-index-menu-bar-header;\n  }\n}\n\n.menu-content {\n  @include transform(none);\n  box-shadow: $menu-side-shadow;\n}\n\n.menu-open .menu-content .pane,\n.menu-open .menu-content .scroll-content {\n  pointer-events: none;\n}\n\n.grade-b .menu-content,\n.grade-c .menu-content {\n  @include box-sizing(content-box);\n  right: -1px;\n  left: -1px;\n  border-right: 1px solid #ccc;\n  border-left: 1px solid #ccc;\n  box-shadow: none;\n}\n\n.menu-left {\n  left: 0;\n}\n\n.menu-right {\n  right: 0;\n}\n\n.aside-open.aside-resizing .menu-right {\n  display: none;\n}\n\n.menu-animated {\n  @include transition-transform($menu-animation-speed ease);\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_mixins.scss",
    "content": "\n// Button Mixins\n// --------------------------------------------------\n\n@mixin button-style($bg-color, $border-color, $active-bg-color, $active-border-color, $color) {\n  border-color: $border-color;\n  background-color: $bg-color;\n  color: $color;\n\n  // Give desktop users something to play with\n  &:hover {\n    color: $color;\n    text-decoration: none;\n  }\n  &.active,\n  &.activated {\n    border-color: $active-border-color;\n    background-color: $active-bg-color;\n    box-shadow: inset 0 1px 4px rgba(0,0,0,0.1);\n  }\n}\n\n@mixin button-clear($color, $font-size:\"\") {\n  &.button-clear {\n    border-color: transparent;\n    background: none;\n    box-shadow: none;\n    color: $color;\n\n    @if $font-size != \"\" {\n      font-size: $font-size;\n    }\n  }\n  &.button-icon {\n    border-color: transparent;\n    background: none;\n  }\n}\n\n@mixin button-outline($color, $text-color:\"\") {\n  &.button-outline {\n    border-color: $color;\n    background: transparent;\n    @if $text-color == \"\" {\n      $text-color: $color;\n    }\n    color: $text-color;\n    &.active,\n    &.activated {\n      background-color: $color;\n      box-shadow: none;\n      color: #fff;\n    }\n  }\n}\n\n\n// Bar Mixins\n// --------------------------------------------------\n\n@mixin bar-style($bg-color, $border-color, $color) {\n  border-color: $border-color;\n  background-color: $bg-color;\n  background-image: linear-gradient(0deg, $border-color, $border-color 50%, transparent 50%);\n  color: $color;\n\n  .title {\n    color: $color;\n  }\n}\n\n\n// Tab Mixins\n// --------------------------------------------------\n\n@mixin tab-style($bg-color, $border-color, $color) {\n  border-color: $border-color;\n  background-color: $bg-color;\n  background-image: linear-gradient(0deg, $border-color, $border-color 50%, transparent 50%);\n  color: $color;\n}\n\n@mixin tab-badge-style($bg-color, $color) {\n  .tab-item .badge {\n    background-color: $bg-color;\n    color: $color;\n  }\n}\n\n\n// Item Mixins\n// --------------------------------------------------\n\n@mixin item-style($bg-color, $border-color, $color) {\n  border-color: $border-color;\n  background-color: $bg-color;\n  color: $color;\n}\n\n@mixin item-active-style($active-bg-color, $active-border-color) {\n  border-color: $active-border-color;\n  background-color: $active-bg-color;\n}\n\n\n// Badge Mixins\n// --------------------------------------------------\n\n@mixin badge-style($bg-color, $color) {\n  background-color: $bg-color;\n  color: $color;\n}\n\n\n// Range Mixins\n// --------------------------------------------------\n\n@mixin range-style($track-bg-color) {\n  &::-webkit-slider-thumb:before {\n    background: $track-bg-color;\n  }\n  &::-ms-fill-lower{\n    background: $track-bg-color;\n  }\n}\n\n\n// Checkbox Mixins\n// --------------------------------------------------\n\n@mixin checkbox-style($off-border-color, $on-bg-color, $on-border-color) {\n  & input:before,\n  & .checkbox-icon:before {\n    border-color: $off-border-color;\n  }\n\n  // what the background looks like when its checked\n  & input:checked:before,\n  & input:checked + .checkbox-icon:before {\n    background: $on-bg-color;\n    border-color: $on-border-color;\n  }\n}\n\n\n// Toggle Mixins\n// --------------------------------------------------\n\n@mixin toggle-style($on-border-color, $on-bg-color) {\n  // the track when the toggle is \"on\"\n  & input:checked + .track {\n    border-color: $on-border-color;\n    background-color: $on-bg-color;\n  }\n}\n@mixin toggle-small-style($on-bg-color) {\n  // the track when the toggle is \"on\"\n  & input:checked + .track {\n    background-color: rgba($on-bg-color, .5);\n  }\n  & input:checked + .track .handle {\n    background-color: $on-bg-color;\n  }\n}\n\n\n// Clearfix\n// --------------------------------------------------\n\n@mixin clearfix {\n  *zoom: 1;\n  &:before,\n  &:after {\n    display: table;\n    content: \"\";\n    line-height: 0;\n  }\n  &:after {\n    clear: both;\n  }\n}\n\n\n// Placeholder text\n// --------------------------------------------------\n\n@mixin placeholder($color: $input-color-placeholder, $text-indent: 0) {\n  &::-moz-placeholder { // Firefox 19+\n    color: $color;\n  }\n  &:-ms-input-placeholder {\n    color: $color;\n  }\n  &::-webkit-input-placeholder {\n    color: $color;\n    // Safari placeholder margin issue\n    text-indent: $text-indent;\n  }\n}\n\n\n// Text Mixins\n// --------------------------------------------------\n\n@mixin text-size-adjust($value: none) {\n  -webkit-text-size-adjust: $value;\n     -moz-text-size-adjust: $value;\n          text-size-adjust: $value;\n}\n@mixin tap-highlight-transparent() {\n  -webkit-tap-highlight-color: rgba(0,0,0,0);\n  -webkit-tap-highlight-color: transparent; // For some Androids\n}\n@mixin touch-callout($value: none) {\n  -webkit-touch-callout: $value;\n}\n\n\n// Font Mixins\n// --------------------------------------------------\n\n@mixin font-family-serif() {\n  font-family: $serif-font-family;\n}\n@mixin font-family-sans-serif() {\n  font-family: $sans-font-family;\n}\n@mixin font-family-monospace() {\n  font-family: $mono-font-family;\n}\n@mixin font-shorthand($size: $base-font-size, $weight: normal, $line-height: $base-line-height) {\n  font-weight: $weight;\n  font-size: $size;\n  line-height: $line-height;\n}\n@mixin font-serif($size: $base-font-size, $weight: normal, $line-height: $base-line-height) {\n  @include font-family-serif();\n  @include font-shorthand($size, $weight, $line-height);\n}\n@mixin font-sans-serif($size: $base-font-size, $weight: normal, $line-height: $base-line-height) {\n  @include font-family-sans-serif();\n  @include font-shorthand($size, $weight, $line-height);\n}\n@mixin font-monospace($size: $base-font-size, $weight: normal, $line-height: $base-line-height) {\n  @include font-family-monospace();\n  @include font-shorthand($size, $weight, $line-height);\n}\n@mixin font-smoothing($font-smoothing) {\n  -webkit-font-smoothing: $font-smoothing;\n          font-smoothing: $font-smoothing;\n}\n\n\n// Appearance\n// --------------------------------------------------\n\n@mixin appearance($val) {\n  -webkit-appearance: $val;\n     -moz-appearance: $val;\n          appearance: $val;\n}\n\n\n// Border Radius Mixins\n// --------------------------------------------------\n\n@mixin border-radius($radius) {\n  -webkit-border-radius: $radius;\n          border-radius: $radius;\n}\n\n// Single Corner Border Radius\n@mixin border-top-left-radius($radius) {\n  -webkit-border-top-left-radius: $radius;\n          border-top-left-radius: $radius;\n}\n@mixin border-top-right-radius($radius) {\n  -webkit-border-top-right-radius: $radius;\n          border-top-right-radius: $radius;\n}\n@mixin border-bottom-right-radius($radius) {\n  -webkit-border-bottom-right-radius: $radius;\n          border-bottom-right-radius: $radius;\n}\n@mixin border-bottom-left-radius($radius) {\n  -webkit-border-bottom-left-radius: $radius;\n          border-bottom-left-radius: $radius;\n}\n\n// Single Side Border Radius\n@mixin border-top-radius($radius) {\n  @include border-top-right-radius($radius);\n  @include border-top-left-radius($radius);\n}\n@mixin border-right-radius($radius) {\n  @include border-top-right-radius($radius);\n  @include border-bottom-right-radius($radius);\n}\n@mixin border-bottom-radius($radius) {\n  @include border-bottom-right-radius($radius);\n  @include border-bottom-left-radius($radius);\n}\n@mixin border-left-radius($radius) {\n  @include border-top-left-radius($radius);\n  @include border-bottom-left-radius($radius);\n}\n\n\n// Box shadows\n// --------------------------------------------------\n\n@mixin box-shadow($shadow...) {\n  -webkit-box-shadow: $shadow;\n          box-shadow: $shadow;\n}\n\n\n// Transition Mixins\n// --------------------------------------------------\n\n@mixin transition($transition...) {\n  -webkit-transition: $transition;\n          transition: $transition;\n}\n@mixin transition-delay($transition-delay) {\n  -webkit-transition-delay: $transition-delay;\n          transition-delay: $transition-delay;\n}\n@mixin transition-duration($transition-duration) {\n  -webkit-transition-duration: $transition-duration;\n          transition-duration: $transition-duration;\n}\n@mixin transition-timing-function($transition-timing) {\n   -webkit-transition-timing-function: $transition-timing;\n           transition-timing-function: $transition-timing;\n }\n @mixin transition-property($property) {\n  -webkit-transition-property: $property;\n          transition-property: $property;\n}\n@mixin transition-transform($properties...) {\n  // special case cuz of transform vendor prefixes\n  -webkit-transition: -webkit-transform $properties;\n          transition: transform $properties;\n}\n\n\n// Animation Mixins\n// --------------------------------------------------\n\n@mixin animation($animation) {\n -webkit-animation: $animation;\n         animation: $animation;\n}\n@mixin animation-duration($duration) {\n -webkit-animation-duration: $duration;\n         animation-duration: $duration;\n}\n@mixin animation-direction($direction) {\n -webkit-animation-direction: $direction;\n         animation-direction: $direction;\n}\n@mixin animation-timing-function($animation-timing) {\n -webkit-animation-timing-function: $animation-timing;\n         animation-timing-function: $animation-timing;\n}\n@mixin animation-fill-mode($fill-mode) {\n -webkit-animation-fill-mode: $fill-mode;\n         animation-fill-mode: $fill-mode;\n}\n@mixin animation-name($name...) {\n -webkit-animation-name: $name;\n         animation-name: $name;\n}\n@mixin animation-iteration-count($count) {\n -webkit-animation-iteration-count: $count;\n         animation-iteration-count: $count;\n}\n\n\n// Transformation Mixins\n// --------------------------------------------------\n\n@mixin rotate($degrees) {\n  @include transform( rotate($degrees) );\n}\n@mixin scale($ratio) {\n  @include transform( scale($ratio) );\n}\n@mixin translate($x, $y) {\n  @include transform( translate($x, $y) );\n}\n@mixin skew($x, $y) {\n  @include transform( skew($x, $y) );\n  -webkit-backface-visibility: hidden;\n}\n@mixin translate3d($x, $y, $z) {\n  @include transform( translate3d($x, $y, $z) );\n}\n@mixin translateZ($z) {\n  @include transform( translateZ($z) );\n}\n@mixin transform($val) {\n  -webkit-transform: $val;\n          transform: $val;\n}\n\n@mixin transform-origin($left, $top) {\n  -webkit-transform-origin: $left $top;\n          transform-origin: $left $top;\n}\n\n\n// Backface visibility\n// --------------------------------------------------\n// Prevent browsers from flickering when using CSS 3D transforms.\n// Default value is `visible`, but can be changed to `hidden\n\n@mixin backface-visibility($visibility){\n  -webkit-backface-visibility: $visibility;\n          backface-visibility: $visibility;\n}\n\n\n// Background clipping\n// --------------------------------------------------\n\n@mixin background-clip($clip) {\n  -webkit-background-clip: $clip;\n          background-clip: $clip;\n}\n\n\n// Background sizing\n// --------------------------------------------------\n\n@mixin background-size($size) {\n  -webkit-background-size: $size;\n          background-size: $size;\n}\n\n\n// Box sizing\n// --------------------------------------------------\n\n@mixin box-sizing($boxmodel) {\n  -webkit-box-sizing: $boxmodel;\n     -moz-box-sizing: $boxmodel;\n          box-sizing: $boxmodel;\n}\n\n\n// User select\n// --------------------------------------------------\n\n@mixin user-select($select) {\n  -webkit-user-select: $select;\n     -moz-user-select: $select;\n      -ms-user-select: $select;\n          user-select: $select;\n}\n\n\n// Content Columns\n// --------------------------------------------------\n\n@mixin content-columns($columnCount, $columnGap: $grid-gutter-width) {\n  -webkit-column-count: $columnCount;\n     -moz-column-count: $columnCount;\n          column-count: $columnCount;\n  -webkit-column-gap: $columnGap;\n     -moz-column-gap: $columnGap;\n          column-gap: $columnGap;\n}\n\n\n// Flexbox Mixins\n// --------------------------------------------------\n// http://philipwalton.github.io/solved-by-flexbox/\n// https://github.com/philipwalton/solved-by-flexbox\n\n@mixin display-flex {\n  display: -webkit-box;\n  display: -webkit-flex;\n  display: -moz-box;\n  display: -moz-flex;\n  display: -ms-flexbox;\n  display: flex;\n}\n\n@mixin display-inline-flex {\n  display: -webkit-inline-box;\n  display: -webkit-inline-flex;\n  display: -moz-inline-flex;\n  display: -ms-inline-flexbox;\n  display: inline-flex;\n}\n\n@mixin flex-direction($value: row) {\n  @if $value == row-reverse {\n    -webkit-box-direction: reverse;\n    -webkit-box-orient: horizontal;\n  } @else if $value == column {\n    -webkit-box-direction: normal;\n    -webkit-box-orient: vertical;\n  } @else if $value == column-reverse {\n    -webkit-box-direction: reverse;\n    -webkit-box-orient: vertical;\n  } @else {\n    -webkit-box-direction: normal;\n    -webkit-box-orient: horizontal;\n  }\n  -webkit-flex-direction: $value;\n  -moz-flex-direction: $value;\n  -ms-flex-direction: $value;\n  flex-direction: $value;\n}\n\n@mixin flex-wrap($value: nowrap) {\n  // No Webkit Box fallback.\n  -webkit-flex-wrap: $value;\n  -moz-flex-wrap: $value;\n  @if $value == nowrap {\n      -ms-flex-wrap: none;\n  } @else {\n      -ms-flex-wrap: $value;\n  }\n  flex-wrap: $value;\n}\n\n@mixin flex($fg: 1, $fs: null, $fb: null) {\n  -webkit-box-flex: $fg;\n  -webkit-flex: $fg $fs $fb;\n  -moz-box-flex: $fg;\n  -moz-flex: $fg $fs $fb;\n  -ms-flex: $fg $fs $fb;\n  flex: $fg $fs $fb;\n}\n\n@mixin flex-flow($values: (row nowrap)) {\n  // No Webkit Box fallback.\n  -webkit-flex-flow: $values;\n  -moz-flex-flow: $values;\n  -ms-flex-flow: $values;\n  flex-flow: $values;\n}\n\n@mixin align-items($value: stretch) {\n  @if $value == flex-start {\n    -webkit-box-align: start;\n    -ms-flex-align: start;\n  } @else if $value == flex-end {\n    -webkit-box-align: end;\n    -ms-flex-align: end;\n  } @else {\n    -webkit-box-align: $value;\n    -ms-flex-align: $value;\n  }\n  -webkit-align-items: $value;\n  -moz-align-items: $value;\n  align-items: $value;\n}\n\n@mixin align-self($value: auto) {\n  -webkit-align-self: $value;\n  -moz-align-self: $value;\n  @if $value == flex-start {\n    -ms-flex-item-align: start;\n  } @else if $value == flex-end {\n    -ms-flex-item-align: end;\n  } @else {\n    -ms-flex-item-align: $value;\n  }\n  align-self: $value;\n}\n\n@mixin align-content($value: stretch) {\n  -webkit-align-content: $value;\n  -moz-align-content: $value;\n  @if $value == flex-start {\n    -ms-flex-line-pack: start;\n  } @else if $value == flex-end {\n    -ms-flex-line-pack: end;\n  } @else {\n    -ms-flex-line-pack: $value;\n  }\n  align-content: $value;\n}\n\n@mixin justify-content($value: stretch) {\n  @if $value == flex-start {\n    -webkit-box-pack: start;\n    -ms-flex-pack: start;\n  } @else if $value == flex-end {\n    -webkit-box-pack: end;\n    -ms-flex-pack: end;\n  } @else if $value == space-between {\n    -webkit-box-pack: justify;\n    -ms-flex-pack: justify;\n  } @else {\n    -webkit-box-pack: $value;\n    -ms-flex-pack: $value;\n  }\n  -webkit-justify-content: $value;\n  -moz-justify-content: $value;\n  justify-content: $value;\n}\n\n@mixin flex-order($n) {\n  -webkit-order: $n;\n  -ms-flex-order: $n;\n  order: $n;\n  -webkit-box-ordinal-group: $n;\n}\n\n@mixin responsive-grid-break($selector, $max-width) {\n  @media (max-width: $max-width) {\n    #{$selector} {\n      -webkit-box-direction: normal;\n      -moz-box-direction: normal;\n      -webkit-box-orient: vertical;\n      -moz-box-orient: vertical;\n      -webkit-flex-direction: column;\n      -ms-flex-direction: column;\n      flex-direction: column;\n\n      .col, .col-10, .col-20, .col-25, .col-33, .col-34, .col-50, .col-66, .col-67, .col-75, .col-80, .col-90 {\n        @include flex(1);\n        margin-bottom: ($grid-padding-width * 3) / 2;\n        margin-left: 0;\n        max-width: 100%;\n        width: 100%;\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_modal.scss",
    "content": "\n/**\n * Modals\n * --------------------------------------------------\n * Modals are independent windows that slide in from off-screen.\n */\n\n.modal-backdrop,\n.modal-backdrop-bg {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: $z-index-modal;\n  width: 100%;\n  height: 100%;\n}\n\n.modal-backdrop-bg {\n  pointer-events: none;\n}\n\n.modal {\n  display: block;\n  position: absolute;\n  top: 0;\n  z-index: $z-index-modal;\n  overflow: hidden;\n  min-height: 100%;\n  width: 100%;\n  background-color: $modal-bg-color;\n}\n\n@media (min-width: $modal-inset-mode-break-point) {\n  // inset mode is when the modal doesn't fill the entire\n  // display but instead is centered within a large display\n  .modal {\n    top: $modal-inset-mode-top;\n    right: $modal-inset-mode-right;\n    bottom: $modal-inset-mode-bottom;\n    left: $modal-inset-mode-left;\n    min-height: $modal-inset-mode-min-height;\n    width: (100% - $modal-inset-mode-left - $modal-inset-mode-right);\n  }\n\n  .modal.ng-leave-active {\n    bottom: 0;\n  }\n\n  // remove ios header padding from inset header\n  .platform-ios.platform-cordova .modal-wrapper .modal {\n    .bar-header:not(.bar-subheader) {\n      height: $bar-height;\n      > * {\n        margin-top: 0;\n      }\n    }\n    .tabs-top > .tabs,\n    .tabs.tabs-top {\n      top: $bar-height;\n    }\n    .has-header,\n    .bar-subheader {\n      top: $bar-height;\n    }\n    .has-subheader {\n      top: $bar-height + $bar-subheader-height;\n    }\n    .has-header.has-tabs-top {\n      top: $bar-height + $tabs-height;\n    }\n    .has-header.has-subheader.has-tabs-top {\n      top: $bar-height + $bar-subheader-height + $tabs-height;\n    }\n  }\n\n  .modal-backdrop-bg {\n    @include transition(opacity 300ms ease-in-out);\n    background-color: $modal-backdrop-bg-active;\n    opacity: 0;\n  }\n\n  .active .modal-backdrop-bg {\n    opacity: 0.5;\n  }\n}\n\n// disable clicks on all but the modal\n.modal-open {\n  pointer-events: none;\n\n  .modal,\n  .modal-backdrop {\n    pointer-events: auto;\n  }\n  // prevent clicks on modal when loading overlay is active though\n  &.loading-active {\n    .modal,\n    .modal-backdrop {\n      pointer-events: none;\n    }\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_platform.scss",
    "content": "\n/**\n * Platform\n * --------------------------------------------------\n * Platform specific tweaks\n */\n\n.platform-ios.platform-cordova {\n  // iOS has a status bar which sits on top of the header.\n  // Bump down everything to make room for it. However, if\n  // if its in Cordova, and set to fullscreen, then disregard the bump.\n  &:not(.fullscreen) {\n    .bar-header:not(.bar-subheader) {\n      height: $bar-height + $ios-statusbar-height;\n\n      &.item-input-inset .item-input-wrapper {\n        margin-top: 19px !important;\n      }\n\n      > * {\n        margin-top: $ios-statusbar-height;\n      }\n    }\n    .tabs-top > .tabs,\n    .tabs.tabs-top {\n      top: $bar-height + $ios-statusbar-height;\n    }\n\n    .has-header,\n    .bar-subheader {\n      top: $bar-height + $ios-statusbar-height;\n    }\n    .has-subheader {\n      top: $bar-height + $bar-subheader-height + $ios-statusbar-height;\n    }\n    .has-header.has-tabs-top {\n      top: $bar-height + $tabs-height + $ios-statusbar-height;\n    }\n    .has-header.has-subheader.has-tabs-top {\n      top: $bar-height + $bar-subheader-height + $tabs-height + $ios-statusbar-height;\n    }\n  }\n  &.status-bar-hide {\n    // Cordova doesn't adjust the body height correctly, this makes up for it\n    margin-bottom: 20px;\n  }\n}\n\n@media (orientation:landscape) {\n  .platform-ios.platform-browser.platform-ipad {\n    position: fixed; // required for iPad 7 Safari\n  }\n}\n\n.platform-c:not(.enable-transitions) * {\n  // disable transitions on grade-c devices (Android 2)\n  -webkit-transition: none !important;\n  transition: none !important;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_popover.scss",
    "content": "\n/**\n * Popovers\n * --------------------------------------------------\n * Popovers are independent views which float over content\n */\n\n.popover-backdrop {\n  position: fixed;\n  top: 0;\n  left: 0;\n  z-index: $z-index-popover;\n  width: 100%;\n  height: 100%;\n  background-color: $popover-backdrop-bg-inactive;\n\n  &.active {\n    background-color: $popover-backdrop-bg-active;\n  }\n}\n\n.popover {\n  position: absolute;\n  top: 25%;\n  left: 50%;\n  z-index: $z-index-popover;\n  display: block;\n  margin-top: 12px;\n  margin-left: -$popover-width / 2;\n  height: $popover-height;\n  width: $popover-width;\n  background-color: $popover-bg-color;\n  box-shadow: $popover-box-shadow;\n  opacity: 0;\n\n  .item:first-child {\n    border-top: 0;\n  }\n\n  .item:last-child {\n    border-bottom: 0;\n  }\n\n  &.popover-bottom {\n    margin-top: -12px;\n  }\n}\n\n\n// Set popover border-radius\n.popover,\n.popover .bar-header {\n  border-radius: $popover-border-radius;\n}\n.popover .scroll-content {\n  z-index: 1;\n  margin: 2px 0;\n}\n.popover .bar-header {\n  border-bottom-right-radius: 0;\n  border-bottom-left-radius: 0;\n}\n.popover .has-header {\n  border-top-right-radius: 0;\n  border-top-left-radius: 0;\n}\n.popover-arrow {\n  display: none;\n}\n\n\n// iOS Popover\n.platform-ios {\n\n  .popover {\n    box-shadow: $popover-box-shadow-ios;\n    border-radius: $popover-border-radius-ios;\n  }\n  .popover .bar-header {\n    @include border-top-radius($popover-border-radius-ios);\n  }\n  .popover .scroll-content {\n    margin: 8px 0;\n    border-radius: $popover-border-radius-ios;\n  }\n  .popover .scroll-content.has-header {\n    margin-top: 0;\n  }\n  .popover-arrow {\n    position: absolute;\n    display: block;\n    top: -17px;\n    width: 30px;\n    height: 19px;\n    overflow: hidden;\n\n    &:after {\n      position: absolute;\n      top: 12px;\n      left: 5px;\n      width: 20px;\n      height: 20px;\n      background-color: $popover-bg-color;\n      border-radius: 3px;\n      content: '';\n      @include rotate(-45deg);\n    }\n  }\n  .popover-bottom .popover-arrow {\n    top: auto;\n    bottom: -10px;\n    &:after {\n      top: -6px;\n    }\n  }\n}\n\n\n// Android Popover\n.platform-android {\n\n  .popover {\n    margin-top: -32px;\n    background-color: $popover-bg-color-android;\n    box-shadow: $popover-box-shadow-android;\n\n    .item {\n      border-color: $popover-bg-color-android;\n      background-color: $popover-bg-color-android;\n      color: #4d4d4d;\n    }\n    &.popover-bottom {\n      margin-top: 32px;\n    }\n  }\n\n  .popover-backdrop,\n  .popover-backdrop.active {\n    background-color: transparent;\n  }\n}\n\n\n// disable clicks on all but the popover\n.popover-open {\n  pointer-events: none;\n\n  .popover,\n  .popover-backdrop {\n    pointer-events: auto;\n  }\n  // prevent clicks on popover when loading overlay is active though\n  &.loading-active {\n    .popover,\n    .popover-backdrop {\n      pointer-events: none;\n    }\n  }\n}\n\n\n// wider popover on larger viewports\n@media (min-width: $popover-large-break-point) {\n  .popover {\n    width: $popover-large-width;\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_popup.scss",
    "content": "\n/**\n * Popups\n * --------------------------------------------------\n */\n\n.popup-container {\n  position: absolute;\n  top: 0;\n  left: 0;\n  bottom: 0;\n  right: 0;\n  background: rgba(0,0,0,0);\n\n  @include display-flex();\n  @include justify-content(center);\n  @include align-items(center);\n\n  z-index: $z-index-popup;\n\n  // Start hidden\n  visibility: hidden;\n  &.popup-showing {\n    visibility: visible;\n  }\n\n  &.popup-hidden .popup {\n    @include animation-name(scaleOut);\n    @include animation-duration($popup-leave-animation-duration);\n    @include animation-timing-function(ease-in-out);\n    @include animation-fill-mode(both);\n  }\n\n  &.active .popup {\n    @include animation-name(superScaleIn);\n    @include animation-duration($popup-enter-animation-duration);\n    @include animation-timing-function(ease-in-out);\n    @include animation-fill-mode(both);\n  }\n\n  .popup {\n    width: $popup-width;\n    max-width: 100%;\n    max-height: 90%;\n\n    border-radius: $popup-border-radius;\n    background-color: $popup-background-color;\n\n    @include display-flex();\n    @include flex-direction(column);\n  }\n\n  input,\n  textarea {\n    width: 100%;\n  }\n}\n\n.popup-head {\n  padding: 15px 10px;\n  border-bottom: 1px solid #eee;\n  text-align: center;\n}\n.popup-title {\n  margin: 0;\n  padding: 0;\n  font-size: 15px;\n}\n.popup-sub-title {\n  margin: 5px 0 0 0;\n  padding: 0;\n  font-weight: normal;\n  font-size: 11px;\n}\n.popup-body {\n  padding: 10px;\n  overflow: auto;\n}\n\n.popup-buttons {\n  @include display-flex();\n  @include flex-direction(row);\n  padding: 10px;\n  min-height: $popup-button-min-height + 20;\n\n  .button {\n    @include flex(1);\n    display: block;\n    min-height: $popup-button-min-height;\n    border-radius: $popup-button-border-radius;\n    line-height: $popup-button-line-height;\n\n    margin-right: 5px;\n    &:last-child {\n      margin-right: 0px;\n    }\n  }\n}\n\n.popup-open {\n  pointer-events: none;\n\n  &.modal-open .modal {\n    pointer-events: none;\n  }\n\n  .popup-backdrop, .popup {\n    pointer-events: auto;\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_progress.scss",
    "content": "\n/**\n * Progress\n * --------------------------------------------------\n */\n\nprogress {\n  display: block;\n  margin: $progress-margin;\n  width: $progress-width;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_radio.scss",
    "content": "\n/**\n * Radio Button Inputs\n * --------------------------------------------------\n */\n\n.item-radio {\n  padding: 0;\n\n  &:hover {\n    cursor: pointer;\n  }\n}\n\n.item-radio .item-content {\n  /* give some room to the right for the checkmark icon */\n  padding-right: $item-padding * 4;\n}\n\n.item-radio .radio-icon {\n  /* checkmark icon will be hidden by default */\n  position: absolute;\n  top: 0;\n  right: 0;\n  z-index: $z-index-item-radio;\n  visibility: hidden;\n  padding: $item-padding - 2;\n  height: 100%;\n  font-size: 24px;\n}\n\n.item-radio input {\n  /* hide any radio button inputs elements (the ugly circles) */\n  position: absolute;\n  left: -9999px;\n\n  &:checked ~ .item-content {\n    /* style the item content when its checked */\n    background: #f7f7f7;\n  }\n\n  &:checked ~ .radio-icon {\n    /* show the checkmark icon when its checked */\n    visibility: visible;\n  }\n}\n\n// Hack for Android to correctly display the checked item\n// http://timpietrusky.com/advanced-checkbox-hack\n.platform-android.grade-b .item-radio,\n.platform-android.grade-c .item-radio {\n  -webkit-animation: androidCheckedbugfix infinite 1s;\n}\n@-webkit-keyframes androidCheckedbugfix {\n  from { padding: 0; }\n  to { padding: 0; }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_range.scss",
    "content": "\n/**\n * Range\n * --------------------------------------------------\n */\n\n .range input{\n  display: inline-block;\n  overflow: hidden;\n  margin-top: 5px;\n  margin-bottom: 5px;\n  padding-right: 2px;\n  padding-left: 1px;\n  width: auto;\n  height: $range-slider-height + 15;\n  outline: none;\n  background: -webkit-gradient(linear, 50% 0%, 50% 100%, color-stop(0%, $range-default-track-bg), color-stop(100%, $range-default-track-bg));\n  background: linear-gradient(to right, $range-default-track-bg 0%, $range-default-track-bg 100%);\n  background-position: center;\n  background-size: 99% $range-track-height;\n  background-repeat: no-repeat;\n  -webkit-appearance: none;\n\n  &::-webkit-slider-thumb {\n    position: relative;\n    width: $range-slider-width;\n    height: $range-slider-height;\n    border-radius: $range-slider-border-radius;\n    background-color: $toggle-handle-off-bg-color;\n    box-shadow: $range-slider-box-shadow;\n    cursor: pointer;\n    -webkit-appearance: none;\n    border: 0;\n  }\n\n  &::-webkit-slider-thumb:before{\n    /* what creates the colorful line on the left side of the slider */\n    position: absolute;\n    top: ($range-slider-height / 2) - ($range-track-height / 2);\n    left: -2001px;\n    width: 2000px;\n    height: $range-track-height;\n    background: $dark;\n    content: ' ';\n  }\n\n  &::-webkit-slider-thumb:after {\n    /* create a larger (but hidden) hit area */\n    position: absolute;\n    top: -15px;\n    left: -15px;\n    padding: 30px;\n    content: ' ';\n    //background: red;\n    //opacity: .5;\n  }\n   &::-ms-track{\n     background: transparent;\n     border-color: transparent;\n     border-width: 11px 0 16px;\n     color:transparent;\n     margin-top:20px;\n   }\n   &::-ms-thumb {\n     width: $range-slider-width;\n     height: $range-slider-height;\n     border-radius: $range-slider-border-radius;\n     background-color: $toggle-handle-off-bg-color;\n     border-color:$toggle-handle-off-bg-color;\n     box-shadow: $range-slider-box-shadow;\n     margin-left:1px;\n     margin-right:1px;\n     outline:none;\n   }\n   &::-ms-fill-lower{\n     height: $range-track-height;\n     background:$dark;\n   }\n   &::-ms-fill-upper {\n     height: $range-track-height;\n     background:$range-default-track-bg;\n   }\n}\n\n.range {\n  @include display-flex();\n  @include align-items(center);\n  padding: 2px 11px;\n\n  &.range-light {\n    input { @include range-style($range-light-track-bg); }\n  }\n  &.range-stable {\n    input { @include range-style($range-stable-track-bg); }\n  }\n  &.range-positive {\n    input { @include range-style($range-positive-track-bg); }\n  }\n  &.range-calm {\n    input { @include range-style($range-calm-track-bg); }\n  }\n  &.range-balanced {\n    input { @include range-style($range-balanced-track-bg); }\n  }\n  &.range-assertive {\n    input { @include range-style($range-assertive-track-bg); }\n  }\n  &.range-energized {\n    input { @include range-style($range-energized-track-bg); }\n  }\n  &.range-royal {\n    input { @include range-style($range-royal-track-bg); }\n  }\n  &.range-dark {\n    input { @include range-style($range-dark-track-bg); }\n  }\n}\n\n.range .icon {\n  @include flex(0);\n  display: block;\n  min-width: $range-icon-size;\n  text-align: center;\n  font-size: $range-icon-size;\n}\n\n.range input {\n  @include flex(1);\n  display: block;\n  margin-right: 10px;\n  margin-left: 10px;\n}\n\n.range-label {\n  @include flex(0, 0, auto);\n  display: block;\n  white-space: nowrap;\n}\n\n.range-label:first-child {\n  padding-left: 5px;\n}\n.range input + .range-label {\n  padding-right: 5px;\n  padding-left: 0;\n}\n\n// WP range height must be auto\n.platform-windowsphone{\n  .range input{\n    height:auto;\n  }\n}"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_refresher.scss",
    "content": "\n// Scroll refresher (for pull to refresh)\n.scroll-refresher {\n  position: absolute;\n  top: -60px;\n  right: 0;\n  left: 0;\n  overflow: hidden;\n  margin: auto;\n  height: 60px;\n  .ionic-refresher-content {\n    position: absolute;\n    bottom: 15px;\n    left: 0;\n    width: 100%;\n    color: $scroll-refresh-icon-color;\n    text-align: center;\n\n    font-size: 30px;\n\n    .text-refreshing,\n    .text-pulling {\n      font-size: 16px;\n      line-height: 16px;\n    }\n    &.ionic-refresher-with-text {\n      bottom: 10px;\n    }\n  }\n\n  .icon-refreshing,\n  .icon-pulling {\n    width: 100%;\n    -webkit-backface-visibility: hidden;\n    backface-visibility: hidden;\n    -webkit-transform-style: preserve-3d;\n    transform-style: preserve-3d;\n  }\n  .icon-pulling {\n    @include animation-name(refresh-spin-back);\n    @include animation-duration(200ms);\n    @include animation-timing-function(linear);\n    @include animation-fill-mode(none);\n    -webkit-transform: translate3d(0,0,0) rotate(0deg);\n    transform: translate3d(0,0,0) rotate(0deg);\n  }\n  .icon-refreshing,\n  .text-refreshing {\n    display: none;\n  }\n  .icon-refreshing {\n    @include animation-duration(1.5s);\n  }\n\n  &.active {\n    .icon-pulling:not(.pulling-rotation-disabled) {\n      @include animation-name(refresh-spin);\n      -webkit-transform: translate3d(0,0,0) rotate(-180deg);\n      transform: translate3d(0,0,0) rotate(-180deg);\n    }\n    &.refreshing {\n      @include transition(-webkit-transform .2s);\n      @include transition(transform .2s);\n      -webkit-transform: scale(1,1);\n      transform: scale(1,1);\n\n      .icon-pulling,\n      .text-pulling {\n        display: none;\n      }\n      .icon-refreshing,\n      .text-refreshing {\n        display: block;\n      }\n      &.refreshing-tail {\n        -webkit-transform: scale(0,0);\n        transform: scale(0,0);\n      }\n    }\n  }\n}\n.overflow-scroll > .scroll{\n  &.overscroll{\n    position:fixed;\n  }\n  -webkit-overflow-scrolling:touch;\n  width:100%;\n}\n\n@-webkit-keyframes refresh-spin {\n  0%   { -webkit-transform: translate3d(0,0,0) rotate(0); }\n  100% { -webkit-transform: translate3d(0,0,0) rotate(180deg); }\n}\n\n@keyframes refresh-spin {\n  0%   { transform: translate3d(0,0,0) rotate(0); }\n  100% { transform: translate3d(0,0,0) rotate(180deg); }\n}\n\n@-webkit-keyframes refresh-spin-back {\n  0%   { -webkit-transform: translate3d(0,0,0) rotate(180deg); }\n  100% { -webkit-transform: translate3d(0,0,0) rotate(0); }\n}\n\n@keyframes refresh-spin-back {\n  0%   { transform: translate3d(0,0,0) rotate(180deg); }\n  100% { transform: translate3d(0,0,0) rotate(0); }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_reset.scss",
    "content": "\n/**\n * Resets\n * --------------------------------------------------\n * Adapted from normalize.css and some reset.css. We don't care even one\n * bit about old IE, so we don't need any hacks for that in here.\n *\n * There are probably other things we could remove here, as well.\n *\n * normalize.css v2.1.2 | MIT License | git.io/normalize\n\n * Eric Meyer's Reset CSS v2.0 (http://meyerweb.com/eric/tools/css/reset/)\n * http://cssreset.com\n */\n\nhtml, body, div, span, applet, object, iframe,\nh1, h2, h3, h4, h5, h6, p, blockquote, pre,\na, abbr, acronym, address, big, cite, code,\ndel, dfn, em, img, ins, kbd, q, s, samp,\nsmall, strike, strong, sub, sup, tt, var,\nb, i, u, center,\ndl, dt, dd, ol, ul, li,\nfieldset, form, label, legend,\ntable, caption, tbody, tfoot, thead, tr, th, td,\narticle, aside, canvas, details, embed, fieldset,\nfigure, figcaption, footer, header, hgroup,\nmenu, nav, output, ruby, section, summary,\ntime, mark, audio, video {\n  margin: 0;\n  padding: 0;\n  border: 0;\n  vertical-align: baseline;\n  font: inherit;\n  font-size: 100%;\n}\n\nol, ul {\n  list-style: none;\n}\nblockquote, q {\n  quotes: none;\n}\nblockquote:before, blockquote:after,\nq:before, q:after {\n  content: '';\n  content: none;\n}\n\n/**\n * Prevent modern browsers from displaying `audio` without controls.\n * Remove excess height in iOS 5 devices.\n */\n\naudio:not([controls]) {\n  display: none;\n  height: 0;\n}\n\n/**\n * Hide the `template` element in IE, Safari, and Firefox < 22.\n */\n\n[hidden],\ntemplate {\n  display: none;\n}\n\nscript {\n  display: none !important;\n}\n\n/* ==========================================================================\n   Base\n   ========================================================================== */\n\n/**\n * 1. Set default font family to sans-serif.\n * 2. Prevent iOS text size adjust after orientation change, without disabling\n *  user zoom.\n */\n\nhtml {\n  @include user-select(none);\n  font-family: sans-serif; /* 1 */\n  -webkit-text-size-adjust: 100%;\n  -ms-text-size-adjust: 100%; /* 2 */\n  -webkit-text-size-adjust: 100%; /* 2 */\n}\n\n/**\n * Remove default margin.\n */\n\nbody {\n  margin: 0;\n  line-height: 1;\n}\n\n\n/**\n * Remove default outlines.\n */\na,\nbutton,\n:focus,\na:focus,\nbutton:focus,\na:active,\na:hover {\n  outline: 0;\n}\n\n/* *\n * Remove tap highlight color\n */\n\na {\n  -webkit-user-drag: none;\n  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);\n  -webkit-tap-highlight-color: transparent;\n\n  &[href]:hover {\n    cursor: pointer;\n  }\n}\n\n/* ==========================================================================\n   Typography\n   ========================================================================== */\n\n\n/**\n * Address style set to `bolder` in Firefox 4+, Safari 5, and Chrome.\n */\n\nb,\nstrong {\n  font-weight: bold;\n}\n\n/**\n * Address styling not present in Safari 5 and Chrome.\n */\n\ndfn {\n  font-style: italic;\n}\n\n/**\n * Address differences between Firefox and other browsers.\n */\n\nhr {\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n  height: 0;\n}\n\n\n/**\n * Correct font family set oddly in Safari 5 and Chrome.\n */\n\ncode,\nkbd,\npre,\nsamp {\n  font-size: 1em;\n  font-family: monospace, serif;\n}\n\n/**\n * Improve readability of pre-formatted text in all browsers.\n */\n\npre {\n  white-space: pre-wrap;\n}\n\n/**\n * Set consistent quote types.\n */\n\nq {\n  quotes: \"\\201C\" \"\\201D\" \"\\2018\" \"\\2019\";\n}\n\n/**\n * Address inconsistent and variable font size in all browsers.\n */\n\nsmall {\n  font-size: 80%;\n}\n\n/**\n * Prevent `sub` and `sup` affecting `line-height` in all browsers.\n */\n\nsub,\nsup {\n  position: relative;\n  vertical-align: baseline;\n  font-size: 75%;\n  line-height: 0;\n}\n\nsup {\n  top: -0.5em;\n}\n\nsub {\n  bottom: -0.25em;\n}\n\n/**\n * Define consistent border, margin, and padding.\n */\n\nfieldset {\n  margin: 0 2px;\n  padding: 0.35em 0.625em 0.75em;\n  border: 1px solid #c0c0c0;\n}\n\n/**\n * 1. Correct `color` not being inherited in IE 8/9.\n * 2. Remove padding so people aren't caught out if they zero out fieldsets.\n */\n\nlegend {\n  padding: 0; /* 2 */\n  border: 0; /* 1 */\n}\n\n/**\n * 1. Correct font family not being inherited in all browsers.\n * 2. Correct font size not being inherited in all browsers.\n * 3. Address margins set differently in Firefox 4+, Safari 5, and Chrome.\n * 4. Remove any default :focus styles\n * 5. Make sure webkit font smoothing is being inherited\n * 6. Remove default gradient in Android Firefox / FirefoxOS\n */\n\nbutton,\ninput,\nselect,\ntextarea {\n  margin: 0; /* 3 */\n  font-size: 100%; /* 2 */\n  font-family: inherit; /* 1 */\n  outline-offset: 0; /* 4 */\n  outline-style: none; /* 4 */\n  outline-width: 0; /* 4 */\n  -webkit-font-smoothing: inherit; /* 5 */\n  background-image: none; /* 6 */\n}\n\n/**\n * Address Firefox 4+ setting `line-height` on `input` using `importnt` in\n * the UA stylesheet.\n */\n\nbutton,\ninput {\n  line-height: normal;\n}\n\n/**\n * Address inconsistent `text-transform` inheritance for `button` and `select`.\n * All other form control elements do not inherit `text-transform` values.\n * Correct `button` style inheritance in Chrome, Safari 5+, and IE 8+.\n * Correct `select` style inheritance in Firefox 4+ and Opera.\n */\n\nbutton,\nselect {\n  text-transform: none;\n}\n\n/**\n * 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`\n *  and `video` controls.\n * 2. Correct inability to style clickable `input` types in iOS.\n * 3. Improve usability and consistency of cursor style between image-type\n *  `input` and others.\n */\n\nbutton,\nhtml input[type=\"button\"], /* 1 */\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n  cursor: pointer; /* 3 */\n  -webkit-appearance: button; /* 2 */\n}\n\n/**\n * Re-set default cursor for disabled elements.\n */\n\nbutton[disabled],\nhtml input[disabled] {\n  cursor: default;\n}\n\n/**\n * 1. Address `appearance` set to `searchfield` in Safari 5 and Chrome.\n * 2. Address `box-sizing` set to `border-box` in Safari 5 and Chrome\n *  (include `-moz` to future-proof).\n */\n\ninput[type=\"search\"] {\n  -webkit-box-sizing: content-box; /* 2 */\n  -moz-box-sizing: content-box;\n  box-sizing: content-box;\n  -webkit-appearance: textfield; /* 1 */\n}\n\n/**\n * Remove inner padding and search cancel button in Safari 5 and Chrome\n * on OS X.\n */\n\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n  -webkit-appearance: none;\n}\n\n/**\n * Remove inner padding and border in Firefox 4+.\n */\n\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n  padding: 0;\n  border: 0;\n}\n\n/**\n * 1. Remove default vertical scrollbar in IE 8/9.\n * 2. Improve readability and alignment in all browsers.\n */\n\ntextarea {\n  overflow: auto; /* 1 */\n  vertical-align: top; /* 2 */\n}\n\n\nimg {\n  -webkit-user-drag: none;\n}\n\n/* ==========================================================================\n   Tables\n   ========================================================================== */\n\n/**\n * Remove most spacing between table cells.\n */\n\ntable {\n  border-spacing: 0;\n  border-collapse: collapse;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_scaffolding.scss",
    "content": "\n/**\n * Scaffolding\n * --------------------------------------------------\n */\n\n*,\n*:before,\n*:after {\n  @include box-sizing(border-box);\n}\n\nhtml {\n  overflow: hidden;\n  -ms-touch-action: pan-y;\n  touch-action: pan-y;\n}\n\nbody,\n.ionic-body {\n  @include touch-callout(none);\n  @include font-smoothing(antialiased);\n  @include text-size-adjust(none);\n  @include tap-highlight-transparent();\n  @include user-select(none);\n\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  overflow: hidden;\n\n  margin: 0;\n  padding: 0;\n\n  color: $base-color;\n  word-wrap: break-word;\n  font-size: $font-size-base;\n  font-family: $font-family-base;\n  line-height: $line-height-computed;\n  text-rendering: optimizeLegibility;\n  -webkit-backface-visibility: hidden;\n  -webkit-user-drag: none;\n  -ms-content-zooming: none;\n}\n\nbody.grade-b,\nbody.grade-c {\n  // disable optimizeLegibility for low end devices\n  text-rendering: auto;\n}\n\n.content {\n  // used for content areas not using the content directive\n  position: relative;\n}\n\n.scroll-content {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  overflow: hidden;\n\n  // Hide the top border if any\n  margin-top: -1px;\n\n  // Prevents any distortion of lines\n  padding-top: 1px;\n  margin-bottom: -1px;\n\n  width: auto;\n  height: auto;\n}\n\n.menu .scroll-content.scroll-content-false{\n  z-index: $z-index-scroll-content-false;\n}\n\n.scroll-view {\n  position: relative;\n  display: block;\n  overflow: hidden;\n\n  // Hide the top border if any\n  margin-top: -1px;\n}\n\n/**\n * Scroll is the scroll view component available for complex and custom\n * scroll view functionality.\n */\n.scroll {\n  @include user-select(none);\n  @include touch-callout(none);\n  @include text-size-adjust(none);\n  @include transform-origin(left, top);\n}\n/**\n * Set ms-viewport to prevent MS \"page squish\" and allow fluid scrolling\n * https://msdn.microsoft.com/en-us/library/ie/hh869615(v=vs.85).aspx\n */\n@-ms-viewport { width: device-width; }\n\n// Scroll bar styles\n.scroll-bar {\n  position: absolute;\n  z-index: $z-index-scroll-bar;\n}\n// hide the scroll-bar during animations\n.ng-animate .scroll-bar {\n  visibility: hidden;\n}\n.scroll-bar-h {\n  right: 2px;\n  bottom: 3px;\n  left: 2px;\n  height: 3px;\n\n  .scroll-bar-indicator {\n    height: 100%;\n  }\n}\n\n.scroll-bar-v {\n  top: 2px;\n  right: 3px;\n  bottom: 2px;\n  width: 3px;\n\n  .scroll-bar-indicator {\n    width: 100%;\n  }\n}\n.scroll-bar-indicator {\n  position: absolute;\n  border-radius: 4px;\n  background: rgba(0,0,0,0.3);\n  opacity: 1;\n  @include transition(opacity .3s linear);\n\n  &.scroll-bar-fade-out {\n    opacity: 0;\n  }\n}\n.platform-android .scroll-bar-indicator {\n  // android doesn't have rounded ends on scrollbar\n  border-radius: 0;\n}\n.grade-b .scroll-bar-indicator,\n.grade-c .scroll-bar-indicator {\n  // disable rgba background and border radius for low end devices\n  background: #aaa;\n\n  &.scroll-bar-fade-out {\n    @include transition(none);\n  }\n}\n\nion-infinite-scroll {\n  height: 60px;\n  width: 100%;\n  display: block;\n\n  @include display-flex();\n  @include flex-direction(row);\n  @include justify-content(center);\n  @include align-items(center);\n\n  .icon {\n    color: #666666;\n    font-size: 30px;\n    color: $scroll-refresh-icon-color;\n  }\n  .icon:before,\n  .spinner{\n    -webkit-transform: translate3d(0,0,0);\n    transform: translate3d(0,0,0);\n  }\n  &:not(.active){\n    .spinner,\n    .icon:before{\n      -webkit-transform: translate3d(-1000px,0,0);\n      transform: translate3d(-1000px,0,0);\n    }\n  }\n}\n\n.overflow-scroll {\n  overflow-x: hidden;\n  overflow-y: scroll;\n  -webkit-overflow-scrolling: touch;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  position: absolute;\n\n  .scroll {\n    position: static;\n    height: 100%;\n    -webkit-transform: translate3d(0, 0, 0);   // fix iOS bug where relative children of scroller disapear while scrolling.  see: http://stackoverflow.com/questions/9807620/ipad-safari-scrolling-causes-html-elements-to-disappear-and-reappear-with-a-dela\n  }\n}\n\n\n// Pad top/bottom of content so it doesn't hide behind .bar-title and .bar-tab.\n// Note: For these to work, content must come after both bars in the markup\n/* If you change these, change platform.scss as well */\n.has-header {\n  top: $bar-height;\n}\n// Force no header\n.no-header {\n  top: 0;\n}\n\n.has-subheader {\n  top: $bar-height + $bar-subheader-height;\n}\n.has-tabs-top {\n  top: $bar-height + $tabs-height;\n}\n.has-header.has-subheader.has-tabs-top {\n  top: $bar-height + $bar-subheader-height + $tabs-height;\n}\n\n.has-footer {\n  bottom: $bar-footer-height;\n}\n.has-subfooter {\n  bottom: $bar-footer-height + $bar-subfooter-height;\n}\n\n.has-tabs,\n.bar-footer.has-tabs {\n  bottom: $tabs-height;\n  &.pane{\n    bottom: $tabs-height;\n    height:auto;\n  }\n}\n\n.has-footer.has-tabs {\n  bottom: $tabs-height + $bar-footer-height;\n}\n\n// A full screen section with a solid background\n.pane {\n  @include translate3d(0,0,0);\n  @include transition-duration(0);\n  z-index: $z-index-pane;\n}\n.view {\n  z-index: $z-index-view;\n}\n.pane,\n.view {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  background-color: $base-background-color;\n  overflow: hidden;\n}\n.view-container {\n  position: absolute;\n  display: block;\n  width: 100%;\n  height: 100%;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_select.scss",
    "content": "\n/**\n * Select\n * --------------------------------------------------\n */\n\n.item-select {\n  position: relative;\n\n  select {\n    @include appearance(none);\n    position: absolute;\n    top: 0;\n    bottom: 0;\n    right: 0;\n    padding: ($item-padding - 2) ($item-padding * 3) ($item-padding) $item-padding;\n    max-width: 65%;\n\n    border: none;\n    background: $item-default-bg;\n    color: #333;\n\n    // hack to hide default dropdown arrow in FF\n    text-indent: .01px;\n    text-overflow: '';\n\n    white-space: nowrap;\n    font-size: $font-size-base;\n\n    cursor: pointer;\n    direction: rtl; // right align the select text\n  }\n\n  select::-ms-expand {\n    // hide default dropdown arrow in IE\n    display: none;\n  }\n\n  option {\n    direction: ltr;\n  }\n\n  &:after {\n    position: absolute;\n    top: 50%;\n    right: $item-padding;\n    margin-top: -3px;\n    width: 0;\n    height: 0;\n    border-top: 5px solid;\n    border-right: 5px solid rgba(0, 0, 0, 0);\n    border-left: 5px solid rgba(0, 0, 0, 0);\n    color: #999;\n    content: \"\";\n    pointer-events: none;\n  }\n  &.item-light {\n    select{\n      background:$item-light-bg;\n      color:$item-light-text;\n    }\n  }\n  &.item-stable {\n    select{\n      background:$item-stable-bg;\n      color:$item-stable-text;\n    }\n    &:after, .input-label{\n      color:darken($item-stable-border,30%);\n    }\n  }\n  &.item-positive {\n    select{\n      background:$item-positive-bg;\n      color:$item-positive-text;\n    }\n    &:after, .input-label{\n      color:$item-positive-text;\n    }\n  }\n  &.item-calm {\n    select{\n      background:$item-calm-bg;\n      color:$item-calm-text;\n    }\n    &:after, .input-label{\n      color:$item-calm-text;\n    }\n  }\n  &.item-assertive {\n    select{\n      background:$item-assertive-bg;\n      color:$item-assertive-text;\n    }\n    &:after, .input-label{\n      color:$item-assertive-text;\n    }\n  }\n  &.item-balanced {\n    select{\n      background:$item-balanced-bg;\n      color:$item-balanced-text;\n    }\n    &:after, .input-label{\n      color:$item-balanced-text;\n    }\n  }\n  &.item-energized  {\n    select{\n      background:$item-energized-bg;\n      color:$item-energized-text;\n    }\n    &:after, .input-label{\n      color:$item-energized-text;\n    }\n  }\n  &.item-royal {\n    select{\n      background:$item-royal-bg;\n      color:$item-royal-text;\n    }\n    &:after, .input-label{\n      color:$item-royal-text;\n    }\n  }\n  &.item-dark  {\n    select{\n      background:$item-dark-bg;\n      color:$item-dark-text;\n    }\n    &:after, .input-label{\n      color:$item-dark-text;\n    }\n  }\n}\n\nselect {\n  &[multiple],\n  &[size] {\n    height: auto;\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_slide-box.scss",
    "content": "\n/**\n * Slide Box\n * --------------------------------------------------\n */\n\n.slider {\n  position: relative;\n  visibility: hidden;\n  // Make sure items don't scroll over ever\n  overflow: hidden;\n}\n\n.slider-slides {\n  position: relative;\n  height: 100%;\n}\n\n.slider-slide {\n  position: relative;\n  display: block;\n  float: left;\n  width: 100%;\n  height: 100%;\n  vertical-align: top;\n}\n\n.slider-slide-image {\n  > img {\n    width: 100%;\n  }\n}\n\n.slider-pager {\n  position: absolute;\n  bottom: 20px;\n  z-index: $z-index-slider-pager;\n  width: 100%;\n  height: 15px;\n  text-align: center;\n\n  .slider-pager-page {\n    display: inline-block;\n    margin: 0px 3px;\n    width: 15px;\n    color: #000;\n    text-decoration: none;\n\n    opacity: 0.3;\n\n    &.active {\n      @include transition(opacity 0.4s ease-in);\n      opacity: 1;\n    }\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_spinner.scss",
    "content": "/**\n * Spinners\n * --------------------------------------------------\n */\n\n.spinner {\n  svg {\n    width: $spinner-width;\n    height: $spinner-height;\n  }\n\n  stroke: $spinner-default-stroke;\n  fill: $spinner-default-fill;\n\n  &.spinner-light {\n    stroke: $spinner-light-stroke;\n    fill: $spinner-light-fill;\n  }\n  &.spinner-stable {\n    stroke: $spinner-stable-stroke;\n    fill: $spinner-stable-fill;\n  }\n  &.spinner-positive {\n    stroke: $spinner-positive-stroke;\n    fill: $spinner-positive-fill;\n  }\n  &.spinner-calm {\n    stroke: $spinner-calm-stroke;\n    fill: $spinner-calm-fill;\n  }\n  &.spinner-balanced {\n    stroke: $spinner-balanced-stroke;\n    fill: $spinner-balanced-fill;\n  }\n  &.spinner-assertive {\n    stroke: $spinner-assertive-stroke;\n    fill: $spinner-assertive-fill;\n  }\n  &.spinner-energized {\n    stroke: $spinner-energized-stroke;\n    fill: $spinner-energized-fill;\n  }\n  &.spinner-royal {\n    stroke: $spinner-royal-stroke;\n    fill: $spinner-royal-fill;\n  }\n  &.spinner-dark {\n    stroke: $spinner-dark-stroke;\n    fill: $spinner-dark-fill;\n  }\n}\n\n.spinner-android {\n  stroke: #4b8bf4;\n}\n\n.spinner-ios,\n.spinner-ios-small {\n  stroke: #69717d;\n}\n\n.spinner-spiral {\n  .stop1 {\n    stop-color: $spinner-light-fill;\n    stop-opacity: 0;\n  }\n\n  &.spinner-light {\n    .stop1 {\n      stop-color: $spinner-default-fill;\n    }\n    .stop2 {\n      stop-color: $spinner-light-fill;\n    }\n  }\n  &.spinner-stable .stop2 {\n    stop-color: $spinner-stable-fill;\n  }\n  &.spinner-positive .stop2 {\n    stop-color: $spinner-positive-fill;\n  }\n  &.spinner-calm .stop2 {\n    stop-color: $spinner-calm-fill;\n  }\n  &.spinner-balanced .stop2 {\n    stop-color: $spinner-balanced-fill;\n  }\n  &.spinner-assertive .stop2 {\n    stop-color: $spinner-assertive-fill;\n  }\n  &.spinner-energized .stop2 {\n    stop-color: $spinner-energized-fill;\n  }\n  &.spinner-royal .stop2 {\n    stop-color: $spinner-royal-fill;\n  }\n  &.spinner-dark .stop2 {\n    stop-color: $spinner-dark-fill;\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_tabs.scss",
    "content": "/**\n * Tabs\n * --------------------------------------------------\n * A navigation bar with any number of tab items supported.\n */\n\n.tabs {\n  @include display-flex();\n  @include flex-direction(horizontal);\n  @include justify-content(center);\n  @include translate3d(0,0,0);\n\n  @include tab-style($tabs-default-bg, $tabs-default-border, $tabs-default-text);\n  @include tab-badge-style($tabs-default-text, $tabs-default-bg);\n\n  position: absolute;\n  bottom: 0;\n\n  z-index: $z-index-tabs;\n\n  width: 100%;\n  height: $tabs-height;\n\n  border-style: solid;\n  border-top-width: 1px;\n\n  background-size: 0;\n  line-height: $tabs-height;\n\n  @media (min--moz-device-pixel-ratio: 1.5),\n         (-webkit-min-device-pixel-ratio: 1.5),\n         (min-device-pixel-ratio: 1.5),\n         (min-resolution: 144dpi),\n         (min-resolution: 1.5dppx) {\n    padding-top: 2px;\n    border-top: none !important;\n    border-bottom: none;\n    background-position: top;\n    background-size: 100% 1px;\n    background-repeat: no-repeat;\n  }\n\n}\n/* Allow parent element of tabs to define color, or just the tab itself */\n.tabs-light > .tabs,\n.tabs.tabs-light {\n  @include tab-style($tabs-light-bg, $tabs-light-border, $tabs-light-text);\n  @include tab-badge-style($tabs-light-text, $tabs-light-bg);\n}\n.tabs-stable > .tabs,\n.tabs.tabs-stable {\n  @include tab-style($tabs-stable-bg, $tabs-stable-border, $tabs-stable-text);\n  @include tab-badge-style($tabs-stable-text, $tabs-stable-bg);\n}\n.tabs-positive > .tabs,\n.tabs.tabs-positive {\n  @include tab-style($tabs-positive-bg, $tabs-positive-border, $tabs-positive-text);\n  @include tab-badge-style($tabs-positive-text, $tabs-positive-bg);\n}\n.tabs-calm > .tabs,\n.tabs.tabs-calm {\n  @include tab-style($tabs-calm-bg, $tabs-calm-border, $tabs-calm-text);\n  @include tab-badge-style($tabs-calm-text, $tabs-calm-bg);\n}\n.tabs-assertive > .tabs,\n.tabs.tabs-assertive {\n  @include tab-style($tabs-assertive-bg, $tabs-assertive-border, $tabs-assertive-text);\n  @include tab-badge-style($tabs-assertive-text, $tabs-assertive-bg);\n}\n.tabs-balanced > .tabs,\n.tabs.tabs-balanced {\n  @include tab-style($tabs-balanced-bg, $tabs-balanced-border, $tabs-balanced-text);\n  @include tab-badge-style($tabs-balanced-text, $tabs-balanced-bg);\n}\n.tabs-energized > .tabs,\n.tabs.tabs-energized {\n  @include tab-style($tabs-energized-bg, $tabs-energized-border, $tabs-energized-text);\n  @include tab-badge-style($tabs-energized-text, $tabs-energized-bg);\n}\n.tabs-royal > .tabs,\n.tabs.tabs-royal {\n  @include tab-style($tabs-royal-bg, $tabs-royal-border, $tabs-royal-text);\n  @include tab-badge-style($tabs-royal-text, $tabs-royal-bg);\n}\n.tabs-dark > .tabs,\n.tabs.tabs-dark {\n  @include tab-style($tabs-dark-bg, $tabs-dark-border, $tabs-dark-text);\n  @include tab-badge-style($tabs-dark-text, $tabs-dark-bg);\n}\n\n@mixin tabs-striped($style, $color, $background) {\n  &.#{$style} {\n    .tabs{\n      background-color: $background;\n    }\n    .tab-item {\n      color: rgba($color, $tabs-striped-off-opacity);\n      opacity: 1;\n      .badge{\n        opacity:$tabs-striped-off-opacity;\n      }\n      &.tab-item-active,\n      &.active,\n      &.activated {\n        margin-top: -$tabs-striped-border-width;\n        color: $color;\n        border-style: solid;\n        border-width: $tabs-striped-border-width 0 0 0;\n        border-color: $color;\n      }\n    }\n  }\n  &.tabs-top{\n    .tab-item {\n      &.tab-item-active,\n      &.active,\n      &.activated {\n        .badge {\n          top: 4%;\n        }\n      }\n    }\n  }\n}\n\n@mixin tabs-background($style, $color, $border-color) {\n  .#{$style} {\n    .tabs,\n    &> .tabs{\n      background-color: $color;\n      background-image: linear-gradient(0deg, $border-color, $border-color 50%, transparent 50%);\n      border-color: $border-color;\n    }\n  }\n}\n\n@mixin tabs-striped-background($style, $color) {\n  &.#{$style} {\n    .tabs {\n      background-color: $color;\n      background-image:none;\n    }\n  }\n}\n\n@mixin tabs-color($style, $color) {\n  .#{$style} {\n    .tab-item {\n      color: rgba($color, $tabs-off-opacity);\n      opacity: 1;\n      .badge{\n        opacity:$tabs-off-opacity;\n      }\n      &.tab-item-active,\n      &.active,\n      &.activated {\n        color: $color;\n        border: 0 solid $color;\n        .badge{\n          opacity: 1;\n        }\n      }\n    }\n  }\n}\n\n@mixin tabs-striped-color($style, $color) {\n  &.#{$style} {\n    .tab-item {\n      color: rgba($color, $tabs-striped-off-opacity);\n      opacity: 1;\n      .badge{\n        opacity:$tabs-striped-off-opacity;\n      }\n      &.tab-item-active,\n      &.active,\n      &.activated {\n        margin-top: -$tabs-striped-border-width;\n        color: $color;\n        border: 0 solid $color;\n        border-top-width: $tabs-striped-border-width;\n        .badge{\n          top:$tabs-striped-border-width;\n          opacity: 1;\n        }\n      }\n    }\n  }\n}\n\n.tabs-striped {\n  .tabs {\n    background-color: white;\n    background-image: none;\n    border: none;\n    border-bottom: 1px solid #ddd;\n    padding-top: $tabs-striped-border-width;\n  }\n  .tab-item {\n    // default android tab style\n    &.tab-item-active,\n    &.active,\n    &.activated {\n      margin-top: -$tabs-striped-border-width;\n      border-style: solid;\n      border-width: $tabs-striped-border-width 0 0 0;\n      border-color: $dark;\n      .badge{\n        top:$tabs-striped-border-width;\n        opacity: 1;\n      }\n    }\n  }\n  @include tabs-striped('tabs-light', $dark, $light);\n  @include tabs-striped('tabs-stable', $dark, $stable);\n  @include tabs-striped('tabs-positive', $light, $positive);\n  @include tabs-striped('tabs-calm', $light, $calm);\n  @include tabs-striped('tabs-assertive', $light, $assertive);\n  @include tabs-striped('tabs-balanced', $light, $balanced);\n  @include tabs-striped('tabs-energized', $light, $energized);\n  @include tabs-striped('tabs-royal', $light, $royal);\n  @include tabs-striped('tabs-dark', $light, $dark);\n\n  // doing this twice so striped tabs styles don't override specific bg and color vals\n  @include tabs-striped-background('tabs-background-light', $light);\n  @include tabs-striped-background('tabs-background-stable', $stable);\n  @include tabs-striped-background('tabs-background-positive', $positive);\n  @include tabs-striped-background('tabs-background-calm', $calm);\n  @include tabs-striped-background('tabs-background-assertive', $assertive);\n  @include tabs-striped-background('tabs-background-balanced', $balanced);\n  @include tabs-striped-background('tabs-background-energized',$energized);\n  @include tabs-striped-background('tabs-background-royal', $royal);\n  @include tabs-striped-background('tabs-background-dark', $dark);\n\n  @include tabs-striped-color('tabs-color-light', $light);\n  @include tabs-striped-color('tabs-color-stable', $stable);\n  @include tabs-striped-color('tabs-color-positive', $positive);\n  @include tabs-striped-color('tabs-color-calm', $calm);\n  @include tabs-striped-color('tabs-color-assertive', $assertive);\n  @include tabs-striped-color('tabs-color-balanced', $balanced);\n  @include tabs-striped-color('tabs-color-energized',$energized);\n  @include tabs-striped-color('tabs-color-royal', $royal);\n  @include tabs-striped-color('tabs-color-dark', $dark);\n\n}\n\n@include tabs-background('tabs-background-light', $light, $bar-light-border);\n@include tabs-background('tabs-background-stable', $stable, $bar-stable-border);\n@include tabs-background('tabs-background-positive', $positive, $bar-positive-border);\n@include tabs-background('tabs-background-calm', $calm, $bar-calm-border);\n@include tabs-background('tabs-background-assertive', $assertive, $bar-assertive-border);\n@include tabs-background('tabs-background-balanced', $balanced, $bar-balanced-border);\n@include tabs-background('tabs-background-energized',$energized, $bar-energized-border);\n@include tabs-background('tabs-background-royal', $royal, $bar-royal-border);\n@include tabs-background('tabs-background-dark', $dark, $bar-dark-border);\n\n@include tabs-color('tabs-color-light', $light);\n@include tabs-color('tabs-color-stable', $stable);\n@include tabs-color('tabs-color-positive', $positive);\n@include tabs-color('tabs-color-calm', $calm);\n@include tabs-color('tabs-color-assertive', $assertive);\n@include tabs-color('tabs-color-balanced', $balanced);\n@include tabs-color('tabs-color-energized',$energized);\n@include tabs-color('tabs-color-royal', $royal);\n@include tabs-color('tabs-color-dark', $dark);\n\n@mixin tabs-standard-color($style, $color, $off-color:$dark) {\n  &.#{$style} {\n    .tab-item {\n      color: $off-color;\n      &.tab-item-active,\n      &.active,\n      &.activated {\n        color: $color;\n      }\n    }\n  }\n}\n\nion-tabs {\n  @include tabs-standard-color('tabs-color-active-light', $light, $dark);\n  @include tabs-standard-color('tabs-color-active-stable', $stable, $dark);\n  @include tabs-standard-color('tabs-color-active-positive', $positive, $dark);\n  @include tabs-standard-color('tabs-color-active-calm', $calm, $dark);\n  @include tabs-standard-color('tabs-color-active-assertive', $assertive, $dark);\n  @include tabs-standard-color('tabs-color-active-balanced', $balanced, $dark);\n  @include tabs-standard-color('tabs-color-active-energized',$energized, $dark);\n  @include tabs-standard-color('tabs-color-active-royal', $royal, $dark);\n  @include tabs-standard-color('tabs-color-active-dark', $dark, $light);\n}\n\n.tabs-top {\n  &.tabs-striped {\n    padding-bottom:0;\n    .tab-item{\n      background: transparent;\n      // animate the top bar, leave bottom for platform consistency\n      -webkit-transition: color .1s ease;\n      -moz-transition: color .1s ease;\n      -ms-transition: color .1s ease;\n      -o-transition: color .1s ease;\n      transition: color .1s ease;\n      &.tab-item-active,\n      &.active,\n      &.activated {\n        margin-top: $tabs-striped-border-width - 1px;\n        border-width: 0px 0px $tabs-striped-border-width 0px !important;\n        border-style: solid;\n        > .badge, > i{\n          margin-top: -$tabs-striped-border-width + 1px;\n        }\n      }\n      .badge{\n        -webkit-transition: color .2s ease;\n        -moz-transition: color .2s ease;\n        -ms-transition: color .2s ease;\n        -o-transition: color .2s ease;\n        transition: color .2s ease;\n      }\n    }\n  }\n}\n\n/* Allow parent element to have tabs-top */\n/* If you change this, change platform.scss as well */\n.tabs-top > .tabs,\n.tabs.tabs-top {\n  top: $bar-height;\n  padding-top: 0;\n  background-position: bottom;\n  border-top-width: 0;\n  border-bottom-width: 1px;\n  .tab-item {\n    &.tab-item-active,\n    &.active,\n    &.activated {\n      .badge {\n        top: 4%;\n      }\n    }\n  }\n}\n.tabs-top ~ .bar-header {\n  border-bottom-width: 0;\n}\n\n.tab-item {\n  @include flex(1);\n  display: block;\n  overflow: hidden;\n\n  max-width: $tab-item-max-width;\n  height: 100%;\n\n  color: inherit;\n  text-align: center;\n  text-decoration: none;\n  text-overflow: ellipsis;\n  white-space: nowrap;\n\n  font-weight: 400;\n  font-size: $tabs-text-font-size;\n  font-family: $font-family-sans-serif;\n\n  opacity: 0.7;\n\n  &:hover {\n    cursor: pointer;\n  }\n  &.tab-hidden{\n    display:none;\n  }\n}\n\n.tabs-item-hide > .tabs,\n.tabs.tabs-item-hide {\n  display: none;\n}\n\n.tabs-icon-top > .tabs .tab-item,\n.tabs-icon-top.tabs .tab-item,\n.tabs-icon-bottom > .tabs .tab-item,\n.tabs-icon-bottom.tabs .tab-item {\n  font-size: $tabs-text-font-size-side-icon;\n  line-height: $tabs-text-font-size;\n}\n\n.tab-item .icon {\n  display: block;\n  margin: 0 auto;\n  height: $tabs-icon-size;\n  font-size: $tabs-icon-size;\n}\n\n.tabs-icon-left.tabs .tab-item,\n.tabs-icon-left > .tabs .tab-item,\n.tabs-icon-right.tabs .tab-item,\n.tabs-icon-right > .tabs .tab-item {\n  font-size: $tabs-text-font-size-side-icon;\n\n  .icon {\n    display: inline-block;\n    vertical-align: top;\n    margin-top: -.1em;\n\n    &:before {\n    font-size: $tabs-icon-size - 8;\n    line-height: $tabs-height;\n    }\n  }\n}\n\n.tabs-icon-left > .tabs .tab-item .icon,\n.tabs-icon-left.tabs .tab-item .icon {\n  padding-right: 3px;\n}\n\n.tabs-icon-right > .tabs .tab-item .icon,\n.tabs-icon-right.tabs .tab-item .icon {\n  padding-left: 3px;\n}\n\n.tabs-icon-only > .tabs .icon,\n.tabs-icon-only.tabs .icon {\n  line-height: inherit;\n}\n\n\n.tab-item.has-badge {\n  position: relative;\n}\n\n.tab-item .badge {\n  position: absolute;\n  top: 4%;\n  right: 33%; // fallback\n  right: calc(50% - 26px);\n  padding: $tabs-badge-padding;\n  height: auto;\n  font-size: $tabs-badge-font-size;\n  line-height: $tabs-badge-font-size + 4;\n}\n\n\n/* Navigational tab */\n\n/* Active state for tab */\n.tab-item.tab-item-active,\n.tab-item.active,\n.tab-item.activated {\n  opacity: 1;\n\n  &.tab-item-light {\n    color: $light;\n  }\n  &.tab-item-stable {\n    color: $stable;\n  }\n  &.tab-item-positive {\n    color: $positive;\n  }\n  &.tab-item-calm {\n    color: $calm;\n  }\n  &.tab-item-assertive {\n    color: $assertive;\n  }\n  &.tab-item-balanced {\n    color: $balanced;\n  }\n  &.tab-item-energized {\n    color: $energized;\n  }\n  &.tab-item-royal {\n    color: $royal;\n  }\n  &.tab-item-dark {\n    color: $dark;\n  }\n}\n\n.item.tabs {\n  @include display-flex();\n  padding: 0;\n\n  .icon:before {\n    position: relative;\n  }\n}\n\n.tab-item.disabled,\n.tab-item[disabled] {\n  opacity: .4;\n  cursor: default;\n  pointer-events: none;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_toggle.scss",
    "content": "\n/**\n * Toggle\n * --------------------------------------------------\n */\n\n.item-toggle {\n  pointer-events: none;\n}\n\n.toggle {\n  // set the color defaults\n  @include toggle-style($toggle-on-default-border, $toggle-on-default-bg);\n\n  position: relative;\n  display: inline-block;\n  pointer-events: auto;\n  margin: -$toggle-hit-area-expansion;\n  padding: $toggle-hit-area-expansion;\n\n  &.dragging {\n    .handle {\n      background-color: $toggle-handle-dragging-bg-color !important;\n    }\n  }\n\n}\n\n.toggle {\n  &.toggle-light  {\n    @include toggle-style($toggle-on-light-border, $toggle-on-light-bg);\n  }\n  &.toggle-stable  {\n    @include toggle-style($toggle-on-stable-border, $toggle-on-stable-bg);\n  }\n  &.toggle-positive  {\n    @include toggle-style($toggle-on-positive-border, $toggle-on-positive-bg);\n  }\n  &.toggle-calm  {\n    @include toggle-style($toggle-on-calm-border, $toggle-on-calm-bg);\n  }\n  &.toggle-assertive  {\n    @include toggle-style($toggle-on-assertive-border, $toggle-on-assertive-bg);\n  }\n  &.toggle-balanced  {\n    @include toggle-style($toggle-on-balanced-border, $toggle-on-balanced-bg);\n  }\n  &.toggle-energized  {\n    @include toggle-style($toggle-on-energized-border, $toggle-on-energized-bg);\n  }\n  &.toggle-royal  {\n    @include toggle-style($toggle-on-royal-border, $toggle-on-royal-bg);\n  }\n  &.toggle-dark  {\n    @include toggle-style($toggle-on-dark-border, $toggle-on-dark-bg);\n  }\n}\n\n.toggle input {\n  // hide the actual input checkbox\n  display: none;\n}\n\n/* the track appearance when the toggle is \"off\" */\n.toggle .track {\n  @include transition-timing-function(ease-in-out);\n  @include transition-duration($toggle-transition-duration);\n  @include transition-property((background-color, border));\n\n  display: inline-block;\n  box-sizing: border-box;\n  width: $toggle-width;\n  height: $toggle-height;\n  border: solid $toggle-border-width $toggle-off-border-color;\n  border-radius: $toggle-border-radius;\n  background-color: $toggle-off-bg-color;\n  content: ' ';\n  cursor: pointer;\n  pointer-events: none;\n}\n\n/* Fix to avoid background color bleeding */\n/* (occured on (at least) Android 4.2, Asus MeMO Pad HD7 ME173X) */\n.platform-android4_2 .toggle .track {\n  -webkit-background-clip: padding-box;\n}\n\n/* the handle (circle) thats inside the toggle's track area */\n/* also the handle's appearance when it is \"off\" */\n.toggle .handle {\n  @include transition($toggle-transition-duration cubic-bezier(0, 1.1, 1, 1.1));\n  @include transition-property((background-color, transform));\n  position: absolute;\n  display: block;\n  width: $toggle-handle-width;\n  height: $toggle-handle-height;\n  border-radius: $toggle-handle-radius;\n  background-color: $toggle-handle-off-bg-color;\n  top: $toggle-border-width + $toggle-hit-area-expansion;\n  left: $toggle-border-width + $toggle-hit-area-expansion;\n  box-shadow: 0 2px 7px rgba(0,0,0,.35), 0 1px 1px rgba(0,0,0,.15);\n\n  &:before {\n    // used to create a larger (but hidden) hit area to slide the handle\n    position: absolute;\n    top: -4px;\n    left: ( ($toggle-handle-width / 2) * -1) - 8;\n    padding: ($toggle-handle-height / 2) + 5 ($toggle-handle-width + 7);\n    content: \" \";\n  }\n}\n\n.toggle input:checked + .track .handle {\n  // the handle when the toggle is \"on\"\n  @include translate3d($toggle-width - $toggle-handle-width - ($toggle-border-width * 2), 0, 0);\n  background-color: $toggle-handle-on-bg-color;\n}\n\n.item-toggle.active {\n  box-shadow: none;\n}\n\n.item-toggle,\n.item-toggle.item-complex .item-content {\n  // make sure list item content have enough padding on right to fit the toggle\n  padding-right: ($item-padding * 3) + $toggle-width;\n}\n\n.item-toggle.item-complex {\n  padding-right: 0;\n}\n\n.item-toggle .toggle {\n  // position the toggle to the right within a list item\n  position: absolute;\n  top: ($item-padding / 2) + 2;\n  right: $item-padding;\n  z-index: $z-index-item-toggle;\n}\n\n.toggle input:disabled + .track {\n  opacity: .6;\n}\n\n.toggle-small {\n\n  .track {\n    border: 0;\n    width: 34px;\n    height: 15px;\n    background: #9e9e9e;\n  }\n  input:checked + .track {\n    background: rgba(0,150,137,.5);\n  }\n  .handle {\n    top: 2px;\n    left: 4px;\n    width: 21px;\n    height: 21px;\n    box-shadow: 0 2px 5px rgba(0,0,0,.25);\n  }\n  input:checked + .track .handle {\n    @include translate3d(16px, 0, 0);\n    background: rgb(0,150,137);\n  }\n  &.item-toggle .toggle {\n    top: 19px;\n  }\n\n  .toggle-light  {\n    @include toggle-small-style($toggle-on-light-bg);\n  }\n  .toggle-stable  {\n    @include toggle-small-style($toggle-on-stable-bg);\n  }\n  .toggle-positive  {\n    @include toggle-small-style($toggle-on-positive-bg);\n  }\n  .toggle-calm  {\n    @include toggle-small-style($toggle-on-calm-bg);\n  }\n  .toggle-assertive  {\n    @include toggle-small-style($toggle-on-assertive-bg);\n  }\n  .toggle-balanced  {\n    @include toggle-small-style($toggle-on-balanced-bg);\n  }\n  .toggle-energized  {\n    @include toggle-small-style($toggle-on-energized-bg);\n  }\n  .toggle-royal  {\n    @include toggle-small-style($toggle-on-royal-bg);\n  }\n  .toggle-dark  {\n    @include toggle-small-style($toggle-on-dark-bg);\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_transitions.scss",
    "content": "\n// iOS View Transitions\n// -------------------------------\n\n$ios-transition-duration:              500ms !default;\n$ios-transition-timing-function:       cubic-bezier(.36, .66, .04, 1) !default;\n$ios-transition-container-bg-color:    #000 !default;\n\n\n[nav-view-transition=\"ios\"] {\n\n  [nav-view=\"entering\"],\n  [nav-view=\"leaving\"] {\n    @include transition-duration( $ios-transition-duration );\n    @include transition-timing-function( $ios-transition-timing-function );\n    -webkit-transition-property: opacity, -webkit-transform, box-shadow;\n            transition-property: opacity, transform, box-shadow;\n  }\n\n  &[nav-view-direction=\"forward\"],\n  &[nav-view-direction=\"back\"] {\n    background-color: $ios-transition-container-bg-color;\n  }\n\n  [nav-view=\"active\"],\n  &[nav-view-direction=\"forward\"] [nav-view=\"entering\"],\n  &[nav-view-direction=\"back\"] [nav-view=\"leaving\"] {\n    z-index: $z-index-view-above;\n  }\n\n  &[nav-view-direction=\"back\"] [nav-view=\"entering\"],\n  &[nav-view-direction=\"forward\"] [nav-view=\"leaving\"] {\n    z-index: $z-index-view-below;\n  }\n\n}\n\n\n\n// iOS Nav Bar Transitions\n// -------------------------------\n\n[nav-bar-transition=\"ios\"] {\n\n  .title,\n  .buttons,\n  .back-text {\n    @include transition-duration( $ios-transition-duration );\n    @include transition-timing-function( $ios-transition-timing-function );\n    -webkit-transition-property: opacity, -webkit-transform;\n            transition-property: opacity, transform;\n  }\n\n  [nav-bar=\"active\"],\n  [nav-bar=\"entering\"] {\n    z-index: $z-index-bar-above;\n\n   .bar {\n      background: transparent;\n    }\n  }\n\n  [nav-bar=\"cached\"] {\n    display: block;\n\n    .header-item {\n      display: none;\n    }\n  }\n\n}\n\n\n\n// Android View Transitions\n// -------------------------------\n\n$android-transition-duration:             200ms !default;\n$android-transition-timing-function:      cubic-bezier(0.4, 0.6, 0.2, 1) !default;\n\n\n[nav-view-transition=\"android\"] {\n\n  [nav-view=\"entering\"],\n  [nav-view=\"leaving\"] {\n    @include transition-duration( $android-transition-duration );\n    @include transition-timing-function( $android-transition-timing-function );\n    -webkit-transition-property: -webkit-transform;\n            transition-property: transform;\n  }\n\n  [nav-view=\"active\"],\n  &[nav-view-direction=\"forward\"] [nav-view=\"entering\"],\n  &[nav-view-direction=\"back\"] [nav-view=\"leaving\"] {\n    z-index: $z-index-view-above;\n  }\n\n  &[nav-view-direction=\"back\"] [nav-view=\"entering\"],\n  &[nav-view-direction=\"forward\"] [nav-view=\"leaving\"] {\n    z-index: $z-index-view-below;\n  }\n\n}\n\n\n\n// Android Nav Bar Transitions\n// -------------------------------\n\n[nav-bar-transition=\"android\"] {\n\n  .title,\n  .buttons {\n    @include transition-duration( $android-transition-duration );\n    @include transition-timing-function( $android-transition-timing-function );\n    -webkit-transition-property: opacity;\n            transition-property: opacity;\n  }\n\n  [nav-bar=\"active\"],\n  [nav-bar=\"entering\"] {\n    z-index: $z-index-bar-above;\n\n   .bar {\n      background: transparent;\n    }\n  }\n\n  [nav-bar=\"cached\"] {\n    display: block;\n\n    .header-item {\n      display: none;\n    }\n  }\n\n}\n\n\n\n// Nav Swipe\n// -------------------------------\n\n[nav-swipe=\"fast\"] {\n  [nav-view],\n  .title,\n  .buttons,\n  .back-text {\n    @include transition-duration(50ms);\n    @include transition-timing-function(linear);\n  }\n}\n\n[nav-swipe=\"slow\"] {\n  [nav-view],\n  .title,\n  .buttons,\n  .back-text {\n    @include transition-duration(160ms);\n    @include transition-timing-function(linear);\n  }\n}\n\n\n\n// Transition Settings\n// -------------------------------\n\n[nav-view=\"cached\"],\n[nav-bar=\"cached\"] {\n  display: none;\n}\n\n[nav-view=\"stage\"] {\n  opacity: 0;\n  @include transition-duration( 0 );\n}\n\n[nav-bar=\"stage\"] {\n  .title,\n  .buttons,\n  .back-text {\n    position: absolute;\n    opacity: 0;\n    @include transition-duration(0s);\n  }\n}\n\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_type.scss",
    "content": "\n/**\n * Typography\n * --------------------------------------------------\n */\n\n\n// Body text\n// -------------------------\n\np {\n  margin: 0 0 ($line-height-computed / 2);\n}\n\n\n// Emphasis & misc\n// -------------------------\n\nsmall   { font-size: 85%; }\ncite    { font-style: normal; }\n\n\n// Alignment\n// -------------------------\n\n.text-left           { text-align: left; }\n.text-right          { text-align: right; }\n.text-center         { text-align: center; }\n\n\n// Headings\n// -------------------------\n\nh1, h2, h3, h4, h5, h6,\n.h1, .h2, .h3, .h4, .h5, .h6 {\n  color: $base-color;\n  font-weight: $headings-font-weight;\n  font-family: $headings-font-family;\n  line-height: $headings-line-height;\n\n  small {\n    font-weight: normal;\n    line-height: 1;\n  }\n}\n\nh1, .h1,\nh2, .h2,\nh3, .h3 {\n  margin-top: $line-height-computed;\n  margin-bottom: ($line-height-computed / 2);\n\n  &:first-child {\n    margin-top: 0;\n  }\n\n  + h1, + .h1,\n  + h2, + .h2,\n  + h3, + .h3 {\n    margin-top: ($line-height-computed / 2);\n  }\n}\n\nh4, .h4,\nh5, .h5,\nh6, .h6 {\n  margin-top: ($line-height-computed / 2);\n  margin-bottom: ($line-height-computed / 2);\n}\n\nh1, .h1 { font-size: floor($font-size-base * 2.60); } // ~36px\nh2, .h2 { font-size: floor($font-size-base * 2.15); } // ~30px\nh3, .h3 { font-size: ceil($font-size-base * 1.70); } // ~24px\nh4, .h4 { font-size: ceil($font-size-base * 1.25); } // ~18px\nh5, .h5 { font-size:  $font-size-base; }\nh6, .h6 { font-size: ceil($font-size-base * 0.85); } // ~12px\n\nh1 small, .h1 small { font-size: ceil($font-size-base * 1.70); } // ~24px\nh2 small, .h2 small { font-size: ceil($font-size-base * 1.25); } // ~18px\nh3 small, .h3 small,\nh4 small, .h4 small { font-size: $font-size-base; }\n\n\n// Description Lists\n// -------------------------\n\ndl {\n  margin-bottom: $line-height-computed;\n}\ndt,\ndd {\n  line-height: $line-height-base;\n}\ndt {\n  font-weight: bold;\n}\n\n\n// Blockquotes\n// -------------------------\n\nblockquote {\n  margin: 0 0 $line-height-computed;\n  padding: ($line-height-computed / 2) $line-height-computed;\n  border-left: 5px solid gray;\n  \n  p {\n    font-weight: 300;\n    font-size: ($font-size-base * 1.25);\n    line-height: 1.25;\n  }\n  \n  p:last-child {\n    margin-bottom: 0;\n  }\n\n  small {\n    display: block;\n    line-height: $line-height-base;\n    &:before {\n      content: '\\2014 \\00A0';// EM DASH, NBSP;\n    }\n  }\n}\n\n\n// Quotes\n// -------------------------\n\nq:before,\nq:after,\nblockquote:before,\nblockquote:after {\n  content: \"\";\n}\n\n\n// Addresses\n// -------------------------\n\naddress {\n  display: block;\n  margin-bottom: $line-height-computed;\n  font-style: normal;\n  line-height: $line-height-base;\n}\n\n\n// Links\n// -------------------------\n\na.subdued {\n  padding-right: 10px;\n  color: #888;\n  text-decoration: none;\n\n  &:hover {\n    text-decoration: none;\n  }\n  &:last-child {\n    padding-right: 0;\n  }\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_util.scss",
    "content": "\n/**\n * Utility Classes\n * --------------------------------------------------\n */\n\n.hide {\n  display: none;\n}\n.opacity-hide {\n  opacity: 0;\n}\n.grade-b .opacity-hide,\n.grade-c .opacity-hide {\n  opacity: 1;\n  display: none;\n}\n.show {\n  display: block;\n}\n.opacity-show {\n  opacity: 1;\n}\n.invisible {\n  visibility: hidden;\n}\n\n.keyboard-open .hide-on-keyboard-open {\n  display: none;\n}\n\n.keyboard-open .tabs.hide-on-keyboard-open + .pane .has-tabs,\n.keyboard-open .bar-footer.hide-on-keyboard-open + .pane .has-footer {\n  bottom: 0;\n}\n\n.inline {\n  display: inline-block;\n}\n\n.disable-pointer-events {\n  pointer-events: none;\n}\n\n.enable-pointer-events {\n  pointer-events: auto;\n}\n\n.disable-user-behavior {\n  // used to prevent the browser from doing its native behavior. this doesnt\n  // prevent the scrolling, but cancels the contextmenu, tap highlighting, etc\n\n  @include user-select(none);\n  @include touch-callout(none);\n  @include tap-highlight-transparent();\n\n  -webkit-user-drag: none;\n\n  -ms-touch-action: none;\n  -ms-content-zooming: none;\n}\n\n// Fill the screen to block clicks (a better pointer-events: none) for the body\n// to avoid full-page reflows and paints which can cause flickers\n.click-block {\n  position: absolute;\n  top: 0;\n  right: 0;\n  bottom: 0;\n  left: 0;\n  opacity: 0;\n  z-index: $z-index-click-block;\n  @include translate3d(0, 0, 0);\n  overflow: hidden;\n}\n.click-block-hide {\n  @include translate3d(-9999px, 0, 0);\n}\n\n.no-resize {\n  resize: none;\n}\n\n.block {\n  display: block;\n  clear: both;\n  &:after {\n    display: block;\n    visibility: hidden;\n    clear: both;\n    height: 0;\n    content: \".\";\n  }\n}\n\n.full-image {\n  width: 100%;\n}\n\n.clearfix {\n  *zoom: 1;\n  &:before,\n  &:after {\n    display: table;\n    content: \"\";\n    // Fixes Opera/contenteditable bug:\n    // http://nicolasgallagher.com/micro-clearfix-hack/#comment-36952\n    line-height: 0;\n  }\n  &:after {\n    clear: both;\n  }\n}\n\n/**\n * Content Padding\n * --------------------------------------------------\n */\n\n.padding {\n  padding: $content-padding;\n}\n\n.padding-top,\n.padding-vertical {\n  padding-top: $content-padding;\n}\n\n.padding-right,\n.padding-horizontal {\n  padding-right: $content-padding;\n}\n\n.padding-bottom,\n.padding-vertical {\n  padding-bottom: $content-padding;\n}\n\n.padding-left,\n.padding-horizontal {\n  padding-left: $content-padding;\n}\n\n\n/**\n * Scrollable iFrames\n * --------------------------------------------------\n */\n\n.iframe-wrapper {\n  position: fixed;\n  -webkit-overflow-scrolling: touch;\n  overflow: scroll;\n\n  iframe {\n    height: 100%;\n    width: 100%;\n  }\n}\n\n\n/**\n * Rounded\n * --------------------------------------------------\n */\n\n.rounded {\n  border-radius: $border-radius-base;\n}\n\n\n/**\n * Utility Colors\n * --------------------------------------------------\n * Utility colors are added to help set a naming convention. You'll\n * notice we purposely do not use words like \"red\" or \"blue\", but\n * instead have colors which represent an emotion or generic theme.\n */\n\n.light, a.light {\n  color: $light;\n}\n.light-bg {\n  background-color: $light;\n}\n.light-border {\n  border-color: $button-light-border;\n}\n\n.stable, a.stable {\n  color: $stable;\n}\n.stable-bg {\n  background-color: $stable;\n}\n.stable-border {\n  border-color: $button-stable-border;\n}\n\n.positive, a.positive {\n  color: $positive;\n}\n.positive-bg {\n  background-color: $positive;\n}\n.positive-border {\n  border-color: $button-positive-border;\n}\n\n.calm, a.calm {\n  color: $calm;\n}\n.calm-bg {\n  background-color: $calm;\n}\n.calm-border {\n  border-color: $button-calm-border;\n}\n\n.assertive, a.assertive {\n  color: $assertive;\n}\n.assertive-bg {\n  background-color: $assertive;\n}\n.assertive-border {\n  border-color: $button-assertive-border;\n}\n\n.balanced, a.balanced {\n  color: $balanced;\n}\n.balanced-bg {\n  background-color: $balanced;\n}\n.balanced-border {\n  border-color: $button-balanced-border;\n}\n\n.energized, a.energized {\n  color: $energized;\n}\n.energized-bg {\n  background-color: $energized;\n}\n.energized-border {\n  border-color: $button-energized-border;\n}\n\n.royal, a.royal {\n  color: $royal;\n}\n.royal-bg {\n  background-color: $royal;\n}\n.royal-border {\n  border-color: $button-royal-border;\n}\n\n.dark, a.dark {\n  color: $dark;\n}\n.dark-bg {\n  background-color: $dark;\n}\n.dark-border {\n  border-color: $button-dark-border;\n}\n\n[collection-repeat] {\n  /* Position is set by transforms */\n  left: 0 !important;\n  top: 0 !important;\n  position: absolute !important;\n  z-index: 1;\n}\n.collection-repeat-container {\n  position: relative;\n  z-index: 1; //make sure it's above the after-container\n}\n.collection-repeat-after-container {\n  z-index: 0;\n  display: block;\n\n  /* when scrolling horizontally, make sure the after container doesn't take up 100% width */\n  &.horizontal {\n    display: inline-block;\n  }\n}\n\n// ng-show fix for windows phone\n// https://www.hoessl.eu/2014/12/on-using-the-ionic-framework-for-windows-phone-8-1-apps/\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak,\n.x-ng-cloak, .ng-hide:not(.ng-hide-animate) {\n  display: none !important;\n}"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/_variables.scss",
    "content": "\n// Colors\n// -------------------------------\n\n$light:                           #fff !default;\n$stable:                          #f8f8f8 !default;\n$positive:                        #387ef5 !default;\n$calm:                            #11c1f3 !default;\n$balanced:                        #33cd5f !default;\n$energized:                       #ffc900 !default;\n$assertive:                       #ef473a !default;\n$royal:                           #886aea !default;\n$dark:                            #444 !default;\n\n\n// Base\n// -------------------------------\n\n$font-family-sans-serif:          \"Helvetica Neue\", \"Roboto\", \"Segoe UI\", sans-serif !default;\n$font-family-light-sans-serif:    \"HelveticaNeue-Light\", \"Roboto-Light\", \"Segoe UI-Light\", sans-serif-light !default;\n$font-family-serif:               serif !default;\n$font-family-monospace:           monospace !default;\n\n$font-family-base:                $font-family-sans-serif !default;\n$font-size-base:                  14px !default;\n$font-size-large:                 18px !default;\n$font-size-small:                 11px !default;\n\n$line-height-base:                1.428571429 !default; // 20/14\n$line-height-computed:            floor($font-size-base * $line-height-base) !default; // ~20px\n$line-height-large:               1.33 !default;\n$line-height-small:               1.5 !default;\n\n$headings-font-family:            $font-family-base !default;\n$headings-font-weight:            500 !default;\n$headings-line-height:            1.2 !default;\n\n$base-background-color:           #fff !default;\n$base-color:                      #000 !default;\n\n$link-color:                      $positive !default;\n$link-hover-color:                darken($link-color, 15%) !default;\n\n$content-padding:                 10px !default;\n\n$padding-base-vertical:           6px !default;\n$padding-base-horizontal:         12px !default;\n\n$padding-large-vertical:          10px !default;\n$padding-large-horizontal:        16px !default;\n\n$padding-small-vertical:          5px !default;\n$padding-small-horizontal:        10px !default;\n\n$border-radius-base:              4px !default;\n$border-radius-large:             6px !default;\n$border-radius-small:             3px !default;\n\n\n// Content\n// -------------------------------\n\n$scroll-refresh-icon-color:       #666666 !default;\n\n\n// Buttons\n// -------------------------------\n\n$button-color:                    #222 !default;\n$button-block-margin:             10px !default;\n$button-clear-padding:            6px !default;\n$button-border-radius:            2px !default;\n$button-border-width:             1px !default;\n\n$button-font-size:                16px !default;\n$button-height:                   42px !default;\n$button-padding:                  12px !default;\n$button-icon-size:                24px !default;\n\n$button-large-font-size:          20px !default;\n$button-large-height:             54px !default;\n$button-large-padding:            16px !default;\n$button-large-icon-size:          32px !default;\n\n$button-small-font-size:          12px !default;\n$button-small-height:             28px !default;\n$button-small-padding:            4px !default;\n$button-small-icon-size:          16px !default;\n\n$button-bar-button-font-size:     13px !default;\n$button-bar-button-height:        32px !default;\n$button-bar-button-padding:       8px !default;\n$button-bar-button-icon-size:     20px !default;\n\n$button-light-bg:                 $light !default;\n$button-light-text:               #444 !default;\n$button-light-border:             #ddd !default;\n$button-light-active-bg:          #fafafa !default;\n$button-light-active-border:      #ccc !default;\n\n$button-stable-bg:                $stable !default;\n$button-stable-text:              #444 !default;\n$button-stable-border:            #b2b2b2 !default;\n$button-stable-active-bg:         #e5e5e5 !default;\n$button-stable-active-border:     #a2a2a2 !default;\n\n$button-positive-bg:              $positive !default;\n$button-positive-text:            #fff !default;\n$button-positive-border:          darken($positive, 10%) !default;\n$button-positive-active-bg:       darken($positive, 10%) !default;\n$button-positive-active-border:   darken($positive, 10%) !default;\n\n$button-calm-bg:                  $calm !default;\n$button-calm-text:                #fff !default;\n$button-calm-border:              darken($calm, 10%) !default;\n$button-calm-active-bg:           darken($calm, 10%) !default;\n$button-calm-active-border:       darken($calm, 10%) !default;\n\n$button-assertive-bg:             $assertive !default;\n$button-assertive-text:           #fff !default;\n$button-assertive-border:         darken($assertive, 10%) !default;\n$button-assertive-active-bg:      darken($assertive, 10%) !default;\n$button-assertive-active-border:  darken($assertive, 10%) !default;\n\n$button-balanced-bg:              $balanced !default;\n$button-balanced-text:            #fff !default;\n$button-balanced-border:          darken($balanced, 10%) !default;\n$button-balanced-active-bg:       darken($balanced, 10%) !default;\n$button-balanced-active-border:   darken($balanced, 10%) !default;\n\n$button-energized-bg:             $energized !default;\n$button-energized-text:           #fff !default;\n$button-energized-border:         darken($energized, 5%) !default;\n$button-energized-active-bg:      darken($energized, 5%) !default;\n$button-energized-active-border:  darken($energized, 5%) !default;\n\n$button-royal-bg:                 $royal !default;\n$button-royal-text:               #fff !default;\n$button-royal-border:             darken($royal, 8%) !default;\n$button-royal-active-bg:          darken($royal, 8%) !default;\n$button-royal-active-border:      darken($royal, 8%) !default;\n\n$button-dark-bg:                  $dark !default;\n$button-dark-text:                #fff !default;\n$button-dark-border:              #111 !default;\n$button-dark-active-bg:           #262626 !default;\n$button-dark-active-border:       #000 !default;\n\n$button-default-bg:               $button-stable-bg !default;\n$button-default-text:             $button-stable-text !default;\n$button-default-border:           $button-stable-border !default;\n$button-default-active-bg:        $button-stable-active-bg !default;\n$button-default-active-border:    $button-stable-active-border !default;\n\n\n// Bars\n// -------------------------------\n\n$bar-height:                      44px !default;\n$bar-title-font-size:             17px !default;\n$bar-padding-portrait:            5px !default;\n$bar-padding-landscape:           5px !default;\n$bar-transparency:                1 !default;\n\n$bar-footer-height:               $bar-height !default;\n$bar-subheader-height:            $bar-height !default;\n$bar-subfooter-height:            $bar-height !default;\n\n$bar-light-bg:                    rgba($button-light-bg, $bar-transparency) !default;\n$bar-light-text:                  $button-light-text !default;\n$bar-light-border:                $button-light-border !default;\n$bar-light-active-bg:             $button-light-active-bg !default;\n$bar-light-active-border:         $button-light-active-border !default;\n\n$bar-stable-bg:                   rgba($button-stable-bg, $bar-transparency) !default;\n$bar-stable-text:                 $button-stable-text !default;\n$bar-stable-border:               $button-stable-border !default;\n$bar-stable-active-bg:            $button-stable-active-bg !default;\n$bar-stable-active-border:        $button-stable-active-border !default;\n\n$bar-positive-bg:                 rgba($button-positive-bg, $bar-transparency) !default;\n$bar-positive-text:               $button-positive-text !default;\n$bar-positive-border:             $button-positive-border !default;\n$bar-positive-active-bg:          $button-positive-active-bg !default;\n$bar-positive-active-border:      $button-positive-active-border !default;\n\n$bar-calm-bg:                     rgba($button-calm-bg, $bar-transparency) !default;\n$bar-calm-text:                   $button-calm-text !default;\n$bar-calm-border:                 $button-calm-border !default;\n$bar-calm-active-bg:              $button-calm-active-bg !default;\n$bar-calm-active-border:          $button-calm-active-border !default;\n\n$bar-assertive-bg:                rgba($button-assertive-bg, $bar-transparency) !default;\n$bar-assertive-text:              $button-assertive-text !default;\n$bar-assertive-border:            $button-assertive-border !default;\n$bar-assertive-active-bg:         $button-assertive-active-bg !default;\n$bar-assertive-active-border:     $button-assertive-active-border !default;\n\n$bar-balanced-bg:                 rgba($button-balanced-bg, $bar-transparency) !default;\n$bar-balanced-text:               $button-balanced-text !default;\n$bar-balanced-border:             $button-balanced-border !default;\n$bar-balanced-active-bg:          $button-balanced-active-bg !default;\n$bar-balanced-active-border:      $button-balanced-active-border !default;\n\n$bar-energized-bg:                rgba($button-energized-bg, $bar-transparency) !default;\n$bar-energized-text:              $button-energized-text !default;\n$bar-energized-border:            $button-energized-border !default;\n$bar-energized-active-bg:         $button-energized-active-bg !default;\n$bar-energized-active-border:     $button-energized-active-border !default;\n\n$bar-royal-bg:                    rgba($button-royal-bg, $bar-transparency) !default;\n$bar-royal-text:                  $button-royal-text !default;\n$bar-royal-border:                $button-royal-border !default;\n$bar-royal-active-bg:             $button-royal-active-bg !default;\n$bar-royal-active-border:         $button-royal-active-border !default;\n\n$bar-dark-bg:                     rgba($button-dark-bg, $bar-transparency) !default;\n$bar-dark-text:                   $button-dark-text !default;\n$bar-dark-border:                 $button-dark-border !default;\n$bar-dark-active-bg:              $button-dark-active-bg !default;\n$bar-dark-active-border:          $button-dark-active-border !default;\n\n$bar-default-bg:                  $bar-light-bg !default;\n$bar-default-text:                $bar-light-text !default;\n$bar-default-border:              $bar-light-border !default;\n$bar-default-active-bg:           $bar-light-active-bg !default;\n$bar-default-active-border:       $bar-light-active-border !default;\n\n\n// Tabs\n// -------------------------------\n\n$tabs-height:                     49px !default;\n$tabs-text-font-size:             14px !default;\n$tabs-text-font-size-side-icon:   10px !default;\n$tabs-icon-size:                  32px !default;\n$tabs-badge-padding:              1px 6px !default;\n$tabs-badge-font-size:            12px !default;\n\n$tabs-light-bg:                   $button-light-bg !default;\n$tabs-light-border:               $button-light-border !default;\n$tabs-light-text:                 $button-light-text !default;\n\n$tabs-stable-bg:                  $button-stable-bg !default;\n$tabs-stable-border:              $button-stable-border !default;\n$tabs-stable-text:                $button-stable-text !default;\n\n$tabs-positive-bg:                $button-positive-bg !default;\n$tabs-positive-border:            $button-positive-border !default;\n$tabs-positive-text:              $button-positive-text !default;\n\n$tabs-calm-bg:                    $button-calm-bg !default;\n$tabs-calm-border:                $button-calm-border !default;\n$tabs-calm-text:                  $button-calm-text !default;\n\n$tabs-assertive-bg:               $button-assertive-bg !default;\n$tabs-assertive-border:           $button-assertive-border !default;\n$tabs-assertive-text:             $button-assertive-text !default;\n\n$tabs-balanced-bg:                $button-balanced-bg !default;\n$tabs-balanced-border:            $button-balanced-border !default;\n$tabs-balanced-text:              $button-balanced-text !default;\n\n$tabs-energized-bg:               $button-energized-bg !default;\n$tabs-energized-border:           $button-energized-border !default;\n$tabs-energized-text:             $button-energized-text !default;\n\n$tabs-royal-bg:                   $button-royal-bg !default;\n$tabs-royal-border:               $button-royal-border !default;\n$tabs-royal-text:                 $button-royal-text !default;\n\n$tabs-dark-bg:                    $button-dark-bg !default;\n$tabs-dark-border:                $button-dark-border !default;\n$tabs-dark-text:                  $button-dark-text !default;\n\n$tabs-default-bg:                 $tabs-stable-bg !default;\n$tabs-default-border:             $tabs-stable-border !default;\n$tabs-default-text:               $tabs-stable-text !default;\n\n$tab-item-max-width:              150px !default;\n\n$tabs-off-opacity:                0.4 !default;\n$tabs-striped-off-opacity:        $tabs-off-opacity !default;\n$tabs-striped-off-color:          #000 !default;\n$tabs-striped-border-width:       2px !default;\n\n\n// Items\n// -------------------------------\n\n$item-font-size:                  16px !default;\n$item-border-width:               1px !default;\n$item-padding:                    16px !default;\n\n$item-button-font-size:           18px !default;\n$item-button-line-height:         32px !default;\n$item-icon-font-size:             32px !default;\n$item-icon-fill-font-size:        28px !default;\n\n$item-icon-accessory-color:       #ccc !default;\n$item-icon-accessory-font-size:   16px !default;\n\n$item-avatar-width:               40px !default;\n$item-avatar-height:              40px !default;\n$item-avatar-border-radius:       50% !default;\n\n$item-thumbnail-width:            80px !default;\n$item-thumbnail-height:           80px !default;\n$item-thumbnail-margin:           10px !default;\n\n$item-divider-bg:                 #f5f5f5 !default;\n$item-divider-color:              #222 !default;\n$item-divider-padding:            5px 15px !default;\n\n$item-light-bg:                   $button-light-bg !default;\n$item-light-border:               $button-light-border !default;\n$item-light-text:                 $button-light-text !default;\n$item-light-active-bg:            $button-light-active-bg !default;\n$item-light-active-border:        $button-light-active-border !default;\n\n$item-stable-bg:                  $button-stable-bg !default;\n$item-stable-border:              $button-stable-border !default;\n$item-stable-text:                $button-stable-text !default;\n$item-stable-active-bg:           $button-stable-active-bg !default;\n$item-stable-active-border:       $button-stable-active-border !default;\n\n$item-positive-bg:                $button-positive-bg !default;\n$item-positive-border:            $button-positive-border !default;\n$item-positive-text:              $button-positive-text !default;\n$item-positive-active-bg:         $button-positive-active-bg !default;\n$item-positive-active-border:     $button-positive-active-border !default;\n\n$item-calm-bg:                    $button-calm-bg !default;\n$item-calm-border:                $button-calm-border !default;\n$item-calm-text:                  $button-calm-text !default;\n$item-calm-active-bg:             $button-calm-active-bg !default;\n$item-calm-active-border:         $button-calm-active-border !default;\n\n$item-assertive-bg:               $button-assertive-bg !default;\n$item-assertive-border:           $button-assertive-border !default;\n$item-assertive-text:             $button-assertive-text !default;\n$item-assertive-active-bg:        $button-assertive-active-bg !default;\n$item-assertive-active-border:    $button-assertive-active-border !default;\n\n$item-balanced-bg:                $button-balanced-bg !default;\n$item-balanced-border:            $button-balanced-border !default;\n$item-balanced-text:              $button-balanced-text !default;\n$item-balanced-active-bg:         $button-balanced-active-bg !default;\n$item-balanced-active-border:     $button-balanced-active-border !default;\n\n$item-energized-bg:               $button-energized-bg !default;\n$item-energized-border:           $button-energized-border !default;\n$item-energized-text:             $button-energized-text !default;\n$item-energized-active-bg:        $button-energized-active-bg !default;\n$item-energized-active-border:    $button-energized-active-border !default;\n\n$item-royal-bg:                   $button-royal-bg !default;\n$item-royal-border:               $button-royal-border !default;\n$item-royal-text:                 $button-royal-text !default;\n$item-royal-active-bg:            $button-royal-active-bg !default;\n$item-royal-active-border:        $button-royal-active-border !default;\n\n$item-dark-bg:                    $button-dark-bg !default;\n$item-dark-border:                $button-dark-border !default;\n$item-dark-text:                  $button-dark-text !default;\n$item-dark-active-bg:             $button-dark-active-bg !default;\n$item-dark-active-border:         $button-dark-active-border !default;\n\n$item-default-bg:                 $item-light-bg !default;\n$item-default-border:             $item-light-border !default;\n$item-default-text:               $item-light-text !default;\n$item-default-active-bg:          #D9D9D9 !default;\n$item-default-active-border:      $item-light-active-border !default;\n\n\n// Item Editing\n// -------------------------------\n\n$item-edit-transition-duration:   250ms !default;\n$item-edit-transition-function:   ease-in-out !default;\n\n$item-remove-transition-duration:   300ms !default;\n$item-remove-transition-function:   ease-in !default;\n$item-remove-descendents-transition-function:  cubic-bezier(.25,.81,.24,1) !default;\n\n$item-left-edit-left:             8px !default;  // item's left side edit's \"left\" property\n\n$item-right-edit-open-width:      50px !default;\n$item-left-edit-open-width:       50px !default;\n\n$item-delete-icon-size:           24px !default;\n$item-delete-icon-color:          $assertive !default;\n\n$item-reorder-icon-size:          32px !default;\n$item-reorder-icon-color:         $dark !default;\n\n\n// Lists\n// -------------------------------\n\n$list-header-bg:                  transparent !default;\n$list-header-color:               #222 !default;\n$list-header-padding:             5px 15px !default;\n$list-header-margin-top:          20px !default;\n\n\n// Cards\n// -------------------------------\n\n$card-header-bg:                  #F5F5F5 !default;\n$card-body-bg:                    #fff !default;\n$card-footer-bg:                  #F5F5F5 !default;\n\n$card-padding:                    10px !default;\n$card-border-width:               1px !default;\n\n$card-border-color:               #ccc !default;\n$card-border-radius:              2px !default;\n$card-box-shadow:                 0 1px 3px rgba(0, 0, 0, .3) !default;\n\n\n// Forms\n// -------------------------------\n\n$input-height-base:               ($line-height-computed + ($padding-base-vertical * 2) + 2) !default;\n$input-height-large:              (floor($font-size-large * $line-height-large) + ($padding-large-vertical * 2) + 2) !default;\n$input-height-small:              (floor($font-size-small * $line-height-small) + ($padding-small-vertical * 2) + 2) !default;\n\n$input-bg:                        $light !default;\n$input-bg-disabled:               $stable !default;\n\n$input-color:                     #111 !default;\n$input-border:                    $item-default-border !default;\n$input-border-width:              $item-border-width !default;\n$input-label-color:               $dark !default;\n$input-color-placeholder:         lighten($dark, 40%) !default;\n\n\n// Progress\n// -------------------------------\n\n$progress-width:                  100% !default;\n$progress-margin:                 15px auto !default;\n\n\n// Toggle\n// -------------------------------\n\n$toggle-width:                    51px !default;\n$toggle-height:                   31px !default;\n$toggle-border-width:             2px !default;\n$toggle-border-radius:            20px !default;\n\n$toggle-handle-width:             $toggle-height - ($toggle-border-width * 2) !default;\n$toggle-handle-height:            $toggle-handle-width !default;\n$toggle-handle-radius:            $toggle-handle-width !default;\n$toggle-handle-dragging-bg-color: darken(#fff, 5%) !default;\n\n$toggle-off-bg-color:             #fff !default;\n$toggle-off-border-color:         #e6e6e6 !default;\n\n$toggle-on-light-bg:              $button-light-border !default;\n$toggle-on-light-border:          $toggle-on-light-bg !default;\n$toggle-on-stable-bg:             $button-stable-border !default;\n$toggle-on-stable-border:         $toggle-on-stable-bg !default;\n$toggle-on-positive-bg:           $positive !default;\n$toggle-on-positive-border:       $toggle-on-positive-bg !default;\n$toggle-on-calm-bg:               $calm !default;\n$toggle-on-calm-border:           $toggle-on-calm-bg !default;\n$toggle-on-assertive-bg:          $assertive !default;\n$toggle-on-assertive-border:      $toggle-on-assertive-bg !default;\n$toggle-on-balanced-bg:           $balanced !default;\n$toggle-on-balanced-border:       $toggle-on-balanced-bg !default;\n$toggle-on-energized-bg:          $energized !default;\n$toggle-on-energized-border:      $toggle-on-energized-bg !default;\n$toggle-on-royal-bg:              $royal !default;\n$toggle-on-royal-border:          $toggle-on-royal-bg !default;\n$toggle-on-dark-bg:               $dark !default;\n$toggle-on-dark-border:           $toggle-on-dark-bg !default;\n$toggle-on-default-bg:            #4cd964 !default;\n$toggle-on-default-border:        $toggle-on-default-bg !default;\n\n$toggle-handle-off-bg-color:      $light !default;\n$toggle-handle-on-bg-color:       $toggle-handle-off-bg-color !default;\n\n$toggle-transition-duration:      .3s !default;\n\n$toggle-hit-area-expansion:   5px;\n\n\n// Checkbox\n// -------------------------------\n\n$checkbox-width:                  28px !default;\n$checkbox-height:                 28px !default;\n$checkbox-border-radius:          $checkbox-width !default;\n$checkbox-border-width:           1px !default;\n\n$checkbox-off-bg-color:           #fff !default;\n$checkbox-off-border-light:       $button-light-border !default;\n$checkbox-on-bg-light:            $button-light-border !default;\n$checkbox-off-border-stable:      $button-stable-border !default;\n$checkbox-on-bg-stable:           $button-stable-border !default;\n$checkbox-off-border-positive:    $positive !default;\n$checkbox-on-bg-positive:         $positive !default;\n$checkbox-off-border-calm:        $calm !default;\n$checkbox-on-bg-calm:             $calm !default;\n$checkbox-off-border-assertive:   $assertive !default;\n$checkbox-on-bg-assertive:        $assertive !default;\n$checkbox-off-border-balanced:    $balanced !default;\n$checkbox-on-bg-balanced:         $balanced !default;\n$checkbox-off-border-energized:   $energized !default;\n$checkbox-on-bg-energized:        $energized !default;\n$checkbox-off-border-royal:       $royal !default;\n$checkbox-on-bg-royal:            $royal !default;\n$checkbox-off-border-dark:        $dark !default;\n$checkbox-on-bg-dark:             $dark !default;\n$checkbox-off-border-default:     $button-light-border !default;\n$checkbox-on-bg-default:          $positive !default;\n$checkbox-on-border-default:      $positive !default;\n\n$checkbox-check-width:            1px !default;\n$checkbox-check-color:            #fff !default;\n\n\n// Range\n// -------------------------------\n\n$range-track-height:              2px !default;\n$range-slider-width:              28px !default;\n$range-slider-height:             28px !default;\n$range-slider-border-radius:      50% !default;\n$range-icon-size:                 24px !default;\n$range-slider-box-shadow:         0 0 2px rgba(0,0,0,.3), 0 3px 5px rgba(0,0,0,0.2) !default;\n\n$range-light-track-bg:            $button-light-border !default;\n$range-stable-track-bg:           $button-stable-border !default;\n$range-positive-track-bg:         $button-positive-bg !default;\n$range-calm-track-bg:             $button-calm-bg !default;\n$range-balanced-track-bg:         $button-balanced-bg !default;\n$range-assertive-track-bg:        $button-assertive-bg !default;\n$range-energized-track-bg:        $button-energized-bg !default;\n$range-royal-track-bg:            $button-royal-bg !default;\n$range-dark-track-bg:             $button-dark-bg !default;\n$range-default-track-bg:          #ccc !default;\n\n\n// Menus\n// -------------------------------\n\n$menu-bg:                         #fff !default;\n$menu-width:                      275px !default;\n$menu-animation-speed:            200ms !default;\n\n$menu-side-shadow:                -1px 0px 2px rgba(0, 0, 0, 0.2), 1px 0px 2px rgba(0,0,0,0.2) !default;\n\n\n// Modals\n// -------------------------------\n\n$modal-bg-color:                  #fff !default;\n$modal-backdrop-bg-active:        #000 !default;\n$modal-backdrop-bg-inactive:      rgba(0,0,0,0) !default;\n\n$modal-inset-mode-break-point:    680px !default;  // @media min-width\n$modal-inset-mode-top:            20% !default;\n$modal-inset-mode-right:          20% !default;\n$modal-inset-mode-bottom:         20% !default;\n$modal-inset-mode-left:           20% !default;\n$modal-inset-mode-min-height:     240px !default;\n\n\n// Popovers\n// -------------------------------\n\n$popover-bg-color:                $light !default;\n$popover-backdrop-bg-active:      rgba(0,0,0,0.1) !default;\n$popover-backdrop-bg-inactive:    rgba(0,0,0,0) !default;\n$popover-width:                   220px !default;\n$popover-height:                  280px !default;\n$popover-large-break-point:       680px !default;\n$popover-large-width:             360px !default;\n\n$popover-box-shadow:              0 1px 3px rgba(0,0,0,0.4) !default;\n$popover-border-radius:           2px !default;\n\n$popover-box-shadow-ios:          0 0 40px rgba(0,0,0,0.08) !default;\n$popover-border-radius-ios:       10px !default;\n\n$popover-bg-color-android:        #fafafa !default;\n$popover-box-shadow-android:      0 2px 6px rgba(0,0,0,0.35) !default;\n\n\n// Grids\n// -------------------------------\n\n$grid-padding-width:              10px !default;\n$grid-responsive-sm-break:        567px !default;  // smaller than landscape phone\n$grid-responsive-md-break:        767px !default;  // smaller than portrait tablet\n$grid-responsive-lg-break:        1023px !default; // smaller than landscape tablet\n\n\n// Action Sheets\n// -------------------------------\n\n$sheet-margin:                    8px !default;\n$sheet-border-radius:             4px !default;\n\n$sheet-options-bg-color:          #f1f2f3 !default;\n$sheet-options-bg-active-color:   #e4e5e7 !default;\n$sheet-options-text-color:        #007aff !default;\n$sheet-options-border-color:      #d1d3d6 !default;\n\n\n// Popups\n// -------------------------------\n\n$popup-width:                     250px !default;\n$popup-enter-animation:           superScaleIn !default;\n$popup-enter-animation-duration:  0.2s !default;\n$popup-leave-animation-duration:  0.1s !default;\n\n$popup-border-radius:             0px !default;\n$popup-background-color:          rgba(255,255,255,0.9) !default;\n\n$popup-button-border-radius:      2px !default;\n$popup-button-line-height:        20px !default;\n$popup-button-min-height:         45px !default;\n\n\n// Loading\n// -------------------------------\n\n$loading-text-color:              #fff !default;\n$loading-bg-color:                rgba(0,0,0,0.7) !default;\n$loading-padding:                 20px !default;\n$loading-border-radius:           5px !default;\n$loading-font-size:               15px !default;\n\n$loading-backdrop-fadein-duration:0.1s !default;\n$loading-backdrop-bg-color:       rgba(0,0,0,0.4) !default;\n\n\n// Badges\n// -------------------------------\n\n$badge-font-size:                 14px !default;\n$badge-line-height:               16px !default;\n$badge-font-weight:               bold !default;\n$badge-border-radius:             10px !default;\n\n$badge-light-bg:                  $button-light-bg !default;\n$badge-light-text:                $button-light-text !default;\n\n$badge-stable-bg:                 $button-stable-bg !default;\n$badge-stable-text:               $button-stable-text !default;\n\n$badge-positive-bg:               $button-positive-bg !default;\n$badge-positive-text:             $button-positive-text !default;\n\n$badge-calm-bg:                   $button-calm-bg !default;\n$badge-calm-text:                 $button-calm-text !default;\n\n$badge-balanced-bg:               $button-balanced-bg !default;\n$badge-balanced-text:             $button-balanced-text !default;\n\n$badge-assertive-bg:              $button-assertive-bg !default;\n$badge-assertive-text:            $button-assertive-text !default;\n\n$badge-energized-bg:              $button-energized-bg !default;\n$badge-energized-text:            $button-energized-text !default;\n\n$badge-royal-bg:                  $button-royal-bg !default;\n$badge-royal-text:                $button-royal-text !default;\n\n$badge-dark-bg:                   $button-dark-bg !default;\n$badge-dark-text:                 $button-dark-text !default;\n\n$badge-default-bg:                transparent !default;\n$badge-default-text:              #AAAAAA !default;\n\n\n// Spinners\n// -------------------------------\n\n$spinner-width:                   28px !default;\n$spinner-height:                  28px !default;\n\n$spinner-light-stroke:            $light !default;\n$spinner-light-fill:              $light !default;\n\n$spinner-stable-stroke:           $stable !default;\n$spinner-stable-fill:             $stable !default;\n\n$spinner-positive-stroke:         $positive !default;\n$spinner-positive-fill:           $positive !default;\n\n$spinner-calm-stroke:             $calm !default;\n$spinner-calm-fill:               $calm !default;\n\n$spinner-balanced-stroke:         $balanced !default;\n$spinner-balanced-fill:           $balanced !default;\n\n$spinner-assertive-stroke:        $assertive !default;\n$spinner-assertive-fill:          $assertive !default;\n\n$spinner-energized-stroke:        $energized !default;\n$spinner-energized-fill:          $energized !default;\n\n$spinner-royal-stroke:            $royal !default;\n$spinner-royal-fill:              $royal !default;\n\n$spinner-dark-stroke:             $dark !default;\n$spinner-dark-fill:               $dark !default;\n\n$spinner-default-stroke:          $dark !default;\n$spinner-default-fill:            $dark !default;\n\n\n// Z-Indexes\n// -------------------------------\n\n$z-index-bar-title:               0 !default;\n$z-index-item-drag:               0 !default;\n$z-index-item-edit:               0 !default;\n$z-index-menu:                    0 !default;\n$z-index-badge:                   1 !default;\n$z-index-bar-button:              1 !default;\n$z-index-item-options:            1 !default;\n$z-index-pane:                    1 !default;\n$z-index-slider-pager:            1 !default;\n$z-index-view:                    1 !default;\n$z-index-view-below:              2 !default;\n$z-index-item:                    2 !default;\n$z-index-item-checkbox:           3 !default;\n$z-index-item-radio:              3 !default;\n$z-index-item-reorder:            3 !default;\n$z-index-item-toggle:             3 !default;\n$z-index-view-above:              3 !default;\n$z-index-tabs:                    5 !default;\n$z-index-item-reordering:         9 !default;\n$z-index-bar:                     9 !default;\n$z-index-bar-above:               10 !default;\n$z-index-menu-scroll-content:     10 !default;\n$z-index-modal:                   10 !default;\n$z-index-popover:                 10 !default;\n$z-index-action-sheet:            11 !default;\n$z-index-backdrop:                11 !default;\n$z-index-menu-bar-header:         11 !default;\n$z-index-scroll-content-false:    11 !default;\n$z-index-popup:                   12 !default;\n$z-index-loading:                 13 !default;\n$z-index-scroll-bar:              9999 !default;\n$z-index-click-block:             99999 !default;\n\n\n// Platform\n// -------------------------------\n\n$ios-statusbar-height:           20px !default;\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/ionic.scss",
    "content": "@charset \"UTF-8\";\n\n@import\n  // Ionicons\n  \"ionicons/ionicons.scss\",\n\n  // Variables\n  \"mixins\",\n  \"variables\",\n\n  // Base\n  \"reset\",\n  \"scaffolding\",\n  \"type\",\n\n  // Components\n  \"action-sheet\",\n  \"backdrop\",\n  \"bar\",\n  \"tabs\",\n  \"menu\",\n  \"modal\",\n  \"popover\",\n  \"popup\",\n  \"loading\",\n  \"items\",\n  \"list\",\n  \"badge\",\n  \"slide-box\",\n  \"refresher\",\n  \"spinner\",\n\n  // Forms\n  \"form\",\n  \"checkbox\",\n  \"toggle\",\n  \"radio\",\n  \"range\",\n  \"select\",\n  \"progress\",\n\n  // Buttons\n  \"button\",\n  \"button-bar\",\n\n  // Util\n  \"grid\",\n  \"util\",\n  \"platform\",\n\n  // Animations\n  \"animations\",\n  \"transitions\";\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/ionicons/_ionicons-font.scss",
    "content": "// Ionicons Font Path\n// --------------------------\n\n@font-face {\n font-family: $ionicons-font-family;\n src:url(\"#{$ionicons-font-path}/ionicons.eot?v=#{$ionicons-version}\");\n src:url(\"#{$ionicons-font-path}/ionicons.eot?v=#{$ionicons-version}#iefix\") format(\"embedded-opentype\"),\n  url(\"#{$ionicons-font-path}/ionicons.ttf?v=#{$ionicons-version}\") format(\"truetype\"),\n  url(\"#{$ionicons-font-path}/ionicons.woff?v=#{$ionicons-version}\") format(\"woff\"),\n  url(\"#{$ionicons-font-path}/ionicons.woff\") format(\"woff\"), /* for WP8 */\n  url(\"#{$ionicons-font-path}/ionicons.svg?v=#{$ionicons-version}#Ionicons\") format(\"svg\");\n font-weight: normal;\n font-style: normal;\n}\n\n.ion {\n  display: inline-block;\n  font-family: $ionicons-font-family;\n  speak: none;\n  font-style: normal;\n  font-weight: normal;\n  font-variant: normal;\n  text-transform: none;\n  text-rendering: auto;\n  line-height: 1;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/ionicons/_ionicons-icons.scss",
    "content": "// Ionicons Icons\n// --------------------------\n\n.ionicons,\n.#{$ionicons-prefix}alert:before,\n.#{$ionicons-prefix}alert-circled:before,\n.#{$ionicons-prefix}android-add:before,\n.#{$ionicons-prefix}android-add-circle:before,\n.#{$ionicons-prefix}android-alarm-clock:before,\n.#{$ionicons-prefix}android-alert:before,\n.#{$ionicons-prefix}android-apps:before,\n.#{$ionicons-prefix}android-archive:before,\n.#{$ionicons-prefix}android-arrow-back:before,\n.#{$ionicons-prefix}android-arrow-down:before,\n.#{$ionicons-prefix}android-arrow-dropdown:before,\n.#{$ionicons-prefix}android-arrow-dropdown-circle:before,\n.#{$ionicons-prefix}android-arrow-dropleft:before,\n.#{$ionicons-prefix}android-arrow-dropleft-circle:before,\n.#{$ionicons-prefix}android-arrow-dropright:before,\n.#{$ionicons-prefix}android-arrow-dropright-circle:before,\n.#{$ionicons-prefix}android-arrow-dropup:before,\n.#{$ionicons-prefix}android-arrow-dropup-circle:before,\n.#{$ionicons-prefix}android-arrow-forward:before,\n.#{$ionicons-prefix}android-arrow-up:before,\n.#{$ionicons-prefix}android-attach:before,\n.#{$ionicons-prefix}android-bar:before,\n.#{$ionicons-prefix}android-bicycle:before,\n.#{$ionicons-prefix}android-boat:before,\n.#{$ionicons-prefix}android-bookmark:before,\n.#{$ionicons-prefix}android-bulb:before,\n.#{$ionicons-prefix}android-bus:before,\n.#{$ionicons-prefix}android-calendar:before,\n.#{$ionicons-prefix}android-call:before,\n.#{$ionicons-prefix}android-camera:before,\n.#{$ionicons-prefix}android-cancel:before,\n.#{$ionicons-prefix}android-car:before,\n.#{$ionicons-prefix}android-cart:before,\n.#{$ionicons-prefix}android-chat:before,\n.#{$ionicons-prefix}android-checkbox:before,\n.#{$ionicons-prefix}android-checkbox-blank:before,\n.#{$ionicons-prefix}android-checkbox-outline:before,\n.#{$ionicons-prefix}android-checkbox-outline-blank:before,\n.#{$ionicons-prefix}android-checkmark-circle:before,\n.#{$ionicons-prefix}android-clipboard:before,\n.#{$ionicons-prefix}android-close:before,\n.#{$ionicons-prefix}android-cloud:before,\n.#{$ionicons-prefix}android-cloud-circle:before,\n.#{$ionicons-prefix}android-cloud-done:before,\n.#{$ionicons-prefix}android-cloud-outline:before,\n.#{$ionicons-prefix}android-color-palette:before,\n.#{$ionicons-prefix}android-compass:before,\n.#{$ionicons-prefix}android-contact:before,\n.#{$ionicons-prefix}android-contacts:before,\n.#{$ionicons-prefix}android-contract:before,\n.#{$ionicons-prefix}android-create:before,\n.#{$ionicons-prefix}android-delete:before,\n.#{$ionicons-prefix}android-desktop:before,\n.#{$ionicons-prefix}android-document:before,\n.#{$ionicons-prefix}android-done:before,\n.#{$ionicons-prefix}android-done-all:before,\n.#{$ionicons-prefix}android-download:before,\n.#{$ionicons-prefix}android-drafts:before,\n.#{$ionicons-prefix}android-exit:before,\n.#{$ionicons-prefix}android-expand:before,\n.#{$ionicons-prefix}android-favorite:before,\n.#{$ionicons-prefix}android-favorite-outline:before,\n.#{$ionicons-prefix}android-film:before,\n.#{$ionicons-prefix}android-folder:before,\n.#{$ionicons-prefix}android-folder-open:before,\n.#{$ionicons-prefix}android-funnel:before,\n.#{$ionicons-prefix}android-globe:before,\n.#{$ionicons-prefix}android-hand:before,\n.#{$ionicons-prefix}android-hangout:before,\n.#{$ionicons-prefix}android-happy:before,\n.#{$ionicons-prefix}android-home:before,\n.#{$ionicons-prefix}android-image:before,\n.#{$ionicons-prefix}android-laptop:before,\n.#{$ionicons-prefix}android-list:before,\n.#{$ionicons-prefix}android-locate:before,\n.#{$ionicons-prefix}android-lock:before,\n.#{$ionicons-prefix}android-mail:before,\n.#{$ionicons-prefix}android-map:before,\n.#{$ionicons-prefix}android-menu:before,\n.#{$ionicons-prefix}android-microphone:before,\n.#{$ionicons-prefix}android-microphone-off:before,\n.#{$ionicons-prefix}android-more-horizontal:before,\n.#{$ionicons-prefix}android-more-vertical:before,\n.#{$ionicons-prefix}android-navigate:before,\n.#{$ionicons-prefix}android-notifications:before,\n.#{$ionicons-prefix}android-notifications-none:before,\n.#{$ionicons-prefix}android-notifications-off:before,\n.#{$ionicons-prefix}android-open:before,\n.#{$ionicons-prefix}android-options:before,\n.#{$ionicons-prefix}android-people:before,\n.#{$ionicons-prefix}android-person:before,\n.#{$ionicons-prefix}android-person-add:before,\n.#{$ionicons-prefix}android-phone-landscape:before,\n.#{$ionicons-prefix}android-phone-portrait:before,\n.#{$ionicons-prefix}android-pin:before,\n.#{$ionicons-prefix}android-plane:before,\n.#{$ionicons-prefix}android-playstore:before,\n.#{$ionicons-prefix}android-print:before,\n.#{$ionicons-prefix}android-radio-button-off:before,\n.#{$ionicons-prefix}android-radio-button-on:before,\n.#{$ionicons-prefix}android-refresh:before,\n.#{$ionicons-prefix}android-remove:before,\n.#{$ionicons-prefix}android-remove-circle:before,\n.#{$ionicons-prefix}android-restaurant:before,\n.#{$ionicons-prefix}android-sad:before,\n.#{$ionicons-prefix}android-search:before,\n.#{$ionicons-prefix}android-send:before,\n.#{$ionicons-prefix}android-settings:before,\n.#{$ionicons-prefix}android-share:before,\n.#{$ionicons-prefix}android-share-alt:before,\n.#{$ionicons-prefix}android-star:before,\n.#{$ionicons-prefix}android-star-half:before,\n.#{$ionicons-prefix}android-star-outline:before,\n.#{$ionicons-prefix}android-stopwatch:before,\n.#{$ionicons-prefix}android-subway:before,\n.#{$ionicons-prefix}android-sunny:before,\n.#{$ionicons-prefix}android-sync:before,\n.#{$ionicons-prefix}android-textsms:before,\n.#{$ionicons-prefix}android-time:before,\n.#{$ionicons-prefix}android-train:before,\n.#{$ionicons-prefix}android-unlock:before,\n.#{$ionicons-prefix}android-upload:before,\n.#{$ionicons-prefix}android-volume-down:before,\n.#{$ionicons-prefix}android-volume-mute:before,\n.#{$ionicons-prefix}android-volume-off:before,\n.#{$ionicons-prefix}android-volume-up:before,\n.#{$ionicons-prefix}android-walk:before,\n.#{$ionicons-prefix}android-warning:before,\n.#{$ionicons-prefix}android-watch:before,\n.#{$ionicons-prefix}android-wifi:before,\n.#{$ionicons-prefix}aperture:before,\n.#{$ionicons-prefix}archive:before,\n.#{$ionicons-prefix}arrow-down-a:before,\n.#{$ionicons-prefix}arrow-down-b:before,\n.#{$ionicons-prefix}arrow-down-c:before,\n.#{$ionicons-prefix}arrow-expand:before,\n.#{$ionicons-prefix}arrow-graph-down-left:before,\n.#{$ionicons-prefix}arrow-graph-down-right:before,\n.#{$ionicons-prefix}arrow-graph-up-left:before,\n.#{$ionicons-prefix}arrow-graph-up-right:before,\n.#{$ionicons-prefix}arrow-left-a:before,\n.#{$ionicons-prefix}arrow-left-b:before,\n.#{$ionicons-prefix}arrow-left-c:before,\n.#{$ionicons-prefix}arrow-move:before,\n.#{$ionicons-prefix}arrow-resize:before,\n.#{$ionicons-prefix}arrow-return-left:before,\n.#{$ionicons-prefix}arrow-return-right:before,\n.#{$ionicons-prefix}arrow-right-a:before,\n.#{$ionicons-prefix}arrow-right-b:before,\n.#{$ionicons-prefix}arrow-right-c:before,\n.#{$ionicons-prefix}arrow-shrink:before,\n.#{$ionicons-prefix}arrow-swap:before,\n.#{$ionicons-prefix}arrow-up-a:before,\n.#{$ionicons-prefix}arrow-up-b:before,\n.#{$ionicons-prefix}arrow-up-c:before,\n.#{$ionicons-prefix}asterisk:before,\n.#{$ionicons-prefix}at:before,\n.#{$ionicons-prefix}backspace:before,\n.#{$ionicons-prefix}backspace-outline:before,\n.#{$ionicons-prefix}bag:before,\n.#{$ionicons-prefix}battery-charging:before,\n.#{$ionicons-prefix}battery-empty:before,\n.#{$ionicons-prefix}battery-full:before,\n.#{$ionicons-prefix}battery-half:before,\n.#{$ionicons-prefix}battery-low:before,\n.#{$ionicons-prefix}beaker:before,\n.#{$ionicons-prefix}beer:before,\n.#{$ionicons-prefix}bluetooth:before,\n.#{$ionicons-prefix}bonfire:before,\n.#{$ionicons-prefix}bookmark:before,\n.#{$ionicons-prefix}bowtie:before,\n.#{$ionicons-prefix}briefcase:before,\n.#{$ionicons-prefix}bug:before,\n.#{$ionicons-prefix}calculator:before,\n.#{$ionicons-prefix}calendar:before,\n.#{$ionicons-prefix}camera:before,\n.#{$ionicons-prefix}card:before,\n.#{$ionicons-prefix}cash:before,\n.#{$ionicons-prefix}chatbox:before,\n.#{$ionicons-prefix}chatbox-working:before,\n.#{$ionicons-prefix}chatboxes:before,\n.#{$ionicons-prefix}chatbubble:before,\n.#{$ionicons-prefix}chatbubble-working:before,\n.#{$ionicons-prefix}chatbubbles:before,\n.#{$ionicons-prefix}checkmark:before,\n.#{$ionicons-prefix}checkmark-circled:before,\n.#{$ionicons-prefix}checkmark-round:before,\n.#{$ionicons-prefix}chevron-down:before,\n.#{$ionicons-prefix}chevron-left:before,\n.#{$ionicons-prefix}chevron-right:before,\n.#{$ionicons-prefix}chevron-up:before,\n.#{$ionicons-prefix}clipboard:before,\n.#{$ionicons-prefix}clock:before,\n.#{$ionicons-prefix}close:before,\n.#{$ionicons-prefix}close-circled:before,\n.#{$ionicons-prefix}close-round:before,\n.#{$ionicons-prefix}closed-captioning:before,\n.#{$ionicons-prefix}cloud:before,\n.#{$ionicons-prefix}code:before,\n.#{$ionicons-prefix}code-download:before,\n.#{$ionicons-prefix}code-working:before,\n.#{$ionicons-prefix}coffee:before,\n.#{$ionicons-prefix}compass:before,\n.#{$ionicons-prefix}compose:before,\n.#{$ionicons-prefix}connection-bars:before,\n.#{$ionicons-prefix}contrast:before,\n.#{$ionicons-prefix}crop:before,\n.#{$ionicons-prefix}cube:before,\n.#{$ionicons-prefix}disc:before,\n.#{$ionicons-prefix}document:before,\n.#{$ionicons-prefix}document-text:before,\n.#{$ionicons-prefix}drag:before,\n.#{$ionicons-prefix}earth:before,\n.#{$ionicons-prefix}easel:before,\n.#{$ionicons-prefix}edit:before,\n.#{$ionicons-prefix}egg:before,\n.#{$ionicons-prefix}eject:before,\n.#{$ionicons-prefix}email:before,\n.#{$ionicons-prefix}email-unread:before,\n.#{$ionicons-prefix}erlenmeyer-flask:before,\n.#{$ionicons-prefix}erlenmeyer-flask-bubbles:before,\n.#{$ionicons-prefix}eye:before,\n.#{$ionicons-prefix}eye-disabled:before,\n.#{$ionicons-prefix}female:before,\n.#{$ionicons-prefix}filing:before,\n.#{$ionicons-prefix}film-marker:before,\n.#{$ionicons-prefix}fireball:before,\n.#{$ionicons-prefix}flag:before,\n.#{$ionicons-prefix}flame:before,\n.#{$ionicons-prefix}flash:before,\n.#{$ionicons-prefix}flash-off:before,\n.#{$ionicons-prefix}folder:before,\n.#{$ionicons-prefix}fork:before,\n.#{$ionicons-prefix}fork-repo:before,\n.#{$ionicons-prefix}forward:before,\n.#{$ionicons-prefix}funnel:before,\n.#{$ionicons-prefix}gear-a:before,\n.#{$ionicons-prefix}gear-b:before,\n.#{$ionicons-prefix}grid:before,\n.#{$ionicons-prefix}hammer:before,\n.#{$ionicons-prefix}happy:before,\n.#{$ionicons-prefix}happy-outline:before,\n.#{$ionicons-prefix}headphone:before,\n.#{$ionicons-prefix}heart:before,\n.#{$ionicons-prefix}heart-broken:before,\n.#{$ionicons-prefix}help:before,\n.#{$ionicons-prefix}help-buoy:before,\n.#{$ionicons-prefix}help-circled:before,\n.#{$ionicons-prefix}home:before,\n.#{$ionicons-prefix}icecream:before,\n.#{$ionicons-prefix}image:before,\n.#{$ionicons-prefix}images:before,\n.#{$ionicons-prefix}information:before,\n.#{$ionicons-prefix}information-circled:before,\n.#{$ionicons-prefix}ionic:before,\n.#{$ionicons-prefix}ios-alarm:before,\n.#{$ionicons-prefix}ios-alarm-outline:before,\n.#{$ionicons-prefix}ios-albums:before,\n.#{$ionicons-prefix}ios-albums-outline:before,\n.#{$ionicons-prefix}ios-americanfootball:before,\n.#{$ionicons-prefix}ios-americanfootball-outline:before,\n.#{$ionicons-prefix}ios-analytics:before,\n.#{$ionicons-prefix}ios-analytics-outline:before,\n.#{$ionicons-prefix}ios-arrow-back:before,\n.#{$ionicons-prefix}ios-arrow-down:before,\n.#{$ionicons-prefix}ios-arrow-forward:before,\n.#{$ionicons-prefix}ios-arrow-left:before,\n.#{$ionicons-prefix}ios-arrow-right:before,\n.#{$ionicons-prefix}ios-arrow-thin-down:before,\n.#{$ionicons-prefix}ios-arrow-thin-left:before,\n.#{$ionicons-prefix}ios-arrow-thin-right:before,\n.#{$ionicons-prefix}ios-arrow-thin-up:before,\n.#{$ionicons-prefix}ios-arrow-up:before,\n.#{$ionicons-prefix}ios-at:before,\n.#{$ionicons-prefix}ios-at-outline:before,\n.#{$ionicons-prefix}ios-barcode:before,\n.#{$ionicons-prefix}ios-barcode-outline:before,\n.#{$ionicons-prefix}ios-baseball:before,\n.#{$ionicons-prefix}ios-baseball-outline:before,\n.#{$ionicons-prefix}ios-basketball:before,\n.#{$ionicons-prefix}ios-basketball-outline:before,\n.#{$ionicons-prefix}ios-bell:before,\n.#{$ionicons-prefix}ios-bell-outline:before,\n.#{$ionicons-prefix}ios-body:before,\n.#{$ionicons-prefix}ios-body-outline:before,\n.#{$ionicons-prefix}ios-bolt:before,\n.#{$ionicons-prefix}ios-bolt-outline:before,\n.#{$ionicons-prefix}ios-book:before,\n.#{$ionicons-prefix}ios-book-outline:before,\n.#{$ionicons-prefix}ios-bookmarks:before,\n.#{$ionicons-prefix}ios-bookmarks-outline:before,\n.#{$ionicons-prefix}ios-box:before,\n.#{$ionicons-prefix}ios-box-outline:before,\n.#{$ionicons-prefix}ios-briefcase:before,\n.#{$ionicons-prefix}ios-briefcase-outline:before,\n.#{$ionicons-prefix}ios-browsers:before,\n.#{$ionicons-prefix}ios-browsers-outline:before,\n.#{$ionicons-prefix}ios-calculator:before,\n.#{$ionicons-prefix}ios-calculator-outline:before,\n.#{$ionicons-prefix}ios-calendar:before,\n.#{$ionicons-prefix}ios-calendar-outline:before,\n.#{$ionicons-prefix}ios-camera:before,\n.#{$ionicons-prefix}ios-camera-outline:before,\n.#{$ionicons-prefix}ios-cart:before,\n.#{$ionicons-prefix}ios-cart-outline:before,\n.#{$ionicons-prefix}ios-chatboxes:before,\n.#{$ionicons-prefix}ios-chatboxes-outline:before,\n.#{$ionicons-prefix}ios-chatbubble:before,\n.#{$ionicons-prefix}ios-chatbubble-outline:before,\n.#{$ionicons-prefix}ios-checkmark:before,\n.#{$ionicons-prefix}ios-checkmark-empty:before,\n.#{$ionicons-prefix}ios-checkmark-outline:before,\n.#{$ionicons-prefix}ios-circle-filled:before,\n.#{$ionicons-prefix}ios-circle-outline:before,\n.#{$ionicons-prefix}ios-clock:before,\n.#{$ionicons-prefix}ios-clock-outline:before,\n.#{$ionicons-prefix}ios-close:before,\n.#{$ionicons-prefix}ios-close-empty:before,\n.#{$ionicons-prefix}ios-close-outline:before,\n.#{$ionicons-prefix}ios-cloud:before,\n.#{$ionicons-prefix}ios-cloud-download:before,\n.#{$ionicons-prefix}ios-cloud-download-outline:before,\n.#{$ionicons-prefix}ios-cloud-outline:before,\n.#{$ionicons-prefix}ios-cloud-upload:before,\n.#{$ionicons-prefix}ios-cloud-upload-outline:before,\n.#{$ionicons-prefix}ios-cloudy:before,\n.#{$ionicons-prefix}ios-cloudy-night:before,\n.#{$ionicons-prefix}ios-cloudy-night-outline:before,\n.#{$ionicons-prefix}ios-cloudy-outline:before,\n.#{$ionicons-prefix}ios-cog:before,\n.#{$ionicons-prefix}ios-cog-outline:before,\n.#{$ionicons-prefix}ios-color-filter:before,\n.#{$ionicons-prefix}ios-color-filter-outline:before,\n.#{$ionicons-prefix}ios-color-wand:before,\n.#{$ionicons-prefix}ios-color-wand-outline:before,\n.#{$ionicons-prefix}ios-compose:before,\n.#{$ionicons-prefix}ios-compose-outline:before,\n.#{$ionicons-prefix}ios-contact:before,\n.#{$ionicons-prefix}ios-contact-outline:before,\n.#{$ionicons-prefix}ios-copy:before,\n.#{$ionicons-prefix}ios-copy-outline:before,\n.#{$ionicons-prefix}ios-crop:before,\n.#{$ionicons-prefix}ios-crop-strong:before,\n.#{$ionicons-prefix}ios-download:before,\n.#{$ionicons-prefix}ios-download-outline:before,\n.#{$ionicons-prefix}ios-drag:before,\n.#{$ionicons-prefix}ios-email:before,\n.#{$ionicons-prefix}ios-email-outline:before,\n.#{$ionicons-prefix}ios-eye:before,\n.#{$ionicons-prefix}ios-eye-outline:before,\n.#{$ionicons-prefix}ios-fastforward:before,\n.#{$ionicons-prefix}ios-fastforward-outline:before,\n.#{$ionicons-prefix}ios-filing:before,\n.#{$ionicons-prefix}ios-filing-outline:before,\n.#{$ionicons-prefix}ios-film:before,\n.#{$ionicons-prefix}ios-film-outline:before,\n.#{$ionicons-prefix}ios-flag:before,\n.#{$ionicons-prefix}ios-flag-outline:before,\n.#{$ionicons-prefix}ios-flame:before,\n.#{$ionicons-prefix}ios-flame-outline:before,\n.#{$ionicons-prefix}ios-flask:before,\n.#{$ionicons-prefix}ios-flask-outline:before,\n.#{$ionicons-prefix}ios-flower:before,\n.#{$ionicons-prefix}ios-flower-outline:before,\n.#{$ionicons-prefix}ios-folder:before,\n.#{$ionicons-prefix}ios-folder-outline:before,\n.#{$ionicons-prefix}ios-football:before,\n.#{$ionicons-prefix}ios-football-outline:before,\n.#{$ionicons-prefix}ios-game-controller-a:before,\n.#{$ionicons-prefix}ios-game-controller-a-outline:before,\n.#{$ionicons-prefix}ios-game-controller-b:before,\n.#{$ionicons-prefix}ios-game-controller-b-outline:before,\n.#{$ionicons-prefix}ios-gear:before,\n.#{$ionicons-prefix}ios-gear-outline:before,\n.#{$ionicons-prefix}ios-glasses:before,\n.#{$ionicons-prefix}ios-glasses-outline:before,\n.#{$ionicons-prefix}ios-grid-view:before,\n.#{$ionicons-prefix}ios-grid-view-outline:before,\n.#{$ionicons-prefix}ios-heart:before,\n.#{$ionicons-prefix}ios-heart-outline:before,\n.#{$ionicons-prefix}ios-help:before,\n.#{$ionicons-prefix}ios-help-empty:before,\n.#{$ionicons-prefix}ios-help-outline:before,\n.#{$ionicons-prefix}ios-home:before,\n.#{$ionicons-prefix}ios-home-outline:before,\n.#{$ionicons-prefix}ios-infinite:before,\n.#{$ionicons-prefix}ios-infinite-outline:before,\n.#{$ionicons-prefix}ios-information:before,\n.#{$ionicons-prefix}ios-information-empty:before,\n.#{$ionicons-prefix}ios-information-outline:before,\n.#{$ionicons-prefix}ios-ionic-outline:before,\n.#{$ionicons-prefix}ios-keypad:before,\n.#{$ionicons-prefix}ios-keypad-outline:before,\n.#{$ionicons-prefix}ios-lightbulb:before,\n.#{$ionicons-prefix}ios-lightbulb-outline:before,\n.#{$ionicons-prefix}ios-list:before,\n.#{$ionicons-prefix}ios-list-outline:before,\n.#{$ionicons-prefix}ios-location:before,\n.#{$ionicons-prefix}ios-location-outline:before,\n.#{$ionicons-prefix}ios-locked:before,\n.#{$ionicons-prefix}ios-locked-outline:before,\n.#{$ionicons-prefix}ios-loop:before,\n.#{$ionicons-prefix}ios-loop-strong:before,\n.#{$ionicons-prefix}ios-medical:before,\n.#{$ionicons-prefix}ios-medical-outline:before,\n.#{$ionicons-prefix}ios-medkit:before,\n.#{$ionicons-prefix}ios-medkit-outline:before,\n.#{$ionicons-prefix}ios-mic:before,\n.#{$ionicons-prefix}ios-mic-off:before,\n.#{$ionicons-prefix}ios-mic-outline:before,\n.#{$ionicons-prefix}ios-minus:before,\n.#{$ionicons-prefix}ios-minus-empty:before,\n.#{$ionicons-prefix}ios-minus-outline:before,\n.#{$ionicons-prefix}ios-monitor:before,\n.#{$ionicons-prefix}ios-monitor-outline:before,\n.#{$ionicons-prefix}ios-moon:before,\n.#{$ionicons-prefix}ios-moon-outline:before,\n.#{$ionicons-prefix}ios-more:before,\n.#{$ionicons-prefix}ios-more-outline:before,\n.#{$ionicons-prefix}ios-musical-note:before,\n.#{$ionicons-prefix}ios-musical-notes:before,\n.#{$ionicons-prefix}ios-navigate:before,\n.#{$ionicons-prefix}ios-navigate-outline:before,\n.#{$ionicons-prefix}ios-nutrition:before,\n.#{$ionicons-prefix}ios-nutrition-outline:before,\n.#{$ionicons-prefix}ios-paper:before,\n.#{$ionicons-prefix}ios-paper-outline:before,\n.#{$ionicons-prefix}ios-paperplane:before,\n.#{$ionicons-prefix}ios-paperplane-outline:before,\n.#{$ionicons-prefix}ios-partlysunny:before,\n.#{$ionicons-prefix}ios-partlysunny-outline:before,\n.#{$ionicons-prefix}ios-pause:before,\n.#{$ionicons-prefix}ios-pause-outline:before,\n.#{$ionicons-prefix}ios-paw:before,\n.#{$ionicons-prefix}ios-paw-outline:before,\n.#{$ionicons-prefix}ios-people:before,\n.#{$ionicons-prefix}ios-people-outline:before,\n.#{$ionicons-prefix}ios-person:before,\n.#{$ionicons-prefix}ios-person-outline:before,\n.#{$ionicons-prefix}ios-personadd:before,\n.#{$ionicons-prefix}ios-personadd-outline:before,\n.#{$ionicons-prefix}ios-photos:before,\n.#{$ionicons-prefix}ios-photos-outline:before,\n.#{$ionicons-prefix}ios-pie:before,\n.#{$ionicons-prefix}ios-pie-outline:before,\n.#{$ionicons-prefix}ios-pint:before,\n.#{$ionicons-prefix}ios-pint-outline:before,\n.#{$ionicons-prefix}ios-play:before,\n.#{$ionicons-prefix}ios-play-outline:before,\n.#{$ionicons-prefix}ios-plus:before,\n.#{$ionicons-prefix}ios-plus-empty:before,\n.#{$ionicons-prefix}ios-plus-outline:before,\n.#{$ionicons-prefix}ios-pricetag:before,\n.#{$ionicons-prefix}ios-pricetag-outline:before,\n.#{$ionicons-prefix}ios-pricetags:before,\n.#{$ionicons-prefix}ios-pricetags-outline:before,\n.#{$ionicons-prefix}ios-printer:before,\n.#{$ionicons-prefix}ios-printer-outline:before,\n.#{$ionicons-prefix}ios-pulse:before,\n.#{$ionicons-prefix}ios-pulse-strong:before,\n.#{$ionicons-prefix}ios-rainy:before,\n.#{$ionicons-prefix}ios-rainy-outline:before,\n.#{$ionicons-prefix}ios-recording:before,\n.#{$ionicons-prefix}ios-recording-outline:before,\n.#{$ionicons-prefix}ios-redo:before,\n.#{$ionicons-prefix}ios-redo-outline:before,\n.#{$ionicons-prefix}ios-refresh:before,\n.#{$ionicons-prefix}ios-refresh-empty:before,\n.#{$ionicons-prefix}ios-refresh-outline:before,\n.#{$ionicons-prefix}ios-reload:before,\n.#{$ionicons-prefix}ios-reverse-camera:before,\n.#{$ionicons-prefix}ios-reverse-camera-outline:before,\n.#{$ionicons-prefix}ios-rewind:before,\n.#{$ionicons-prefix}ios-rewind-outline:before,\n.#{$ionicons-prefix}ios-rose:before,\n.#{$ionicons-prefix}ios-rose-outline:before,\n.#{$ionicons-prefix}ios-search:before,\n.#{$ionicons-prefix}ios-search-strong:before,\n.#{$ionicons-prefix}ios-settings:before,\n.#{$ionicons-prefix}ios-settings-strong:before,\n.#{$ionicons-prefix}ios-shuffle:before,\n.#{$ionicons-prefix}ios-shuffle-strong:before,\n.#{$ionicons-prefix}ios-skipbackward:before,\n.#{$ionicons-prefix}ios-skipbackward-outline:before,\n.#{$ionicons-prefix}ios-skipforward:before,\n.#{$ionicons-prefix}ios-skipforward-outline:before,\n.#{$ionicons-prefix}ios-snowy:before,\n.#{$ionicons-prefix}ios-speedometer:before,\n.#{$ionicons-prefix}ios-speedometer-outline:before,\n.#{$ionicons-prefix}ios-star:before,\n.#{$ionicons-prefix}ios-star-half:before,\n.#{$ionicons-prefix}ios-star-outline:before,\n.#{$ionicons-prefix}ios-stopwatch:before,\n.#{$ionicons-prefix}ios-stopwatch-outline:before,\n.#{$ionicons-prefix}ios-sunny:before,\n.#{$ionicons-prefix}ios-sunny-outline:before,\n.#{$ionicons-prefix}ios-telephone:before,\n.#{$ionicons-prefix}ios-telephone-outline:before,\n.#{$ionicons-prefix}ios-tennisball:before,\n.#{$ionicons-prefix}ios-tennisball-outline:before,\n.#{$ionicons-prefix}ios-thunderstorm:before,\n.#{$ionicons-prefix}ios-thunderstorm-outline:before,\n.#{$ionicons-prefix}ios-time:before,\n.#{$ionicons-prefix}ios-time-outline:before,\n.#{$ionicons-prefix}ios-timer:before,\n.#{$ionicons-prefix}ios-timer-outline:before,\n.#{$ionicons-prefix}ios-toggle:before,\n.#{$ionicons-prefix}ios-toggle-outline:before,\n.#{$ionicons-prefix}ios-trash:before,\n.#{$ionicons-prefix}ios-trash-outline:before,\n.#{$ionicons-prefix}ios-undo:before,\n.#{$ionicons-prefix}ios-undo-outline:before,\n.#{$ionicons-prefix}ios-unlocked:before,\n.#{$ionicons-prefix}ios-unlocked-outline:before,\n.#{$ionicons-prefix}ios-upload:before,\n.#{$ionicons-prefix}ios-upload-outline:before,\n.#{$ionicons-prefix}ios-videocam:before,\n.#{$ionicons-prefix}ios-videocam-outline:before,\n.#{$ionicons-prefix}ios-volume-high:before,\n.#{$ionicons-prefix}ios-volume-low:before,\n.#{$ionicons-prefix}ios-wineglass:before,\n.#{$ionicons-prefix}ios-wineglass-outline:before,\n.#{$ionicons-prefix}ios-world:before,\n.#{$ionicons-prefix}ios-world-outline:before,\n.#{$ionicons-prefix}ipad:before,\n.#{$ionicons-prefix}iphone:before,\n.#{$ionicons-prefix}ipod:before,\n.#{$ionicons-prefix}jet:before,\n.#{$ionicons-prefix}key:before,\n.#{$ionicons-prefix}knife:before,\n.#{$ionicons-prefix}laptop:before,\n.#{$ionicons-prefix}leaf:before,\n.#{$ionicons-prefix}levels:before,\n.#{$ionicons-prefix}lightbulb:before,\n.#{$ionicons-prefix}link:before,\n.#{$ionicons-prefix}load-a:before,\n.#{$ionicons-prefix}load-b:before,\n.#{$ionicons-prefix}load-c:before,\n.#{$ionicons-prefix}load-d:before,\n.#{$ionicons-prefix}location:before,\n.#{$ionicons-prefix}lock-combination:before,\n.#{$ionicons-prefix}locked:before,\n.#{$ionicons-prefix}log-in:before,\n.#{$ionicons-prefix}log-out:before,\n.#{$ionicons-prefix}loop:before,\n.#{$ionicons-prefix}magnet:before,\n.#{$ionicons-prefix}male:before,\n.#{$ionicons-prefix}man:before,\n.#{$ionicons-prefix}map:before,\n.#{$ionicons-prefix}medkit:before,\n.#{$ionicons-prefix}merge:before,\n.#{$ionicons-prefix}mic-a:before,\n.#{$ionicons-prefix}mic-b:before,\n.#{$ionicons-prefix}mic-c:before,\n.#{$ionicons-prefix}minus:before,\n.#{$ionicons-prefix}minus-circled:before,\n.#{$ionicons-prefix}minus-round:before,\n.#{$ionicons-prefix}model-s:before,\n.#{$ionicons-prefix}monitor:before,\n.#{$ionicons-prefix}more:before,\n.#{$ionicons-prefix}mouse:before,\n.#{$ionicons-prefix}music-note:before,\n.#{$ionicons-prefix}navicon:before,\n.#{$ionicons-prefix}navicon-round:before,\n.#{$ionicons-prefix}navigate:before,\n.#{$ionicons-prefix}network:before,\n.#{$ionicons-prefix}no-smoking:before,\n.#{$ionicons-prefix}nuclear:before,\n.#{$ionicons-prefix}outlet:before,\n.#{$ionicons-prefix}paintbrush:before,\n.#{$ionicons-prefix}paintbucket:before,\n.#{$ionicons-prefix}paper-airplane:before,\n.#{$ionicons-prefix}paperclip:before,\n.#{$ionicons-prefix}pause:before,\n.#{$ionicons-prefix}person:before,\n.#{$ionicons-prefix}person-add:before,\n.#{$ionicons-prefix}person-stalker:before,\n.#{$ionicons-prefix}pie-graph:before,\n.#{$ionicons-prefix}pin:before,\n.#{$ionicons-prefix}pinpoint:before,\n.#{$ionicons-prefix}pizza:before,\n.#{$ionicons-prefix}plane:before,\n.#{$ionicons-prefix}planet:before,\n.#{$ionicons-prefix}play:before,\n.#{$ionicons-prefix}playstation:before,\n.#{$ionicons-prefix}plus:before,\n.#{$ionicons-prefix}plus-circled:before,\n.#{$ionicons-prefix}plus-round:before,\n.#{$ionicons-prefix}podium:before,\n.#{$ionicons-prefix}pound:before,\n.#{$ionicons-prefix}power:before,\n.#{$ionicons-prefix}pricetag:before,\n.#{$ionicons-prefix}pricetags:before,\n.#{$ionicons-prefix}printer:before,\n.#{$ionicons-prefix}pull-request:before,\n.#{$ionicons-prefix}qr-scanner:before,\n.#{$ionicons-prefix}quote:before,\n.#{$ionicons-prefix}radio-waves:before,\n.#{$ionicons-prefix}record:before,\n.#{$ionicons-prefix}refresh:before,\n.#{$ionicons-prefix}reply:before,\n.#{$ionicons-prefix}reply-all:before,\n.#{$ionicons-prefix}ribbon-a:before,\n.#{$ionicons-prefix}ribbon-b:before,\n.#{$ionicons-prefix}sad:before,\n.#{$ionicons-prefix}sad-outline:before,\n.#{$ionicons-prefix}scissors:before,\n.#{$ionicons-prefix}search:before,\n.#{$ionicons-prefix}settings:before,\n.#{$ionicons-prefix}share:before,\n.#{$ionicons-prefix}shuffle:before,\n.#{$ionicons-prefix}skip-backward:before,\n.#{$ionicons-prefix}skip-forward:before,\n.#{$ionicons-prefix}social-android:before,\n.#{$ionicons-prefix}social-android-outline:before,\n.#{$ionicons-prefix}social-angular:before,\n.#{$ionicons-prefix}social-angular-outline:before,\n.#{$ionicons-prefix}social-apple:before,\n.#{$ionicons-prefix}social-apple-outline:before,\n.#{$ionicons-prefix}social-bitcoin:before,\n.#{$ionicons-prefix}social-bitcoin-outline:before,\n.#{$ionicons-prefix}social-buffer:before,\n.#{$ionicons-prefix}social-buffer-outline:before,\n.#{$ionicons-prefix}social-chrome:before,\n.#{$ionicons-prefix}social-chrome-outline:before,\n.#{$ionicons-prefix}social-codepen:before,\n.#{$ionicons-prefix}social-codepen-outline:before,\n.#{$ionicons-prefix}social-css3:before,\n.#{$ionicons-prefix}social-css3-outline:before,\n.#{$ionicons-prefix}social-designernews:before,\n.#{$ionicons-prefix}social-designernews-outline:before,\n.#{$ionicons-prefix}social-dribbble:before,\n.#{$ionicons-prefix}social-dribbble-outline:before,\n.#{$ionicons-prefix}social-dropbox:before,\n.#{$ionicons-prefix}social-dropbox-outline:before,\n.#{$ionicons-prefix}social-euro:before,\n.#{$ionicons-prefix}social-euro-outline:before,\n.#{$ionicons-prefix}social-facebook:before,\n.#{$ionicons-prefix}social-facebook-outline:before,\n.#{$ionicons-prefix}social-foursquare:before,\n.#{$ionicons-prefix}social-foursquare-outline:before,\n.#{$ionicons-prefix}social-freebsd-devil:before,\n.#{$ionicons-prefix}social-github:before,\n.#{$ionicons-prefix}social-github-outline:before,\n.#{$ionicons-prefix}social-google:before,\n.#{$ionicons-prefix}social-google-outline:before,\n.#{$ionicons-prefix}social-googleplus:before,\n.#{$ionicons-prefix}social-googleplus-outline:before,\n.#{$ionicons-prefix}social-hackernews:before,\n.#{$ionicons-prefix}social-hackernews-outline:before,\n.#{$ionicons-prefix}social-html5:before,\n.#{$ionicons-prefix}social-html5-outline:before,\n.#{$ionicons-prefix}social-instagram:before,\n.#{$ionicons-prefix}social-instagram-outline:before,\n.#{$ionicons-prefix}social-javascript:before,\n.#{$ionicons-prefix}social-javascript-outline:before,\n.#{$ionicons-prefix}social-linkedin:before,\n.#{$ionicons-prefix}social-linkedin-outline:before,\n.#{$ionicons-prefix}social-markdown:before,\n.#{$ionicons-prefix}social-nodejs:before,\n.#{$ionicons-prefix}social-octocat:before,\n.#{$ionicons-prefix}social-pinterest:before,\n.#{$ionicons-prefix}social-pinterest-outline:before,\n.#{$ionicons-prefix}social-python:before,\n.#{$ionicons-prefix}social-reddit:before,\n.#{$ionicons-prefix}social-reddit-outline:before,\n.#{$ionicons-prefix}social-rss:before,\n.#{$ionicons-prefix}social-rss-outline:before,\n.#{$ionicons-prefix}social-sass:before,\n.#{$ionicons-prefix}social-skype:before,\n.#{$ionicons-prefix}social-skype-outline:before,\n.#{$ionicons-prefix}social-snapchat:before,\n.#{$ionicons-prefix}social-snapchat-outline:before,\n.#{$ionicons-prefix}social-tumblr:before,\n.#{$ionicons-prefix}social-tumblr-outline:before,\n.#{$ionicons-prefix}social-tux:before,\n.#{$ionicons-prefix}social-twitch:before,\n.#{$ionicons-prefix}social-twitch-outline:before,\n.#{$ionicons-prefix}social-twitter:before,\n.#{$ionicons-prefix}social-twitter-outline:before,\n.#{$ionicons-prefix}social-usd:before,\n.#{$ionicons-prefix}social-usd-outline:before,\n.#{$ionicons-prefix}social-vimeo:before,\n.#{$ionicons-prefix}social-vimeo-outline:before,\n.#{$ionicons-prefix}social-whatsapp:before,\n.#{$ionicons-prefix}social-whatsapp-outline:before,\n.#{$ionicons-prefix}social-windows:before,\n.#{$ionicons-prefix}social-windows-outline:before,\n.#{$ionicons-prefix}social-wordpress:before,\n.#{$ionicons-prefix}social-wordpress-outline:before,\n.#{$ionicons-prefix}social-yahoo:before,\n.#{$ionicons-prefix}social-yahoo-outline:before,\n.#{$ionicons-prefix}social-yen:before,\n.#{$ionicons-prefix}social-yen-outline:before,\n.#{$ionicons-prefix}social-youtube:before,\n.#{$ionicons-prefix}social-youtube-outline:before,\n.#{$ionicons-prefix}soup-can:before,\n.#{$ionicons-prefix}soup-can-outline:before,\n.#{$ionicons-prefix}speakerphone:before,\n.#{$ionicons-prefix}speedometer:before,\n.#{$ionicons-prefix}spoon:before,\n.#{$ionicons-prefix}star:before,\n.#{$ionicons-prefix}stats-bars:before,\n.#{$ionicons-prefix}steam:before,\n.#{$ionicons-prefix}stop:before,\n.#{$ionicons-prefix}thermometer:before,\n.#{$ionicons-prefix}thumbsdown:before,\n.#{$ionicons-prefix}thumbsup:before,\n.#{$ionicons-prefix}toggle:before,\n.#{$ionicons-prefix}toggle-filled:before,\n.#{$ionicons-prefix}transgender:before,\n.#{$ionicons-prefix}trash-a:before,\n.#{$ionicons-prefix}trash-b:before,\n.#{$ionicons-prefix}trophy:before,\n.#{$ionicons-prefix}tshirt:before,\n.#{$ionicons-prefix}tshirt-outline:before,\n.#{$ionicons-prefix}umbrella:before,\n.#{$ionicons-prefix}university:before,\n.#{$ionicons-prefix}unlocked:before,\n.#{$ionicons-prefix}upload:before,\n.#{$ionicons-prefix}usb:before,\n.#{$ionicons-prefix}videocamera:before,\n.#{$ionicons-prefix}volume-high:before,\n.#{$ionicons-prefix}volume-low:before,\n.#{$ionicons-prefix}volume-medium:before,\n.#{$ionicons-prefix}volume-mute:before,\n.#{$ionicons-prefix}wand:before,\n.#{$ionicons-prefix}waterdrop:before,\n.#{$ionicons-prefix}wifi:before,\n.#{$ionicons-prefix}wineglass:before,\n.#{$ionicons-prefix}woman:before,\n.#{$ionicons-prefix}wrench:before,\n.#{$ionicons-prefix}xbox:before\n{\n  @extend .ion;\n}\n.#{$ionicons-prefix}alert:before { content: $ionicon-var-alert; }\n.#{$ionicons-prefix}alert-circled:before { content: $ionicon-var-alert-circled; }\n.#{$ionicons-prefix}android-add:before { content: $ionicon-var-android-add; }\n.#{$ionicons-prefix}android-add-circle:before { content: $ionicon-var-android-add-circle; }\n.#{$ionicons-prefix}android-alarm-clock:before { content: $ionicon-var-android-alarm-clock; }\n.#{$ionicons-prefix}android-alert:before { content: $ionicon-var-android-alert; }\n.#{$ionicons-prefix}android-apps:before { content: $ionicon-var-android-apps; }\n.#{$ionicons-prefix}android-archive:before { content: $ionicon-var-android-archive; }\n.#{$ionicons-prefix}android-arrow-back:before { content: $ionicon-var-android-arrow-back; }\n.#{$ionicons-prefix}android-arrow-down:before { content: $ionicon-var-android-arrow-down; }\n.#{$ionicons-prefix}android-arrow-dropdown:before { content: $ionicon-var-android-arrow-dropdown; }\n.#{$ionicons-prefix}android-arrow-dropdown-circle:before { content: $ionicon-var-android-arrow-dropdown-circle; }\n.#{$ionicons-prefix}android-arrow-dropleft:before { content: $ionicon-var-android-arrow-dropleft; }\n.#{$ionicons-prefix}android-arrow-dropleft-circle:before { content: $ionicon-var-android-arrow-dropleft-circle; }\n.#{$ionicons-prefix}android-arrow-dropright:before { content: $ionicon-var-android-arrow-dropright; }\n.#{$ionicons-prefix}android-arrow-dropright-circle:before { content: $ionicon-var-android-arrow-dropright-circle; }\n.#{$ionicons-prefix}android-arrow-dropup:before { content: $ionicon-var-android-arrow-dropup; }\n.#{$ionicons-prefix}android-arrow-dropup-circle:before { content: $ionicon-var-android-arrow-dropup-circle; }\n.#{$ionicons-prefix}android-arrow-forward:before { content: $ionicon-var-android-arrow-forward; }\n.#{$ionicons-prefix}android-arrow-up:before { content: $ionicon-var-android-arrow-up; }\n.#{$ionicons-prefix}android-attach:before { content: $ionicon-var-android-attach; }\n.#{$ionicons-prefix}android-bar:before { content: $ionicon-var-android-bar; }\n.#{$ionicons-prefix}android-bicycle:before { content: $ionicon-var-android-bicycle; }\n.#{$ionicons-prefix}android-boat:before { content: $ionicon-var-android-boat; }\n.#{$ionicons-prefix}android-bookmark:before { content: $ionicon-var-android-bookmark; }\n.#{$ionicons-prefix}android-bulb:before { content: $ionicon-var-android-bulb; }\n.#{$ionicons-prefix}android-bus:before { content: $ionicon-var-android-bus; }\n.#{$ionicons-prefix}android-calendar:before { content: $ionicon-var-android-calendar; }\n.#{$ionicons-prefix}android-call:before { content: $ionicon-var-android-call; }\n.#{$ionicons-prefix}android-camera:before { content: $ionicon-var-android-camera; }\n.#{$ionicons-prefix}android-cancel:before { content: $ionicon-var-android-cancel; }\n.#{$ionicons-prefix}android-car:before { content: $ionicon-var-android-car; }\n.#{$ionicons-prefix}android-cart:before { content: $ionicon-var-android-cart; }\n.#{$ionicons-prefix}android-chat:before { content: $ionicon-var-android-chat; }\n.#{$ionicons-prefix}android-checkbox:before { content: $ionicon-var-android-checkbox; }\n.#{$ionicons-prefix}android-checkbox-blank:before { content: $ionicon-var-android-checkbox-blank; }\n.#{$ionicons-prefix}android-checkbox-outline:before { content: $ionicon-var-android-checkbox-outline; }\n.#{$ionicons-prefix}android-checkbox-outline-blank:before { content: $ionicon-var-android-checkbox-outline-blank; }\n.#{$ionicons-prefix}android-checkmark-circle:before { content: $ionicon-var-android-checkmark-circle; }\n.#{$ionicons-prefix}android-clipboard:before { content: $ionicon-var-android-clipboard; }\n.#{$ionicons-prefix}android-close:before { content: $ionicon-var-android-close; }\n.#{$ionicons-prefix}android-cloud:before { content: $ionicon-var-android-cloud; }\n.#{$ionicons-prefix}android-cloud-circle:before { content: $ionicon-var-android-cloud-circle; }\n.#{$ionicons-prefix}android-cloud-done:before { content: $ionicon-var-android-cloud-done; }\n.#{$ionicons-prefix}android-cloud-outline:before { content: $ionicon-var-android-cloud-outline; }\n.#{$ionicons-prefix}android-color-palette:before { content: $ionicon-var-android-color-palette; }\n.#{$ionicons-prefix}android-compass:before { content: $ionicon-var-android-compass; }\n.#{$ionicons-prefix}android-contact:before { content: $ionicon-var-android-contact; }\n.#{$ionicons-prefix}android-contacts:before { content: $ionicon-var-android-contacts; }\n.#{$ionicons-prefix}android-contract:before { content: $ionicon-var-android-contract; }\n.#{$ionicons-prefix}android-create:before { content: $ionicon-var-android-create; }\n.#{$ionicons-prefix}android-delete:before { content: $ionicon-var-android-delete; }\n.#{$ionicons-prefix}android-desktop:before { content: $ionicon-var-android-desktop; }\n.#{$ionicons-prefix}android-document:before { content: $ionicon-var-android-document; }\n.#{$ionicons-prefix}android-done:before { content: $ionicon-var-android-done; }\n.#{$ionicons-prefix}android-done-all:before { content: $ionicon-var-android-done-all; }\n.#{$ionicons-prefix}android-download:before { content: $ionicon-var-android-download; }\n.#{$ionicons-prefix}android-drafts:before { content: $ionicon-var-android-drafts; }\n.#{$ionicons-prefix}android-exit:before { content: $ionicon-var-android-exit; }\n.#{$ionicons-prefix}android-expand:before { content: $ionicon-var-android-expand; }\n.#{$ionicons-prefix}android-favorite:before { content: $ionicon-var-android-favorite; }\n.#{$ionicons-prefix}android-favorite-outline:before { content: $ionicon-var-android-favorite-outline; }\n.#{$ionicons-prefix}android-film:before { content: $ionicon-var-android-film; }\n.#{$ionicons-prefix}android-folder:before { content: $ionicon-var-android-folder; }\n.#{$ionicons-prefix}android-folder-open:before { content: $ionicon-var-android-folder-open; }\n.#{$ionicons-prefix}android-funnel:before { content: $ionicon-var-android-funnel; }\n.#{$ionicons-prefix}android-globe:before { content: $ionicon-var-android-globe; }\n.#{$ionicons-prefix}android-hand:before { content: $ionicon-var-android-hand; }\n.#{$ionicons-prefix}android-hangout:before { content: $ionicon-var-android-hangout; }\n.#{$ionicons-prefix}android-happy:before { content: $ionicon-var-android-happy; }\n.#{$ionicons-prefix}android-home:before { content: $ionicon-var-android-home; }\n.#{$ionicons-prefix}android-image:before { content: $ionicon-var-android-image; }\n.#{$ionicons-prefix}android-laptop:before { content: $ionicon-var-android-laptop; }\n.#{$ionicons-prefix}android-list:before { content: $ionicon-var-android-list; }\n.#{$ionicons-prefix}android-locate:before { content: $ionicon-var-android-locate; }\n.#{$ionicons-prefix}android-lock:before { content: $ionicon-var-android-lock; }\n.#{$ionicons-prefix}android-mail:before { content: $ionicon-var-android-mail; }\n.#{$ionicons-prefix}android-map:before { content: $ionicon-var-android-map; }\n.#{$ionicons-prefix}android-menu:before { content: $ionicon-var-android-menu; }\n.#{$ionicons-prefix}android-microphone:before { content: $ionicon-var-android-microphone; }\n.#{$ionicons-prefix}android-microphone-off:before { content: $ionicon-var-android-microphone-off; }\n.#{$ionicons-prefix}android-more-horizontal:before { content: $ionicon-var-android-more-horizontal; }\n.#{$ionicons-prefix}android-more-vertical:before { content: $ionicon-var-android-more-vertical; }\n.#{$ionicons-prefix}android-navigate:before { content: $ionicon-var-android-navigate; }\n.#{$ionicons-prefix}android-notifications:before { content: $ionicon-var-android-notifications; }\n.#{$ionicons-prefix}android-notifications-none:before { content: $ionicon-var-android-notifications-none; }\n.#{$ionicons-prefix}android-notifications-off:before { content: $ionicon-var-android-notifications-off; }\n.#{$ionicons-prefix}android-open:before { content: $ionicon-var-android-open; }\n.#{$ionicons-prefix}android-options:before { content: $ionicon-var-android-options; }\n.#{$ionicons-prefix}android-people:before { content: $ionicon-var-android-people; }\n.#{$ionicons-prefix}android-person:before { content: $ionicon-var-android-person; }\n.#{$ionicons-prefix}android-person-add:before { content: $ionicon-var-android-person-add; }\n.#{$ionicons-prefix}android-phone-landscape:before { content: $ionicon-var-android-phone-landscape; }\n.#{$ionicons-prefix}android-phone-portrait:before { content: $ionicon-var-android-phone-portrait; }\n.#{$ionicons-prefix}android-pin:before { content: $ionicon-var-android-pin; }\n.#{$ionicons-prefix}android-plane:before { content: $ionicon-var-android-plane; }\n.#{$ionicons-prefix}android-playstore:before { content: $ionicon-var-android-playstore; }\n.#{$ionicons-prefix}android-print:before { content: $ionicon-var-android-print; }\n.#{$ionicons-prefix}android-radio-button-off:before { content: $ionicon-var-android-radio-button-off; }\n.#{$ionicons-prefix}android-radio-button-on:before { content: $ionicon-var-android-radio-button-on; }\n.#{$ionicons-prefix}android-refresh:before { content: $ionicon-var-android-refresh; }\n.#{$ionicons-prefix}android-remove:before { content: $ionicon-var-android-remove; }\n.#{$ionicons-prefix}android-remove-circle:before { content: $ionicon-var-android-remove-circle; }\n.#{$ionicons-prefix}android-restaurant:before { content: $ionicon-var-android-restaurant; }\n.#{$ionicons-prefix}android-sad:before { content: $ionicon-var-android-sad; }\n.#{$ionicons-prefix}android-search:before { content: $ionicon-var-android-search; }\n.#{$ionicons-prefix}android-send:before { content: $ionicon-var-android-send; }\n.#{$ionicons-prefix}android-settings:before { content: $ionicon-var-android-settings; }\n.#{$ionicons-prefix}android-share:before { content: $ionicon-var-android-share; }\n.#{$ionicons-prefix}android-share-alt:before { content: $ionicon-var-android-share-alt; }\n.#{$ionicons-prefix}android-star:before { content: $ionicon-var-android-star; }\n.#{$ionicons-prefix}android-star-half:before { content: $ionicon-var-android-star-half; }\n.#{$ionicons-prefix}android-star-outline:before { content: $ionicon-var-android-star-outline; }\n.#{$ionicons-prefix}android-stopwatch:before { content: $ionicon-var-android-stopwatch; }\n.#{$ionicons-prefix}android-subway:before { content: $ionicon-var-android-subway; }\n.#{$ionicons-prefix}android-sunny:before { content: $ionicon-var-android-sunny; }\n.#{$ionicons-prefix}android-sync:before { content: $ionicon-var-android-sync; }\n.#{$ionicons-prefix}android-textsms:before { content: $ionicon-var-android-textsms; }\n.#{$ionicons-prefix}android-time:before { content: $ionicon-var-android-time; }\n.#{$ionicons-prefix}android-train:before { content: $ionicon-var-android-train; }\n.#{$ionicons-prefix}android-unlock:before { content: $ionicon-var-android-unlock; }\n.#{$ionicons-prefix}android-upload:before { content: $ionicon-var-android-upload; }\n.#{$ionicons-prefix}android-volume-down:before { content: $ionicon-var-android-volume-down; }\n.#{$ionicons-prefix}android-volume-mute:before { content: $ionicon-var-android-volume-mute; }\n.#{$ionicons-prefix}android-volume-off:before { content: $ionicon-var-android-volume-off; }\n.#{$ionicons-prefix}android-volume-up:before { content: $ionicon-var-android-volume-up; }\n.#{$ionicons-prefix}android-walk:before { content: $ionicon-var-android-walk; }\n.#{$ionicons-prefix}android-warning:before { content: $ionicon-var-android-warning; }\n.#{$ionicons-prefix}android-watch:before { content: $ionicon-var-android-watch; }\n.#{$ionicons-prefix}android-wifi:before { content: $ionicon-var-android-wifi; }\n.#{$ionicons-prefix}aperture:before { content: $ionicon-var-aperture; }\n.#{$ionicons-prefix}archive:before { content: $ionicon-var-archive; }\n.#{$ionicons-prefix}arrow-down-a:before { content: $ionicon-var-arrow-down-a; }\n.#{$ionicons-prefix}arrow-down-b:before { content: $ionicon-var-arrow-down-b; }\n.#{$ionicons-prefix}arrow-down-c:before { content: $ionicon-var-arrow-down-c; }\n.#{$ionicons-prefix}arrow-expand:before { content: $ionicon-var-arrow-expand; }\n.#{$ionicons-prefix}arrow-graph-down-left:before { content: $ionicon-var-arrow-graph-down-left; }\n.#{$ionicons-prefix}arrow-graph-down-right:before { content: $ionicon-var-arrow-graph-down-right; }\n.#{$ionicons-prefix}arrow-graph-up-left:before { content: $ionicon-var-arrow-graph-up-left; }\n.#{$ionicons-prefix}arrow-graph-up-right:before { content: $ionicon-var-arrow-graph-up-right; }\n.#{$ionicons-prefix}arrow-left-a:before { content: $ionicon-var-arrow-left-a; }\n.#{$ionicons-prefix}arrow-left-b:before { content: $ionicon-var-arrow-left-b; }\n.#{$ionicons-prefix}arrow-left-c:before { content: $ionicon-var-arrow-left-c; }\n.#{$ionicons-prefix}arrow-move:before { content: $ionicon-var-arrow-move; }\n.#{$ionicons-prefix}arrow-resize:before { content: $ionicon-var-arrow-resize; }\n.#{$ionicons-prefix}arrow-return-left:before { content: $ionicon-var-arrow-return-left; }\n.#{$ionicons-prefix}arrow-return-right:before { content: $ionicon-var-arrow-return-right; }\n.#{$ionicons-prefix}arrow-right-a:before { content: $ionicon-var-arrow-right-a; }\n.#{$ionicons-prefix}arrow-right-b:before { content: $ionicon-var-arrow-right-b; }\n.#{$ionicons-prefix}arrow-right-c:before { content: $ionicon-var-arrow-right-c; }\n.#{$ionicons-prefix}arrow-shrink:before { content: $ionicon-var-arrow-shrink; }\n.#{$ionicons-prefix}arrow-swap:before { content: $ionicon-var-arrow-swap; }\n.#{$ionicons-prefix}arrow-up-a:before { content: $ionicon-var-arrow-up-a; }\n.#{$ionicons-prefix}arrow-up-b:before { content: $ionicon-var-arrow-up-b; }\n.#{$ionicons-prefix}arrow-up-c:before { content: $ionicon-var-arrow-up-c; }\n.#{$ionicons-prefix}asterisk:before { content: $ionicon-var-asterisk; }\n.#{$ionicons-prefix}at:before { content: $ionicon-var-at; }\n.#{$ionicons-prefix}backspace:before { content: $ionicon-var-backspace; }\n.#{$ionicons-prefix}backspace-outline:before { content: $ionicon-var-backspace-outline; }\n.#{$ionicons-prefix}bag:before { content: $ionicon-var-bag; }\n.#{$ionicons-prefix}battery-charging:before { content: $ionicon-var-battery-charging; }\n.#{$ionicons-prefix}battery-empty:before { content: $ionicon-var-battery-empty; }\n.#{$ionicons-prefix}battery-full:before { content: $ionicon-var-battery-full; }\n.#{$ionicons-prefix}battery-half:before { content: $ionicon-var-battery-half; }\n.#{$ionicons-prefix}battery-low:before { content: $ionicon-var-battery-low; }\n.#{$ionicons-prefix}beaker:before { content: $ionicon-var-beaker; }\n.#{$ionicons-prefix}beer:before { content: $ionicon-var-beer; }\n.#{$ionicons-prefix}bluetooth:before { content: $ionicon-var-bluetooth; }\n.#{$ionicons-prefix}bonfire:before { content: $ionicon-var-bonfire; }\n.#{$ionicons-prefix}bookmark:before { content: $ionicon-var-bookmark; }\n.#{$ionicons-prefix}bowtie:before { content: $ionicon-var-bowtie; }\n.#{$ionicons-prefix}briefcase:before { content: $ionicon-var-briefcase; }\n.#{$ionicons-prefix}bug:before { content: $ionicon-var-bug; }\n.#{$ionicons-prefix}calculator:before { content: $ionicon-var-calculator; }\n.#{$ionicons-prefix}calendar:before { content: $ionicon-var-calendar; }\n.#{$ionicons-prefix}camera:before { content: $ionicon-var-camera; }\n.#{$ionicons-prefix}card:before { content: $ionicon-var-card; }\n.#{$ionicons-prefix}cash:before { content: $ionicon-var-cash; }\n.#{$ionicons-prefix}chatbox:before { content: $ionicon-var-chatbox; }\n.#{$ionicons-prefix}chatbox-working:before { content: $ionicon-var-chatbox-working; }\n.#{$ionicons-prefix}chatboxes:before { content: $ionicon-var-chatboxes; }\n.#{$ionicons-prefix}chatbubble:before { content: $ionicon-var-chatbubble; }\n.#{$ionicons-prefix}chatbubble-working:before { content: $ionicon-var-chatbubble-working; }\n.#{$ionicons-prefix}chatbubbles:before { content: $ionicon-var-chatbubbles; }\n.#{$ionicons-prefix}checkmark:before { content: $ionicon-var-checkmark; }\n.#{$ionicons-prefix}checkmark-circled:before { content: $ionicon-var-checkmark-circled; }\n.#{$ionicons-prefix}checkmark-round:before { content: $ionicon-var-checkmark-round; }\n.#{$ionicons-prefix}chevron-down:before { content: $ionicon-var-chevron-down; }\n.#{$ionicons-prefix}chevron-left:before { content: $ionicon-var-chevron-left; }\n.#{$ionicons-prefix}chevron-right:before { content: $ionicon-var-chevron-right; }\n.#{$ionicons-prefix}chevron-up:before { content: $ionicon-var-chevron-up; }\n.#{$ionicons-prefix}clipboard:before { content: $ionicon-var-clipboard; }\n.#{$ionicons-prefix}clock:before { content: $ionicon-var-clock; }\n.#{$ionicons-prefix}close:before { content: $ionicon-var-close; }\n.#{$ionicons-prefix}close-circled:before { content: $ionicon-var-close-circled; }\n.#{$ionicons-prefix}close-round:before { content: $ionicon-var-close-round; }\n.#{$ionicons-prefix}closed-captioning:before { content: $ionicon-var-closed-captioning; }\n.#{$ionicons-prefix}cloud:before { content: $ionicon-var-cloud; }\n.#{$ionicons-prefix}code:before { content: $ionicon-var-code; }\n.#{$ionicons-prefix}code-download:before { content: $ionicon-var-code-download; }\n.#{$ionicons-prefix}code-working:before { content: $ionicon-var-code-working; }\n.#{$ionicons-prefix}coffee:before { content: $ionicon-var-coffee; }\n.#{$ionicons-prefix}compass:before { content: $ionicon-var-compass; }\n.#{$ionicons-prefix}compose:before { content: $ionicon-var-compose; }\n.#{$ionicons-prefix}connection-bars:before { content: $ionicon-var-connection-bars; }\n.#{$ionicons-prefix}contrast:before { content: $ionicon-var-contrast; }\n.#{$ionicons-prefix}crop:before { content: $ionicon-var-crop; }\n.#{$ionicons-prefix}cube:before { content: $ionicon-var-cube; }\n.#{$ionicons-prefix}disc:before { content: $ionicon-var-disc; }\n.#{$ionicons-prefix}document:before { content: $ionicon-var-document; }\n.#{$ionicons-prefix}document-text:before { content: $ionicon-var-document-text; }\n.#{$ionicons-prefix}drag:before { content: $ionicon-var-drag; }\n.#{$ionicons-prefix}earth:before { content: $ionicon-var-earth; }\n.#{$ionicons-prefix}easel:before { content: $ionicon-var-easel; }\n.#{$ionicons-prefix}edit:before { content: $ionicon-var-edit; }\n.#{$ionicons-prefix}egg:before { content: $ionicon-var-egg; }\n.#{$ionicons-prefix}eject:before { content: $ionicon-var-eject; }\n.#{$ionicons-prefix}email:before { content: $ionicon-var-email; }\n.#{$ionicons-prefix}email-unread:before { content: $ionicon-var-email-unread; }\n.#{$ionicons-prefix}erlenmeyer-flask:before { content: $ionicon-var-erlenmeyer-flask; }\n.#{$ionicons-prefix}erlenmeyer-flask-bubbles:before { content: $ionicon-var-erlenmeyer-flask-bubbles; }\n.#{$ionicons-prefix}eye:before { content: $ionicon-var-eye; }\n.#{$ionicons-prefix}eye-disabled:before { content: $ionicon-var-eye-disabled; }\n.#{$ionicons-prefix}female:before { content: $ionicon-var-female; }\n.#{$ionicons-prefix}filing:before { content: $ionicon-var-filing; }\n.#{$ionicons-prefix}film-marker:before { content: $ionicon-var-film-marker; }\n.#{$ionicons-prefix}fireball:before { content: $ionicon-var-fireball; }\n.#{$ionicons-prefix}flag:before { content: $ionicon-var-flag; }\n.#{$ionicons-prefix}flame:before { content: $ionicon-var-flame; }\n.#{$ionicons-prefix}flash:before { content: $ionicon-var-flash; }\n.#{$ionicons-prefix}flash-off:before { content: $ionicon-var-flash-off; }\n.#{$ionicons-prefix}folder:before { content: $ionicon-var-folder; }\n.#{$ionicons-prefix}fork:before { content: $ionicon-var-fork; }\n.#{$ionicons-prefix}fork-repo:before { content: $ionicon-var-fork-repo; }\n.#{$ionicons-prefix}forward:before { content: $ionicon-var-forward; }\n.#{$ionicons-prefix}funnel:before { content: $ionicon-var-funnel; }\n.#{$ionicons-prefix}gear-a:before { content: $ionicon-var-gear-a; }\n.#{$ionicons-prefix}gear-b:before { content: $ionicon-var-gear-b; }\n.#{$ionicons-prefix}grid:before { content: $ionicon-var-grid; }\n.#{$ionicons-prefix}hammer:before { content: $ionicon-var-hammer; }\n.#{$ionicons-prefix}happy:before { content: $ionicon-var-happy; }\n.#{$ionicons-prefix}happy-outline:before { content: $ionicon-var-happy-outline; }\n.#{$ionicons-prefix}headphone:before { content: $ionicon-var-headphone; }\n.#{$ionicons-prefix}heart:before { content: $ionicon-var-heart; }\n.#{$ionicons-prefix}heart-broken:before { content: $ionicon-var-heart-broken; }\n.#{$ionicons-prefix}help:before { content: $ionicon-var-help; }\n.#{$ionicons-prefix}help-buoy:before { content: $ionicon-var-help-buoy; }\n.#{$ionicons-prefix}help-circled:before { content: $ionicon-var-help-circled; }\n.#{$ionicons-prefix}home:before { content: $ionicon-var-home; }\n.#{$ionicons-prefix}icecream:before { content: $ionicon-var-icecream; }\n.#{$ionicons-prefix}image:before { content: $ionicon-var-image; }\n.#{$ionicons-prefix}images:before { content: $ionicon-var-images; }\n.#{$ionicons-prefix}information:before { content: $ionicon-var-information; }\n.#{$ionicons-prefix}information-circled:before { content: $ionicon-var-information-circled; }\n.#{$ionicons-prefix}ionic:before { content: $ionicon-var-ionic; }\n.#{$ionicons-prefix}ios-alarm:before { content: $ionicon-var-ios-alarm; }\n.#{$ionicons-prefix}ios-alarm-outline:before { content: $ionicon-var-ios-alarm-outline; }\n.#{$ionicons-prefix}ios-albums:before { content: $ionicon-var-ios-albums; }\n.#{$ionicons-prefix}ios-albums-outline:before { content: $ionicon-var-ios-albums-outline; }\n.#{$ionicons-prefix}ios-americanfootball:before { content: $ionicon-var-ios-americanfootball; }\n.#{$ionicons-prefix}ios-americanfootball-outline:before { content: $ionicon-var-ios-americanfootball-outline; }\n.#{$ionicons-prefix}ios-analytics:before { content: $ionicon-var-ios-analytics; }\n.#{$ionicons-prefix}ios-analytics-outline:before { content: $ionicon-var-ios-analytics-outline; }\n.#{$ionicons-prefix}ios-arrow-back:before { content: $ionicon-var-ios-arrow-back; }\n.#{$ionicons-prefix}ios-arrow-down:before { content: $ionicon-var-ios-arrow-down; }\n.#{$ionicons-prefix}ios-arrow-forward:before { content: $ionicon-var-ios-arrow-forward; }\n.#{$ionicons-prefix}ios-arrow-left:before { content: $ionicon-var-ios-arrow-left; }\n.#{$ionicons-prefix}ios-arrow-right:before { content: $ionicon-var-ios-arrow-right; }\n.#{$ionicons-prefix}ios-arrow-thin-down:before { content: $ionicon-var-ios-arrow-thin-down; }\n.#{$ionicons-prefix}ios-arrow-thin-left:before { content: $ionicon-var-ios-arrow-thin-left; }\n.#{$ionicons-prefix}ios-arrow-thin-right:before { content: $ionicon-var-ios-arrow-thin-right; }\n.#{$ionicons-prefix}ios-arrow-thin-up:before { content: $ionicon-var-ios-arrow-thin-up; }\n.#{$ionicons-prefix}ios-arrow-up:before { content: $ionicon-var-ios-arrow-up; }\n.#{$ionicons-prefix}ios-at:before { content: $ionicon-var-ios-at; }\n.#{$ionicons-prefix}ios-at-outline:before { content: $ionicon-var-ios-at-outline; }\n.#{$ionicons-prefix}ios-barcode:before { content: $ionicon-var-ios-barcode; }\n.#{$ionicons-prefix}ios-barcode-outline:before { content: $ionicon-var-ios-barcode-outline; }\n.#{$ionicons-prefix}ios-baseball:before { content: $ionicon-var-ios-baseball; }\n.#{$ionicons-prefix}ios-baseball-outline:before { content: $ionicon-var-ios-baseball-outline; }\n.#{$ionicons-prefix}ios-basketball:before { content: $ionicon-var-ios-basketball; }\n.#{$ionicons-prefix}ios-basketball-outline:before { content: $ionicon-var-ios-basketball-outline; }\n.#{$ionicons-prefix}ios-bell:before { content: $ionicon-var-ios-bell; }\n.#{$ionicons-prefix}ios-bell-outline:before { content: $ionicon-var-ios-bell-outline; }\n.#{$ionicons-prefix}ios-body:before { content: $ionicon-var-ios-body; }\n.#{$ionicons-prefix}ios-body-outline:before { content: $ionicon-var-ios-body-outline; }\n.#{$ionicons-prefix}ios-bolt:before { content: $ionicon-var-ios-bolt; }\n.#{$ionicons-prefix}ios-bolt-outline:before { content: $ionicon-var-ios-bolt-outline; }\n.#{$ionicons-prefix}ios-book:before { content: $ionicon-var-ios-book; }\n.#{$ionicons-prefix}ios-book-outline:before { content: $ionicon-var-ios-book-outline; }\n.#{$ionicons-prefix}ios-bookmarks:before { content: $ionicon-var-ios-bookmarks; }\n.#{$ionicons-prefix}ios-bookmarks-outline:before { content: $ionicon-var-ios-bookmarks-outline; }\n.#{$ionicons-prefix}ios-box:before { content: $ionicon-var-ios-box; }\n.#{$ionicons-prefix}ios-box-outline:before { content: $ionicon-var-ios-box-outline; }\n.#{$ionicons-prefix}ios-briefcase:before { content: $ionicon-var-ios-briefcase; }\n.#{$ionicons-prefix}ios-briefcase-outline:before { content: $ionicon-var-ios-briefcase-outline; }\n.#{$ionicons-prefix}ios-browsers:before { content: $ionicon-var-ios-browsers; }\n.#{$ionicons-prefix}ios-browsers-outline:before { content: $ionicon-var-ios-browsers-outline; }\n.#{$ionicons-prefix}ios-calculator:before { content: $ionicon-var-ios-calculator; }\n.#{$ionicons-prefix}ios-calculator-outline:before { content: $ionicon-var-ios-calculator-outline; }\n.#{$ionicons-prefix}ios-calendar:before { content: $ionicon-var-ios-calendar; }\n.#{$ionicons-prefix}ios-calendar-outline:before { content: $ionicon-var-ios-calendar-outline; }\n.#{$ionicons-prefix}ios-camera:before { content: $ionicon-var-ios-camera; }\n.#{$ionicons-prefix}ios-camera-outline:before { content: $ionicon-var-ios-camera-outline; }\n.#{$ionicons-prefix}ios-cart:before { content: $ionicon-var-ios-cart; }\n.#{$ionicons-prefix}ios-cart-outline:before { content: $ionicon-var-ios-cart-outline; }\n.#{$ionicons-prefix}ios-chatboxes:before { content: $ionicon-var-ios-chatboxes; }\n.#{$ionicons-prefix}ios-chatboxes-outline:before { content: $ionicon-var-ios-chatboxes-outline; }\n.#{$ionicons-prefix}ios-chatbubble:before { content: $ionicon-var-ios-chatbubble; }\n.#{$ionicons-prefix}ios-chatbubble-outline:before { content: $ionicon-var-ios-chatbubble-outline; }\n.#{$ionicons-prefix}ios-checkmark:before { content: $ionicon-var-ios-checkmark; }\n.#{$ionicons-prefix}ios-checkmark-empty:before { content: $ionicon-var-ios-checkmark-empty; }\n.#{$ionicons-prefix}ios-checkmark-outline:before { content: $ionicon-var-ios-checkmark-outline; }\n.#{$ionicons-prefix}ios-circle-filled:before { content: $ionicon-var-ios-circle-filled; }\n.#{$ionicons-prefix}ios-circle-outline:before { content: $ionicon-var-ios-circle-outline; }\n.#{$ionicons-prefix}ios-clock:before { content: $ionicon-var-ios-clock; }\n.#{$ionicons-prefix}ios-clock-outline:before { content: $ionicon-var-ios-clock-outline; }\n.#{$ionicons-prefix}ios-close:before { content: $ionicon-var-ios-close; }\n.#{$ionicons-prefix}ios-close-empty:before { content: $ionicon-var-ios-close-empty; }\n.#{$ionicons-prefix}ios-close-outline:before { content: $ionicon-var-ios-close-outline; }\n.#{$ionicons-prefix}ios-cloud:before { content: $ionicon-var-ios-cloud; }\n.#{$ionicons-prefix}ios-cloud-download:before { content: $ionicon-var-ios-cloud-download; }\n.#{$ionicons-prefix}ios-cloud-download-outline:before { content: $ionicon-var-ios-cloud-download-outline; }\n.#{$ionicons-prefix}ios-cloud-outline:before { content: $ionicon-var-ios-cloud-outline; }\n.#{$ionicons-prefix}ios-cloud-upload:before { content: $ionicon-var-ios-cloud-upload; }\n.#{$ionicons-prefix}ios-cloud-upload-outline:before { content: $ionicon-var-ios-cloud-upload-outline; }\n.#{$ionicons-prefix}ios-cloudy:before { content: $ionicon-var-ios-cloudy; }\n.#{$ionicons-prefix}ios-cloudy-night:before { content: $ionicon-var-ios-cloudy-night; }\n.#{$ionicons-prefix}ios-cloudy-night-outline:before { content: $ionicon-var-ios-cloudy-night-outline; }\n.#{$ionicons-prefix}ios-cloudy-outline:before { content: $ionicon-var-ios-cloudy-outline; }\n.#{$ionicons-prefix}ios-cog:before { content: $ionicon-var-ios-cog; }\n.#{$ionicons-prefix}ios-cog-outline:before { content: $ionicon-var-ios-cog-outline; }\n.#{$ionicons-prefix}ios-color-filter:before { content: $ionicon-var-ios-color-filter; }\n.#{$ionicons-prefix}ios-color-filter-outline:before { content: $ionicon-var-ios-color-filter-outline; }\n.#{$ionicons-prefix}ios-color-wand:before { content: $ionicon-var-ios-color-wand; }\n.#{$ionicons-prefix}ios-color-wand-outline:before { content: $ionicon-var-ios-color-wand-outline; }\n.#{$ionicons-prefix}ios-compose:before { content: $ionicon-var-ios-compose; }\n.#{$ionicons-prefix}ios-compose-outline:before { content: $ionicon-var-ios-compose-outline; }\n.#{$ionicons-prefix}ios-contact:before { content: $ionicon-var-ios-contact; }\n.#{$ionicons-prefix}ios-contact-outline:before { content: $ionicon-var-ios-contact-outline; }\n.#{$ionicons-prefix}ios-copy:before { content: $ionicon-var-ios-copy; }\n.#{$ionicons-prefix}ios-copy-outline:before { content: $ionicon-var-ios-copy-outline; }\n.#{$ionicons-prefix}ios-crop:before { content: $ionicon-var-ios-crop; }\n.#{$ionicons-prefix}ios-crop-strong:before { content: $ionicon-var-ios-crop-strong; }\n.#{$ionicons-prefix}ios-download:before { content: $ionicon-var-ios-download; }\n.#{$ionicons-prefix}ios-download-outline:before { content: $ionicon-var-ios-download-outline; }\n.#{$ionicons-prefix}ios-drag:before { content: $ionicon-var-ios-drag; }\n.#{$ionicons-prefix}ios-email:before { content: $ionicon-var-ios-email; }\n.#{$ionicons-prefix}ios-email-outline:before { content: $ionicon-var-ios-email-outline; }\n.#{$ionicons-prefix}ios-eye:before { content: $ionicon-var-ios-eye; }\n.#{$ionicons-prefix}ios-eye-outline:before { content: $ionicon-var-ios-eye-outline; }\n.#{$ionicons-prefix}ios-fastforward:before { content: $ionicon-var-ios-fastforward; }\n.#{$ionicons-prefix}ios-fastforward-outline:before { content: $ionicon-var-ios-fastforward-outline; }\n.#{$ionicons-prefix}ios-filing:before { content: $ionicon-var-ios-filing; }\n.#{$ionicons-prefix}ios-filing-outline:before { content: $ionicon-var-ios-filing-outline; }\n.#{$ionicons-prefix}ios-film:before { content: $ionicon-var-ios-film; }\n.#{$ionicons-prefix}ios-film-outline:before { content: $ionicon-var-ios-film-outline; }\n.#{$ionicons-prefix}ios-flag:before { content: $ionicon-var-ios-flag; }\n.#{$ionicons-prefix}ios-flag-outline:before { content: $ionicon-var-ios-flag-outline; }\n.#{$ionicons-prefix}ios-flame:before { content: $ionicon-var-ios-flame; }\n.#{$ionicons-prefix}ios-flame-outline:before { content: $ionicon-var-ios-flame-outline; }\n.#{$ionicons-prefix}ios-flask:before { content: $ionicon-var-ios-flask; }\n.#{$ionicons-prefix}ios-flask-outline:before { content: $ionicon-var-ios-flask-outline; }\n.#{$ionicons-prefix}ios-flower:before { content: $ionicon-var-ios-flower; }\n.#{$ionicons-prefix}ios-flower-outline:before { content: $ionicon-var-ios-flower-outline; }\n.#{$ionicons-prefix}ios-folder:before { content: $ionicon-var-ios-folder; }\n.#{$ionicons-prefix}ios-folder-outline:before { content: $ionicon-var-ios-folder-outline; }\n.#{$ionicons-prefix}ios-football:before { content: $ionicon-var-ios-football; }\n.#{$ionicons-prefix}ios-football-outline:before { content: $ionicon-var-ios-football-outline; }\n.#{$ionicons-prefix}ios-game-controller-a:before { content: $ionicon-var-ios-game-controller-a; }\n.#{$ionicons-prefix}ios-game-controller-a-outline:before { content: $ionicon-var-ios-game-controller-a-outline; }\n.#{$ionicons-prefix}ios-game-controller-b:before { content: $ionicon-var-ios-game-controller-b; }\n.#{$ionicons-prefix}ios-game-controller-b-outline:before { content: $ionicon-var-ios-game-controller-b-outline; }\n.#{$ionicons-prefix}ios-gear:before { content: $ionicon-var-ios-gear; }\n.#{$ionicons-prefix}ios-gear-outline:before { content: $ionicon-var-ios-gear-outline; }\n.#{$ionicons-prefix}ios-glasses:before { content: $ionicon-var-ios-glasses; }\n.#{$ionicons-prefix}ios-glasses-outline:before { content: $ionicon-var-ios-glasses-outline; }\n.#{$ionicons-prefix}ios-grid-view:before { content: $ionicon-var-ios-grid-view; }\n.#{$ionicons-prefix}ios-grid-view-outline:before { content: $ionicon-var-ios-grid-view-outline; }\n.#{$ionicons-prefix}ios-heart:before { content: $ionicon-var-ios-heart; }\n.#{$ionicons-prefix}ios-heart-outline:before { content: $ionicon-var-ios-heart-outline; }\n.#{$ionicons-prefix}ios-help:before { content: $ionicon-var-ios-help; }\n.#{$ionicons-prefix}ios-help-empty:before { content: $ionicon-var-ios-help-empty; }\n.#{$ionicons-prefix}ios-help-outline:before { content: $ionicon-var-ios-help-outline; }\n.#{$ionicons-prefix}ios-home:before { content: $ionicon-var-ios-home; }\n.#{$ionicons-prefix}ios-home-outline:before { content: $ionicon-var-ios-home-outline; }\n.#{$ionicons-prefix}ios-infinite:before { content: $ionicon-var-ios-infinite; }\n.#{$ionicons-prefix}ios-infinite-outline:before { content: $ionicon-var-ios-infinite-outline; }\n.#{$ionicons-prefix}ios-information:before { content: $ionicon-var-ios-information; }\n.#{$ionicons-prefix}ios-information-empty:before { content: $ionicon-var-ios-information-empty; }\n.#{$ionicons-prefix}ios-information-outline:before { content: $ionicon-var-ios-information-outline; }\n.#{$ionicons-prefix}ios-ionic-outline:before { content: $ionicon-var-ios-ionic-outline; }\n.#{$ionicons-prefix}ios-keypad:before { content: $ionicon-var-ios-keypad; }\n.#{$ionicons-prefix}ios-keypad-outline:before { content: $ionicon-var-ios-keypad-outline; }\n.#{$ionicons-prefix}ios-lightbulb:before { content: $ionicon-var-ios-lightbulb; }\n.#{$ionicons-prefix}ios-lightbulb-outline:before { content: $ionicon-var-ios-lightbulb-outline; }\n.#{$ionicons-prefix}ios-list:before { content: $ionicon-var-ios-list; }\n.#{$ionicons-prefix}ios-list-outline:before { content: $ionicon-var-ios-list-outline; }\n.#{$ionicons-prefix}ios-location:before { content: $ionicon-var-ios-location; }\n.#{$ionicons-prefix}ios-location-outline:before { content: $ionicon-var-ios-location-outline; }\n.#{$ionicons-prefix}ios-locked:before { content: $ionicon-var-ios-locked; }\n.#{$ionicons-prefix}ios-locked-outline:before { content: $ionicon-var-ios-locked-outline; }\n.#{$ionicons-prefix}ios-loop:before { content: $ionicon-var-ios-loop; }\n.#{$ionicons-prefix}ios-loop-strong:before { content: $ionicon-var-ios-loop-strong; }\n.#{$ionicons-prefix}ios-medical:before { content: $ionicon-var-ios-medical; }\n.#{$ionicons-prefix}ios-medical-outline:before { content: $ionicon-var-ios-medical-outline; }\n.#{$ionicons-prefix}ios-medkit:before { content: $ionicon-var-ios-medkit; }\n.#{$ionicons-prefix}ios-medkit-outline:before { content: $ionicon-var-ios-medkit-outline; }\n.#{$ionicons-prefix}ios-mic:before { content: $ionicon-var-ios-mic; }\n.#{$ionicons-prefix}ios-mic-off:before { content: $ionicon-var-ios-mic-off; }\n.#{$ionicons-prefix}ios-mic-outline:before { content: $ionicon-var-ios-mic-outline; }\n.#{$ionicons-prefix}ios-minus:before { content: $ionicon-var-ios-minus; }\n.#{$ionicons-prefix}ios-minus-empty:before { content: $ionicon-var-ios-minus-empty; }\n.#{$ionicons-prefix}ios-minus-outline:before { content: $ionicon-var-ios-minus-outline; }\n.#{$ionicons-prefix}ios-monitor:before { content: $ionicon-var-ios-monitor; }\n.#{$ionicons-prefix}ios-monitor-outline:before { content: $ionicon-var-ios-monitor-outline; }\n.#{$ionicons-prefix}ios-moon:before { content: $ionicon-var-ios-moon; }\n.#{$ionicons-prefix}ios-moon-outline:before { content: $ionicon-var-ios-moon-outline; }\n.#{$ionicons-prefix}ios-more:before { content: $ionicon-var-ios-more; }\n.#{$ionicons-prefix}ios-more-outline:before { content: $ionicon-var-ios-more-outline; }\n.#{$ionicons-prefix}ios-musical-note:before { content: $ionicon-var-ios-musical-note; }\n.#{$ionicons-prefix}ios-musical-notes:before { content: $ionicon-var-ios-musical-notes; }\n.#{$ionicons-prefix}ios-navigate:before { content: $ionicon-var-ios-navigate; }\n.#{$ionicons-prefix}ios-navigate-outline:before { content: $ionicon-var-ios-navigate-outline; }\n.#{$ionicons-prefix}ios-nutrition:before { content: $ionicon-var-ios-nutrition; }\n.#{$ionicons-prefix}ios-nutrition-outline:before { content: $ionicon-var-ios-nutrition-outline; }\n.#{$ionicons-prefix}ios-paper:before { content: $ionicon-var-ios-paper; }\n.#{$ionicons-prefix}ios-paper-outline:before { content: $ionicon-var-ios-paper-outline; }\n.#{$ionicons-prefix}ios-paperplane:before { content: $ionicon-var-ios-paperplane; }\n.#{$ionicons-prefix}ios-paperplane-outline:before { content: $ionicon-var-ios-paperplane-outline; }\n.#{$ionicons-prefix}ios-partlysunny:before { content: $ionicon-var-ios-partlysunny; }\n.#{$ionicons-prefix}ios-partlysunny-outline:before { content: $ionicon-var-ios-partlysunny-outline; }\n.#{$ionicons-prefix}ios-pause:before { content: $ionicon-var-ios-pause; }\n.#{$ionicons-prefix}ios-pause-outline:before { content: $ionicon-var-ios-pause-outline; }\n.#{$ionicons-prefix}ios-paw:before { content: $ionicon-var-ios-paw; }\n.#{$ionicons-prefix}ios-paw-outline:before { content: $ionicon-var-ios-paw-outline; }\n.#{$ionicons-prefix}ios-people:before { content: $ionicon-var-ios-people; }\n.#{$ionicons-prefix}ios-people-outline:before { content: $ionicon-var-ios-people-outline; }\n.#{$ionicons-prefix}ios-person:before { content: $ionicon-var-ios-person; }\n.#{$ionicons-prefix}ios-person-outline:before { content: $ionicon-var-ios-person-outline; }\n.#{$ionicons-prefix}ios-personadd:before { content: $ionicon-var-ios-personadd; }\n.#{$ionicons-prefix}ios-personadd-outline:before { content: $ionicon-var-ios-personadd-outline; }\n.#{$ionicons-prefix}ios-photos:before { content: $ionicon-var-ios-photos; }\n.#{$ionicons-prefix}ios-photos-outline:before { content: $ionicon-var-ios-photos-outline; }\n.#{$ionicons-prefix}ios-pie:before { content: $ionicon-var-ios-pie; }\n.#{$ionicons-prefix}ios-pie-outline:before { content: $ionicon-var-ios-pie-outline; }\n.#{$ionicons-prefix}ios-pint:before { content: $ionicon-var-ios-pint; }\n.#{$ionicons-prefix}ios-pint-outline:before { content: $ionicon-var-ios-pint-outline; }\n.#{$ionicons-prefix}ios-play:before { content: $ionicon-var-ios-play; }\n.#{$ionicons-prefix}ios-play-outline:before { content: $ionicon-var-ios-play-outline; }\n.#{$ionicons-prefix}ios-plus:before { content: $ionicon-var-ios-plus; }\n.#{$ionicons-prefix}ios-plus-empty:before { content: $ionicon-var-ios-plus-empty; }\n.#{$ionicons-prefix}ios-plus-outline:before { content: $ionicon-var-ios-plus-outline; }\n.#{$ionicons-prefix}ios-pricetag:before { content: $ionicon-var-ios-pricetag; }\n.#{$ionicons-prefix}ios-pricetag-outline:before { content: $ionicon-var-ios-pricetag-outline; }\n.#{$ionicons-prefix}ios-pricetags:before { content: $ionicon-var-ios-pricetags; }\n.#{$ionicons-prefix}ios-pricetags-outline:before { content: $ionicon-var-ios-pricetags-outline; }\n.#{$ionicons-prefix}ios-printer:before { content: $ionicon-var-ios-printer; }\n.#{$ionicons-prefix}ios-printer-outline:before { content: $ionicon-var-ios-printer-outline; }\n.#{$ionicons-prefix}ios-pulse:before { content: $ionicon-var-ios-pulse; }\n.#{$ionicons-prefix}ios-pulse-strong:before { content: $ionicon-var-ios-pulse-strong; }\n.#{$ionicons-prefix}ios-rainy:before { content: $ionicon-var-ios-rainy; }\n.#{$ionicons-prefix}ios-rainy-outline:before { content: $ionicon-var-ios-rainy-outline; }\n.#{$ionicons-prefix}ios-recording:before { content: $ionicon-var-ios-recording; }\n.#{$ionicons-prefix}ios-recording-outline:before { content: $ionicon-var-ios-recording-outline; }\n.#{$ionicons-prefix}ios-redo:before { content: $ionicon-var-ios-redo; }\n.#{$ionicons-prefix}ios-redo-outline:before { content: $ionicon-var-ios-redo-outline; }\n.#{$ionicons-prefix}ios-refresh:before { content: $ionicon-var-ios-refresh; }\n.#{$ionicons-prefix}ios-refresh-empty:before { content: $ionicon-var-ios-refresh-empty; }\n.#{$ionicons-prefix}ios-refresh-outline:before { content: $ionicon-var-ios-refresh-outline; }\n.#{$ionicons-prefix}ios-reload:before { content: $ionicon-var-ios-reload; }\n.#{$ionicons-prefix}ios-reverse-camera:before { content: $ionicon-var-ios-reverse-camera; }\n.#{$ionicons-prefix}ios-reverse-camera-outline:before { content: $ionicon-var-ios-reverse-camera-outline; }\n.#{$ionicons-prefix}ios-rewind:before { content: $ionicon-var-ios-rewind; }\n.#{$ionicons-prefix}ios-rewind-outline:before { content: $ionicon-var-ios-rewind-outline; }\n.#{$ionicons-prefix}ios-rose:before { content: $ionicon-var-ios-rose; }\n.#{$ionicons-prefix}ios-rose-outline:before { content: $ionicon-var-ios-rose-outline; }\n.#{$ionicons-prefix}ios-search:before { content: $ionicon-var-ios-search; }\n.#{$ionicons-prefix}ios-search-strong:before { content: $ionicon-var-ios-search-strong; }\n.#{$ionicons-prefix}ios-settings:before { content: $ionicon-var-ios-settings; }\n.#{$ionicons-prefix}ios-settings-strong:before { content: $ionicon-var-ios-settings-strong; }\n.#{$ionicons-prefix}ios-shuffle:before { content: $ionicon-var-ios-shuffle; }\n.#{$ionicons-prefix}ios-shuffle-strong:before { content: $ionicon-var-ios-shuffle-strong; }\n.#{$ionicons-prefix}ios-skipbackward:before { content: $ionicon-var-ios-skipbackward; }\n.#{$ionicons-prefix}ios-skipbackward-outline:before { content: $ionicon-var-ios-skipbackward-outline; }\n.#{$ionicons-prefix}ios-skipforward:before { content: $ionicon-var-ios-skipforward; }\n.#{$ionicons-prefix}ios-skipforward-outline:before { content: $ionicon-var-ios-skipforward-outline; }\n.#{$ionicons-prefix}ios-snowy:before { content: $ionicon-var-ios-snowy; }\n.#{$ionicons-prefix}ios-speedometer:before { content: $ionicon-var-ios-speedometer; }\n.#{$ionicons-prefix}ios-speedometer-outline:before { content: $ionicon-var-ios-speedometer-outline; }\n.#{$ionicons-prefix}ios-star:before { content: $ionicon-var-ios-star; }\n.#{$ionicons-prefix}ios-star-half:before { content: $ionicon-var-ios-star-half; }\n.#{$ionicons-prefix}ios-star-outline:before { content: $ionicon-var-ios-star-outline; }\n.#{$ionicons-prefix}ios-stopwatch:before { content: $ionicon-var-ios-stopwatch; }\n.#{$ionicons-prefix}ios-stopwatch-outline:before { content: $ionicon-var-ios-stopwatch-outline; }\n.#{$ionicons-prefix}ios-sunny:before { content: $ionicon-var-ios-sunny; }\n.#{$ionicons-prefix}ios-sunny-outline:before { content: $ionicon-var-ios-sunny-outline; }\n.#{$ionicons-prefix}ios-telephone:before { content: $ionicon-var-ios-telephone; }\n.#{$ionicons-prefix}ios-telephone-outline:before { content: $ionicon-var-ios-telephone-outline; }\n.#{$ionicons-prefix}ios-tennisball:before { content: $ionicon-var-ios-tennisball; }\n.#{$ionicons-prefix}ios-tennisball-outline:before { content: $ionicon-var-ios-tennisball-outline; }\n.#{$ionicons-prefix}ios-thunderstorm:before { content: $ionicon-var-ios-thunderstorm; }\n.#{$ionicons-prefix}ios-thunderstorm-outline:before { content: $ionicon-var-ios-thunderstorm-outline; }\n.#{$ionicons-prefix}ios-time:before { content: $ionicon-var-ios-time; }\n.#{$ionicons-prefix}ios-time-outline:before { content: $ionicon-var-ios-time-outline; }\n.#{$ionicons-prefix}ios-timer:before { content: $ionicon-var-ios-timer; }\n.#{$ionicons-prefix}ios-timer-outline:before { content: $ionicon-var-ios-timer-outline; }\n.#{$ionicons-prefix}ios-toggle:before { content: $ionicon-var-ios-toggle; }\n.#{$ionicons-prefix}ios-toggle-outline:before { content: $ionicon-var-ios-toggle-outline; }\n.#{$ionicons-prefix}ios-trash:before { content: $ionicon-var-ios-trash; }\n.#{$ionicons-prefix}ios-trash-outline:before { content: $ionicon-var-ios-trash-outline; }\n.#{$ionicons-prefix}ios-undo:before { content: $ionicon-var-ios-undo; }\n.#{$ionicons-prefix}ios-undo-outline:before { content: $ionicon-var-ios-undo-outline; }\n.#{$ionicons-prefix}ios-unlocked:before { content: $ionicon-var-ios-unlocked; }\n.#{$ionicons-prefix}ios-unlocked-outline:before { content: $ionicon-var-ios-unlocked-outline; }\n.#{$ionicons-prefix}ios-upload:before { content: $ionicon-var-ios-upload; }\n.#{$ionicons-prefix}ios-upload-outline:before { content: $ionicon-var-ios-upload-outline; }\n.#{$ionicons-prefix}ios-videocam:before { content: $ionicon-var-ios-videocam; }\n.#{$ionicons-prefix}ios-videocam-outline:before { content: $ionicon-var-ios-videocam-outline; }\n.#{$ionicons-prefix}ios-volume-high:before { content: $ionicon-var-ios-volume-high; }\n.#{$ionicons-prefix}ios-volume-low:before { content: $ionicon-var-ios-volume-low; }\n.#{$ionicons-prefix}ios-wineglass:before { content: $ionicon-var-ios-wineglass; }\n.#{$ionicons-prefix}ios-wineglass-outline:before { content: $ionicon-var-ios-wineglass-outline; }\n.#{$ionicons-prefix}ios-world:before { content: $ionicon-var-ios-world; }\n.#{$ionicons-prefix}ios-world-outline:before { content: $ionicon-var-ios-world-outline; }\n.#{$ionicons-prefix}ipad:before { content: $ionicon-var-ipad; }\n.#{$ionicons-prefix}iphone:before { content: $ionicon-var-iphone; }\n.#{$ionicons-prefix}ipod:before { content: $ionicon-var-ipod; }\n.#{$ionicons-prefix}jet:before { content: $ionicon-var-jet; }\n.#{$ionicons-prefix}key:before { content: $ionicon-var-key; }\n.#{$ionicons-prefix}knife:before { content: $ionicon-var-knife; }\n.#{$ionicons-prefix}laptop:before { content: $ionicon-var-laptop; }\n.#{$ionicons-prefix}leaf:before { content: $ionicon-var-leaf; }\n.#{$ionicons-prefix}levels:before { content: $ionicon-var-levels; }\n.#{$ionicons-prefix}lightbulb:before { content: $ionicon-var-lightbulb; }\n.#{$ionicons-prefix}link:before { content: $ionicon-var-link; }\n.#{$ionicons-prefix}load-a:before { content: $ionicon-var-load-a; }\n.#{$ionicons-prefix}load-b:before { content: $ionicon-var-load-b; }\n.#{$ionicons-prefix}load-c:before { content: $ionicon-var-load-c; }\n.#{$ionicons-prefix}load-d:before { content: $ionicon-var-load-d; }\n.#{$ionicons-prefix}location:before { content: $ionicon-var-location; }\n.#{$ionicons-prefix}lock-combination:before { content: $ionicon-var-lock-combination; }\n.#{$ionicons-prefix}locked:before { content: $ionicon-var-locked; }\n.#{$ionicons-prefix}log-in:before { content: $ionicon-var-log-in; }\n.#{$ionicons-prefix}log-out:before { content: $ionicon-var-log-out; }\n.#{$ionicons-prefix}loop:before { content: $ionicon-var-loop; }\n.#{$ionicons-prefix}magnet:before { content: $ionicon-var-magnet; }\n.#{$ionicons-prefix}male:before { content: $ionicon-var-male; }\n.#{$ionicons-prefix}man:before { content: $ionicon-var-man; }\n.#{$ionicons-prefix}map:before { content: $ionicon-var-map; }\n.#{$ionicons-prefix}medkit:before { content: $ionicon-var-medkit; }\n.#{$ionicons-prefix}merge:before { content: $ionicon-var-merge; }\n.#{$ionicons-prefix}mic-a:before { content: $ionicon-var-mic-a; }\n.#{$ionicons-prefix}mic-b:before { content: $ionicon-var-mic-b; }\n.#{$ionicons-prefix}mic-c:before { content: $ionicon-var-mic-c; }\n.#{$ionicons-prefix}minus:before { content: $ionicon-var-minus; }\n.#{$ionicons-prefix}minus-circled:before { content: $ionicon-var-minus-circled; }\n.#{$ionicons-prefix}minus-round:before { content: $ionicon-var-minus-round; }\n.#{$ionicons-prefix}model-s:before { content: $ionicon-var-model-s; }\n.#{$ionicons-prefix}monitor:before { content: $ionicon-var-monitor; }\n.#{$ionicons-prefix}more:before { content: $ionicon-var-more; }\n.#{$ionicons-prefix}mouse:before { content: $ionicon-var-mouse; }\n.#{$ionicons-prefix}music-note:before { content: $ionicon-var-music-note; }\n.#{$ionicons-prefix}navicon:before { content: $ionicon-var-navicon; }\n.#{$ionicons-prefix}navicon-round:before { content: $ionicon-var-navicon-round; }\n.#{$ionicons-prefix}navigate:before { content: $ionicon-var-navigate; }\n.#{$ionicons-prefix}network:before { content: $ionicon-var-network; }\n.#{$ionicons-prefix}no-smoking:before { content: $ionicon-var-no-smoking; }\n.#{$ionicons-prefix}nuclear:before { content: $ionicon-var-nuclear; }\n.#{$ionicons-prefix}outlet:before { content: $ionicon-var-outlet; }\n.#{$ionicons-prefix}paintbrush:before { content: $ionicon-var-paintbrush; }\n.#{$ionicons-prefix}paintbucket:before { content: $ionicon-var-paintbucket; }\n.#{$ionicons-prefix}paper-airplane:before { content: $ionicon-var-paper-airplane; }\n.#{$ionicons-prefix}paperclip:before { content: $ionicon-var-paperclip; }\n.#{$ionicons-prefix}pause:before { content: $ionicon-var-pause; }\n.#{$ionicons-prefix}person:before { content: $ionicon-var-person; }\n.#{$ionicons-prefix}person-add:before { content: $ionicon-var-person-add; }\n.#{$ionicons-prefix}person-stalker:before { content: $ionicon-var-person-stalker; }\n.#{$ionicons-prefix}pie-graph:before { content: $ionicon-var-pie-graph; }\n.#{$ionicons-prefix}pin:before { content: $ionicon-var-pin; }\n.#{$ionicons-prefix}pinpoint:before { content: $ionicon-var-pinpoint; }\n.#{$ionicons-prefix}pizza:before { content: $ionicon-var-pizza; }\n.#{$ionicons-prefix}plane:before { content: $ionicon-var-plane; }\n.#{$ionicons-prefix}planet:before { content: $ionicon-var-planet; }\n.#{$ionicons-prefix}play:before { content: $ionicon-var-play; }\n.#{$ionicons-prefix}playstation:before { content: $ionicon-var-playstation; }\n.#{$ionicons-prefix}plus:before { content: $ionicon-var-plus; }\n.#{$ionicons-prefix}plus-circled:before { content: $ionicon-var-plus-circled; }\n.#{$ionicons-prefix}plus-round:before { content: $ionicon-var-plus-round; }\n.#{$ionicons-prefix}podium:before { content: $ionicon-var-podium; }\n.#{$ionicons-prefix}pound:before { content: $ionicon-var-pound; }\n.#{$ionicons-prefix}power:before { content: $ionicon-var-power; }\n.#{$ionicons-prefix}pricetag:before { content: $ionicon-var-pricetag; }\n.#{$ionicons-prefix}pricetags:before { content: $ionicon-var-pricetags; }\n.#{$ionicons-prefix}printer:before { content: $ionicon-var-printer; }\n.#{$ionicons-prefix}pull-request:before { content: $ionicon-var-pull-request; }\n.#{$ionicons-prefix}qr-scanner:before { content: $ionicon-var-qr-scanner; }\n.#{$ionicons-prefix}quote:before { content: $ionicon-var-quote; }\n.#{$ionicons-prefix}radio-waves:before { content: $ionicon-var-radio-waves; }\n.#{$ionicons-prefix}record:before { content: $ionicon-var-record; }\n.#{$ionicons-prefix}refresh:before { content: $ionicon-var-refresh; }\n.#{$ionicons-prefix}reply:before { content: $ionicon-var-reply; }\n.#{$ionicons-prefix}reply-all:before { content: $ionicon-var-reply-all; }\n.#{$ionicons-prefix}ribbon-a:before { content: $ionicon-var-ribbon-a; }\n.#{$ionicons-prefix}ribbon-b:before { content: $ionicon-var-ribbon-b; }\n.#{$ionicons-prefix}sad:before { content: $ionicon-var-sad; }\n.#{$ionicons-prefix}sad-outline:before { content: $ionicon-var-sad-outline; }\n.#{$ionicons-prefix}scissors:before { content: $ionicon-var-scissors; }\n.#{$ionicons-prefix}search:before { content: $ionicon-var-search; }\n.#{$ionicons-prefix}settings:before { content: $ionicon-var-settings; }\n.#{$ionicons-prefix}share:before { content: $ionicon-var-share; }\n.#{$ionicons-prefix}shuffle:before { content: $ionicon-var-shuffle; }\n.#{$ionicons-prefix}skip-backward:before { content: $ionicon-var-skip-backward; }\n.#{$ionicons-prefix}skip-forward:before { content: $ionicon-var-skip-forward; }\n.#{$ionicons-prefix}social-android:before { content: $ionicon-var-social-android; }\n.#{$ionicons-prefix}social-android-outline:before { content: $ionicon-var-social-android-outline; }\n.#{$ionicons-prefix}social-angular:before { content: $ionicon-var-social-angular; }\n.#{$ionicons-prefix}social-angular-outline:before { content: $ionicon-var-social-angular-outline; }\n.#{$ionicons-prefix}social-apple:before { content: $ionicon-var-social-apple; }\n.#{$ionicons-prefix}social-apple-outline:before { content: $ionicon-var-social-apple-outline; }\n.#{$ionicons-prefix}social-bitcoin:before { content: $ionicon-var-social-bitcoin; }\n.#{$ionicons-prefix}social-bitcoin-outline:before { content: $ionicon-var-social-bitcoin-outline; }\n.#{$ionicons-prefix}social-buffer:before { content: $ionicon-var-social-buffer; }\n.#{$ionicons-prefix}social-buffer-outline:before { content: $ionicon-var-social-buffer-outline; }\n.#{$ionicons-prefix}social-chrome:before { content: $ionicon-var-social-chrome; }\n.#{$ionicons-prefix}social-chrome-outline:before { content: $ionicon-var-social-chrome-outline; }\n.#{$ionicons-prefix}social-codepen:before { content: $ionicon-var-social-codepen; }\n.#{$ionicons-prefix}social-codepen-outline:before { content: $ionicon-var-social-codepen-outline; }\n.#{$ionicons-prefix}social-css3:before { content: $ionicon-var-social-css3; }\n.#{$ionicons-prefix}social-css3-outline:before { content: $ionicon-var-social-css3-outline; }\n.#{$ionicons-prefix}social-designernews:before { content: $ionicon-var-social-designernews; }\n.#{$ionicons-prefix}social-designernews-outline:before { content: $ionicon-var-social-designernews-outline; }\n.#{$ionicons-prefix}social-dribbble:before { content: $ionicon-var-social-dribbble; }\n.#{$ionicons-prefix}social-dribbble-outline:before { content: $ionicon-var-social-dribbble-outline; }\n.#{$ionicons-prefix}social-dropbox:before { content: $ionicon-var-social-dropbox; }\n.#{$ionicons-prefix}social-dropbox-outline:before { content: $ionicon-var-social-dropbox-outline; }\n.#{$ionicons-prefix}social-euro:before { content: $ionicon-var-social-euro; }\n.#{$ionicons-prefix}social-euro-outline:before { content: $ionicon-var-social-euro-outline; }\n.#{$ionicons-prefix}social-facebook:before { content: $ionicon-var-social-facebook; }\n.#{$ionicons-prefix}social-facebook-outline:before { content: $ionicon-var-social-facebook-outline; }\n.#{$ionicons-prefix}social-foursquare:before { content: $ionicon-var-social-foursquare; }\n.#{$ionicons-prefix}social-foursquare-outline:before { content: $ionicon-var-social-foursquare-outline; }\n.#{$ionicons-prefix}social-freebsd-devil:before { content: $ionicon-var-social-freebsd-devil; }\n.#{$ionicons-prefix}social-github:before { content: $ionicon-var-social-github; }\n.#{$ionicons-prefix}social-github-outline:before { content: $ionicon-var-social-github-outline; }\n.#{$ionicons-prefix}social-google:before { content: $ionicon-var-social-google; }\n.#{$ionicons-prefix}social-google-outline:before { content: $ionicon-var-social-google-outline; }\n.#{$ionicons-prefix}social-googleplus:before { content: $ionicon-var-social-googleplus; }\n.#{$ionicons-prefix}social-googleplus-outline:before { content: $ionicon-var-social-googleplus-outline; }\n.#{$ionicons-prefix}social-hackernews:before { content: $ionicon-var-social-hackernews; }\n.#{$ionicons-prefix}social-hackernews-outline:before { content: $ionicon-var-social-hackernews-outline; }\n.#{$ionicons-prefix}social-html5:before { content: $ionicon-var-social-html5; }\n.#{$ionicons-prefix}social-html5-outline:before { content: $ionicon-var-social-html5-outline; }\n.#{$ionicons-prefix}social-instagram:before { content: $ionicon-var-social-instagram; }\n.#{$ionicons-prefix}social-instagram-outline:before { content: $ionicon-var-social-instagram-outline; }\n.#{$ionicons-prefix}social-javascript:before { content: $ionicon-var-social-javascript; }\n.#{$ionicons-prefix}social-javascript-outline:before { content: $ionicon-var-social-javascript-outline; }\n.#{$ionicons-prefix}social-linkedin:before { content: $ionicon-var-social-linkedin; }\n.#{$ionicons-prefix}social-linkedin-outline:before { content: $ionicon-var-social-linkedin-outline; }\n.#{$ionicons-prefix}social-markdown:before { content: $ionicon-var-social-markdown; }\n.#{$ionicons-prefix}social-nodejs:before { content: $ionicon-var-social-nodejs; }\n.#{$ionicons-prefix}social-octocat:before { content: $ionicon-var-social-octocat; }\n.#{$ionicons-prefix}social-pinterest:before { content: $ionicon-var-social-pinterest; }\n.#{$ionicons-prefix}social-pinterest-outline:before { content: $ionicon-var-social-pinterest-outline; }\n.#{$ionicons-prefix}social-python:before { content: $ionicon-var-social-python; }\n.#{$ionicons-prefix}social-reddit:before { content: $ionicon-var-social-reddit; }\n.#{$ionicons-prefix}social-reddit-outline:before { content: $ionicon-var-social-reddit-outline; }\n.#{$ionicons-prefix}social-rss:before { content: $ionicon-var-social-rss; }\n.#{$ionicons-prefix}social-rss-outline:before { content: $ionicon-var-social-rss-outline; }\n.#{$ionicons-prefix}social-sass:before { content: $ionicon-var-social-sass; }\n.#{$ionicons-prefix}social-skype:before { content: $ionicon-var-social-skype; }\n.#{$ionicons-prefix}social-skype-outline:before { content: $ionicon-var-social-skype-outline; }\n.#{$ionicons-prefix}social-snapchat:before { content: $ionicon-var-social-snapchat; }\n.#{$ionicons-prefix}social-snapchat-outline:before { content: $ionicon-var-social-snapchat-outline; }\n.#{$ionicons-prefix}social-tumblr:before { content: $ionicon-var-social-tumblr; }\n.#{$ionicons-prefix}social-tumblr-outline:before { content: $ionicon-var-social-tumblr-outline; }\n.#{$ionicons-prefix}social-tux:before { content: $ionicon-var-social-tux; }\n.#{$ionicons-prefix}social-twitch:before { content: $ionicon-var-social-twitch; }\n.#{$ionicons-prefix}social-twitch-outline:before { content: $ionicon-var-social-twitch-outline; }\n.#{$ionicons-prefix}social-twitter:before { content: $ionicon-var-social-twitter; }\n.#{$ionicons-prefix}social-twitter-outline:before { content: $ionicon-var-social-twitter-outline; }\n.#{$ionicons-prefix}social-usd:before { content: $ionicon-var-social-usd; }\n.#{$ionicons-prefix}social-usd-outline:before { content: $ionicon-var-social-usd-outline; }\n.#{$ionicons-prefix}social-vimeo:before { content: $ionicon-var-social-vimeo; }\n.#{$ionicons-prefix}social-vimeo-outline:before { content: $ionicon-var-social-vimeo-outline; }\n.#{$ionicons-prefix}social-whatsapp:before { content: $ionicon-var-social-whatsapp; }\n.#{$ionicons-prefix}social-whatsapp-outline:before { content: $ionicon-var-social-whatsapp-outline; }\n.#{$ionicons-prefix}social-windows:before { content: $ionicon-var-social-windows; }\n.#{$ionicons-prefix}social-windows-outline:before { content: $ionicon-var-social-windows-outline; }\n.#{$ionicons-prefix}social-wordpress:before { content: $ionicon-var-social-wordpress; }\n.#{$ionicons-prefix}social-wordpress-outline:before { content: $ionicon-var-social-wordpress-outline; }\n.#{$ionicons-prefix}social-yahoo:before { content: $ionicon-var-social-yahoo; }\n.#{$ionicons-prefix}social-yahoo-outline:before { content: $ionicon-var-social-yahoo-outline; }\n.#{$ionicons-prefix}social-yen:before { content: $ionicon-var-social-yen; }\n.#{$ionicons-prefix}social-yen-outline:before { content: $ionicon-var-social-yen-outline; }\n.#{$ionicons-prefix}social-youtube:before { content: $ionicon-var-social-youtube; }\n.#{$ionicons-prefix}social-youtube-outline:before { content: $ionicon-var-social-youtube-outline; }\n.#{$ionicons-prefix}soup-can:before { content: $ionicon-var-soup-can; }\n.#{$ionicons-prefix}soup-can-outline:before { content: $ionicon-var-soup-can-outline; }\n.#{$ionicons-prefix}speakerphone:before { content: $ionicon-var-speakerphone; }\n.#{$ionicons-prefix}speedometer:before { content: $ionicon-var-speedometer; }\n.#{$ionicons-prefix}spoon:before { content: $ionicon-var-spoon; }\n.#{$ionicons-prefix}star:before { content: $ionicon-var-star; }\n.#{$ionicons-prefix}stats-bars:before { content: $ionicon-var-stats-bars; }\n.#{$ionicons-prefix}steam:before { content: $ionicon-var-steam; }\n.#{$ionicons-prefix}stop:before { content: $ionicon-var-stop; }\n.#{$ionicons-prefix}thermometer:before { content: $ionicon-var-thermometer; }\n.#{$ionicons-prefix}thumbsdown:before { content: $ionicon-var-thumbsdown; }\n.#{$ionicons-prefix}thumbsup:before { content: $ionicon-var-thumbsup; }\n.#{$ionicons-prefix}toggle:before { content: $ionicon-var-toggle; }\n.#{$ionicons-prefix}toggle-filled:before { content: $ionicon-var-toggle-filled; }\n.#{$ionicons-prefix}transgender:before { content: $ionicon-var-transgender; }\n.#{$ionicons-prefix}trash-a:before { content: $ionicon-var-trash-a; }\n.#{$ionicons-prefix}trash-b:before { content: $ionicon-var-trash-b; }\n.#{$ionicons-prefix}trophy:before { content: $ionicon-var-trophy; }\n.#{$ionicons-prefix}tshirt:before { content: $ionicon-var-tshirt; }\n.#{$ionicons-prefix}tshirt-outline:before { content: $ionicon-var-tshirt-outline; }\n.#{$ionicons-prefix}umbrella:before { content: $ionicon-var-umbrella; }\n.#{$ionicons-prefix}university:before { content: $ionicon-var-university; }\n.#{$ionicons-prefix}unlocked:before { content: $ionicon-var-unlocked; }\n.#{$ionicons-prefix}upload:before { content: $ionicon-var-upload; }\n.#{$ionicons-prefix}usb:before { content: $ionicon-var-usb; }\n.#{$ionicons-prefix}videocamera:before { content: $ionicon-var-videocamera; }\n.#{$ionicons-prefix}volume-high:before { content: $ionicon-var-volume-high; }\n.#{$ionicons-prefix}volume-low:before { content: $ionicon-var-volume-low; }\n.#{$ionicons-prefix}volume-medium:before { content: $ionicon-var-volume-medium; }\n.#{$ionicons-prefix}volume-mute:before { content: $ionicon-var-volume-mute; }\n.#{$ionicons-prefix}wand:before { content: $ionicon-var-wand; }\n.#{$ionicons-prefix}waterdrop:before { content: $ionicon-var-waterdrop; }\n.#{$ionicons-prefix}wifi:before { content: $ionicon-var-wifi; }\n.#{$ionicons-prefix}wineglass:before { content: $ionicon-var-wineglass; }\n.#{$ionicons-prefix}woman:before { content: $ionicon-var-woman; }\n.#{$ionicons-prefix}wrench:before { content: $ionicon-var-wrench; }\n.#{$ionicons-prefix}xbox:before { content: $ionicon-var-xbox; }"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/ionicons/_ionicons-variables.scss",
    "content": "// Ionicons Variables\n// --------------------------\n\n$ionicons-font-path: \"../fonts\" !default;\n$ionicons-font-family: \"Ionicons\" !default;\n$ionicons-version: \"2.0.1\" !default;\n$ionicons-prefix: ion- !default;\n\n$ionicon-var-alert: \"\\f101\";\n$ionicon-var-alert-circled: \"\\f100\";\n$ionicon-var-android-add: \"\\f2c7\";\n$ionicon-var-android-add-circle: \"\\f359\";\n$ionicon-var-android-alarm-clock: \"\\f35a\";\n$ionicon-var-android-alert: \"\\f35b\";\n$ionicon-var-android-apps: \"\\f35c\";\n$ionicon-var-android-archive: \"\\f2c9\";\n$ionicon-var-android-arrow-back: \"\\f2ca\";\n$ionicon-var-android-arrow-down: \"\\f35d\";\n$ionicon-var-android-arrow-dropdown: \"\\f35f\";\n$ionicon-var-android-arrow-dropdown-circle: \"\\f35e\";\n$ionicon-var-android-arrow-dropleft: \"\\f361\";\n$ionicon-var-android-arrow-dropleft-circle: \"\\f360\";\n$ionicon-var-android-arrow-dropright: \"\\f363\";\n$ionicon-var-android-arrow-dropright-circle: \"\\f362\";\n$ionicon-var-android-arrow-dropup: \"\\f365\";\n$ionicon-var-android-arrow-dropup-circle: \"\\f364\";\n$ionicon-var-android-arrow-forward: \"\\f30f\";\n$ionicon-var-android-arrow-up: \"\\f366\";\n$ionicon-var-android-attach: \"\\f367\";\n$ionicon-var-android-bar: \"\\f368\";\n$ionicon-var-android-bicycle: \"\\f369\";\n$ionicon-var-android-boat: \"\\f36a\";\n$ionicon-var-android-bookmark: \"\\f36b\";\n$ionicon-var-android-bulb: \"\\f36c\";\n$ionicon-var-android-bus: \"\\f36d\";\n$ionicon-var-android-calendar: \"\\f2d1\";\n$ionicon-var-android-call: \"\\f2d2\";\n$ionicon-var-android-camera: \"\\f2d3\";\n$ionicon-var-android-cancel: \"\\f36e\";\n$ionicon-var-android-car: \"\\f36f\";\n$ionicon-var-android-cart: \"\\f370\";\n$ionicon-var-android-chat: \"\\f2d4\";\n$ionicon-var-android-checkbox: \"\\f374\";\n$ionicon-var-android-checkbox-blank: \"\\f371\";\n$ionicon-var-android-checkbox-outline: \"\\f373\";\n$ionicon-var-android-checkbox-outline-blank: \"\\f372\";\n$ionicon-var-android-checkmark-circle: \"\\f375\";\n$ionicon-var-android-clipboard: \"\\f376\";\n$ionicon-var-android-close: \"\\f2d7\";\n$ionicon-var-android-cloud: \"\\f37a\";\n$ionicon-var-android-cloud-circle: \"\\f377\";\n$ionicon-var-android-cloud-done: \"\\f378\";\n$ionicon-var-android-cloud-outline: \"\\f379\";\n$ionicon-var-android-color-palette: \"\\f37b\";\n$ionicon-var-android-compass: \"\\f37c\";\n$ionicon-var-android-contact: \"\\f2d8\";\n$ionicon-var-android-contacts: \"\\f2d9\";\n$ionicon-var-android-contract: \"\\f37d\";\n$ionicon-var-android-create: \"\\f37e\";\n$ionicon-var-android-delete: \"\\f37f\";\n$ionicon-var-android-desktop: \"\\f380\";\n$ionicon-var-android-document: \"\\f381\";\n$ionicon-var-android-done: \"\\f383\";\n$ionicon-var-android-done-all: \"\\f382\";\n$ionicon-var-android-download: \"\\f2dd\";\n$ionicon-var-android-drafts: \"\\f384\";\n$ionicon-var-android-exit: \"\\f385\";\n$ionicon-var-android-expand: \"\\f386\";\n$ionicon-var-android-favorite: \"\\f388\";\n$ionicon-var-android-favorite-outline: \"\\f387\";\n$ionicon-var-android-film: \"\\f389\";\n$ionicon-var-android-folder: \"\\f2e0\";\n$ionicon-var-android-folder-open: \"\\f38a\";\n$ionicon-var-android-funnel: \"\\f38b\";\n$ionicon-var-android-globe: \"\\f38c\";\n$ionicon-var-android-hand: \"\\f2e3\";\n$ionicon-var-android-hangout: \"\\f38d\";\n$ionicon-var-android-happy: \"\\f38e\";\n$ionicon-var-android-home: \"\\f38f\";\n$ionicon-var-android-image: \"\\f2e4\";\n$ionicon-var-android-laptop: \"\\f390\";\n$ionicon-var-android-list: \"\\f391\";\n$ionicon-var-android-locate: \"\\f2e9\";\n$ionicon-var-android-lock: \"\\f392\";\n$ionicon-var-android-mail: \"\\f2eb\";\n$ionicon-var-android-map: \"\\f393\";\n$ionicon-var-android-menu: \"\\f394\";\n$ionicon-var-android-microphone: \"\\f2ec\";\n$ionicon-var-android-microphone-off: \"\\f395\";\n$ionicon-var-android-more-horizontal: \"\\f396\";\n$ionicon-var-android-more-vertical: \"\\f397\";\n$ionicon-var-android-navigate: \"\\f398\";\n$ionicon-var-android-notifications: \"\\f39b\";\n$ionicon-var-android-notifications-none: \"\\f399\";\n$ionicon-var-android-notifications-off: \"\\f39a\";\n$ionicon-var-android-open: \"\\f39c\";\n$ionicon-var-android-options: \"\\f39d\";\n$ionicon-var-android-people: \"\\f39e\";\n$ionicon-var-android-person: \"\\f3a0\";\n$ionicon-var-android-person-add: \"\\f39f\";\n$ionicon-var-android-phone-landscape: \"\\f3a1\";\n$ionicon-var-android-phone-portrait: \"\\f3a2\";\n$ionicon-var-android-pin: \"\\f3a3\";\n$ionicon-var-android-plane: \"\\f3a4\";\n$ionicon-var-android-playstore: \"\\f2f0\";\n$ionicon-var-android-print: \"\\f3a5\";\n$ionicon-var-android-radio-button-off: \"\\f3a6\";\n$ionicon-var-android-radio-button-on: \"\\f3a7\";\n$ionicon-var-android-refresh: \"\\f3a8\";\n$ionicon-var-android-remove: \"\\f2f4\";\n$ionicon-var-android-remove-circle: \"\\f3a9\";\n$ionicon-var-android-restaurant: \"\\f3aa\";\n$ionicon-var-android-sad: \"\\f3ab\";\n$ionicon-var-android-search: \"\\f2f5\";\n$ionicon-var-android-send: \"\\f2f6\";\n$ionicon-var-android-settings: \"\\f2f7\";\n$ionicon-var-android-share: \"\\f2f8\";\n$ionicon-var-android-share-alt: \"\\f3ac\";\n$ionicon-var-android-star: \"\\f2fc\";\n$ionicon-var-android-star-half: \"\\f3ad\";\n$ionicon-var-android-star-outline: \"\\f3ae\";\n$ionicon-var-android-stopwatch: \"\\f2fd\";\n$ionicon-var-android-subway: \"\\f3af\";\n$ionicon-var-android-sunny: \"\\f3b0\";\n$ionicon-var-android-sync: \"\\f3b1\";\n$ionicon-var-android-textsms: \"\\f3b2\";\n$ionicon-var-android-time: \"\\f3b3\";\n$ionicon-var-android-train: \"\\f3b4\";\n$ionicon-var-android-unlock: \"\\f3b5\";\n$ionicon-var-android-upload: \"\\f3b6\";\n$ionicon-var-android-volume-down: \"\\f3b7\";\n$ionicon-var-android-volume-mute: \"\\f3b8\";\n$ionicon-var-android-volume-off: \"\\f3b9\";\n$ionicon-var-android-volume-up: \"\\f3ba\";\n$ionicon-var-android-walk: \"\\f3bb\";\n$ionicon-var-android-warning: \"\\f3bc\";\n$ionicon-var-android-watch: \"\\f3bd\";\n$ionicon-var-android-wifi: \"\\f305\";\n$ionicon-var-aperture: \"\\f313\";\n$ionicon-var-archive: \"\\f102\";\n$ionicon-var-arrow-down-a: \"\\f103\";\n$ionicon-var-arrow-down-b: \"\\f104\";\n$ionicon-var-arrow-down-c: \"\\f105\";\n$ionicon-var-arrow-expand: \"\\f25e\";\n$ionicon-var-arrow-graph-down-left: \"\\f25f\";\n$ionicon-var-arrow-graph-down-right: \"\\f260\";\n$ionicon-var-arrow-graph-up-left: \"\\f261\";\n$ionicon-var-arrow-graph-up-right: \"\\f262\";\n$ionicon-var-arrow-left-a: \"\\f106\";\n$ionicon-var-arrow-left-b: \"\\f107\";\n$ionicon-var-arrow-left-c: \"\\f108\";\n$ionicon-var-arrow-move: \"\\f263\";\n$ionicon-var-arrow-resize: \"\\f264\";\n$ionicon-var-arrow-return-left: \"\\f265\";\n$ionicon-var-arrow-return-right: \"\\f266\";\n$ionicon-var-arrow-right-a: \"\\f109\";\n$ionicon-var-arrow-right-b: \"\\f10a\";\n$ionicon-var-arrow-right-c: \"\\f10b\";\n$ionicon-var-arrow-shrink: \"\\f267\";\n$ionicon-var-arrow-swap: \"\\f268\";\n$ionicon-var-arrow-up-a: \"\\f10c\";\n$ionicon-var-arrow-up-b: \"\\f10d\";\n$ionicon-var-arrow-up-c: \"\\f10e\";\n$ionicon-var-asterisk: \"\\f314\";\n$ionicon-var-at: \"\\f10f\";\n$ionicon-var-backspace: \"\\f3bf\";\n$ionicon-var-backspace-outline: \"\\f3be\";\n$ionicon-var-bag: \"\\f110\";\n$ionicon-var-battery-charging: \"\\f111\";\n$ionicon-var-battery-empty: \"\\f112\";\n$ionicon-var-battery-full: \"\\f113\";\n$ionicon-var-battery-half: \"\\f114\";\n$ionicon-var-battery-low: \"\\f115\";\n$ionicon-var-beaker: \"\\f269\";\n$ionicon-var-beer: \"\\f26a\";\n$ionicon-var-bluetooth: \"\\f116\";\n$ionicon-var-bonfire: \"\\f315\";\n$ionicon-var-bookmark: \"\\f26b\";\n$ionicon-var-bowtie: \"\\f3c0\";\n$ionicon-var-briefcase: \"\\f26c\";\n$ionicon-var-bug: \"\\f2be\";\n$ionicon-var-calculator: \"\\f26d\";\n$ionicon-var-calendar: \"\\f117\";\n$ionicon-var-camera: \"\\f118\";\n$ionicon-var-card: \"\\f119\";\n$ionicon-var-cash: \"\\f316\";\n$ionicon-var-chatbox: \"\\f11b\";\n$ionicon-var-chatbox-working: \"\\f11a\";\n$ionicon-var-chatboxes: \"\\f11c\";\n$ionicon-var-chatbubble: \"\\f11e\";\n$ionicon-var-chatbubble-working: \"\\f11d\";\n$ionicon-var-chatbubbles: \"\\f11f\";\n$ionicon-var-checkmark: \"\\f122\";\n$ionicon-var-checkmark-circled: \"\\f120\";\n$ionicon-var-checkmark-round: \"\\f121\";\n$ionicon-var-chevron-down: \"\\f123\";\n$ionicon-var-chevron-left: \"\\f124\";\n$ionicon-var-chevron-right: \"\\f125\";\n$ionicon-var-chevron-up: \"\\f126\";\n$ionicon-var-clipboard: \"\\f127\";\n$ionicon-var-clock: \"\\f26e\";\n$ionicon-var-close: \"\\f12a\";\n$ionicon-var-close-circled: \"\\f128\";\n$ionicon-var-close-round: \"\\f129\";\n$ionicon-var-closed-captioning: \"\\f317\";\n$ionicon-var-cloud: \"\\f12b\";\n$ionicon-var-code: \"\\f271\";\n$ionicon-var-code-download: \"\\f26f\";\n$ionicon-var-code-working: \"\\f270\";\n$ionicon-var-coffee: \"\\f272\";\n$ionicon-var-compass: \"\\f273\";\n$ionicon-var-compose: \"\\f12c\";\n$ionicon-var-connection-bars: \"\\f274\";\n$ionicon-var-contrast: \"\\f275\";\n$ionicon-var-crop: \"\\f3c1\";\n$ionicon-var-cube: \"\\f318\";\n$ionicon-var-disc: \"\\f12d\";\n$ionicon-var-document: \"\\f12f\";\n$ionicon-var-document-text: \"\\f12e\";\n$ionicon-var-drag: \"\\f130\";\n$ionicon-var-earth: \"\\f276\";\n$ionicon-var-easel: \"\\f3c2\";\n$ionicon-var-edit: \"\\f2bf\";\n$ionicon-var-egg: \"\\f277\";\n$ionicon-var-eject: \"\\f131\";\n$ionicon-var-email: \"\\f132\";\n$ionicon-var-email-unread: \"\\f3c3\";\n$ionicon-var-erlenmeyer-flask: \"\\f3c5\";\n$ionicon-var-erlenmeyer-flask-bubbles: \"\\f3c4\";\n$ionicon-var-eye: \"\\f133\";\n$ionicon-var-eye-disabled: \"\\f306\";\n$ionicon-var-female: \"\\f278\";\n$ionicon-var-filing: \"\\f134\";\n$ionicon-var-film-marker: \"\\f135\";\n$ionicon-var-fireball: \"\\f319\";\n$ionicon-var-flag: \"\\f279\";\n$ionicon-var-flame: \"\\f31a\";\n$ionicon-var-flash: \"\\f137\";\n$ionicon-var-flash-off: \"\\f136\";\n$ionicon-var-folder: \"\\f139\";\n$ionicon-var-fork: \"\\f27a\";\n$ionicon-var-fork-repo: \"\\f2c0\";\n$ionicon-var-forward: \"\\f13a\";\n$ionicon-var-funnel: \"\\f31b\";\n$ionicon-var-gear-a: \"\\f13d\";\n$ionicon-var-gear-b: \"\\f13e\";\n$ionicon-var-grid: \"\\f13f\";\n$ionicon-var-hammer: \"\\f27b\";\n$ionicon-var-happy: \"\\f31c\";\n$ionicon-var-happy-outline: \"\\f3c6\";\n$ionicon-var-headphone: \"\\f140\";\n$ionicon-var-heart: \"\\f141\";\n$ionicon-var-heart-broken: \"\\f31d\";\n$ionicon-var-help: \"\\f143\";\n$ionicon-var-help-buoy: \"\\f27c\";\n$ionicon-var-help-circled: \"\\f142\";\n$ionicon-var-home: \"\\f144\";\n$ionicon-var-icecream: \"\\f27d\";\n$ionicon-var-image: \"\\f147\";\n$ionicon-var-images: \"\\f148\";\n$ionicon-var-information: \"\\f14a\";\n$ionicon-var-information-circled: \"\\f149\";\n$ionicon-var-ionic: \"\\f14b\";\n$ionicon-var-ios-alarm: \"\\f3c8\";\n$ionicon-var-ios-alarm-outline: \"\\f3c7\";\n$ionicon-var-ios-albums: \"\\f3ca\";\n$ionicon-var-ios-albums-outline: \"\\f3c9\";\n$ionicon-var-ios-americanfootball: \"\\f3cc\";\n$ionicon-var-ios-americanfootball-outline: \"\\f3cb\";\n$ionicon-var-ios-analytics: \"\\f3ce\";\n$ionicon-var-ios-analytics-outline: \"\\f3cd\";\n$ionicon-var-ios-arrow-back: \"\\f3cf\";\n$ionicon-var-ios-arrow-down: \"\\f3d0\";\n$ionicon-var-ios-arrow-forward: \"\\f3d1\";\n$ionicon-var-ios-arrow-left: \"\\f3d2\";\n$ionicon-var-ios-arrow-right: \"\\f3d3\";\n$ionicon-var-ios-arrow-thin-down: \"\\f3d4\";\n$ionicon-var-ios-arrow-thin-left: \"\\f3d5\";\n$ionicon-var-ios-arrow-thin-right: \"\\f3d6\";\n$ionicon-var-ios-arrow-thin-up: \"\\f3d7\";\n$ionicon-var-ios-arrow-up: \"\\f3d8\";\n$ionicon-var-ios-at: \"\\f3da\";\n$ionicon-var-ios-at-outline: \"\\f3d9\";\n$ionicon-var-ios-barcode: \"\\f3dc\";\n$ionicon-var-ios-barcode-outline: \"\\f3db\";\n$ionicon-var-ios-baseball: \"\\f3de\";\n$ionicon-var-ios-baseball-outline: \"\\f3dd\";\n$ionicon-var-ios-basketball: \"\\f3e0\";\n$ionicon-var-ios-basketball-outline: \"\\f3df\";\n$ionicon-var-ios-bell: \"\\f3e2\";\n$ionicon-var-ios-bell-outline: \"\\f3e1\";\n$ionicon-var-ios-body: \"\\f3e4\";\n$ionicon-var-ios-body-outline: \"\\f3e3\";\n$ionicon-var-ios-bolt: \"\\f3e6\";\n$ionicon-var-ios-bolt-outline: \"\\f3e5\";\n$ionicon-var-ios-book: \"\\f3e8\";\n$ionicon-var-ios-book-outline: \"\\f3e7\";\n$ionicon-var-ios-bookmarks: \"\\f3ea\";\n$ionicon-var-ios-bookmarks-outline: \"\\f3e9\";\n$ionicon-var-ios-box: \"\\f3ec\";\n$ionicon-var-ios-box-outline: \"\\f3eb\";\n$ionicon-var-ios-briefcase: \"\\f3ee\";\n$ionicon-var-ios-briefcase-outline: \"\\f3ed\";\n$ionicon-var-ios-browsers: \"\\f3f0\";\n$ionicon-var-ios-browsers-outline: \"\\f3ef\";\n$ionicon-var-ios-calculator: \"\\f3f2\";\n$ionicon-var-ios-calculator-outline: \"\\f3f1\";\n$ionicon-var-ios-calendar: \"\\f3f4\";\n$ionicon-var-ios-calendar-outline: \"\\f3f3\";\n$ionicon-var-ios-camera: \"\\f3f6\";\n$ionicon-var-ios-camera-outline: \"\\f3f5\";\n$ionicon-var-ios-cart: \"\\f3f8\";\n$ionicon-var-ios-cart-outline: \"\\f3f7\";\n$ionicon-var-ios-chatboxes: \"\\f3fa\";\n$ionicon-var-ios-chatboxes-outline: \"\\f3f9\";\n$ionicon-var-ios-chatbubble: \"\\f3fc\";\n$ionicon-var-ios-chatbubble-outline: \"\\f3fb\";\n$ionicon-var-ios-checkmark: \"\\f3ff\";\n$ionicon-var-ios-checkmark-empty: \"\\f3fd\";\n$ionicon-var-ios-checkmark-outline: \"\\f3fe\";\n$ionicon-var-ios-circle-filled: \"\\f400\";\n$ionicon-var-ios-circle-outline: \"\\f401\";\n$ionicon-var-ios-clock: \"\\f403\";\n$ionicon-var-ios-clock-outline: \"\\f402\";\n$ionicon-var-ios-close: \"\\f406\";\n$ionicon-var-ios-close-empty: \"\\f404\";\n$ionicon-var-ios-close-outline: \"\\f405\";\n$ionicon-var-ios-cloud: \"\\f40c\";\n$ionicon-var-ios-cloud-download: \"\\f408\";\n$ionicon-var-ios-cloud-download-outline: \"\\f407\";\n$ionicon-var-ios-cloud-outline: \"\\f409\";\n$ionicon-var-ios-cloud-upload: \"\\f40b\";\n$ionicon-var-ios-cloud-upload-outline: \"\\f40a\";\n$ionicon-var-ios-cloudy: \"\\f410\";\n$ionicon-var-ios-cloudy-night: \"\\f40e\";\n$ionicon-var-ios-cloudy-night-outline: \"\\f40d\";\n$ionicon-var-ios-cloudy-outline: \"\\f40f\";\n$ionicon-var-ios-cog: \"\\f412\";\n$ionicon-var-ios-cog-outline: \"\\f411\";\n$ionicon-var-ios-color-filter: \"\\f414\";\n$ionicon-var-ios-color-filter-outline: \"\\f413\";\n$ionicon-var-ios-color-wand: \"\\f416\";\n$ionicon-var-ios-color-wand-outline: \"\\f415\";\n$ionicon-var-ios-compose: \"\\f418\";\n$ionicon-var-ios-compose-outline: \"\\f417\";\n$ionicon-var-ios-contact: \"\\f41a\";\n$ionicon-var-ios-contact-outline: \"\\f419\";\n$ionicon-var-ios-copy: \"\\f41c\";\n$ionicon-var-ios-copy-outline: \"\\f41b\";\n$ionicon-var-ios-crop: \"\\f41e\";\n$ionicon-var-ios-crop-strong: \"\\f41d\";\n$ionicon-var-ios-download: \"\\f420\";\n$ionicon-var-ios-download-outline: \"\\f41f\";\n$ionicon-var-ios-drag: \"\\f421\";\n$ionicon-var-ios-email: \"\\f423\";\n$ionicon-var-ios-email-outline: \"\\f422\";\n$ionicon-var-ios-eye: \"\\f425\";\n$ionicon-var-ios-eye-outline: \"\\f424\";\n$ionicon-var-ios-fastforward: \"\\f427\";\n$ionicon-var-ios-fastforward-outline: \"\\f426\";\n$ionicon-var-ios-filing: \"\\f429\";\n$ionicon-var-ios-filing-outline: \"\\f428\";\n$ionicon-var-ios-film: \"\\f42b\";\n$ionicon-var-ios-film-outline: \"\\f42a\";\n$ionicon-var-ios-flag: \"\\f42d\";\n$ionicon-var-ios-flag-outline: \"\\f42c\";\n$ionicon-var-ios-flame: \"\\f42f\";\n$ionicon-var-ios-flame-outline: \"\\f42e\";\n$ionicon-var-ios-flask: \"\\f431\";\n$ionicon-var-ios-flask-outline: \"\\f430\";\n$ionicon-var-ios-flower: \"\\f433\";\n$ionicon-var-ios-flower-outline: \"\\f432\";\n$ionicon-var-ios-folder: \"\\f435\";\n$ionicon-var-ios-folder-outline: \"\\f434\";\n$ionicon-var-ios-football: \"\\f437\";\n$ionicon-var-ios-football-outline: \"\\f436\";\n$ionicon-var-ios-game-controller-a: \"\\f439\";\n$ionicon-var-ios-game-controller-a-outline: \"\\f438\";\n$ionicon-var-ios-game-controller-b: \"\\f43b\";\n$ionicon-var-ios-game-controller-b-outline: \"\\f43a\";\n$ionicon-var-ios-gear: \"\\f43d\";\n$ionicon-var-ios-gear-outline: \"\\f43c\";\n$ionicon-var-ios-glasses: \"\\f43f\";\n$ionicon-var-ios-glasses-outline: \"\\f43e\";\n$ionicon-var-ios-grid-view: \"\\f441\";\n$ionicon-var-ios-grid-view-outline: \"\\f440\";\n$ionicon-var-ios-heart: \"\\f443\";\n$ionicon-var-ios-heart-outline: \"\\f442\";\n$ionicon-var-ios-help: \"\\f446\";\n$ionicon-var-ios-help-empty: \"\\f444\";\n$ionicon-var-ios-help-outline: \"\\f445\";\n$ionicon-var-ios-home: \"\\f448\";\n$ionicon-var-ios-home-outline: \"\\f447\";\n$ionicon-var-ios-infinite: \"\\f44a\";\n$ionicon-var-ios-infinite-outline: \"\\f449\";\n$ionicon-var-ios-information: \"\\f44d\";\n$ionicon-var-ios-information-empty: \"\\f44b\";\n$ionicon-var-ios-information-outline: \"\\f44c\";\n$ionicon-var-ios-ionic-outline: \"\\f44e\";\n$ionicon-var-ios-keypad: \"\\f450\";\n$ionicon-var-ios-keypad-outline: \"\\f44f\";\n$ionicon-var-ios-lightbulb: \"\\f452\";\n$ionicon-var-ios-lightbulb-outline: \"\\f451\";\n$ionicon-var-ios-list: \"\\f454\";\n$ionicon-var-ios-list-outline: \"\\f453\";\n$ionicon-var-ios-location: \"\\f456\";\n$ionicon-var-ios-location-outline: \"\\f455\";\n$ionicon-var-ios-locked: \"\\f458\";\n$ionicon-var-ios-locked-outline: \"\\f457\";\n$ionicon-var-ios-loop: \"\\f45a\";\n$ionicon-var-ios-loop-strong: \"\\f459\";\n$ionicon-var-ios-medical: \"\\f45c\";\n$ionicon-var-ios-medical-outline: \"\\f45b\";\n$ionicon-var-ios-medkit: \"\\f45e\";\n$ionicon-var-ios-medkit-outline: \"\\f45d\";\n$ionicon-var-ios-mic: \"\\f461\";\n$ionicon-var-ios-mic-off: \"\\f45f\";\n$ionicon-var-ios-mic-outline: \"\\f460\";\n$ionicon-var-ios-minus: \"\\f464\";\n$ionicon-var-ios-minus-empty: \"\\f462\";\n$ionicon-var-ios-minus-outline: \"\\f463\";\n$ionicon-var-ios-monitor: \"\\f466\";\n$ionicon-var-ios-monitor-outline: \"\\f465\";\n$ionicon-var-ios-moon: \"\\f468\";\n$ionicon-var-ios-moon-outline: \"\\f467\";\n$ionicon-var-ios-more: \"\\f46a\";\n$ionicon-var-ios-more-outline: \"\\f469\";\n$ionicon-var-ios-musical-note: \"\\f46b\";\n$ionicon-var-ios-musical-notes: \"\\f46c\";\n$ionicon-var-ios-navigate: \"\\f46e\";\n$ionicon-var-ios-navigate-outline: \"\\f46d\";\n$ionicon-var-ios-nutrition: \"\\f470\";\n$ionicon-var-ios-nutrition-outline: \"\\f46f\";\n$ionicon-var-ios-paper: \"\\f472\";\n$ionicon-var-ios-paper-outline: \"\\f471\";\n$ionicon-var-ios-paperplane: \"\\f474\";\n$ionicon-var-ios-paperplane-outline: \"\\f473\";\n$ionicon-var-ios-partlysunny: \"\\f476\";\n$ionicon-var-ios-partlysunny-outline: \"\\f475\";\n$ionicon-var-ios-pause: \"\\f478\";\n$ionicon-var-ios-pause-outline: \"\\f477\";\n$ionicon-var-ios-paw: \"\\f47a\";\n$ionicon-var-ios-paw-outline: \"\\f479\";\n$ionicon-var-ios-people: \"\\f47c\";\n$ionicon-var-ios-people-outline: \"\\f47b\";\n$ionicon-var-ios-person: \"\\f47e\";\n$ionicon-var-ios-person-outline: \"\\f47d\";\n$ionicon-var-ios-personadd: \"\\f480\";\n$ionicon-var-ios-personadd-outline: \"\\f47f\";\n$ionicon-var-ios-photos: \"\\f482\";\n$ionicon-var-ios-photos-outline: \"\\f481\";\n$ionicon-var-ios-pie: \"\\f484\";\n$ionicon-var-ios-pie-outline: \"\\f483\";\n$ionicon-var-ios-pint: \"\\f486\";\n$ionicon-var-ios-pint-outline: \"\\f485\";\n$ionicon-var-ios-play: \"\\f488\";\n$ionicon-var-ios-play-outline: \"\\f487\";\n$ionicon-var-ios-plus: \"\\f48b\";\n$ionicon-var-ios-plus-empty: \"\\f489\";\n$ionicon-var-ios-plus-outline: \"\\f48a\";\n$ionicon-var-ios-pricetag: \"\\f48d\";\n$ionicon-var-ios-pricetag-outline: \"\\f48c\";\n$ionicon-var-ios-pricetags: \"\\f48f\";\n$ionicon-var-ios-pricetags-outline: \"\\f48e\";\n$ionicon-var-ios-printer: \"\\f491\";\n$ionicon-var-ios-printer-outline: \"\\f490\";\n$ionicon-var-ios-pulse: \"\\f493\";\n$ionicon-var-ios-pulse-strong: \"\\f492\";\n$ionicon-var-ios-rainy: \"\\f495\";\n$ionicon-var-ios-rainy-outline: \"\\f494\";\n$ionicon-var-ios-recording: \"\\f497\";\n$ionicon-var-ios-recording-outline: \"\\f496\";\n$ionicon-var-ios-redo: \"\\f499\";\n$ionicon-var-ios-redo-outline: \"\\f498\";\n$ionicon-var-ios-refresh: \"\\f49c\";\n$ionicon-var-ios-refresh-empty: \"\\f49a\";\n$ionicon-var-ios-refresh-outline: \"\\f49b\";\n$ionicon-var-ios-reload: \"\\f49d\";\n$ionicon-var-ios-reverse-camera: \"\\f49f\";\n$ionicon-var-ios-reverse-camera-outline: \"\\f49e\";\n$ionicon-var-ios-rewind: \"\\f4a1\";\n$ionicon-var-ios-rewind-outline: \"\\f4a0\";\n$ionicon-var-ios-rose: \"\\f4a3\";\n$ionicon-var-ios-rose-outline: \"\\f4a2\";\n$ionicon-var-ios-search: \"\\f4a5\";\n$ionicon-var-ios-search-strong: \"\\f4a4\";\n$ionicon-var-ios-settings: \"\\f4a7\";\n$ionicon-var-ios-settings-strong: \"\\f4a6\";\n$ionicon-var-ios-shuffle: \"\\f4a9\";\n$ionicon-var-ios-shuffle-strong: \"\\f4a8\";\n$ionicon-var-ios-skipbackward: \"\\f4ab\";\n$ionicon-var-ios-skipbackward-outline: \"\\f4aa\";\n$ionicon-var-ios-skipforward: \"\\f4ad\";\n$ionicon-var-ios-skipforward-outline: \"\\f4ac\";\n$ionicon-var-ios-snowy: \"\\f4ae\";\n$ionicon-var-ios-speedometer: \"\\f4b0\";\n$ionicon-var-ios-speedometer-outline: \"\\f4af\";\n$ionicon-var-ios-star: \"\\f4b3\";\n$ionicon-var-ios-star-half: \"\\f4b1\";\n$ionicon-var-ios-star-outline: \"\\f4b2\";\n$ionicon-var-ios-stopwatch: \"\\f4b5\";\n$ionicon-var-ios-stopwatch-outline: \"\\f4b4\";\n$ionicon-var-ios-sunny: \"\\f4b7\";\n$ionicon-var-ios-sunny-outline: \"\\f4b6\";\n$ionicon-var-ios-telephone: \"\\f4b9\";\n$ionicon-var-ios-telephone-outline: \"\\f4b8\";\n$ionicon-var-ios-tennisball: \"\\f4bb\";\n$ionicon-var-ios-tennisball-outline: \"\\f4ba\";\n$ionicon-var-ios-thunderstorm: \"\\f4bd\";\n$ionicon-var-ios-thunderstorm-outline: \"\\f4bc\";\n$ionicon-var-ios-time: \"\\f4bf\";\n$ionicon-var-ios-time-outline: \"\\f4be\";\n$ionicon-var-ios-timer: \"\\f4c1\";\n$ionicon-var-ios-timer-outline: \"\\f4c0\";\n$ionicon-var-ios-toggle: \"\\f4c3\";\n$ionicon-var-ios-toggle-outline: \"\\f4c2\";\n$ionicon-var-ios-trash: \"\\f4c5\";\n$ionicon-var-ios-trash-outline: \"\\f4c4\";\n$ionicon-var-ios-undo: \"\\f4c7\";\n$ionicon-var-ios-undo-outline: \"\\f4c6\";\n$ionicon-var-ios-unlocked: \"\\f4c9\";\n$ionicon-var-ios-unlocked-outline: \"\\f4c8\";\n$ionicon-var-ios-upload: \"\\f4cb\";\n$ionicon-var-ios-upload-outline: \"\\f4ca\";\n$ionicon-var-ios-videocam: \"\\f4cd\";\n$ionicon-var-ios-videocam-outline: \"\\f4cc\";\n$ionicon-var-ios-volume-high: \"\\f4ce\";\n$ionicon-var-ios-volume-low: \"\\f4cf\";\n$ionicon-var-ios-wineglass: \"\\f4d1\";\n$ionicon-var-ios-wineglass-outline: \"\\f4d0\";\n$ionicon-var-ios-world: \"\\f4d3\";\n$ionicon-var-ios-world-outline: \"\\f4d2\";\n$ionicon-var-ipad: \"\\f1f9\";\n$ionicon-var-iphone: \"\\f1fa\";\n$ionicon-var-ipod: \"\\f1fb\";\n$ionicon-var-jet: \"\\f295\";\n$ionicon-var-key: \"\\f296\";\n$ionicon-var-knife: \"\\f297\";\n$ionicon-var-laptop: \"\\f1fc\";\n$ionicon-var-leaf: \"\\f1fd\";\n$ionicon-var-levels: \"\\f298\";\n$ionicon-var-lightbulb: \"\\f299\";\n$ionicon-var-link: \"\\f1fe\";\n$ionicon-var-load-a: \"\\f29a\";\n$ionicon-var-load-b: \"\\f29b\";\n$ionicon-var-load-c: \"\\f29c\";\n$ionicon-var-load-d: \"\\f29d\";\n$ionicon-var-location: \"\\f1ff\";\n$ionicon-var-lock-combination: \"\\f4d4\";\n$ionicon-var-locked: \"\\f200\";\n$ionicon-var-log-in: \"\\f29e\";\n$ionicon-var-log-out: \"\\f29f\";\n$ionicon-var-loop: \"\\f201\";\n$ionicon-var-magnet: \"\\f2a0\";\n$ionicon-var-male: \"\\f2a1\";\n$ionicon-var-man: \"\\f202\";\n$ionicon-var-map: \"\\f203\";\n$ionicon-var-medkit: \"\\f2a2\";\n$ionicon-var-merge: \"\\f33f\";\n$ionicon-var-mic-a: \"\\f204\";\n$ionicon-var-mic-b: \"\\f205\";\n$ionicon-var-mic-c: \"\\f206\";\n$ionicon-var-minus: \"\\f209\";\n$ionicon-var-minus-circled: \"\\f207\";\n$ionicon-var-minus-round: \"\\f208\";\n$ionicon-var-model-s: \"\\f2c1\";\n$ionicon-var-monitor: \"\\f20a\";\n$ionicon-var-more: \"\\f20b\";\n$ionicon-var-mouse: \"\\f340\";\n$ionicon-var-music-note: \"\\f20c\";\n$ionicon-var-navicon: \"\\f20e\";\n$ionicon-var-navicon-round: \"\\f20d\";\n$ionicon-var-navigate: \"\\f2a3\";\n$ionicon-var-network: \"\\f341\";\n$ionicon-var-no-smoking: \"\\f2c2\";\n$ionicon-var-nuclear: \"\\f2a4\";\n$ionicon-var-outlet: \"\\f342\";\n$ionicon-var-paintbrush: \"\\f4d5\";\n$ionicon-var-paintbucket: \"\\f4d6\";\n$ionicon-var-paper-airplane: \"\\f2c3\";\n$ionicon-var-paperclip: \"\\f20f\";\n$ionicon-var-pause: \"\\f210\";\n$ionicon-var-person: \"\\f213\";\n$ionicon-var-person-add: \"\\f211\";\n$ionicon-var-person-stalker: \"\\f212\";\n$ionicon-var-pie-graph: \"\\f2a5\";\n$ionicon-var-pin: \"\\f2a6\";\n$ionicon-var-pinpoint: \"\\f2a7\";\n$ionicon-var-pizza: \"\\f2a8\";\n$ionicon-var-plane: \"\\f214\";\n$ionicon-var-planet: \"\\f343\";\n$ionicon-var-play: \"\\f215\";\n$ionicon-var-playstation: \"\\f30a\";\n$ionicon-var-plus: \"\\f218\";\n$ionicon-var-plus-circled: \"\\f216\";\n$ionicon-var-plus-round: \"\\f217\";\n$ionicon-var-podium: \"\\f344\";\n$ionicon-var-pound: \"\\f219\";\n$ionicon-var-power: \"\\f2a9\";\n$ionicon-var-pricetag: \"\\f2aa\";\n$ionicon-var-pricetags: \"\\f2ab\";\n$ionicon-var-printer: \"\\f21a\";\n$ionicon-var-pull-request: \"\\f345\";\n$ionicon-var-qr-scanner: \"\\f346\";\n$ionicon-var-quote: \"\\f347\";\n$ionicon-var-radio-waves: \"\\f2ac\";\n$ionicon-var-record: \"\\f21b\";\n$ionicon-var-refresh: \"\\f21c\";\n$ionicon-var-reply: \"\\f21e\";\n$ionicon-var-reply-all: \"\\f21d\";\n$ionicon-var-ribbon-a: \"\\f348\";\n$ionicon-var-ribbon-b: \"\\f349\";\n$ionicon-var-sad: \"\\f34a\";\n$ionicon-var-sad-outline: \"\\f4d7\";\n$ionicon-var-scissors: \"\\f34b\";\n$ionicon-var-search: \"\\f21f\";\n$ionicon-var-settings: \"\\f2ad\";\n$ionicon-var-share: \"\\f220\";\n$ionicon-var-shuffle: \"\\f221\";\n$ionicon-var-skip-backward: \"\\f222\";\n$ionicon-var-skip-forward: \"\\f223\";\n$ionicon-var-social-android: \"\\f225\";\n$ionicon-var-social-android-outline: \"\\f224\";\n$ionicon-var-social-angular: \"\\f4d9\";\n$ionicon-var-social-angular-outline: \"\\f4d8\";\n$ionicon-var-social-apple: \"\\f227\";\n$ionicon-var-social-apple-outline: \"\\f226\";\n$ionicon-var-social-bitcoin: \"\\f2af\";\n$ionicon-var-social-bitcoin-outline: \"\\f2ae\";\n$ionicon-var-social-buffer: \"\\f229\";\n$ionicon-var-social-buffer-outline: \"\\f228\";\n$ionicon-var-social-chrome: \"\\f4db\";\n$ionicon-var-social-chrome-outline: \"\\f4da\";\n$ionicon-var-social-codepen: \"\\f4dd\";\n$ionicon-var-social-codepen-outline: \"\\f4dc\";\n$ionicon-var-social-css3: \"\\f4df\";\n$ionicon-var-social-css3-outline: \"\\f4de\";\n$ionicon-var-social-designernews: \"\\f22b\";\n$ionicon-var-social-designernews-outline: \"\\f22a\";\n$ionicon-var-social-dribbble: \"\\f22d\";\n$ionicon-var-social-dribbble-outline: \"\\f22c\";\n$ionicon-var-social-dropbox: \"\\f22f\";\n$ionicon-var-social-dropbox-outline: \"\\f22e\";\n$ionicon-var-social-euro: \"\\f4e1\";\n$ionicon-var-social-euro-outline: \"\\f4e0\";\n$ionicon-var-social-facebook: \"\\f231\";\n$ionicon-var-social-facebook-outline: \"\\f230\";\n$ionicon-var-social-foursquare: \"\\f34d\";\n$ionicon-var-social-foursquare-outline: \"\\f34c\";\n$ionicon-var-social-freebsd-devil: \"\\f2c4\";\n$ionicon-var-social-github: \"\\f233\";\n$ionicon-var-social-github-outline: \"\\f232\";\n$ionicon-var-social-google: \"\\f34f\";\n$ionicon-var-social-google-outline: \"\\f34e\";\n$ionicon-var-social-googleplus: \"\\f235\";\n$ionicon-var-social-googleplus-outline: \"\\f234\";\n$ionicon-var-social-hackernews: \"\\f237\";\n$ionicon-var-social-hackernews-outline: \"\\f236\";\n$ionicon-var-social-html5: \"\\f4e3\";\n$ionicon-var-social-html5-outline: \"\\f4e2\";\n$ionicon-var-social-instagram: \"\\f351\";\n$ionicon-var-social-instagram-outline: \"\\f350\";\n$ionicon-var-social-javascript: \"\\f4e5\";\n$ionicon-var-social-javascript-outline: \"\\f4e4\";\n$ionicon-var-social-linkedin: \"\\f239\";\n$ionicon-var-social-linkedin-outline: \"\\f238\";\n$ionicon-var-social-markdown: \"\\f4e6\";\n$ionicon-var-social-nodejs: \"\\f4e7\";\n$ionicon-var-social-octocat: \"\\f4e8\";\n$ionicon-var-social-pinterest: \"\\f2b1\";\n$ionicon-var-social-pinterest-outline: \"\\f2b0\";\n$ionicon-var-social-python: \"\\f4e9\";\n$ionicon-var-social-reddit: \"\\f23b\";\n$ionicon-var-social-reddit-outline: \"\\f23a\";\n$ionicon-var-social-rss: \"\\f23d\";\n$ionicon-var-social-rss-outline: \"\\f23c\";\n$ionicon-var-social-sass: \"\\f4ea\";\n$ionicon-var-social-skype: \"\\f23f\";\n$ionicon-var-social-skype-outline: \"\\f23e\";\n$ionicon-var-social-snapchat: \"\\f4ec\";\n$ionicon-var-social-snapchat-outline: \"\\f4eb\";\n$ionicon-var-social-tumblr: \"\\f241\";\n$ionicon-var-social-tumblr-outline: \"\\f240\";\n$ionicon-var-social-tux: \"\\f2c5\";\n$ionicon-var-social-twitch: \"\\f4ee\";\n$ionicon-var-social-twitch-outline: \"\\f4ed\";\n$ionicon-var-social-twitter: \"\\f243\";\n$ionicon-var-social-twitter-outline: \"\\f242\";\n$ionicon-var-social-usd: \"\\f353\";\n$ionicon-var-social-usd-outline: \"\\f352\";\n$ionicon-var-social-vimeo: \"\\f245\";\n$ionicon-var-social-vimeo-outline: \"\\f244\";\n$ionicon-var-social-whatsapp: \"\\f4f0\";\n$ionicon-var-social-whatsapp-outline: \"\\f4ef\";\n$ionicon-var-social-windows: \"\\f247\";\n$ionicon-var-social-windows-outline: \"\\f246\";\n$ionicon-var-social-wordpress: \"\\f249\";\n$ionicon-var-social-wordpress-outline: \"\\f248\";\n$ionicon-var-social-yahoo: \"\\f24b\";\n$ionicon-var-social-yahoo-outline: \"\\f24a\";\n$ionicon-var-social-yen: \"\\f4f2\";\n$ionicon-var-social-yen-outline: \"\\f4f1\";\n$ionicon-var-social-youtube: \"\\f24d\";\n$ionicon-var-social-youtube-outline: \"\\f24c\";\n$ionicon-var-soup-can: \"\\f4f4\";\n$ionicon-var-soup-can-outline: \"\\f4f3\";\n$ionicon-var-speakerphone: \"\\f2b2\";\n$ionicon-var-speedometer: \"\\f2b3\";\n$ionicon-var-spoon: \"\\f2b4\";\n$ionicon-var-star: \"\\f24e\";\n$ionicon-var-stats-bars: \"\\f2b5\";\n$ionicon-var-steam: \"\\f30b\";\n$ionicon-var-stop: \"\\f24f\";\n$ionicon-var-thermometer: \"\\f2b6\";\n$ionicon-var-thumbsdown: \"\\f250\";\n$ionicon-var-thumbsup: \"\\f251\";\n$ionicon-var-toggle: \"\\f355\";\n$ionicon-var-toggle-filled: \"\\f354\";\n$ionicon-var-transgender: \"\\f4f5\";\n$ionicon-var-trash-a: \"\\f252\";\n$ionicon-var-trash-b: \"\\f253\";\n$ionicon-var-trophy: \"\\f356\";\n$ionicon-var-tshirt: \"\\f4f7\";\n$ionicon-var-tshirt-outline: \"\\f4f6\";\n$ionicon-var-umbrella: \"\\f2b7\";\n$ionicon-var-university: \"\\f357\";\n$ionicon-var-unlocked: \"\\f254\";\n$ionicon-var-upload: \"\\f255\";\n$ionicon-var-usb: \"\\f2b8\";\n$ionicon-var-videocamera: \"\\f256\";\n$ionicon-var-volume-high: \"\\f257\";\n$ionicon-var-volume-low: \"\\f258\";\n$ionicon-var-volume-medium: \"\\f259\";\n$ionicon-var-volume-mute: \"\\f25a\";\n$ionicon-var-wand: \"\\f358\";\n$ionicon-var-waterdrop: \"\\f25b\";\n$ionicon-var-wifi: \"\\f25c\";\n$ionicon-var-wineglass: \"\\f2b9\";\n$ionicon-var-woman: \"\\f25d\";\n$ionicon-var-wrench: \"\\f2ba\";\n$ionicon-var-xbox: \"\\f30c\";"
  },
  {
    "path": "examples/ionic/www/lib/ionic/scss/ionicons/ionicons.scss",
    "content": "@charset \"UTF-8\";\n@import \"ionicons-variables\";\n/*!\n  Ionicons, v2.0.1\n  Created by Ben Sperry for the Ionic Framework, http://ionicons.com/\n  https://twitter.com/benjsperry  https://twitter.com/ionicframework\n  MIT License: https://github.com/driftyco/ionicons\n\n  Android-style icons originally built by Google’s\n  Material Design Icons: https://github.com/google/material-design-icons\n  used under CC BY http://creativecommons.org/licenses/by/4.0/\n  Modified icons to fit ionicon’s grid from original.\n*/\n\n@import \"ionicons-font\";\n@import \"ionicons-icons\";\n"
  },
  {
    "path": "examples/ionic/www/lib/ionic/version.json",
    "content": "{\n  \"version\": \"1.0.0\",\n  \"codename\": \"uranium-unicorn\",\n  \"date\": \"2015-05-12\",\n  \"time\": \"17:23:22\"\n}\n"
  },
  {
    "path": "examples/ionic/www/lib/satellizer/dist/satellizer.js",
    "content": "/**\n * Satellizer 0.15.5\n * (c) 2016 Sahat Yalkabov \n * License: MIT \n */\n\n(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n    typeof define === 'function' && define.amd ? define(factory) :\n    (global.satellizer = factory());\n}(this, function () { 'use strict';\n\n    var Config = (function () {\n        function Config() {\n            this.baseUrl = '/';\n            this.loginUrl = '/auth/login';\n            this.signupUrl = '/auth/signup';\n            this.unlinkUrl = '/auth/unlink/';\n            this.tokenName = 'token';\n            this.tokenPrefix = 'satellizer';\n            this.tokenHeader = 'Authorization';\n            this.tokenType = 'Bearer';\n            this.storageType = 'localStorage';\n            this.tokenRoot = null;\n            this.withCredentials = false;\n            this.providers = {\n                facebook: {\n                    name: 'facebook',\n                    url: '/auth/facebook',\n                    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ',',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 580, height: 400 }\n                },\n                google: {\n                    name: 'google',\n                    url: '/auth/google',\n                    authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    optionalUrlParams: ['display', 'state'],\n                    scope: ['profile', 'email'],\n                    scopePrefix: 'openid',\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 452, height: 633 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                },\n                github: {\n                    name: 'github',\n                    url: '/auth/github',\n                    authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['scope'],\n                    scope: ['user:email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1020, height: 618 }\n                },\n                instagram: {\n                    name: 'instagram',\n                    url: '/auth/instagram',\n                    authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['basic'],\n                    scopeDelimiter: '+',\n                    oauthType: '2.0'\n                },\n                linkedin: {\n                    name: 'linkedin',\n                    url: '/auth/linkedin',\n                    authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['state'],\n                    scope: ['r_emailaddress'],\n                    scopeDelimiter: ' ',\n                    state: 'STATE',\n                    oauthType: '2.0',\n                    popupOptions: { width: 527, height: 582 }\n                },\n                twitter: {\n                    name: 'twitter',\n                    url: '/auth/twitter',\n                    authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n                    redirectUri: window.location.origin,\n                    oauthType: '1.0',\n                    popupOptions: { width: 495, height: 645 }\n                },\n                twitch: {\n                    name: 'twitch',\n                    url: '/auth/twitch',\n                    authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['user_read'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                live: {\n                    name: 'live',\n                    url: '/auth/live',\n                    authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['wl.emails'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                yahoo: {\n                    name: 'yahoo',\n                    url: '/auth/yahoo',\n                    authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n                    redirectUri: window.location.origin,\n                    scope: [],\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 559, height: 519 }\n                },\n                bitbucket: {\n                    name: 'bitbucket',\n                    url: '/auth/bitbucket',\n                    authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1028, height: 529 }\n                },\n                spotify: {\n                    name: 'spotify',\n                    url: '/auth/spotify',\n                    authorizationEndpoint: 'https://accounts.spotify.com/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['state'],\n                    requiredUrlParams: ['scope'],\n                    scope: ['user-read-email'],\n                    scopePrefix: '',\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 530 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                }\n            };\n            this.httpInterceptor = function () { return true; };\n        }\n        Object.defineProperty(Config, \"getConstant\", {\n            get: function () {\n                return new Config();\n            },\n            enumerable: true,\n            configurable: true\n        });\n        return Config;\n    }());\n    ;\n\n    var AuthProvider = (function () {\n        function AuthProvider(SatellizerConfig) {\n            this.SatellizerConfig = SatellizerConfig;\n        }\n        Object.defineProperty(AuthProvider.prototype, \"baseUrl\", {\n            get: function () { return this.SatellizerConfig.baseUrl; },\n            set: function (value) { this.SatellizerConfig.baseUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"loginUrl\", {\n            get: function () { return this.SatellizerConfig.loginUrl; },\n            set: function (value) { this.SatellizerConfig.loginUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"signupUrl\", {\n            get: function () { return this.SatellizerConfig.signupUrl; },\n            set: function (value) { this.SatellizerConfig.signupUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"unlinkUrl\", {\n            get: function () { return this.SatellizerConfig.unlinkUrl; },\n            set: function (value) { this.SatellizerConfig.unlinkUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenRoot\", {\n            get: function () { return this.SatellizerConfig.tokenRoot; },\n            set: function (value) { this.SatellizerConfig.tokenRoot = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenName\", {\n            get: function () { return this.SatellizerConfig.tokenName; },\n            set: function (value) { this.SatellizerConfig.tokenName = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenPrefix\", {\n            get: function () { return this.SatellizerConfig.tokenPrefix; },\n            set: function (value) { this.SatellizerConfig.tokenPrefix = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenHeader\", {\n            get: function () { return this.SatellizerConfig.tokenHeader; },\n            set: function (value) { this.SatellizerConfig.tokenHeader = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenType\", {\n            get: function () { return this.SatellizerConfig.tokenType; },\n            set: function (value) { this.SatellizerConfig.tokenType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"withCredentials\", {\n            get: function () { return this.SatellizerConfig.withCredentials; },\n            set: function (value) { this.SatellizerConfig.withCredentials = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"storageType\", {\n            get: function () { return this.SatellizerConfig.storageType; },\n            set: function (value) { this.SatellizerConfig.storageType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"httpInterceptor\", {\n            get: function () { return this.SatellizerConfig.httpInterceptor; },\n            set: function (value) {\n                if (typeof value === 'function') {\n                    this.SatellizerConfig.httpInterceptor = value;\n                }\n                else {\n                    this.SatellizerConfig.httpInterceptor = function () { return value; };\n                }\n            },\n            enumerable: true,\n            configurable: true\n        });\n        AuthProvider.prototype.facebook = function (options) {\n            angular.extend(this.SatellizerConfig.providers.facebook, options);\n        };\n        AuthProvider.prototype.google = function (options) {\n            angular.extend(this.SatellizerConfig.providers.google, options);\n        };\n        AuthProvider.prototype.github = function (options) {\n            angular.extend(this.SatellizerConfig.providers.github, options);\n        };\n        AuthProvider.prototype.instagram = function (options) {\n            angular.extend(this.SatellizerConfig.providers.instagram, options);\n        };\n        AuthProvider.prototype.linkedin = function (options) {\n            angular.extend(this.SatellizerConfig.providers.linkedin, options);\n        };\n        AuthProvider.prototype.twitter = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitter, options);\n        };\n        AuthProvider.prototype.twitch = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitch, options);\n        };\n        AuthProvider.prototype.live = function (options) {\n            angular.extend(this.SatellizerConfig.providers.live, options);\n        };\n        AuthProvider.prototype.yahoo = function (options) {\n            angular.extend(this.SatellizerConfig.providers.yahoo, options);\n        };\n        AuthProvider.prototype.bitbucket = function (options) {\n            angular.extend(this.SatellizerConfig.providers.bitbucket, options);\n        };\n        AuthProvider.prototype.spotify = function (options) {\n            angular.extend(this.SatellizerConfig.providers.spotify, options);\n        };\n        AuthProvider.prototype.oauth1 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '1.0'\n            });\n        };\n        AuthProvider.prototype.oauth2 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '2.0'\n            });\n        };\n        AuthProvider.prototype.$get = function (SatellizerShared, SatellizerLocal, SatellizerOAuth) {\n            return {\n                login: function (user, options) { return SatellizerLocal.login(user, options); },\n                signup: function (user, options) { return SatellizerLocal.signup(user, options); },\n                logout: function () { return SatellizerShared.logout(); },\n                authenticate: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                link: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                unlink: function (name, options) { return SatellizerOAuth.unlink(name, options); },\n                isAuthenticated: function () { return SatellizerShared.isAuthenticated(); },\n                getPayload: function () { return SatellizerShared.getPayload(); },\n                getToken: function () { return SatellizerShared.getToken(); },\n                setToken: function (token) { return SatellizerShared.setToken({ access_token: token }); },\n                removeToken: function () { return SatellizerShared.removeToken(); },\n                setStorageType: function (type) { return SatellizerShared.setStorageType(type); }\n            };\n        };\n        AuthProvider.$inject = ['SatellizerConfig'];\n        return AuthProvider;\n    }());\n    AuthProvider.prototype.$get.$inject = ['SatellizerShared', 'SatellizerLocal', 'SatellizerOAuth'];\n\n    function joinUrl(baseUrl, url) {\n        if (/^(?:[a-z]+:)?\\/\\//i.test(url)) {\n            return url;\n        }\n        var joined = [baseUrl, url].join('/');\n        var normalize = function (str) {\n            return str\n                .replace(/[\\/]+/g, '/')\n                .replace(/\\/\\?/g, '?')\n                .replace(/\\/\\#/g, '#')\n                .replace(/\\:\\//g, '://');\n        };\n        return normalize(joined);\n    }\n    function getFullUrlPath(location) {\n        var isHttps = location.protocol === 'https:';\n        return location.protocol + '//' + location.hostname +\n            ':' + (location.port || (isHttps ? '443' : '80')) +\n            (/^\\//.test(location.pathname) ? location.pathname : '/' + location.pathname);\n    }\n    function parseQueryString(str) {\n        var obj = {};\n        var key;\n        var value;\n        angular.forEach((str || '').split('&'), function (keyValue) {\n            if (keyValue) {\n                value = keyValue.split('=');\n                key = decodeURIComponent(value[0]);\n                obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;\n            }\n        });\n        return obj;\n    }\n    function decodeBase64(str) {\n        var buffer;\n        if (typeof module !== 'undefined' && module.exports) {\n            try {\n                buffer = require('buffer').Buffer;\n            }\n            catch (err) {\n            }\n        }\n        var fromCharCode = String.fromCharCode;\n        var re_btou = new RegExp([\n            '[\\xC0-\\xDF][\\x80-\\xBF]',\n            '[\\xE0-\\xEF][\\x80-\\xBF]{2}',\n            '[\\xF0-\\xF7][\\x80-\\xBF]{3}'\n        ].join('|'), 'g');\n        var cb_btou = function (cccc) {\n            switch (cccc.length) {\n                case 4:\n                    var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n                        | ((0x3f & cccc.charCodeAt(1)) << 12)\n                        | ((0x3f & cccc.charCodeAt(2)) << 6)\n                        | (0x3f & cccc.charCodeAt(3));\n                    var offset = cp - 0x10000;\n                    return (fromCharCode((offset >>> 10) + 0xD800)\n                        + fromCharCode((offset & 0x3FF) + 0xDC00));\n                case 3:\n                    return fromCharCode(((0x0f & cccc.charCodeAt(0)) << 12)\n                        | ((0x3f & cccc.charCodeAt(1)) << 6)\n                        | (0x3f & cccc.charCodeAt(2)));\n                default:\n                    return fromCharCode(((0x1f & cccc.charCodeAt(0)) << 6)\n                        | (0x3f & cccc.charCodeAt(1)));\n            }\n        };\n        var btou = function (b) {\n            return b.replace(re_btou, cb_btou);\n        };\n        var _decode = buffer ? function (a) {\n            return (a.constructor === buffer.constructor\n                ? a : new buffer(a, 'base64')).toString();\n        }\n            : function (a) {\n                return btou(atob(a));\n            };\n        return _decode(String(str).replace(/[-_]/g, function (m0) {\n            return m0 === '-' ? '+' : '/';\n        })\n            .replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n    }\n\n    var Shared = (function () {\n        function Shared($q, $window, SatellizerConfig, SatellizerStorage) {\n            this.$q = $q;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerStorage = SatellizerStorage;\n            var _a = this.SatellizerConfig, tokenName = _a.tokenName, tokenPrefix = _a.tokenPrefix;\n            this.prefixedTokenName = tokenPrefix ? [tokenPrefix, tokenName].join('_') : tokenName;\n        }\n        Shared.prototype.getToken = function () {\n            return this.SatellizerStorage.get(this.prefixedTokenName);\n        };\n        Shared.prototype.getPayload = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token && token.split('.').length === 3) {\n                try {\n                    var base64Url = token.split('.')[1];\n                    var base64 = base64Url.replace('-', '+').replace('_', '/');\n                    return JSON.parse(decodeBase64(base64));\n                }\n                catch (e) {\n                }\n            }\n        };\n        Shared.prototype.setToken = function (response) {\n            var tokenRoot = this.SatellizerConfig.tokenRoot;\n            var tokenName = this.SatellizerConfig.tokenName;\n            var accessToken = response && response.access_token;\n            var token;\n            if (accessToken) {\n                if (angular.isObject(accessToken) && angular.isObject(accessToken.data)) {\n                    response = accessToken;\n                }\n                else if (angular.isString(accessToken)) {\n                    token = accessToken;\n                }\n            }\n            if (!token && response) {\n                var tokenRootData = tokenRoot && tokenRoot.split('.').reduce(function (o, x) { return o[x]; }, response.data);\n                token = tokenRootData ? tokenRootData[tokenName] : response.data && response.data[tokenName];\n            }\n            if (token) {\n                this.SatellizerStorage.set(this.prefixedTokenName, token);\n            }\n        };\n        Shared.prototype.removeToken = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n        };\n        Shared.prototype.isAuthenticated = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token) {\n                if (token.split('.').length === 3) {\n                    try {\n                        var base64Url = token.split('.')[1];\n                        var base64 = base64Url.replace('-', '+').replace('_', '/');\n                        var exp = JSON.parse(this.$window.atob(base64)).exp;\n                        if (typeof exp === 'number') {\n                            return Math.round(new Date().getTime() / 1000) < exp;\n                        }\n                    }\n                    catch (e) {\n                        return true; // Pass: Non-JWT token that looks like JWT\n                    }\n                }\n                return true; // Pass: All other tokens\n            }\n            return false; // Fail: No token at all\n        };\n        Shared.prototype.logout = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n            return this.$q.when();\n        };\n        Shared.prototype.setStorageType = function (type) {\n            this.SatellizerConfig.storageType = type;\n        };\n        Shared.$inject = ['$q', '$window', 'SatellizerConfig', 'SatellizerStorage'];\n        return Shared;\n    }());\n\n    var Local = (function () {\n        function Local($http, SatellizerConfig, SatellizerShared) {\n            this.$http = $http;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n        }\n        Local.prototype.login = function (user, options) {\n            var _this = this;\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.loginUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options).then(function (response) {\n                _this.SatellizerShared.setToken(response);\n                return response;\n            });\n        };\n        Local.prototype.signup = function (user, options) {\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.signupUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options);\n        };\n        Local.$inject = ['$http', 'SatellizerConfig', 'SatellizerShared'];\n        return Local;\n    }());\n\n    var Popup = (function () {\n        function Popup($interval, $window, $q) {\n            this.$interval = $interval;\n            this.$window = $window;\n            this.$q = $q;\n            this.popup = null;\n            this.defaults = {\n                redirectUri: null\n            };\n        }\n        Popup.prototype.stringifyOptions = function (options) {\n            var parts = [];\n            angular.forEach(options, function (value, key) {\n                parts.push(key + '=' + value);\n            });\n            return parts.join(',');\n        };\n        Popup.prototype.open = function (url, name, popupOptions, redirectUri, dontPoll) {\n            var width = popupOptions.width || 500;\n            var height = popupOptions.height || 500;\n            var options = this.stringifyOptions({\n                width: width,\n                height: height,\n                top: this.$window.screenY + ((this.$window.outerHeight - height) / 2.5),\n                left: this.$window.screenX + ((this.$window.outerWidth - width) / 2)\n            });\n            var popupName = this.$window['cordova'] || this.$window.navigator.userAgent.indexOf('CriOS') > -1 ? '_blank' : name;\n            this.popup = this.$window.open(url, popupName, options);\n            if (this.popup && this.popup.focus) {\n                this.popup.focus();\n            }\n            if (dontPoll) {\n                return;\n            }\n            if (this.$window['cordova']) {\n                return this.eventListener(redirectUri);\n            }\n            else {\n                if (url === 'about:blank') {\n                    this.popup.location = url;\n                }\n                return this.polling(redirectUri);\n            }\n        };\n        Popup.prototype.polling = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var redirectUriParser = document.createElement('a');\n                redirectUriParser.href = redirectUri;\n                var redirectUriPath = getFullUrlPath(redirectUriParser);\n                var polling = _this.$interval(function () {\n                    if (!_this.popup || _this.popup.closed || _this.popup.closed === undefined) {\n                        _this.$interval.cancel(polling);\n                        reject(new Error('The popup window was closed'));\n                    }\n                    try {\n                        var popupWindowPath = getFullUrlPath(_this.popup.location);\n                        if (popupWindowPath === redirectUriPath) {\n                            if (_this.popup.location.search || _this.popup.location.hash) {\n                                var query = parseQueryString(_this.popup.location.search.substring(1).replace(/\\/$/, ''));\n                                var hash = parseQueryString(_this.popup.location.hash.substring(1).replace(/[\\/$]/, ''));\n                                var params = angular.extend({}, query, hash);\n                                if (params.error) {\n                                    reject(new Error(params.error));\n                                }\n                                else {\n                                    resolve(params);\n                                }\n                            }\n                            else {\n                                reject(new Error('OAuth redirect has occurred but no query or hash parameters were found. ' +\n                                    'They were either not set during the redirect, or were removed—typically by a ' +\n                                    'routing library—before Satellizer could read it.'));\n                            }\n                            _this.$interval.cancel(polling);\n                            _this.popup.close();\n                        }\n                    }\n                    catch (error) {\n                    }\n                }, 500);\n            });\n        };\n        Popup.prototype.eventListener = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                _this.popup.addEventListener('loadstart', function (event) {\n                    if (event.url.indexOf(redirectUri) !== 0) {\n                        return;\n                    }\n                    var parser = document.createElement('a');\n                    parser.href = event.url;\n                    if (parser.search || parser.hash) {\n                        var query = parseQueryString(parser.search.substring(1).replace(/\\/$/, ''));\n                        var hash = parseQueryString(parser.hash.substring(1).replace(/[\\/$]/, ''));\n                        var params = angular.extend({}, query, hash);\n                        if (params.error) {\n                            reject(new Error(params.error));\n                        }\n                        else {\n                            resolve(params);\n                        }\n                        _this.popup.close();\n                    }\n                });\n                _this.popup.addEventListener('loaderror', function () {\n                    reject(new Error('Authorization failed'));\n                });\n                _this.popup.addEventListener('exit', function () {\n                    reject(new Error('The popup window was closed'));\n                });\n            });\n        };\n        Popup.$inject = ['$interval', '$window', '$q'];\n        return Popup;\n    }());\n\n    var OAuth1 = (function () {\n        function OAuth1($http, $window, SatellizerConfig, SatellizerPopup) {\n            this.$http = $http;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.defaults = {\n                name: null,\n                url: null,\n                authorizationEndpoint: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                redirectUri: null,\n                requiredUrlParams: null,\n                defaultUrlParams: null,\n                oauthType: '1.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        ;\n        OAuth1.prototype.init = function (options, userData) {\n            var _this = this;\n            angular.extend(this.defaults, options);\n            var name = options.name, popupOptions = options.popupOptions;\n            var redirectUri = this.defaults.redirectUri;\n            // Should open an empty popup and wait until request token is received\n            if (!this.$window['cordova']) {\n                this.SatellizerPopup.open('about:blank', name, popupOptions, redirectUri, true);\n            }\n            return this.getRequestToken().then(function (response) {\n                return _this.openPopup(options, response).then(function (popupResponse) {\n                    return _this.exchangeForToken(popupResponse, userData);\n                });\n            });\n        };\n        OAuth1.prototype.openPopup = function (options, response) {\n            var url = [options.authorizationEndpoint, this.buildQueryString(response.data)].join('?');\n            var redirectUri = this.defaults.redirectUri;\n            if (this.$window['cordova']) {\n                return this.SatellizerPopup.open(url, options.name, options.popupOptions, redirectUri);\n            }\n            else {\n                this.SatellizerPopup.popup.location = url;\n                return this.SatellizerPopup.polling(redirectUri);\n            }\n        };\n        OAuth1.prototype.getRequestToken = function () {\n            var url = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(url, this.defaults);\n        };\n        OAuth1.prototype.exchangeForToken = function (oauthData, userData) {\n            var payload = angular.extend({}, userData, oauthData);\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth1.prototype.buildQueryString = function (obj) {\n            var str = [];\n            angular.forEach(obj, function (value, key) {\n                str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n            });\n            return str.join('&');\n        };\n        OAuth1.$inject = ['$http', '$window', 'SatellizerConfig', 'SatellizerPopup'];\n        return OAuth1;\n    }());\n\n    var OAuth2 = (function () {\n        function OAuth2($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.defaults = {\n                name: null,\n                url: null,\n                clientId: null,\n                authorizationEndpoint: null,\n                redirectUri: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                state: null,\n                requiredUrlParams: null,\n                defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n                responseType: 'code',\n                responseParams: {\n                    code: 'code',\n                    clientId: 'clientId',\n                    redirectUri: 'redirectUri'\n                },\n                oauthType: '2.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        OAuth2.camelCase = function (name) {\n            return name.replace(/([\\:\\-\\_]+(.))/g, function (_, separator, letter, offset) {\n                return offset ? letter.toUpperCase() : letter;\n            });\n        };\n        OAuth2.prototype.init = function (options, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                angular.extend(_this.defaults, options);\n                var stateName = _this.defaults.name + '_state';\n                var _a = _this.defaults, name = _a.name, state = _a.state, popupOptions = _a.popupOptions, redirectUri = _a.redirectUri, responseType = _a.responseType;\n                if (typeof state === 'function') {\n                    _this.SatellizerStorage.set(stateName, state());\n                }\n                else if (typeof state === 'string') {\n                    _this.SatellizerStorage.set(stateName, state);\n                }\n                var url = [_this.defaults.authorizationEndpoint, _this.buildQueryString()].join('?');\n                _this.SatellizerPopup.open(url, name, popupOptions, redirectUri).then(function (oauth) {\n                    if (responseType === 'token' || !url) {\n                        return resolve(oauth);\n                    }\n                    if (oauth.state && oauth.state !== _this.SatellizerStorage.get(stateName)) {\n                        return reject(new Error('The value returned in the state parameter does not match the state value from your original ' +\n                            'authorization code request.'));\n                    }\n                    resolve(_this.exchangeForToken(oauth, userData));\n                }).catch(function (error) { return reject(error); });\n            });\n        };\n        OAuth2.prototype.exchangeForToken = function (oauthData, userData) {\n            var _this = this;\n            var payload = angular.extend({}, userData);\n            angular.forEach(this.defaults.responseParams, function (value, key) {\n                switch (key) {\n                    case 'code':\n                        payload[value] = oauthData.code;\n                        break;\n                    case 'clientId':\n                        payload[value] = _this.defaults.clientId;\n                        break;\n                    case 'redirectUri':\n                        payload[value] = _this.defaults.redirectUri;\n                        break;\n                    default:\n                        payload[value] = oauthData[key];\n                }\n            });\n            if (oauthData.state) {\n                payload.state = oauthData.state;\n            }\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ?\n                joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) :\n                this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth2.prototype.buildQueryString = function () {\n            var _this = this;\n            var keyValuePairs = [];\n            var urlParamsCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];\n            angular.forEach(urlParamsCategories, function (paramsCategory) {\n                angular.forEach(_this.defaults[paramsCategory], function (paramName) {\n                    var camelizedName = OAuth2.camelCase(paramName);\n                    var paramValue = angular.isFunction(_this.defaults[paramName]) ? _this.defaults[paramName]() : _this.defaults[camelizedName];\n                    if (paramName === 'redirect_uri' && !paramValue) {\n                        return;\n                    }\n                    if (paramName === 'state') {\n                        var stateName = _this.defaults.name + '_state';\n                        paramValue = encodeURIComponent(_this.SatellizerStorage.get(stateName));\n                    }\n                    if (paramName === 'scope' && Array.isArray(paramValue)) {\n                        paramValue = paramValue.join(_this.defaults.scopeDelimiter);\n                        if (_this.defaults.scopePrefix) {\n                            paramValue = [_this.defaults.scopePrefix, paramValue].join(_this.defaults.scopeDelimiter);\n                        }\n                    }\n                    keyValuePairs.push([paramName, paramValue]);\n                });\n            });\n            return keyValuePairs.map(function (pair) { return pair.join('='); }).join('&');\n        };\n        OAuth2.$inject = ['$http', '$window', '$timeout', '$q', 'SatellizerConfig', 'SatellizerPopup', 'SatellizerStorage'];\n        return OAuth2;\n    }());\n\n    var OAuth = (function () {\n        function OAuth($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage, SatellizerShared, SatellizerOAuth1, SatellizerOAuth2) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerOAuth1 = SatellizerOAuth1;\n            this.SatellizerOAuth2 = SatellizerOAuth2;\n        }\n        OAuth.prototype.authenticate = function (name, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var provider = _this.SatellizerConfig.providers[name];\n                var oauth = null;\n                switch (provider.oauthType) {\n                    case '1.0':\n                        oauth = new OAuth1(_this.$http, _this.$window, _this.SatellizerConfig, _this.SatellizerPopup);\n                        break;\n                    case '2.0':\n                        oauth = new OAuth2(_this.$http, _this.$window, _this.$timeout, _this.$q, _this.SatellizerConfig, _this.SatellizerPopup, _this.SatellizerStorage);\n                        break;\n                    default:\n                        return reject(new Error('Invalid OAuth Type'));\n                }\n                return oauth.init(provider, userData).then(function (response) {\n                    if (provider.url) {\n                        _this.SatellizerShared.setToken(response);\n                    }\n                    resolve(response);\n                }).catch(function (error) {\n                    reject(error);\n                });\n            });\n        };\n        OAuth.prototype.unlink = function (provider, httpOptions) {\n            if (httpOptions === void 0) { httpOptions = {}; }\n            httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);\n            httpOptions.data = { provider: provider } || httpOptions.data;\n            httpOptions.method = httpOptions.method || 'POST';\n            httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(httpOptions);\n        };\n        OAuth.$inject = [\n            '$http',\n            '$window',\n            '$timeout',\n            '$q',\n            'SatellizerConfig',\n            'SatellizerPopup',\n            'SatellizerStorage',\n            'SatellizerShared',\n            'SatellizerOAuth1',\n            'SatellizerOAuth2'\n        ];\n        return OAuth;\n    }());\n\n    var Storage = (function () {\n        function Storage($window, SatellizerConfig) {\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.memoryStore = {};\n        }\n        Storage.prototype.get = function (key) {\n            try {\n                return this.$window[this.SatellizerConfig.storageType].getItem(key);\n            }\n            catch (e) {\n                return this.memoryStore[key];\n            }\n        };\n        Storage.prototype.set = function (key, value) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].setItem(key, value);\n            }\n            catch (e) {\n                this.memoryStore[key] = value;\n            }\n        };\n        Storage.prototype.remove = function (key) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].removeItem(key);\n            }\n            catch (e) {\n                delete this.memoryStore[key];\n            }\n        };\n        Storage.$inject = ['$window', 'SatellizerConfig'];\n        return Storage;\n    }());\n\n    var Interceptor = (function () {\n        function Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            var _this = this;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerStorage = SatellizerStorage;\n            this.request = function (config) {\n                if (config['skipAuthorization']) {\n                    return config;\n                }\n                if (_this.SatellizerShared.isAuthenticated() && _this.SatellizerConfig.httpInterceptor()) {\n                    var tokenName = _this.SatellizerConfig.tokenPrefix ?\n                        [_this.SatellizerConfig.tokenPrefix, _this.SatellizerConfig.tokenName].join('_') : _this.SatellizerConfig.tokenName;\n                    var token = _this.SatellizerStorage.get(tokenName);\n                    if (_this.SatellizerConfig.tokenHeader && _this.SatellizerConfig.tokenType) {\n                        token = _this.SatellizerConfig.tokenType + ' ' + token;\n                    }\n                    config.headers[_this.SatellizerConfig.tokenHeader] = token;\n                }\n                return config;\n            };\n        }\n        Interceptor.Factory = function (SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            return new Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage);\n        };\n        Interceptor.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n        return Interceptor;\n    }());\n    Interceptor.Factory.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n\n    var HttpProviderConfig = (function () {\n        function HttpProviderConfig($httpProvider) {\n            this.$httpProvider = $httpProvider;\n            $httpProvider.interceptors.push(Interceptor.Factory);\n        }\n        HttpProviderConfig.$inject = ['$httpProvider'];\n        return HttpProviderConfig;\n    }());\n\n    angular.module('satellizer', [])\n        .provider('$auth', ['SatellizerConfig', function (SatellizerConfig) { return new AuthProvider(SatellizerConfig); }])\n        .constant('SatellizerConfig', Config.getConstant)\n        .service('SatellizerShared', Shared)\n        .service('SatellizerLocal', Local)\n        .service('SatellizerPopup', Popup)\n        .service('SatellizerOAuth', OAuth)\n        .service('SatellizerOAuth2', OAuth2)\n        .service('SatellizerOAuth1', OAuth1)\n        .service('SatellizerStorage', Storage)\n        .service('SatellizerInterceptor', Interceptor)\n        .config(['$httpProvider', function ($httpProvider) { return new HttpProviderConfig($httpProvider); }]);\n    var ng1 = 'satellizer';\n\n    return ng1;\n\n}));\n//# sourceMappingURL=satellizer.js.map\n"
  },
  {
    "path": "examples/ionic/www/lib/satellizer/satellizer.js",
    "content": "/**\n * Satellizer 0.14.1\n * (c) 2016 Sahat Yalkabov\n * License: MIT\n */\n\n// CommonJS package manager support.\nif (typeof module !== 'undefined' && typeof exports !== 'undefined' && module.exports === exports) {\n  module.exports = 'satellizer';\n}\n\n(function(window, angular, undefined) {\n  'use strict';\n\n  if (!window.location.origin) {\n    window.location.origin = window.location.protocol + '//' + window.location.hostname + (window.location.port ? (':' + window.location.port) : '');\n  }\n\n  angular.module('satellizer', [])\n    .constant('SatellizerConfig', {\n      httpInterceptor: function() { return true; },\n      withCredentials: false,\n      tokenRoot: null,\n      baseUrl: '/',\n      loginUrl: '/auth/login',\n      signupUrl: '/auth/signup',\n      unlinkUrl: '/auth/unlink',\n      tokenName: 'token',\n      tokenPrefix: 'satellizer',\n      authHeader: 'Authorization',\n      authToken: 'Bearer',\n      storageType: 'localStorage',\n      providers: {\n        facebook: {\n          name: 'facebook',\n          url: '/auth/facebook',\n          authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n          redirectUri: window.location.origin + '/',\n          requiredUrlParams: ['display', 'scope'],\n          scope: ['email'],\n          scopeDelimiter: ',',\n          display: 'popup',\n          oauthType: '2.0',\n          popupOptions: { width: 580, height: 400 }\n        },\n        google: {\n          name: 'google',\n          url: '/auth/google',\n          authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n          redirectUri: window.location.origin,\n          requiredUrlParams: ['scope'],\n          optionalUrlParams: ['display', 'state'],\n          scope: ['profile', 'email'],\n          scopePrefix: 'openid',\n          scopeDelimiter: ' ',\n          display: 'popup',\n          oauthType: '2.0',\n          popupOptions: { width: 452, height: 633 },\n          state: function() {\n            var rand = Math.random().toString(36).substr(2);\n            return encodeURIComponent(rand);\n          }\n        },\n        github: {\n          name: 'github',\n          url: '/auth/github',\n          authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n          redirectUri: window.location.origin,\n          optionalUrlParams: ['scope'],\n          scope: ['user:email'],\n          scopeDelimiter: ' ',\n          oauthType: '2.0',\n          popupOptions: { width: 1020, height: 618 }\n        },\n        instagram: {\n          name: 'instagram',\n          url: '/auth/instagram',\n          authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n          redirectUri: window.location.origin,\n          requiredUrlParams: ['scope'],\n          scope: ['basic'],\n          scopeDelimiter: '+',\n          oauthType: '2.0'\n        },\n        linkedin: {\n          name: 'linkedin',\n          url: '/auth/linkedin',\n          authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n          redirectUri: window.location.origin,\n          requiredUrlParams: ['state'],\n          scope: ['r_emailaddress'],\n          scopeDelimiter: ' ',\n          state: 'STATE',\n          oauthType: '2.0',\n          popupOptions: { width: 527, height: 582 }\n        },\n        twitter: {\n          name: 'twitter',\n          url: '/auth/twitter',\n          authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n          redirectUri: window.location.origin,\n          oauthType: '1.0',\n          popupOptions: { width: 495, height: 645 }\n        },\n        twitch: {\n          name: 'twitch',\n          url: '/auth/twitch',\n          authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n          redirectUri: window.location.origin,\n          requiredUrlParams: ['scope'],\n          scope: ['user_read'],\n          scopeDelimiter: ' ',\n          display: 'popup',\n          oauthType: '2.0',\n          popupOptions: { width: 500, height: 560 }\n        },\n        live: {\n          name: 'live',\n          url: '/auth/live',\n          authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n          redirectUri: window.location.origin,\n          requiredUrlParams: ['display', 'scope'],\n          scope: ['wl.emails'],\n          scopeDelimiter: ' ',\n          display: 'popup',\n          oauthType: '2.0',\n          popupOptions: { width: 500, height: 560 }\n        },\n        yahoo: {\n          name: 'yahoo',\n          url: '/auth/yahoo',\n          authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n          redirectUri: window.location.origin,\n          scope: [],\n          scopeDelimiter: ',',\n          oauthType: '2.0',\n          popupOptions: { width: 559, height: 519 }\n        },\n        bitbucket: {\n          name: 'bitbucket',\n          url: '/auth/bitbucket',\n          authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n          redirectUri: window.location.origin + '/',\n          requiredUrlParams: ['scope'],\n          scope: ['email'],\n          scopeDelimiter: ' ',\n          oauthType: '2.0',\n          popupOptions: { width: 1028, height: 529 }\n        }\n      }\n    })\n    .provider('$auth', ['SatellizerConfig', function(config) {\n      Object.defineProperties(this, {\n        httpInterceptor: {\n          get: function() { return config.httpInterceptor; },\n          set: function(value) {\n            if (typeof value === 'function') {\n              config.httpInterceptor = value;\n            } else {\n              config.httpInterceptor = function() {\n                return value;\n              };\n            }\n          }\n        },\n        baseUrl: {\n          get: function() { return config.baseUrl; },\n          set: function(value) { config.baseUrl = value; }\n        },\n        loginUrl: {\n          get: function() { return config.loginUrl; },\n          set: function(value) { config.loginUrl = value; }\n        },\n        signupUrl: {\n          get: function() { return config.signupUrl; },\n          set: function(value) { config.signupUrl = value; }\n        },\n        tokenRoot: {\n          get: function() { return config.tokenRoot; },\n          set: function(value) { config.tokenRoot = value; }\n        },\n        tokenName: {\n          get: function() { return config.tokenName; },\n          set: function(value) { config.tokenName = value; }\n        },\n        tokenPrefix: {\n          get: function() { return config.tokenPrefix; },\n          set: function(value) { config.tokenPrefix = value; }\n        },\n        unlinkUrl: {\n          get: function() { return config.unlinkUrl; },\n          set: function(value) { config.unlinkUrl = value; }\n        },\n        authHeader: {\n          get: function() { return config.authHeader; },\n          set: function(value) { config.authHeader = value; }\n        },\n        authToken: {\n          get: function() { return config.authToken; },\n          set: function(value) { config.authToken = value; }\n        },\n        withCredentials: {\n          get: function() { return config.withCredentials; },\n          set: function(value) { config.withCredentials = value; }\n        },\n        storageType: {\n          get: function() { return config.storageType; },\n          set: function(value) { config.storageType = value; }\n        }\n      });\n\n      angular.forEach(Object.keys(config.providers), function(provider) {\n        this[provider] = function(params) {\n          return angular.extend(config.providers[provider], params);\n        };\n      }, this);\n\n      var oauth = function(params) {\n        config.providers[params.name] = config.providers[params.name] || {};\n        angular.extend(config.providers[params.name], params);\n      };\n\n      this.oauth1 = function(params) {\n        oauth(params);\n        config.providers[params.name].oauthType = '1.0';\n      };\n\n      this.oauth2 = function(params) {\n        oauth(params);\n        config.providers[params.name].oauthType = '2.0';\n      };\n\n      this.$get = [\n        '$q',\n        'SatellizerShared',\n        'SatellizerLocal',\n        'SatellizerOauth',\n        function($q, shared, local, oauth) {\n          var $auth = {};\n\n          $auth.login = function(user, opts) {\n            return local.login(user, opts);\n          };\n\n          $auth.signup = function(user, options) {\n            return local.signup(user, options);\n          };\n\n          $auth.logout = function() {\n            return shared.logout();\n          };\n\n          $auth.authenticate = function(name, userData) {\n            return oauth.authenticate(name, userData);\n          };\n\n          $auth.link = function(name, userData) {\n            return oauth.authenticate(name, userData);\n          };\n\n          $auth.unlink = function(provider, opts) {\n            return oauth.unlink(provider, opts);\n          };\n\n          $auth.isAuthenticated = function() {\n            return shared.isAuthenticated();\n          };\n\n          $auth.getToken = function() {\n            return shared.getToken();\n          };\n\n          $auth.setToken = function(token) {\n            shared.setToken({ access_token: token });\n          };\n\n          $auth.removeToken = function() {\n            return shared.removeToken();\n          };\n\n          $auth.getPayload = function() {\n            return shared.getPayload();\n          };\n\n          $auth.setStorageType = function(type) {\n            return shared.setStorageType(type);\n          };\n\n          return $auth;\n        }];\n    }])\n    .factory('SatellizerShared', [\n      '$q',\n      '$window',\n      '$log',\n      'SatellizerConfig',\n      'SatellizerStorage',\n      function($q, $window, $log, config, storage) {\n        var Shared = {};\n\n        var tokenName = config.tokenPrefix ? [config.tokenPrefix, config.tokenName].join('_') : config.tokenName;\n\n        Shared.getToken = function() {\n          return storage.get(tokenName);\n        };\n\n        Shared.getPayload = function() {\n          var token = storage.get(tokenName);\n\n          if (token && token.split('.').length === 3) {\n            try {\n              var base64Url = token.split('.')[1];\n              var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n              return JSON.parse(decodeURIComponent(escape(window.atob(base64))));\n            } catch(e) {\n              return undefined;\n            }\n          }\n        };\n\n        Shared.setToken = function(response) {\n          if (!response) {\n            return $log.warn('Can\\'t set token without passing a value');\n          }\n\n          var accessToken = response && response.access_token;\n          var token;\n\n          if (accessToken) {\n            if (angular.isObject(accessToken) && angular.isObject(accessToken.data)) {\n              response = accessToken;\n            } else if (angular.isString(accessToken)) {\n              token = accessToken;\n            }\n          }\n\n          if (!token && response) {\n            var tokenRootData = config.tokenRoot && config.tokenRoot.split('.').reduce(function(o, x) { return o[x]; }, response.data);\n            token = tokenRootData ? tokenRootData[config.tokenName] : response.data && response.data[config.tokenName];\n          }\n\n          if (!token) {\n            var tokenPath = config.tokenRoot ? config.tokenRoot + '.' + config.tokenName : config.tokenName;\n            return $log.warn('Expecting a token named \"' + tokenPath);\n          }\n\n          storage.set(tokenName, token);\n        };\n\n        Shared.removeToken = function() {\n          storage.remove(tokenName);\n        };\n\n        /**\n         * @returns {boolean}\n         */\n        Shared.isAuthenticated = function() {\n          var token = storage.get(tokenName);\n          // A token is present\n          if (token) {\n            // Token with a valid JWT format XXX.YYY.ZZZ\n            if (token.split('.').length === 3) {\n              // Could be a valid JWT or an access token with the same format\n              try {\n                var base64Url = token.split('.')[1];\n                var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');\n                var exp = JSON.parse($window.atob(base64)).exp;\n                // JWT with an optonal expiration claims\n                if (exp) {\n                  var isExpired = Math.round(new Date().getTime() / 1000) >= exp;\n                  if (isExpired) {\n                    // FAIL: Expired token\n                    return false;\n                  } else {\n                    // PASS: Non-expired token\n                    return true;\n                  }\n                }\n              } catch(e) {\n                // PASS: Non-JWT token that looks like JWT\n                return true;\n              }\n            }\n            // PASS: All other tokens\n            return true;\n          }\n          // FAIL: No token at all\n          return false;\n        };\n\n        Shared.logout = function() {\n          storage.remove(tokenName);\n          return $q.when();\n        };\n\n        Shared.setStorageType = function(type) {\n          config.storageType = type;\n        };\n\n        return Shared;\n      }])\n    .factory('SatellizerOauth', [\n      '$q',\n      '$http',\n      'SatellizerConfig',\n      'SatellizerUtils',\n      'SatellizerShared',\n      'SatellizerOauth1',\n      'SatellizerOauth2',\n      function($q, $http, config, utils, shared, Oauth1, Oauth2) {\n        var Oauth = {};\n\n        Oauth.authenticate = function(name, userData) {\n          var provider = config.providers[name].oauthType === '1.0' ? new Oauth1() : new Oauth2();\n          var deferred = $q.defer();\n\n          provider.open(config.providers[name], userData || {})\n            .then(function(response) {\n              // This is for a scenario when someone wishes to opt out from\n              // Satellizer's magic by doing authorization code exchange and\n              // saving a token manually.\n              if (config.providers[name].url) {\n                shared.setToken(response, false);\n              }\n              deferred.resolve(response);\n            })\n            .catch(function(error) {\n              deferred.reject(error);\n            });\n\n          return deferred.promise;\n        };\n\n        Oauth.unlink = function(provider, opts) {\n          opts = opts || {};\n          opts.url = opts.url ? opts.url : utils.joinUrl(config.baseUrl, config.unlinkUrl);\n          opts.data = { provider: provider } || opts.data;\n          opts.method = opts.method || 'POST';\n          opts.withCredentials = opts.withCredentials || config.withCredentials;\n\n          return $http(opts);\n        };\n\n        return Oauth;\n      }])\n    .factory('SatellizerLocal', [\n      '$http',\n      'SatellizerUtils',\n      'SatellizerShared',\n      'SatellizerConfig',\n      function($http, utils, shared, config) {\n        var Local = {};\n\n        Local.login = function(user, opts) {\n          opts = opts || {};\n          opts.url = opts.url ? opts.url : utils.joinUrl(config.baseUrl, config.loginUrl);\n          opts.data = user || opts.data;\n          opts.method = opts.method || 'POST';\n          opts.withCredentials = opts.withCredentials || config.withCredentials;\n\n          return $http(opts).then(function(response) {\n            shared.setToken(response);\n            return response;\n          });\n        };\n\n        Local.signup = function(user, opts) {\n          opts = opts || {};\n          opts.url = opts.url ? opts.url : utils.joinUrl(config.baseUrl, config.signupUrl);\n          opts.data = user || opts.data;\n          opts.method = opts.method || 'POST';\n          opts.withCredentials = opts.withCredentials || config.withCredentials;\n\n          return $http(opts);\n        };\n\n        return Local;\n      }])\n    .factory('SatellizerOauth2', [\n      '$q',\n      '$http',\n      '$window',\n      '$timeout',\n      'SatellizerPopup',\n      'SatellizerUtils',\n      'SatellizerConfig',\n      'SatellizerStorage',\n      function($q, $http, $window, $timeout, popup, utils, config, storage) {\n        return function() {\n          var Oauth2 = {};\n\n          var defaults = {\n            defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n            responseType: 'code',\n            responseParams: {\n              code: 'code',\n              clientId: 'clientId',\n              redirectUri: 'redirectUri'\n            }\n          };\n\n          Oauth2.open = function(options, userData) {\n            defaults = utils.merge(options, defaults);\n            var defer = $q.defer();\n\n            $timeout(function () {\n              var url;\n              var openPopup;\n              var stateName = defaults.name + '_state';\n\n              if (angular.isFunction(defaults.state)) {\n                storage.set(stateName, defaults.state());\n              } else if (angular.isString(defaults.state)) {\n                storage.set(stateName, defaults.state);\n              }\n\n              url = [defaults.authorizationEndpoint, Oauth2.buildQueryString()].join('?');\n\n              if (window.cordova) {\n                openPopup = popup.open(url, defaults.name, defaults.popupOptions, defaults.redirectUri).eventListener(defaults.redirectUri);\n              } else {\n                openPopup = popup.open(url, defaults.name, defaults.popupOptions, defaults.redirectUri).pollPopup(defaults.redirectUri);\n              }\n\n              openPopup\n                .then(function(oauthData) {\n                  // When no server URL provided, return popup params as-is.\n                  // This is for a scenario when someone wishes to opt out from\n                  // Satellizer's magic by doing authorization code exchange and\n                  // saving a token manually.\n                  if (defaults.responseType === 'token' || !defaults.url) {\n                    return defer.resolve(oauthData);\n                  }\n\n                  if (oauthData.state && oauthData.state !== storage.get(stateName)) {\n                    return defer.reject(\n                      'The value returned in the state parameter does not match the state value from your original ' +\n                      'authorization code request.'\n                    );\n                  }\n\n                  defer.resolve(Oauth2.exchangeForToken(oauthData, userData));\n                }, function (err) {\n                  defer.reject(err);\n                });\n            });\n\n            return defer.promise;\n          };\n\n          Oauth2.exchangeForToken = function(oauthData, userData) {\n            var data = angular.extend({}, userData);\n\n            angular.forEach(defaults.responseParams, function(value, key) {\n              switch (key) {\n                case 'code':\n                  data[value] = oauthData.code;\n                  break;\n                case 'clientId':\n                  data[value] = defaults.clientId;\n                  break;\n                case 'redirectUri':\n                  data[value] = defaults.redirectUri;\n                  break;\n                default:\n                  data[value] = oauthData[key];\n              }\n            });\n\n            if (oauthData.state) {\n              data.state = oauthData.state;\n            }\n\n            var exchangeForTokenUrl = config.baseUrl ? utils.joinUrl(config.baseUrl, defaults.url) : defaults.url;\n\n            return $http.post(exchangeForTokenUrl, data, { withCredentials: config.withCredentials });\n          };\n\n          Oauth2.buildQueryString = function() {\n            var keyValuePairs = [];\n            var urlParamsCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];\n\n            angular.forEach(urlParamsCategories, function(paramsCategory) {\n              angular.forEach(defaults[paramsCategory], function(paramName) {\n                var camelizedName = utils.camelCase(paramName);\n                var paramValue = angular.isFunction(defaults[paramName]) ? defaults[paramName]() : defaults[camelizedName];\n\n                if (paramName === 'redirect_uri' && !paramValue) {\n                    return;\n                }\n\n                if (paramName === 'state') {\n                  var stateName = defaults.name + '_state';\n                  paramValue = encodeURIComponent(storage.get(stateName));\n                }\n\n                if (paramName === 'scope' && Array.isArray(paramValue)) {\n                  paramValue = paramValue.join(defaults.scopeDelimiter);\n\n                  if (defaults.scopePrefix) {\n                    paramValue = [defaults.scopePrefix, paramValue].join(defaults.scopeDelimiter);\n                  }\n                }\n\n                keyValuePairs.push([paramName, paramValue]);\n              });\n            });\n\n            return keyValuePairs.map(function(pair) {\n              return pair.join('=');\n            }).join('&');\n          };\n\n          return Oauth2;\n        };\n      }])\n    .factory('SatellizerOauth1', [\n      '$q',\n      '$http',\n      'SatellizerPopup',\n      'SatellizerConfig',\n      'SatellizerUtils',\n      function($q, $http, popup, config, utils) {\n        return function() {\n          var Oauth1 = {};\n\n          var defaults = {\n            url: null,\n            name: null,\n            popupOptions: null,\n            redirectUri: null,\n            authorizationEndpoint: null\n          };\n\n          Oauth1.open = function(options, userData) {\n            angular.extend(defaults, options);\n            var popupWindow;\n            var serverUrl = config.baseUrl ? utils.joinUrl(config.baseUrl, defaults.url) : defaults.url;\n\n            if (!window.cordova) {\n                popupWindow = popup.open('', defaults.name, defaults.popupOptions, defaults.redirectUri);\n            }\n\n            return $http.post(serverUrl, defaults)\n              .then(function(response) {\n                var url = [defaults.authorizationEndpoint, Oauth1.buildQueryString(response.data)].join('?');\n\n                if (window.cordova) {\n                  popupWindow = popup.open(url, defaults.name, defaults.popupOptions, defaults.redirectUri);\n                } else {\n                  popupWindow.popupWindow.location = url;\n                }\n\n                var popupListener;\n\n                if (window.cordova) {\n                  popupListener = popupWindow.eventListener(defaults.redirectUri);\n                } else {\n                  popupListener = popupWindow.pollPopup(defaults.redirectUri);\n                }\n\n                return popupListener\n                  .then(function(response) {\n                    return Oauth1.exchangeForToken(response, userData);\n                  });\n              });\n\n          };\n\n          Oauth1.exchangeForToken = function(oauthData, userData) {\n            var data = angular.extend({}, userData, oauthData);\n            var exchangeForTokenUrl = config.baseUrl ? utils.joinUrl(config.baseUrl, defaults.url) : defaults.url;\n            return $http.post(exchangeForTokenUrl, data, { withCredentials: config.withCredentials });\n          };\n\n          Oauth1.buildQueryString = function(obj) {\n            var str = [];\n\n            angular.forEach(obj, function(value, key) {\n              str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n            });\n\n            return str.join('&');\n          };\n\n          return Oauth1;\n        };\n      }])\n    .factory('SatellizerPopup', [\n      '$q',\n      '$interval',\n      '$window',\n      'SatellizerConfig',\n      'SatellizerUtils',\n      function($q, $interval, $window, config, utils) {\n        var Popup = {};\n\n        Popup.url = '';\n        Popup.popupWindow = null;\n\n        Popup.open = function(url, name, options) {\n          Popup.url = url;\n\n          var stringifiedOptions = Popup.stringifyOptions(Popup.prepareOptions(options));\n          var UA = $window.navigator.userAgent;\n          var windowName = (window.cordova || UA.indexOf('CriOS') > -1) ? '_blank' : name;\n\n          Popup.popupWindow = $window.open(url, windowName, stringifiedOptions);\n\n          $window.popup = Popup.popupWindow;\n\n          if (Popup.popupWindow && Popup.popupWindow.focus) {\n            Popup.popupWindow.focus();\n          }\n\n          return Popup;\n        };\n\n        Popup.eventListener = function(redirectUri) {\n          var deferred = $q.defer();\n\n          Popup.popupWindow.addEventListener('loadstart', function(event) {\n            if (event.url.indexOf(redirectUri) !== 0) {\n              return;\n            }\n\n            var parser = document.createElement('a');\n            parser.href = event.url;\n\n            if (parser.search || parser.hash) {\n              var queryParams = parser.search.substring(1).replace(/\\/$/, '');\n              var hashParams = parser.hash.substring(1).replace(/\\/$/, '');\n              var hash = utils.parseQueryString(hashParams);\n              var qs = utils.parseQueryString(queryParams);\n\n              angular.extend(qs, hash);\n\n              if (!qs.error) {\n                deferred.resolve(qs);\n              }\n\n              Popup.popupWindow.close();\n            }\n          });\n\n          Popup.popupWindow.addEventListener('loaderror', function() {\n            deferred.reject('Authorization Failed');\n          });\n\n          return deferred.promise;\n        };\n\n        Popup.pollPopup = function(redirectUri) {\n          var deferred = $q.defer();\n\n          var redirectUriParser = document.createElement('a');\n          redirectUriParser.href = redirectUri;\n\n          var redirectUriPath = utils.getFullUrlPath(redirectUriParser);\n\n          var polling = $interval(function() {\n            if (!Popup.popupWindow || Popup.popupWindow.closed || Popup.popupWindow.closed === undefined) {\n              deferred.reject('The popup window was closed.');\n              $interval.cancel(polling);\n            }\n\n            try {\n              var popupWindowPath = utils.getFullUrlPath(Popup.popupWindow.location);\n\n              // Redirect has occurred.\n              if (popupWindowPath === redirectUriPath) {\n                // Contains query/hash parameters as expected.\n                if (Popup.popupWindow.location.search || Popup.popupWindow.location.hash) {\n                  var queryParams = Popup.popupWindow.location.search.substring(1).replace(/\\/$/, '');\n                  var hashParams = Popup.popupWindow.location.hash.substring(1).replace(/[\\/$]/, '');\n                  var hash = utils.parseQueryString(hashParams);\n                  var qs = utils.parseQueryString(queryParams);\n\n                  angular.extend(qs, hash);\n\n                  if (qs.error) {\n                    deferred.reject(qs);\n                  } else {\n                    deferred.resolve(qs);\n                  }\n                } else {\n                  // Does not contain query/hash parameters, can't do anything at this point.\n                  deferred.reject(\n                    'Redirect has occurred but no query or hash parameters were found. ' +\n                    'They were either not set during the redirect, or were removed before Satellizer ' +\n                    'could read them, e.g. AngularJS routing mechanism.'\n                  );\n                }\n\n                $interval.cancel(polling);\n                Popup.popupWindow.close();\n              }\n            } catch (error) {\n              // Ignore DOMException: Blocked a frame with origin from accessing a cross-origin frame.\n              // A hack to get around same-origin security policy errors in IE.\n            }\n          }, 20);\n\n          return deferred.promise;\n        };\n\n        Popup.prepareOptions = function(options) {\n          options = options || {};\n          var width = options.width || 500;\n          var height = options.height || 500;\n\n          return angular.extend({\n            width: width,\n            height: height,\n            left: $window.screenX + (($window.outerWidth - width) / 2),\n            top: $window.screenY + (($window.outerHeight - height) / 2.5)\n          }, options);\n        };\n\n        Popup.stringifyOptions = function(options) {\n          var parts = [];\n          angular.forEach(options, function(value, key) {\n            parts.push(key + '=' + value);\n          });\n          return parts.join(',');\n        };\n\n        return Popup;\n      }])\n    .service('SatellizerUtils', function() {\n      this.getFullUrlPath = function(location) {\n        var isHttps = location.protocol === 'https:';\n        return location.protocol + '//' + location.hostname +\n          ':' + (location.port || (isHttps ? '443' : '80')) +\n          (/^\\//.test(location.pathname) ? location.pathname : '/' + location.pathname);\n      };\n\n      this.camelCase = function(name) {\n        return name.replace(/([\\:\\-\\_]+(.))/g, function(_, separator, letter, offset) {\n          return offset ? letter.toUpperCase() : letter;\n        });\n      };\n\n      this.parseQueryString = function(keyValue) {\n        var obj = {}, key, value;\n        angular.forEach((keyValue || '').split('&'), function(keyValue) {\n          if (keyValue) {\n            value = keyValue.split('=');\n            key = decodeURIComponent(value[0]);\n            obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;\n          }\n        });\n        return obj;\n      };\n\n      this.joinUrl = function(baseUrl, url) {\n        if (/^(?:[a-z]+:)?\\/\\//i.test(url)) {\n          return url;\n        }\n\n        var joined = [baseUrl, url].join('/');\n\n        var normalize = function(str) {\n          return str\n            .replace(/[\\/]+/g, '/')\n            .replace(/\\/\\?/g, '?')\n            .replace(/\\/\\#/g, '#')\n            .replace(/\\:\\//g, '://');\n        };\n\n        return normalize(joined);\n      };\n\n      this.merge = function(obj1, obj2) {\n        var result = {};\n        for (var i in obj1) {\n          if (obj1.hasOwnProperty(i)) {\n            if ((i in obj2) && (typeof obj1[i] === 'object') && (i !== null)) {\n              result[i] = this.merge(obj1[i], obj2[i]);\n            } else {\n              result[i] = obj1[i];\n            }\n          }\n        }\n        for (i in obj2) {\n          if (obj2.hasOwnProperty(i)) {\n            if (i in result) {\n              continue;\n            }\n            result[i] = obj2[i];\n          }\n\n        }\n        return result;\n      };\n    })\n    .factory('SatellizerStorage', ['$window', '$log', 'SatellizerConfig', function($window, $log, config) {\n\n      var store = {};\n\n      // Check if localStorage or sessionStorage is available or enabled\n      var isStorageAvailable = (function() {\n        try {\n          var supported = config.storageType in $window && $window[config.storageType] !== null;\n\n          if (supported) {\n            var key = Math.random().toString(36).substring(7);\n            $window[config.storageType].setItem(key, '');\n            $window[config.storageType].removeItem(key);\n          }\n\n          return supported;\n        } catch (e) {\n          return false;\n        }\n      })();\n\n      if (!isStorageAvailable) {\n        $log.warn(config.storageType + ' is not available.');\n      }\n\n      return {\n        get: function(key) {\n          return isStorageAvailable ? $window[config.storageType].getItem(key) : store[key];\n        },\n        set: function(key, value) {\n          return isStorageAvailable ? $window[config.storageType].setItem(key, value) : store[key] = value;\n        },\n        remove: function(key) {\n          return isStorageAvailable ? $window[config.storageType].removeItem(key): delete store[key];\n        }\n      };\n\n    }])\n    .factory('SatellizerInterceptor', [\n      '$q',\n      'SatellizerConfig',\n      'SatellizerStorage',\n      'SatellizerShared',\n      function($q, config, storage, shared) {\n        return {\n          request: function(request) {\n            if (request.skipAuthorization) {\n              return request;\n            }\n\n            if (shared.isAuthenticated() && config.httpInterceptor(request)) {\n              var tokenName = config.tokenPrefix ? config.tokenPrefix + '_' + config.tokenName : config.tokenName;\n              var token = storage.get(tokenName);\n\n              if (config.authHeader && config.authToken) {\n                token = config.authToken + ' ' + token;\n              }\n\n              request.headers[config.authHeader] = token;\n            }\n\n            return request;\n          },\n          responseError: function(response) {\n            return $q.reject(response);\n          }\n        };\n      }])\n    .config(['$httpProvider', function($httpProvider) {\n      $httpProvider.interceptors.push('SatellizerInterceptor');\n    }]);\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/ionic/www/templates/home.html",
    "content": "<ion-view title=\"Satellizer Ionic\">\n  <ion-content class=\"padding\">\n    <div ng-if=\"!isAuthenticated()\">\n      <button ng-click=\"authenticate('facebook')\" class=\"button button-block icon-left ion-social-facebook\">\n        Sign in with Facebook\n      </button>\n      <button ng-click=\"authenticate('google')\" class=\"button button-block icon-left ion-social-googleplus\">\n        Sign in with Google\n      </button>\n      <button ng-click=\"authenticate('linkedin')\" class=\"button button-block icon-left ion-social-linkedin\">\n        Sign in with LinkedIn\n      </button>\n      <button ng-click=\"authenticate('twitter')\" class=\"button button-block icon-left ion-social-twitter\">\n        Sign in with Twitter\n      </button>\n      <button ng-click=\"authenticate('foursquare')\" class=\"button button-block icon-left ion-social-foursquare-outline\">\n        Sign in with Foursquare\n      </button>\n      <button ng-click=\"authenticate('github')\" class=\"button button-block icon-left ion-social-github\">\n        Sign in with GitHub\n      </button>\n      <button ng-click=\"authenticate('yahoo')\" class=\"button button-block icon-left ion-social-yahoo\">\n        Sign in with Yahoo\n      </button>\n      <button ng-click=\"authenticate('live')\" class=\"button button-block icon-left ion-social-windows\">\n        Sign in with Windows Live\n      </button>\n    </div>\n    <div ng-if=\"isAuthenticated()\">\n      <div class=\"card\">\n        <div class=\"item item-text-wrap\">\n          You are currently logged in.\n        </div>\n      </div>\n      <button ng-click=\"logout()\" class=\"button button-block\">\n        Log Out\n      </button>\n    </div>\n  </ion-content>\n</ion-view>\n"
  },
  {
    "path": "examples/ionic/www/templates/menu.html",
    "content": "<ion-nav-bar class=\"bar-positive nav-title-slide-ios7\">\n  <ion-nav-back-button class=\"button-clear\"><i class=\"icon ion-ios7-arrow-back\"></i> Back</ion-nav-back-button>\n</ion-nav-bar>\n<ion-nav-view name=\"menuContent\" animation=\"slide-left-right\"></ion-nav-view>"
  },
  {
    "path": "examples/server/java/README.md",
    "content": "# Introduction\n\nThe drop wizard example application was developed to, as its name implies, provide examples of some of the features\npresent in drop wizard.\n\n# Overview\n\nIncluded with this application is an example of the optional db API module. The examples provided illustrate a few of\nthe features available in [JDBI](http://jdbi.org), along with demonstrating how these are used from within dropwizard.\n\nThis database example is comprised of the following classes.\n\n* The `PersonDAO` illustrates using the [SQL Object Queries](http://jdbi.org/sql_object_api_queries/) and string template\nfeatures in JDBI.\n\n* All the SQL statements for use in the `PersonDAO` are located in the `Person` class.\n\n* `migrations.xml` illustrates the usage of `dropwizard-migrations` which can create your database prior to running\nyour application for the first time.\n\n* The `PersonResource` and `PeopleResource` are the REST resource which use the PersonDAO to retrieve data from the database, note the injection\nof the PersonDAO in their constructors.\n\nAs with all the modules the db example is wired up in the `initialize` function of the `HelloWorldApplication`.\n\n# Running The Application\n\nTo test the example application run the following commands.\n\n* Setup your sanitizer client example.\n\n    mkdir src/main/resources/assets\n    cp -r ../../client/* src/main/resources/assets\n\n* To package the example run.\n\n        mvn package\n\n* To setup the h2 database run.\n\n        java -jar target/dropwizard-example-1.0.0.jar db migrate example.yml\n\n* To run the server run.\n\n        java -jar target/dropwizard-example-1.0.0.jar server example.yml\n\n* To hit this url to access the service example.\n\n\thttp://localhost:3000/\n\n* To post data into the application you have use your login credentials in example (first line should be done once).\n\n    curl -s -H \"Content-Type: application/json\" -X POST -d '{\"email\":\"test@test.com\",\"password\":\"testtest\"}' http://localhost:3000/auth/login | grep -ioE '\"[^\"]*\"' | tail -1 | grep -ioE '[^\"]*[^\"]' | awk '{print \"Authorization : OAuth \" $1}' > a.txt\n\n\tcurl -H \"Content-Type: application/json\" -H \"$(cat a.txt)\" -X PUT -d '{\"displayName\":\"Other Person\",\"email\":\"other@test.com\"}' http://localhost:3000/api/me\n\n    curl -H \"$(cat a.txt)\" http://localhost:3000/api/me"
  },
  {
    "path": "examples/server/java/example.yml",
    "content": "# Database settings.\ndatabase:\n  # the name of your JDBC driver\n  driverClass: org.h2.Driver\n\n  # the username\n  user: sa\n\n  # the password\n  password: sa\n\n  # the JDBC URL\n  url: jdbc:h2:./target/example\n\nserver:\n  type: simple\n  connector:\n    type: http\n    port: 3000\n  applicationContextPath: /\n\n# Logging settings.\nlogging:\n  # The default level of all loggers. Can be OFF, ERROR, WARN, INFO, DEBUG, TRACE, or ALL.\n  level: INFO\n\n  # Logger-specific levels.\n  loggers:\n    com.example.app: DEBUG\n    org.hibernate.SQL: ALL\n\n  appenders:\n    - type: console\n\nclientSecrets:\n    facebook: 298fb6c080fda239b809ae418bf49700\n    google: xGxxgKAObIRUwOKycySkL9Fi\n    linkedin: Linkedin Client Secret\n    github: Github Client Secret\n    foursquare: Foursquare Secret\n    twitter: Twitter Consumer Key\n    "
  },
  {
    "path": "examples/server/java/pom.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n\t<modelVersion>4.0.0</modelVersion>\n\t<prerequisites>\n\t\t<maven>3.0.0</maven>\n\t</prerequisites>\n\n\t<groupId>io.dropwizard</groupId>\n\t<artifactId>dropwizard-example</artifactId>\n\t<version>1.0.0</version>\n\t<name>Dropwizard Example Application</name>\n\n\t<properties>\n\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n\t\t<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n\t\t<dropwizard.version>0.8.0</dropwizard.version>\n\t</properties>\n\n\t<repositories>\n\t\t<repository>\n\t\t\t<id>sonatype-nexus-snapshots</id>\n\t\t\t<name>Sonatype Nexus Snapshots</name>\n\t\t\t<url>http://oss.sonatype.org/content/repositories/snapshots</url>\n\t\t</repository>\n\t</repositories>\n\n\t<dependencies>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-core</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-auth</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-assets</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-spdy</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-hibernate</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-migrations</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.h2database</groupId>\n\t\t\t<artifactId>h2</artifactId>\n\t\t\t<version>1.4.178</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-testing</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t\t<scope>test</scope>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.mindrot</groupId>\n\t\t\t<artifactId>jbcrypt</artifactId>\n\t\t\t<version>0.3m</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>io.dropwizard</groupId>\n\t\t\t<artifactId>dropwizard-client</artifactId>\n\t\t\t<version>${dropwizard.version}</version>\n\t\t\t<exclusions>\n\t\t\t\t<exclusion>\n\t\t\t\t\t<groupId>org.slf4j</groupId>\n\t\t\t\t\t<artifactId>slf4j-api</artifactId>\n\t\t\t\t</exclusion>\n\t\t\t</exclusions>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>com.nimbusds</groupId>\n\t\t\t<artifactId>nimbus-jose-jwt</artifactId>\n\t\t\t<version>3.1.1</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>joda-time</groupId>\n\t\t\t<artifactId>joda-time</artifactId>\n\t\t\t<version>2.7</version>\n\t\t</dependency>\n\t\t<dependency>\n\t\t\t<groupId>org.apache.commons</groupId>\n\t\t\t<artifactId>commons-lang3</artifactId>\n\t\t\t<version>3.3.2</version>\n\t\t</dependency>\n\t</dependencies>\n\n\t<build>\n\t\t<plugins>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-enforcer-plugin</artifactId>\n\t\t\t\t<version>1.3.1</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>enforce</id>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<rules>\n\t\t\t\t\t\t\t\t<DependencyConvergence />\n\t\t\t\t\t\t\t</rules>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>enforce</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>\n\t\t\t\t<version>3.1</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<source>1.7</source>\n\t\t\t\t\t<target>1.7</target>\n\t\t\t\t\t<encoding>UTF-8</encoding>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-source-plugin</artifactId>\n\t\t\t\t<version>2.2.1</version>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<id>attach-sources</id>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>jar</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-jar-plugin</artifactId>\n\t\t\t\t<version>2.4</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<archive>\n\t\t\t\t\t\t<manifest>\n\t\t\t\t\t\t\t<addDefaultImplementationEntries>true</addDefaultImplementationEntries>\n\t\t\t\t\t\t</manifest>\n\t\t\t\t\t</archive>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-shade-plugin</artifactId>\n\t\t\t\t<version>2.2</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<createDependencyReducedPom>true</createDependencyReducedPom>\n\t\t\t\t\t<filters>\n\t\t\t\t\t\t<filter>\n\t\t\t\t\t\t\t<artifact>*:*</artifact>\n\t\t\t\t\t\t\t<excludes>\n\t\t\t\t\t\t\t\t<exclude>META-INF/*.SF</exclude>\n\t\t\t\t\t\t\t\t<exclude>META-INF/*.DSA</exclude>\n\t\t\t\t\t\t\t\t<exclude>META-INF/*.RSA</exclude>\n\t\t\t\t\t\t\t</excludes>\n\t\t\t\t\t\t</filter>\n\t\t\t\t\t</filters>\n\t\t\t\t</configuration>\n\t\t\t\t<executions>\n\t\t\t\t\t<execution>\n\t\t\t\t\t\t<phase>package</phase>\n\t\t\t\t\t\t<goals>\n\t\t\t\t\t\t\t<goal>shade</goal>\n\t\t\t\t\t\t</goals>\n\t\t\t\t\t\t<configuration>\n\t\t\t\t\t\t\t<transformers>\n\t\t\t\t\t\t\t\t<transformer\n\t\t\t\t\t\t\t\t\timplementation=\"org.apache.maven.plugins.shade.resource.ServicesResourceTransformer\" />\n\t\t\t\t\t\t\t\t<transformer\n\t\t\t\t\t\t\t\t\timplementation=\"org.apache.maven.plugins.shade.resource.ManifestResourceTransformer\">\n\t\t\t\t\t\t\t\t\t<mainClass>com.example.helloworld.HelloWorldApplication</mainClass>\n\t\t\t\t\t\t\t\t</transformer>\n\t\t\t\t\t\t\t</transformers>\n\t\t\t\t\t\t</configuration>\n\t\t\t\t\t</execution>\n\t\t\t\t</executions>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<!-- You'll probably want to remove this for your project. I'm just using \n\t\t\t\t\tit here so that dropwizard-example doesn't get deployed as a library. -->\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-deploy-plugin</artifactId>\n\t\t\t\t<version>2.7</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<skip>true</skip>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t\t<plugin>\n\t\t\t\t<!-- You'll probably want to remove this for your project. I'm just using \n\t\t\t\t\tit here so that dropwizard-example site doesn't get staged and deployed. -->\n\t\t\t\t<groupId>org.apache.maven.plugins</groupId>\n\t\t\t\t<artifactId>maven-site-plugin</artifactId>\n\t\t\t\t<version>3.3</version>\n\t\t\t\t<configuration>\n\t\t\t\t\t<skip>true</skip>\n\t\t\t\t\t<skipDeploy>true</skipDeploy>\n\t\t\t\t</configuration>\n\t\t\t</plugin>\n\t\t</plugins>\n\t</build>\n</project>\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/HelloWorldApplication.java",
    "content": "package com.example.helloworld;\n\nimport io.dropwizard.Application;\nimport io.dropwizard.assets.AssetsBundle;\nimport io.dropwizard.client.JerseyClientBuilder;\nimport io.dropwizard.db.DataSourceFactory;\nimport io.dropwizard.hibernate.HibernateBundle;\nimport io.dropwizard.migrations.MigrationsBundle;\nimport io.dropwizard.setup.Bootstrap;\nimport io.dropwizard.setup.Environment;\n\nimport javax.ws.rs.client.Client;\n\nimport com.example.helloworld.HelloWorldConfiguration.ClientSecretsConfiguration;\nimport com.example.helloworld.auth.AuthFilter;\nimport com.example.helloworld.core.User;\nimport com.example.helloworld.db.UserDAO;\nimport com.example.helloworld.resources.AuthResource;\nimport com.example.helloworld.resources.ClientResource;\nimport com.example.helloworld.resources.UserResource;\n\npublic class HelloWorldApplication extends Application<HelloWorldConfiguration> {\n  public static void main(final String[] args) throws Exception {\n    new HelloWorldApplication().run(args);\n  }\n\n  private final HibernateBundle<HelloWorldConfiguration> hibernateBundle =\n      new HibernateBundle<HelloWorldConfiguration>(User.class) {\n        @Override\n        public DataSourceFactory getDataSourceFactory(final HelloWorldConfiguration configuration) {\n          return configuration.getDataSourceFactory();\n        }\n      };\n\n  @Override\n  public String getName() {\n    return \"hello-world\";\n  }\n\n  @Override\n  public void initialize(final Bootstrap<HelloWorldConfiguration> bootstrap) {\n    bootstrap.addBundle(new MigrationsBundle<HelloWorldConfiguration>() {\n      @Override\n      public DataSourceFactory getDataSourceFactory(final HelloWorldConfiguration configuration) {\n        return configuration.getDataSourceFactory();\n      }\n    });\n\n    bootstrap.addBundle(hibernateBundle);\n\n    bootstrap.addBundle(new AssetsBundle(\"/assets/app.js\", \"/app.js\", null, \"app\"));\n    bootstrap.addBundle(new AssetsBundle(\"/assets/stylesheets\", \"/stylesheets\", null, \"css\"));\n    bootstrap.addBundle(new AssetsBundle(\"/assets/directives\", \"/directives\", null, \"directives\"));\n    bootstrap\n        .addBundle(new AssetsBundle(\"/assets/controllers\", \"/controllers\", null, \"controllers\"));\n    bootstrap.addBundle(new AssetsBundle(\"/assets/services\", \"/services\", null, \"services\"));\n    bootstrap.addBundle(new AssetsBundle(\"/assets/vendor\", \"/vendor\", null, \"vendor\"));\n    bootstrap.addBundle(new AssetsBundle(\"/assets/partials\", \"/partials\", null, \"partials\"));\n  }\n\n  @Override\n  public void run(final HelloWorldConfiguration configuration, final Environment environment)\n      throws ClassNotFoundException {\n\n    final UserDAO dao = new UserDAO(hibernateBundle.getSessionFactory());\n    final Client client =\n        new JerseyClientBuilder(environment).using(configuration.getJerseyClient())\n            .build(getName());\n    final ClientSecretsConfiguration clientSecrets = configuration.getClientSecrets();\n\n    environment.jersey().register(new ClientResource());\n    environment.jersey().register(new UserResource(dao));\n    environment.jersey().register(new AuthResource(client, dao, clientSecrets));\n\n    environment.servlets().addFilter(\"AuthFilter\", new AuthFilter())\n        .addMappingForUrlPatterns(null, true, \"/api/me\");\n  }\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/HelloWorldConfiguration.java",
    "content": "package com.example.helloworld;\n\nimport io.dropwizard.Configuration;\nimport io.dropwizard.client.JerseyClientConfiguration;\nimport io.dropwizard.db.DataSourceFactory;\n\nimport javax.validation.Valid;\nimport javax.validation.constraints.NotNull;\n\nimport org.hibernate.validator.constraints.NotBlank;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\n\npublic class HelloWorldConfiguration extends Configuration {\n\t\n    @Valid\n    @NotNull\n    @JsonProperty\n    private DataSourceFactory database = new DataSourceFactory();\n\n    @Valid\n    @NotNull\n    @JsonProperty\n    private JerseyClientConfiguration httpClient = new JerseyClientConfiguration();\n    \n    @Valid\n    @NotNull\n    @JsonProperty\n    private ClientSecretsConfiguration clientSecrets = new ClientSecretsConfiguration();\n    \n    public DataSourceFactory getDataSourceFactory() {\n        return database;\n    }\n\n    public void setDataSourceFactory(DataSourceFactory dataSourceFactory) {\n        this.database = dataSourceFactory;\n    }\n\n\tpublic JerseyClientConfiguration getJerseyClient() {\n        return httpClient;\n    }\n\t\n\tpublic ClientSecretsConfiguration getClientSecrets() {\n\t\treturn clientSecrets;\n\t}\n\t\n\tpublic static class ClientSecretsConfiguration {\n\t\t\n\t\t@NotBlank\n\t\t@JsonProperty\n\t\tString facebook;\n\t\t\n\t\t@NotBlank\n\t\t@JsonProperty\n\t\tString google;\n\t\t\n\t\t@NotBlank\n\t\t@JsonProperty\n\t\tString linkedin;\n\t\t\n\t\t@NotBlank\n\t\t@JsonProperty\n\t\tString github;\n\t\t\n\t\t@NotBlank\n\t\t@JsonProperty\n\t\tString foursquare;\n\t\t\n\t\t@NotBlank\n\t\t@JsonProperty\n\t\tString twitter;\n\t\t\n\t\tpublic String getFacebook() {\n\t\t\treturn facebook;\n\t\t}\n\t\t\n\t\tpublic String getGoogle() {\n\t\t\treturn google;\n\t\t}\n\t\t\n\t\tpublic String getLinkedin() {\n\t\t\treturn linkedin;\n\t\t}\n\t\t\n\t\tpublic String getFoursquare() {\n\t\t\treturn foursquare;\n\t\t}\n\t\t\n\t\tpublic String getTwitter() {\n\t\t\treturn twitter;\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/auth/AuthFilter.java",
    "content": "package com.example.helloworld.auth;\n\nimport java.io.IOException;\nimport java.text.ParseException;\n\nimport javax.servlet.Filter;\nimport javax.servlet.FilterChain;\nimport javax.servlet.FilterConfig;\nimport javax.servlet.ServletException;\nimport javax.servlet.ServletRequest;\nimport javax.servlet.ServletResponse;\nimport javax.servlet.http.HttpServletRequest;\nimport javax.servlet.http.HttpServletResponse;\n\nimport com.nimbusds.jose.JOSEException;\nimport org.apache.commons.lang3.StringUtils;\nimport org.joda.time.DateTime;\n\nimport com.nimbusds.jwt.JWTClaimsSet;\n\npublic class AuthFilter implements Filter {\n\t\n\tprivate static final String AUTH_ERROR_MSG = \"Please make sure your request has an Authorization header\",\n\t\t\t\t\t\t\t\tEXPIRE_ERROR_MSG = \"Token has expired\",\n\t\t\t\t\t\t\t\tJWT_ERROR_MSG = \"Unable to parse JWT\",\n\t\t\t\t\t\t\t\tJWT_INVALID_MSG = \"Invalid JWT token\"\n\t;\n\t\t\t\t\t\t\t\t\n\n\t@Override\n\tpublic void doFilter(ServletRequest request, ServletResponse response,\n\t\t\tFilterChain chain) throws IOException, ServletException {\n\t\t\n\t\tHttpServletRequest httpRequest = (HttpServletRequest) request;\n\t\tHttpServletResponse httpResponse = (HttpServletResponse) response;\n\t\tString authHeader = httpRequest.getHeader(AuthUtils.AUTH_HEADER_KEY);\n\t\t\n\t\tif (StringUtils.isBlank(authHeader) || authHeader.split(\" \").length != 2) {\n\t\t\thttpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, AUTH_ERROR_MSG);\n\t\t} else {\n\t\t\tJWTClaimsSet claimSet = null;\n\t\t\ttry {\n\t\t\t\tclaimSet = (JWTClaimsSet) AuthUtils.decodeToken(authHeader);\n\t\t\t} catch (ParseException e) {\n\t\t\t\thttpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, JWT_ERROR_MSG);\n\t\t\t\treturn;\n\t\t\t} catch (JOSEException e) {\n\t\t\t\thttpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, JWT_INVALID_MSG);\n\t\t\t\treturn;\n\t\t\t}\n\n\n\t\t\t// ensure that the token is not expired\n\t\t\tif (new DateTime(claimSet.getExpirationTime()).isBefore(DateTime.now())) {\n\t\t\t\thttpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, EXPIRE_ERROR_MSG);\n\t\t\t} else {\n\t\t\t\tchain.doFilter(request, response);\n\t\t\t}\n\t\t}\t\n\t}\n\n    @Override\n    public void destroy() { /* unused */ }\n\n    @Override\n    public void init(FilterConfig filterConfig) throws ServletException { /* unused */ }\n\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/auth/AuthUtils.java",
    "content": "package com.example.helloworld.auth;\n\nimport java.text.ParseException;\n\nimport com.nimbusds.jose.crypto.MACVerifier;\nimport org.joda.time.DateTime;\n\nimport com.example.helloworld.core.Token;\nimport com.nimbusds.jose.JOSEException;\nimport com.nimbusds.jose.JWSAlgorithm;\nimport com.nimbusds.jose.JWSHeader;\nimport com.nimbusds.jose.JWSSigner;\nimport com.nimbusds.jose.crypto.MACSigner;\nimport com.nimbusds.jwt.JWTClaimsSet;\nimport com.nimbusds.jwt.ReadOnlyJWTClaimsSet;\nimport com.nimbusds.jwt.SignedJWT;\n\npublic final class AuthUtils {\n\t\n\tprivate static final JWSHeader JWT_HEADER = new JWSHeader(JWSAlgorithm.HS256);\n\tprivate static final String TOKEN_SECRET = \"aliceinwonderland\";\n\tpublic static final String AUTH_HEADER_KEY = \"Authorization\";\n\t\n\tpublic static String getSubject(String authHeader) throws ParseException, JOSEException {\n\t\treturn decodeToken(authHeader).getSubject();\n\t}\n\t\n\tpublic static ReadOnlyJWTClaimsSet decodeToken(String authHeader) throws ParseException, JOSEException {\n\t\tSignedJWT signedJWT = SignedJWT.parse(getSerializedToken(authHeader));\n\t\tif (signedJWT.verify(new MACVerifier(TOKEN_SECRET))) {\n\t\t\treturn signedJWT.getJWTClaimsSet();\n\t\t} else {\n\t\t\tthrow new JOSEException(\"Signature verification failed\");\n\t\t}\n\t}\n\t\n\tpublic static Token createToken(String host, long sub) throws JOSEException {\n\t\tJWTClaimsSet claim = new JWTClaimsSet();\n\t\tclaim.setSubject(Long.toString(sub));\n\t\tclaim.setIssuer(host);\n\t\tclaim.setIssueTime(DateTime.now().toDate());\n\t\tclaim.setExpirationTime(DateTime.now().plusDays(14).toDate());\n\t\t\n\t\tJWSSigner signer = new MACSigner(TOKEN_SECRET);\n\t\tSignedJWT jwt = new SignedJWT(JWT_HEADER, claim);\n\t\tjwt.sign(signer);\n\t\t\n\t\treturn new Token(jwt.serialize());\n\t}\n\t\n\tpublic static String getSerializedToken(String authHeader) {\n\t\treturn authHeader.split(\" \")[1];\n\t}\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/auth/PasswordService.java",
    "content": "package com.example.helloworld.auth;\n\nimport org.mindrot.jbcrypt.BCrypt;\n\npublic final class PasswordService {\n\tpublic static String hashPassword(String plaintext) {\n\t\treturn BCrypt.hashpw(plaintext, BCrypt.gensalt());\n\t}\n\t\n\tpublic static boolean checkPassword(String plaintext , String hashed) {\n\t\treturn BCrypt.checkpw(plaintext, hashed);\n\t}\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/core/Token.java",
    "content": "package com.example.helloworld.core;\n\nimport com.fasterxml.jackson.annotation.JsonProperty;\n\npublic class Token {\n\tString token;\n\n\tpublic Token(@JsonProperty(\"token\") String token) {\n\t\tthis.token = token;\n\t}\n\n\tpublic String getToken() {\n\t\treturn token;\n\t}\n}"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/core/User.java",
    "content": "package com.example.helloworld.core;\n\nimport javax.persistence.Column;\nimport javax.persistence.Entity;\nimport javax.persistence.GeneratedValue;\nimport javax.persistence.GenerationType;\nimport javax.persistence.Id;\nimport javax.persistence.NamedQueries;\nimport javax.persistence.NamedQuery;\nimport javax.persistence.Table;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.hibernate.validator.constraints.Email;\n\nimport com.fasterxml.jackson.annotation.JsonIgnore;\n\n@Entity\n@Table(name = \"users\")\n@NamedQueries({\n    @NamedQuery(name = \"User.findAll\", query = \"SELECT u FROM User u\"),\n    @NamedQuery(name = \"User.findByEmail\", query = \"SELECT u FROM User u WHERE u.email = :email\"),\n    @NamedQuery(name = \"User.findByFacebook\",\n        query = \"SELECT u FROM User u WHERE u.facebook = :facebook\"),\n    @NamedQuery(name = \"User.findByGoogle\", query = \"SELECT u FROM User u WHERE u.google = :google\"),\n    @NamedQuery(name = \"User.findByGithub\", query = \"SELECT u FROM User u WHERE u.github = :github\"),\n    @NamedQuery(name = \"User.findByLinkedin\",\n        query = \"SELECT u FROM User u WHERE u.linkedin = :linkedin\"),\n    @NamedQuery(name = \"User.findByFoursquare\",\n        query = \"SELECT u FROM User u WHERE u.foursquare = :foursquare\"),\n    @NamedQuery(name = \"User.findByTwitter\",\n        query = \"SELECT u FROM User u WHERE u.twitter = :twitter\")})\npublic class User {\n\n  @Id\n  @GeneratedValue(strategy = GenerationType.IDENTITY)\n  private long id;\n\n  @Email\n  @Column(name = \"email\", unique = true)\n  private String email;\n\n  @Column(name = \"password\")\n  private String password;\n\n  @Column(name = \"display_name\")\n  private String displayName;\n\n  @Column(name = \"facebook\")\n  private String facebook;\n\n  @Column(name = \"google\")\n  private String google;\n\n  @Column(name = \"linkedin\")\n  private String linkedin;\n\n  @Column(name = \"github\")\n  private String github;\n\n  @Column(name = \"foursquare\")\n  private String foursquare;\n\n  @Column(name = \"twitter\")\n  private String twitter;\n\n  public enum Provider {\n    FACEBOOK(\"facebook\"), GOOGLE(\"google\"), LINKEDIN(\"linkedin\"), GITHUB(\"github\"), FOURSQUARE(\n        \"foursquare\"), TWITTER(\"twitter\");\n\n    String name;\n\n    Provider(final String name) {\n      this.name = name;\n    }\n\n    public String getName() {\n      return this.name;\n    }\n\n    public String capitalize() {\n      return StringUtils.capitalize(this.name);\n    }\n  }\n\n  public long getId() {\n    return id;\n  }\n\n  public String getEmail() {\n    return email;\n  }\n\n  @JsonIgnore\n  public String getPassword() {\n    return password;\n  }\n\n  public String getDisplayName() {\n    return displayName;\n  }\n\n  public String getFacebook() {\n    return facebook;\n  }\n\n  public String getGoogle() {\n    return google;\n  }\n\n  public String getLinkedin() {\n    return linkedin;\n  }\n\n  public String getGithub() {\n    return github;\n  }\n\n  public String getFoursquare() {\n    return foursquare;\n  }\n\n  public String getTwitter() {\n    return twitter;\n  }\n\n  public void setEmail(final String email) {\n    this.email = email;\n  }\n\n  public void setPassword(final String password) {\n    this.password = password;\n  }\n\n  public void setDisplayName(final String name) {\n    this.displayName = name;\n  }\n\n  public void setProviderId(final Provider provider, final String value) {\n    switch (provider) {\n      case FACEBOOK:\n        this.facebook = value;\n        break;\n      case GOOGLE:\n        this.google = value;\n        break;\n      case LINKEDIN:\n        this.linkedin = value;\n        break;\n      case GITHUB:\n        this.github = value;\n        break;\n      case FOURSQUARE:\n        this.facebook = value;\n        break;\n      case TWITTER:\n        this.twitter = value;\n        break;\n      default:\n        throw new IllegalArgumentException();\n    }\n  }\n\n  @JsonIgnore\n  public int getSignInMethodCount() throws IllegalArgumentException, IllegalAccessException,\n      NoSuchFieldException, SecurityException {\n    int count = 0;\n\n    if (this.getPassword() != null) {\n      count++;\n    }\n\n    for (final Provider p : Provider.values()) {\n      if (this.getClass().getDeclaredField(p.name).get(this) != null) {\n        count++;\n      }\n    }\n\n    return count;\n  }\n\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/db/UserDAO.java",
    "content": "package com.example.helloworld.db;\n\nimport java.util.List;\n\nimport io.dropwizard.hibernate.AbstractDAO;\n\nimport org.hibernate.SessionFactory;\n\nimport com.example.helloworld.core.User;\nimport com.example.helloworld.core.User.Provider;\nimport com.google.common.base.Optional;\n\npublic class UserDAO extends AbstractDAO<User> {\n    public UserDAO(SessionFactory factory) {\n        super(factory);\n    }\n\n    public Optional<User> findById(Long id) {\n        return Optional.fromNullable(get(id));\n    }\n    \n    public Optional<User> findByEmail(String email) {\n    \tUser foundUser = (User) namedQuery(\"User.findByEmail\")\n\t\t\t\t.setParameter(\"email\", email)\n\t\t\t\t.uniqueResult();\n    \treturn Optional.fromNullable(foundUser);\n    }\n    \n    public Optional<User> findByProvider(Provider provider, String providerId) {\n    \tUser foundUser = (User) namedQuery(String.format(\"User.findBy%s\", provider.capitalize()))\n    \t\t\t\t\t\t\t.setParameter(provider.getName(), providerId)\n    \t\t\t\t\t\t\t.uniqueResult();\n    \treturn Optional.fromNullable(foundUser);\n    }\n\n    public User save(User user) {\n        return persist(user);\n    }\n\n    public List<User> findAll() {\n        return list(namedQuery(\"User.findAll\"));\n    }\n\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/resources/AuthResource.java",
    "content": "package com.example.helloworld.resources;\n\nimport io.dropwizard.hibernate.UnitOfWork;\nimport io.dropwizard.jersey.errors.ErrorMessage;\n\nimport java.io.IOException;\nimport java.text.ParseException;\nimport java.util.Map;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.validation.Valid;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.POST;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.PathParam;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.client.Client;\nimport javax.ws.rs.client.Entity;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.MultivaluedHashMap;\nimport javax.ws.rs.core.MultivaluedMap;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.Status;\n\nimport jersey.repackaged.com.google.common.base.Preconditions;\n\nimport org.apache.commons.lang3.StringUtils;\nimport org.hibernate.validator.constraints.NotBlank;\n\nimport com.example.helloworld.HelloWorldConfiguration.ClientSecretsConfiguration;\nimport com.example.helloworld.auth.AuthUtils;\nimport com.example.helloworld.auth.PasswordService;\nimport com.example.helloworld.core.Token;\nimport com.example.helloworld.core.User;\nimport com.example.helloworld.core.User.Provider;\nimport com.example.helloworld.db.UserDAO;\nimport com.example.helloworld.resources.AuthResource.Payload;\nimport com.example.helloworld.resources.AuthResource.UnlinkRequest;\nimport com.fasterxml.jackson.core.JsonParseException;\nimport com.fasterxml.jackson.core.type.TypeReference;\nimport com.fasterxml.jackson.databind.JsonMappingException;\nimport com.fasterxml.jackson.databind.ObjectMapper;\nimport com.google.common.base.Optional;\nimport com.nimbusds.jose.JOSEException;\n\n@Path(\"/auth\")\n@Produces(MediaType.APPLICATION_JSON)\n@Consumes(MediaType.APPLICATION_JSON)\npublic class AuthResource {\n\n  private final Client client;\n  private final UserDAO dao;\n  private final ClientSecretsConfiguration secrets;\n\n  public static final String CLIENT_ID_KEY = \"client_id\", REDIRECT_URI_KEY = \"redirect_uri\",\n      CLIENT_SECRET = \"client_secret\", CODE_KEY = \"code\", GRANT_TYPE_KEY = \"grant_type\",\n      AUTH_CODE = \"authorization_code\";\n\n  public static final String CONFLICT_MSG = \"There is already a %s account that belongs to you\",\n      NOT_FOUND_MSG = \"User not found\", LOGING_ERROR_MSG = \"Wrong email and/or password\",\n      UNLINK_ERROR_MSG = \"Could not unlink %s account because it is your only sign-in method\";\n\n  public static final ObjectMapper MAPPER = new ObjectMapper();\n\n  public AuthResource(final Client client, final UserDAO dao,\n      final ClientSecretsConfiguration secrets) {\n    this.client = client;\n    this.dao = dao;\n    this.secrets = secrets;\n  }\n\n  @POST\n  @Path(\"login\")\n  @UnitOfWork\n  public Response login(@Valid final User user, @Context final HttpServletRequest request)\n      throws JOSEException {\n    final Optional<User> foundUser = dao.findByEmail(user.getEmail());\n    if (foundUser.isPresent()\n        && PasswordService.checkPassword(user.getPassword(), foundUser.get().getPassword())) {\n      final Token token = AuthUtils.createToken(request.getRemoteHost(), foundUser.get().getId());\n      return Response.ok().entity(token).build();\n    }\n    return Response.status(Status.UNAUTHORIZED).entity(new ErrorMessage(LOGING_ERROR_MSG)).build();\n  }\n\n  @POST\n  @Path(\"signup\")\n  @UnitOfWork\n  public Response signup(@Valid final User user, @Context final HttpServletRequest request)\n      throws JOSEException {\n    user.setPassword(PasswordService.hashPassword(user.getPassword()));\n    final User savedUser = dao.save(user);\n    final Token token = AuthUtils.createToken(request.getRemoteHost(), savedUser.getId());\n    return Response.status(Status.CREATED).entity(token).build();\n  }\n\n  @POST\n  @Path(\"facebook\")\n  @UnitOfWork\n  @Consumes(MediaType.APPLICATION_JSON)\n  public Response loginFacebook(@Valid final Payload payload,\n      @Context final HttpServletRequest request) throws JsonParseException, JsonMappingException,\n      IOException, ParseException, JOSEException {\n    final String accessTokenUrl = \"https://graph.facebook.com/v2.3/oauth/access_token\";\n    final String graphApiUrl = \"https://graph.facebook.com/v2.3/me\";\n\n    Response response;\n\n    // Step 1. Exchange authorization code for access token.\n\n    response =\n        client.target(accessTokenUrl).queryParam(CLIENT_ID_KEY, payload.getClientId())\n            .queryParam(REDIRECT_URI_KEY, payload.getRedirectUri())\n            .queryParam(CLIENT_SECRET, secrets.getFacebook())\n            .queryParam(CODE_KEY, payload.getCode()).request(\"text/plain\")\n            .accept(MediaType.TEXT_PLAIN).get();\n\n    Map<String, Object> responseEntity = getResponseEntity(response);\n        \n    response =\n            client.target(graphApiUrl).queryParam(\"access_token\", responseEntity.get(\"access_token\"))\n                .queryParam(\"expires_in\", responseEntity.get(\"expires_in\")).request(\"text/plain\").get();\n    \n    final Map<String, Object> userInfo = getResponseEntity(response);\n\n    // Step 3. Process the authenticated the user.\n    return processUser(request, Provider.FACEBOOK, userInfo.get(\"id\").toString(),\n        userInfo.get(\"name\").toString());\n  }\n\n\n  @POST\n  @Path(\"google\")\n  @UnitOfWork\n  public Response loginGoogle(@Valid final Payload payload,\n      @Context final HttpServletRequest request) throws JOSEException, ParseException,\n      JsonParseException, JsonMappingException, IOException {\n    final String accessTokenUrl = \"https://accounts.google.com/o/oauth2/token\";\n    final String peopleApiUrl = \"https://www.googleapis.com/plus/v1/people/me/openIdConnect\";\n    Response response;\n\n    // Step 1. Exchange authorization code for access token.\n    final MultivaluedMap<String, String> accessData = new MultivaluedHashMap<String, String>();\n    accessData.add(CLIENT_ID_KEY, payload.getClientId());\n    accessData.add(REDIRECT_URI_KEY, payload.getRedirectUri());\n    accessData.add(CLIENT_SECRET, secrets.getGoogle());\n    accessData.add(CODE_KEY, payload.getCode());\n    accessData.add(GRANT_TYPE_KEY, AUTH_CODE);\n    response = client.target(accessTokenUrl).request().post(Entity.form(accessData));\n    accessData.clear();\n\n    // Step 2. Retrieve profile information about the current user.\n    final String accessToken = (String) getResponseEntity(response).get(\"access_token\");\n    response =\n        client.target(peopleApiUrl).request(\"text/plain\")\n            .header(AuthUtils.AUTH_HEADER_KEY, String.format(\"Bearer %s\", accessToken)).get();\n    final Map<String, Object> userInfo = getResponseEntity(response);\n\n    // Step 3. Process the authenticated the user.\n    return processUser(request, Provider.GOOGLE, userInfo.get(\"sub\").toString(),\n        userInfo.get(\"name\").toString());\n  }\n\n  @POST\n  @Path(\"linkedin\")\n  @UnitOfWork\n  public Response loginLinkedin() {\n    return Response.ok().build();\n  }\n\n  @POST\n  @Path(\"github\")\n  @UnitOfWork\n  public Response loginGithub() {\n    return Response.ok().build();\n  }\n\n  @POST\n  @Path(\"foursquare\")\n  @UnitOfWork\n  public Response loginFoursquare() {\n    return Response.ok().build();\n  }\n\n  @GET\n  @Path(\"twitter\")\n  @UnitOfWork\n  public Response loginTwitter(@Context final HttpServletRequest request) {\n    return Response.ok().build();\n  }\n\n\n  @POST\n  @Path(\"unlink/\")\n  @UnitOfWork\n  public Response unlink(@Valid final UnlinkRequest unlinkRequest,\n      @Context final HttpServletRequest request) throws ParseException, IllegalArgumentException,\n      IllegalAccessException, NoSuchFieldException, SecurityException, JOSEException {\n    final String subject = AuthUtils.getSubject(request.getHeader(AuthUtils.AUTH_HEADER_KEY));\n    final Optional<User> foundUser = dao.findById(Long.parseLong(subject));\n\n    String provider = unlinkRequest.provider;\n    \n    if (!foundUser.isPresent()) {\n      return Response.status(Status.NOT_FOUND).entity(new ErrorMessage(NOT_FOUND_MSG)).build();\n    }\n\n    final User userToUnlink = foundUser.get();\n\n   // check that the user is not trying to unlink the only sign-in method\n    if (userToUnlink.getSignInMethodCount() == 1) {\n      return Response.status(Status.BAD_REQUEST)\n          .entity(new ErrorMessage(String.format(UNLINK_ERROR_MSG, provider))).build();\n    }\n\n    try {\n      userToUnlink.setProviderId(Provider.valueOf(provider.toUpperCase()), null);\n    } catch (final IllegalArgumentException e) {\n      return Response.status(Status.BAD_REQUEST).build();\n    }\n\n    dao.save(userToUnlink);\n\n    return Response.ok().build();\n  }\n\n  \n  public static class UnlinkRequest {\n\t  @NotBlank\n\t  String provider;\n\n\tpublic String getProvider() {\n\t\treturn provider;\n\t}\n\n\tpublic void setProvider(String provider) {\n\t\tthis.provider = provider;\n\t}\n\t  \n  }\n\n  /*\n   * Inner classes for entity wrappers\n   */\n  public static class Payload {\n    @NotBlank\n    String clientId;\n\n    @NotBlank\n    String redirectUri;\n\n    @NotBlank\n    String code;\n\n    public String getClientId() {\n      return clientId;\n    }\n\n    public String getRedirectUri() {\n      return redirectUri;\n    }\n\n    public String getCode() {\n      return code;\n    }\n  }\n\n  /*\n   * Helper methods\n   */\n  private Map<String, Object> getResponseEntity(final Response response) throws JsonParseException,\n      JsonMappingException, IOException {\n    return MAPPER.readValue(response.readEntity(String.class),\n        new TypeReference<Map<String, Object>>() {});\n  }\n\n  private Response processUser(final HttpServletRequest request, final Provider provider,\n      final String id, final String displayName) throws JOSEException, ParseException {\n    final Optional<User> user = dao.findByProvider(provider, id);\n\n    // Step 3a. If user is already signed in then link accounts.\n    User userToSave;\n    final String authHeader = request.getHeader(AuthUtils.AUTH_HEADER_KEY);\n    if (StringUtils.isNotBlank(authHeader)) {\n      if (user.isPresent()) {\n        return Response.status(Status.CONFLICT)\n            .entity(new ErrorMessage(String.format(CONFLICT_MSG, provider.capitalize()))).build();\n      }\n\n      final String subject = AuthUtils.getSubject(authHeader);\n      final Optional<User> foundUser = dao.findById(Long.parseLong(subject));\n      if (!foundUser.isPresent()) {\n        return Response.status(Status.NOT_FOUND).entity(new ErrorMessage(NOT_FOUND_MSG)).build();\n      }\n\n      userToSave = foundUser.get();\n      userToSave.setProviderId(provider, id);\n      if (userToSave.getDisplayName() == null) {\n        userToSave.setDisplayName(displayName);\n      }\n      userToSave = dao.save(userToSave);\n    } else {\n      // Step 3b. Create a new user account or return an existing one.\n      if (user.isPresent()) {\n        userToSave = user.get();\n      } else {\n        userToSave = new User();\n        userToSave.setProviderId(provider, id);\n        userToSave.setDisplayName(displayName);\n        userToSave = dao.save(userToSave);\n      }\n    }\n\n    final Token token = AuthUtils.createToken(request.getRemoteHost(), userToSave.getId());\n    return Response.ok().entity(token).build();\n  }\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/resources/ClientResource.java",
    "content": "package com.example.helloworld.resources;\n\nimport java.io.IOException;\nimport java.net.URL;\n\nimport javax.ws.rs.GET;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\n\nimport com.google.common.base.Charsets;\nimport com.google.common.io.Resources;\n\n@Path(\"/\")\n@Produces(MediaType.TEXT_HTML)\npublic class ClientResource {\n\t\n\t@GET\n\tpublic Response getPage() throws IOException {\n\t\tURL clientPage = Resources.getResource(\"assets/index.html\");\n\t    return Response.ok(Resources.toString(clientPage, Charsets.UTF_8)).build();\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/java/src/main/java/com/example/helloworld/resources/UserResource.java",
    "content": "package com.example.helloworld.resources;\n\nimport com.nimbusds.jose.JOSEException;\nimport io.dropwizard.hibernate.UnitOfWork;\nimport io.dropwizard.jersey.errors.ErrorMessage;\n\nimport java.text.ParseException;\n\nimport javax.servlet.http.HttpServletRequest;\nimport javax.validation.Valid;\nimport javax.ws.rs.Consumes;\nimport javax.ws.rs.GET;\nimport javax.ws.rs.PUT;\nimport javax.ws.rs.Path;\nimport javax.ws.rs.Produces;\nimport javax.ws.rs.core.Context;\nimport javax.ws.rs.core.MediaType;\nimport javax.ws.rs.core.Response;\nimport javax.ws.rs.core.Response.Status;\n\nimport com.example.helloworld.auth.AuthUtils;\nimport com.example.helloworld.core.User;\nimport com.example.helloworld.db.UserDAO;\nimport com.google.common.base.Optional;\n\n@Path(\"/api/me\")\n@Produces(MediaType.APPLICATION_JSON)\n@Consumes(MediaType.APPLICATION_JSON)\npublic class UserResource {\n\t\n\tprivate final UserDAO dao;\n\t\n\tpublic UserResource(UserDAO userDAO) {\n\t\tthis.dao = userDAO;\n\t}\n\n\t@GET\n\t@UnitOfWork\n\tpublic Response getUser(@Context HttpServletRequest request) throws ParseException, JOSEException {\n\t\tOptional<User> foundUser = getAuthUser(request);\n\t\t\n\t\tif (!foundUser.isPresent()) {\n\t\t\treturn Response.status(Status.NOT_FOUND).build();\n\t\t}\n\t\treturn Response.ok().entity(foundUser.get()).build();\n\t}\n\t\n\t// for testing\n\t@GET\n\t@Path(\"/all\")\n\t@UnitOfWork\n\tpublic Response getAllUsers() {\n\t\treturn Response.ok().entity(dao.findAll()).build();\n\t}\n\n\t@PUT\n\t@UnitOfWork\n\tpublic Response updateUser(@Valid User user, @Context HttpServletRequest request) throws ParseException, JOSEException {\n\t\tOptional<User> foundUser = getAuthUser(request);\n\t\t\n\t\tif (!foundUser.isPresent()) {\n\t\t\treturn Response\n\t\t\t\t\t.status(Status.NOT_FOUND)\n\t\t\t\t\t.entity(new ErrorMessage(AuthResource.NOT_FOUND_MSG)).build();\n\t\t}\n\t\t\n\t\tUser userToUpdate = foundUser.get();\n\t\tuserToUpdate.setDisplayName(user.getDisplayName());\n\t\tuserToUpdate.setEmail(user.getEmail());\n\t\tdao.save(userToUpdate);\n\n\t\treturn Response.ok().build();\n\t}\n\t\n\t/*\n\t * Helper methods\n\t */\t\n\tprivate Optional<User> getAuthUser(HttpServletRequest request) throws ParseException, JOSEException {\n\t\tString subject = AuthUtils.getSubject(request.getHeader(AuthUtils.AUTH_HEADER_KEY));\n\t\treturn dao.findById(Long.parseLong(subject));\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/java/src/main/resources/banner.txt",
    "content": "                           web-scale hello world dP for the web\n                                                 88\n  .d8888b. dP.  .dP .d8888b. 88d8b.d8b. 88d888b. 88 .d8888b.\n  88ooood8  `8bd8'  88'  `88 88'`88'`88 88'  `88 88 88ooood8\n  88.  ...  .d88b.  88.  .88 88  88  88 88.  .88 88 88.  ...\n  `88888P' dP'  `dP `88888P8 dP  dP  dP 88Y888P' dP `88888P'\n                                        88\n                                        dP\n"
  },
  {
    "path": "examples/server/java/src/main/resources/migrations.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<databaseChangeLog xmlns=\"http://www.liquibase.org/xml/ns/dbchangelog\"\n\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n\txsi:schemaLocation=\"http://www.liquibase.org/xml/ns/dbchangelog\n         http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.1.xsd\">\n\n\t<changeSet id=\"createUserTable\" author=\"alice.chen\">\n\t\t<createTable tableName=\"users\">\n\t\t\t<column name=\"id\" type=\"bigint\" autoIncrement=\"true\">\n\t\t\t\t<constraints primaryKey=\"true\" nullable=\"false\" />\n\t\t\t</column>\n\t\t\t<column name=\"email\" type=\"varchar(255)\">\n\t\t\t\t<constraints unique=\"true\" />\n\t\t\t</column>\n\t\t\t<column name=\"password\" type=\"varchar(255)\" />\n\t\t\t<column name=\"display_name\" type=\"varchar(255)\" />\n\t\t\t<column name=\"facebook\" type=\"varchar(255)\" />\n\t\t\t<column name=\"google\" type=\"varchar(255)\" />\n\t\t\t<column name=\"linkedin\" type=\"varchar(255)\" />\n\t\t\t<column name=\"github\" type=\"varchar(255)\" />\n\t\t\t<column name=\"foursquare\" type=\"varchar(255)\" />\n\t\t\t<column name=\"twitter\" type=\"varchar(255)\" />\n\t\t</createTable>\n\t</changeSet>\n</databaseChangeLog>\n"
  },
  {
    "path": "examples/server/node/config.js",
    "content": "module.exports = {\n  // App Settings\n  MONGO_URI: process.env.MONGO_URI || 'localhost',\n  TOKEN_SECRET: process.env.TOKEN_SECRET || 'YOUR_UNIQUE_JWT_TOKEN_SECRET',\n\n  // OAuth 2.0\n  FACEBOOK_SECRET: process.env.FACEBOOK_SECRET || '84e952da26fc9e7a12bbc32523efa8a0',\n  FOURSQUARE_SECRET: process.env.FOURSQUARE_SECRET || 'YOUR_FOURSQUARE_CLIENT_SECRET',\n  GOOGLE_SECRET: process.env.GOOGLE_SECRET || 'YOUR_GOOGLE_CLIENT_SECRET',\n  GITHUB_SECRET: process.env.GITHUB_SECRET || 'YOUR_GITHUB_CLIENT_SECRET',\n  INSTAGRAM_SECRET: process.env.INSTAGRAM_SECRET || 'YOUR_INSTAGRAM_CLIENT_SECRET',\n  LINKEDIN_SECRET: process.env.LINKEDIN_SECRET || 'YOUR_LINKEDIN_CLIENT_SECRET',\n  TWITCH_SECRET: process.env.TWITCH_SECRET || 'YOUR_TWITCH_CLIENT_SECRET',\n  WINDOWS_LIVE_SECRET: process.env.WINDOWS_LIVE_SECRET || 'YOUR_MICROSOFT_CLIENT_SECRET',\n  YAHOO_SECRET: process.env.YAHOO_SECRET || 'YOUR_YAHOO_CLIENT_SECRET',\n  BITBUCKET_SECRET: process.env.BITBUCKET_SECRET || 'YOUR_BITBUCKET_CLIENT_SECRET',\n  SPOTIFY_SECRET: process.env.SPOTIFY_SECRET || 'YOUR_SPOTIFY_CLIENT_SECRET',\n\n  // OAuth 1.0\n  TWITTER_KEY: process.env.TWITTER_KEY || 'vdrg4sqxyTPSRdJHKu4UVVdeD',\n  TWITTER_SECRET: process.env.TWITTER_SECRET || 'cUIobhRgRlXsFyObUMg3tBq56EgGSwabmcavQP4fncABvotRMA'\n};\n"
  },
  {
    "path": "examples/server/node/package.json",
    "content": "{\n  \"name\": \"satellizer-server\",\n  \"version\": \"0.0.0\",\n  \"main\": \"server.js\",\n  \"dependencies\": {\n    \"async\": \"^1.5.2\",\n    \"bcryptjs\": \"^2.3.0\",\n    \"body-parser\": \"^1.15.0\",\n    \"colors\": \"^1.1.2\",\n    \"cors\": \"^2.7.1\",\n    \"express\": \"^4.13.4\",\n    \"jwt-simple\": \"^0.4.1\",\n    \"moment\": \"^2.12.0\",\n    \"mongoose\": \"^4.4.6\",\n    \"morgan\": \"^1.7.0\",\n    \"request\": \"^2.69.0\"\n  }\n}\n"
  },
  {
    "path": "examples/server/node/server.js",
    "content": "/**\n * Satellizer Node.js Example\n * (c) 2015 Sahat Yalkabov\n * License: MIT\n */\n\nvar path = require('path');\nvar qs = require('querystring');\n\nvar async = require('async');\nvar bcrypt = require('bcryptjs');\nvar bodyParser = require('body-parser');\nvar colors = require('colors');\nvar cors = require('cors');\nvar express = require('express');\nvar logger = require('morgan');\nvar jwt = require('jwt-simple');\nvar moment = require('moment');\nvar mongoose = require('mongoose');\nvar request = require('request');\n\nvar config = require('./config');\n\nvar userSchema = new mongoose.Schema({\n  email: { type: String, unique: true, lowercase: true },\n  password: { type: String, select: false },\n  displayName: String,\n  picture: String,\n  bitbucket: String,\n  facebook: String,\n  foursquare: String,\n  google: String,\n  github: String,\n  instagram: String,\n  linkedin: String,\n  live: String,\n  yahoo: String,\n  twitter: String,\n  twitch: String,\n  spotify: String\n});\n\nuserSchema.pre('save', function(next) {\n  var user = this;\n  if (!user.isModified('password')) {\n    return next();\n  }\n  bcrypt.genSalt(10, function(err, salt) {\n    bcrypt.hash(user.password, salt, function(err, hash) {\n      user.password = hash;\n      next();\n    });\n  });\n});\n\nuserSchema.methods.comparePassword = function(password, done) {\n  bcrypt.compare(password, this.password, function(err, isMatch) {\n    done(err, isMatch);\n  });\n};\n\nvar User = mongoose.model('User', userSchema);\n\nmongoose.connect(config.MONGO_URI);\nmongoose.connection.on('error', function(err) {\n  console.log('Error: Could not connect to MongoDB. Did you forget to run `mongod`?'.red);\n});\n\nvar app = express();\n\napp.set('port', process.env.NODE_PORT || 3000);\napp.set('host', process.env.NODE_IP || 'localhost');\napp.use(cors());\napp.use(logger('dev'));\napp.use(bodyParser.json());\napp.use(bodyParser.urlencoded({ extended: true }));\n\n// Force HTTPS on Heroku\nif (app.get('env') === 'production') {\n  app.use(function(req, res, next) {\n    var protocol = req.get('x-forwarded-proto');\n    protocol == 'https' ? next() : res.redirect('https://' + req.hostname + req.url);\n  });\n}\napp.use(express.static(path.join(__dirname, '../../client')));\n\n/*\n |--------------------------------------------------------------------------\n | Login Required Middleware\n |--------------------------------------------------------------------------\n */\nfunction ensureAuthenticated(req, res, next) {\n  if (!req.header('Authorization')) {\n    return res.status(401).send({ message: 'Please make sure your request has an Authorization header' });\n  }\n  var token = req.header('Authorization').split(' ')[1];\n\n  var payload = null;\n  try {\n    payload = jwt.decode(token, config.TOKEN_SECRET);\n  }\n  catch (err) {\n    return res.status(401).send({ message: err.message });\n  }\n\n  if (payload.exp <= moment().unix()) {\n    return res.status(401).send({ message: 'Token has expired' });\n  }\n  req.user = payload.sub;\n  next();\n}\n\n/*\n |--------------------------------------------------------------------------\n | Generate JSON Web Token\n |--------------------------------------------------------------------------\n */\nfunction createJWT(user) {\n  var payload = {\n    sub: user._id,\n    iat: moment().unix(),\n    exp: moment().add(14, 'days').unix()\n  };\n  return jwt.encode(payload, config.TOKEN_SECRET);\n}\n\n/*\n |--------------------------------------------------------------------------\n | GET /api/me\n |--------------------------------------------------------------------------\n */\napp.get('/api/me', ensureAuthenticated, function(req, res) {\n  User.findById(req.user, function(err, user) {\n    res.send(user);\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | PUT /api/me\n |--------------------------------------------------------------------------\n */\napp.put('/api/me', ensureAuthenticated, function(req, res) {\n  User.findById(req.user, function(err, user) {\n    if (!user) {\n      return res.status(400).send({ message: 'User not found' });\n    }\n    user.displayName = req.body.displayName || user.displayName;\n    user.email = req.body.email || user.email;\n    user.save(function(err) {\n      res.status(200).end();\n    });\n  });\n});\n\n\n/*\n |--------------------------------------------------------------------------\n | Log in with Email\n |--------------------------------------------------------------------------\n */\napp.post('/auth/login', function(req, res) {\n  User.findOne({ email: req.body.email }, '+password', function(err, user) {\n    if (!user) {\n      return res.status(401).send({ message: 'Invalid email and/or password' });\n    }\n    user.comparePassword(req.body.password, function(err, isMatch) {\n      if (!isMatch) {\n        return res.status(401).send({ message: 'Invalid email and/or password' });\n      }\n      res.send({ token: createJWT(user) });\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Create Email and Password Account\n |--------------------------------------------------------------------------\n */\napp.post('/auth/signup', function(req, res) {\n  User.findOne({ email: req.body.email }, function(err, existingUser) {\n    if (existingUser) {\n      return res.status(409).send({ message: 'Email is already taken' });\n    }\n    var user = new User({\n      displayName: req.body.displayName,\n      email: req.body.email,\n      password: req.body.password\n    });\n    user.save(function(err, result) {\n      if (err) {\n        res.status(500).send({ message: err.message });\n      }\n      res.send({ token: createJWT(result) });\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Google\n |--------------------------------------------------------------------------\n */\napp.post('/auth/google', function(req, res) {\n  var accessTokenUrl = 'https://accounts.google.com/o/oauth2/token';\n  var peopleApiUrl = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect';\n  var params = {\n    code: req.body.code,\n    client_id: req.body.clientId,\n    client_secret: config.GOOGLE_SECRET,\n    redirect_uri: req.body.redirectUri,\n    grant_type: 'authorization_code'\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.post(accessTokenUrl, { json: true, form: params }, function(err, response, token) {\n    var accessToken = token.access_token;\n    var headers = { Authorization: 'Bearer ' + accessToken };\n\n    // Step 2. Retrieve profile information about the current user.\n    request.get({ url: peopleApiUrl, headers: headers, json: true }, function(err, response, profile) {\n      if (profile.error) {\n        return res.status(500).send({message: profile.error.message});\n      }\n      // Step 3a. Link user accounts.\n      if (req.header('Authorization')) {\n        User.findOne({ google: profile.sub }, function(err, existingUser) {\n          if (existingUser) {\n            return res.status(409).send({ message: 'There is already a Google account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, user) {\n            if (!user) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            user.google = profile.sub;\n            user.picture = user.picture || profile.picture.replace('sz=50', 'sz=200');\n            user.displayName = user.displayName || profile.name;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3b. Create a new user account or return an existing one.\n        User.findOne({ google: profile.sub }, function(err, existingUser) {\n          if (existingUser) {\n            return res.send({ token: createJWT(existingUser) });\n          }\n          var user = new User();\n          user.google = profile.sub;\n          user.picture = profile.picture.replace('sz=50', 'sz=200');\n          user.displayName = profile.name;\n          user.save(function(err) {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      }\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with GitHub\n |--------------------------------------------------------------------------\n */\napp.post('/auth/github', function(req, res) {\n  var accessTokenUrl = 'https://github.com/login/oauth/access_token';\n  var userApiUrl = 'https://api.github.com/user';\n  var params = {\n    code: req.body.code,\n    client_id: req.body.clientId,\n    client_secret: config.GITHUB_SECRET,\n    redirect_uri: req.body.redirectUri\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.get({ url: accessTokenUrl, qs: params }, function(err, response, accessToken) {\n    accessToken = qs.parse(accessToken);\n    var headers = { 'User-Agent': 'Satellizer' };\n\n    // Step 2. Retrieve profile information about the current user.\n    request.get({ url: userApiUrl, qs: accessToken, headers: headers, json: true }, function(err, response, profile) {\n\n      // Step 3a. Link user accounts.\n      if (req.header('Authorization')) {\n        User.findOne({ github: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            return res.status(409).send({ message: 'There is already a GitHub account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, user) {\n            if (!user) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            user.github = profile.id;\n            user.picture = user.picture || profile.avatar_url;\n            user.displayName = user.displayName || profile.name;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3b. Create a new user account or return an existing one.\n        User.findOne({ github: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            var token = createJWT(existingUser);\n            return res.send({ token: token });\n          }\n          var user = new User();\n          user.github = profile.id;\n          user.picture = profile.avatar_url;\n          user.displayName = profile.name;\n          user.email = profile.email;\n\n          user.save(function() {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      }\n    });\n  });\n});\n\n/*\n|--------------------------------------------------------------------------\n| Login with Instagram\n|--------------------------------------------------------------------------\n*/\napp.post('/auth/instagram', function(req, res) {\n  var accessTokenUrl = 'https://api.instagram.com/oauth/access_token';\n\n  var params = {\n    client_id: req.body.clientId,\n    redirect_uri: req.body.redirectUri,\n    client_secret: config.INSTAGRAM_SECRET,\n    code: req.body.code,\n    grant_type: 'authorization_code'\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.post({ url: accessTokenUrl, form: params, json: true }, function(error, response, body) {\n\n    // Step 2a. Link user accounts.\n    if (req.header('Authorization')) {\n      User.findOne({ instagram: body.user.id }, function(err, existingUser) {\n        if (existingUser) {\n          return res.status(409).send({ message: 'There is already an Instagram account that belongs to you' });\n        }\n\n        var token = req.header('Authorization').split(' ')[1];\n        var payload = jwt.decode(token, config.TOKEN_SECRET);\n\n        User.findById(payload.sub, function(err, user) {\n          if (!user) {\n            return res.status(400).send({ message: 'User not found' });\n          }\n          user.instagram = body.user.id;\n          user.picture = user.picture || body.user.profile_picture;\n          user.displayName = user.displayName || body.user.username;\n          user.save(function() {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      });\n    } else {\n      // Step 2b. Create a new user account or return an existing one.\n      User.findOne({ instagram: body.user.id }, function(err, existingUser) {\n        if (existingUser) {\n          return res.send({ token: createJWT(existingUser) });\n        }\n\n        var user = new User({\n          instagram: body.user.id,\n          picture: body.user.profile_picture,\n          displayName: body.user.username\n        });\n\n        user.save(function() {\n          var token = createJWT(user);\n          res.send({ token: token, user: user });\n        });\n      });\n    }\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with LinkedIn\n |--------------------------------------------------------------------------\n */\napp.post('/auth/linkedin', function(req, res) {\n  var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';\n  var peopleApiUrl = 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address,picture-url)';\n  var params = {\n    code: req.body.code,\n    client_id: req.body.clientId,\n    client_secret: config.LINKEDIN_SECRET,\n    redirect_uri: req.body.redirectUri,\n    grant_type: 'authorization_code'\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.post(accessTokenUrl, { form: params, json: true }, function(err, response, body) {\n    if (response.statusCode !== 200) {\n      return res.status(response.statusCode).send({ message: body.error_description });\n    }\n    var params = {\n      oauth2_access_token: body.access_token,\n      format: 'json'\n    };\n\n    // Step 2. Retrieve profile information about the current user.\n    request.get({ url: peopleApiUrl, qs: params, json: true }, function(err, response, profile) {\n\n      // Step 3a. Link user accounts.\n      if (req.header('Authorization')) {\n        User.findOne({ linkedin: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            return res.status(409).send({ message: 'There is already a LinkedIn account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, user) {\n            if (!user) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            user.linkedin = profile.id;\n            user.picture = user.picture || profile.pictureUrl;\n            user.displayName = user.displayName || profile.firstName + ' ' + profile.lastName;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3b. Create a new user account or return an existing one.\n        User.findOne({ linkedin: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            return res.send({ token: createJWT(existingUser) });\n          }\n          var user = new User();\n          user.linkedin = profile.id;\n          user.picture = profile.pictureUrl;\n          user.displayName = profile.firstName + ' ' + profile.lastName;\n          user.save(function() {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      }\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Windows Live\n |--------------------------------------------------------------------------\n */\napp.post('/auth/live', function(req, res) {\n  async.waterfall([\n    // Step 1. Exchange authorization code for access token.\n    function(done) {\n      var accessTokenUrl = 'https://login.live.com/oauth20_token.srf';\n      var params = {\n        code: req.body.code,\n        client_id: req.body.clientId,\n        client_secret: config.WINDOWS_LIVE_SECRET,\n        redirect_uri: req.body.redirectUri,\n        grant_type: 'authorization_code'\n      };\n      request.post(accessTokenUrl, { form: params, json: true }, function(err, response, accessToken) {\n        done(null, accessToken);\n      });\n    },\n    // Step 2. Retrieve profile information about the current user.\n    function(accessToken, done) {\n      var profileUrl = 'https://apis.live.net/v5.0/me?access_token=' + accessToken.access_token;\n      request.get({ url: profileUrl, json: true }, function(err, response, profile) {\n        done(err, profile);\n      });\n    },\n    function(profile) {\n      // Step 3a. Link user accounts.\n      if (req.header('Authorization')) {\n        User.findOne({ live: profile.id }, function(err, user) {\n          if (user) {\n            return res.status(409).send({ message: 'There is already a Windows Live account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, existingUser) {\n            if (!existingUser) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            existingUser.live = profile.id;\n            existingUser.displayName = existingUser.displayName || profile.name;\n            existingUser.save(function() {\n              var token = createJWT(existingUser);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3b. Create a new user or return an existing account.\n        User.findOne({ live: profile.id }, function(err, user) {\n          if (user) {\n            return res.send({ token: createJWT(user) });\n          }\n          var newUser = new User();\n          newUser.live = profile.id;\n          newUser.displayName = profile.name;\n          newUser.save(function() {\n            var token = createJWT(newUser);\n            res.send({ token: token });\n          });\n        });\n      }\n    }\n  ]);\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Facebook\n |--------------------------------------------------------------------------\n */\napp.post('/auth/facebook', function(req, res) {\n  var fields = ['id', 'email', 'first_name', 'last_name', 'link', 'name'];\n  var accessTokenUrl = 'https://graph.facebook.com/v2.5/oauth/access_token';\n  var graphApiUrl = 'https://graph.facebook.com/v2.5/me?fields=' + fields.join(',');\n  var params = {\n    code: req.body.code,\n    client_id: req.body.clientId,\n    client_secret: config.FACEBOOK_SECRET,\n    redirect_uri: req.body.redirectUri\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.get({ url: accessTokenUrl, qs: params, json: true }, function(err, response, accessToken) {\n    if (response.statusCode !== 200) {\n      return res.status(500).send({ message: accessToken.error.message });\n    }\n\n    // Step 2. Retrieve profile information about the current user.\n    request.get({ url: graphApiUrl, qs: accessToken, json: true }, function(err, response, profile) {\n      if (response.statusCode !== 200) {\n        return res.status(500).send({ message: profile.error.message });\n      }\n      if (req.header('Authorization')) {\n        User.findOne({ facebook: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            return res.status(409).send({ message: 'There is already a Facebook account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, user) {\n            if (!user) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            user.facebook = profile.id;\n            user.picture = user.picture || 'https://graph.facebook.com/v2.3/' + profile.id + '/picture?type=large';\n            user.displayName = user.displayName || profile.name;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3. Create a new user account or return an existing one.\n        User.findOne({ facebook: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            var token = createJWT(existingUser);\n            return res.send({ token: token });\n          }\n          var user = new User();\n          user.facebook = profile.id;\n          user.picture = 'https://graph.facebook.com/' + profile.id + '/picture?type=large';\n          user.displayName = profile.name;\n          user.save(function() {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      }\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Yahoo\n |--------------------------------------------------------------------------\n */\napp.post('/auth/yahoo', function(req, res) {\n  var accessTokenUrl = 'https://api.login.yahoo.com/oauth2/get_token';\n  var clientId = req.body.clientId;\n  var clientSecret = config.YAHOO_SECRET;\n  var formData = {\n    code: req.body.code,\n    redirect_uri: req.body.redirectUri,\n    grant_type: 'authorization_code'\n  };\n  var headers = { Authorization: 'Basic ' + new Buffer(clientId + ':' + clientSecret).toString('base64') };\n\n  // Step 1. Exchange authorization code for access token.\n  request.post({ url: accessTokenUrl, form: formData, headers: headers, json: true }, function(err, response, body) {\n    var socialApiUrl = 'https://social.yahooapis.com/v1/user/' + body.xoauth_yahoo_guid + '/profile?format=json';\n    var headers = { Authorization: 'Bearer ' + body.access_token };\n\n    // Step 2. Retrieve profile information about the current user.\n    request.get({ url: socialApiUrl, headers: headers, json: true }, function(err, response, body) {\n\n      // Step 3a. Link user accounts.\n      if (req.header('Authorization')) {\n        User.findOne({ yahoo: body.profile.guid }, function(err, existingUser) {\n          if (existingUser) {\n            return res.status(409).send({ message: 'There is already a Yahoo account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, user) {\n            if (!user) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            user.yahoo = body.profile.guid;\n            user.displayName = user.displayName || body.profile.nickname;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3b. Create a new user account or return an existing one.\n        User.findOne({ yahoo: body.profile.guid }, function(err, existingUser) {\n          if (existingUser) {\n            return res.send({ token: createJWT(existingUser) });\n          }\n          var user = new User();\n          user.yahoo = body.profile.guid;\n          user.displayName = body.profile.nickname;\n          user.save(function() {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      }\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Twitter\n | Note: Make sure \"Request email addresses from users\" is enabled\n | under Permissions tab in your Twitter app. (https://apps.twitter.com)\n |--------------------------------------------------------------------------\n */\napp.post('/auth/twitter', function(req, res) {\n  var requestTokenUrl = 'https://api.twitter.com/oauth/request_token';\n  var accessTokenUrl = 'https://api.twitter.com/oauth/access_token';\n  var profileUrl = 'https://api.twitter.com/1.1/account/verify_credentials.json';\n\n  // Part 1 of 2: Initial request from Satellizer.\n  if (!req.body.oauth_token || !req.body.oauth_verifier) {\n    var requestTokenOauth = {\n      consumer_key: config.TWITTER_KEY,\n      consumer_secret: config.TWITTER_SECRET,\n      callback: req.body.redirectUri\n    };\n\n    // Step 1. Obtain request token for the authorization popup.\n    request.post({ url: requestTokenUrl, oauth: requestTokenOauth }, function(err, response, body) {\n      var oauthToken = qs.parse(body);\n\n      // Step 2. Send OAuth token back to open the authorization screen.\n      res.send(oauthToken);\n    });\n  } else {\n    // Part 2 of 2: Second request after Authorize app is clicked.\n    var accessTokenOauth = {\n      consumer_key: config.TWITTER_KEY,\n      consumer_secret: config.TWITTER_SECRET,\n      token: req.body.oauth_token,\n      verifier: req.body.oauth_verifier\n    };\n\n    // Step 3. Exchange oauth token and oauth verifier for access token.\n    request.post({ url: accessTokenUrl, oauth: accessTokenOauth }, function(err, response, accessToken) {\n\n      accessToken = qs.parse(accessToken);\n\n      var profileOauth = {\n        consumer_key: config.TWITTER_KEY,\n        consumer_secret: config.TWITTER_SECRET,\n        token: accessToken.oauth_token,\n        token_secret: accessToken.oauth_token_secret,\n      };\n\n      // Step 4. Retrieve user's profile information and email address.\n      request.get({\n        url: profileUrl,\n        qs: { include_email: true },\n        oauth: profileOauth,\n        json: true\n      }, function(err, response, profile) {\n\n        // Step 5a. Link user accounts.\n        if (req.header('Authorization')) {\n          User.findOne({ twitter: profile.id }, function(err, existingUser) {\n            if (existingUser) {\n              return res.status(409).send({ message: 'There is already a Twitter account that belongs to you' });\n            }\n\n            var token = req.header('Authorization').split(' ')[1];\n            var payload = jwt.decode(token, config.TOKEN_SECRET);\n\n            User.findById(payload.sub, function(err, user) {\n              if (!user) {\n                return res.status(400).send({ message: 'User not found' });\n              }\n\n              user.twitter = profile.id;\n              user.email = profile.email;\n              user.displayName = user.displayName || profile.name;\n              user.picture = user.picture || profile.profile_image_url_https.replace('_normal', '');\n              user.save(function(err) {\n                res.send({ token: createJWT(user) });\n              });\n            });\n          });\n        } else {\n          // Step 5b. Create a new user account or return an existing one.\n          User.findOne({ twitter: profile.id }, function(err, existingUser) {\n            if (existingUser) {\n              return res.send({ token: createJWT(existingUser) });\n            }\n\n            var user = new User();\n            user.twitter = profile.id;\n            user.email = profile.email;\n            user.displayName = profile.name;\n            user.picture = profile.profile_image_url_https.replace('_normal', '');\n            user.save(function() {\n              res.send({ token: createJWT(user) });\n            });\n          });\n        }\n      });\n    });\n  }\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Foursquare\n |--------------------------------------------------------------------------\n */\napp.post('/auth/foursquare', function(req, res) {\n  var accessTokenUrl = 'https://foursquare.com/oauth2/access_token';\n  var profileUrl = 'https://api.foursquare.com/v2/users/self';\n  var formData = {\n    code: req.body.code,\n    client_id: req.body.clientId,\n    client_secret: config.FOURSQUARE_SECRET,\n    redirect_uri: req.body.redirectUri,\n    grant_type: 'authorization_code'\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.post({ url: accessTokenUrl, form: formData, json: true }, function(err, response, body) {\n    var params = {\n      v: '20140806',\n      oauth_token: body.access_token\n    };\n\n    // Step 2. Retrieve information about the current user.\n    request.get({ url: profileUrl, qs: params, json: true }, function(err, response, profile) {\n      profile = profile.response.user;\n\n      // Step 3a. Link user accounts.\n      if (req.header('Authorization')) {\n        User.findOne({ foursquare: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            return res.status(409).send({ message: 'There is already a Foursquare account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, user) {\n            if (!user) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            user.foursquare = profile.id;\n            user.picture = user.picture || profile.photo.prefix + '300x300' + profile.photo.suffix;\n            user.displayName = user.displayName || profile.firstName + ' ' + profile.lastName;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3b. Create a new user account or return an existing one.\n        User.findOne({ foursquare: profile.id }, function(err, existingUser) {\n          if (existingUser) {\n            var token = createJWT(existingUser);\n            return res.send({ token: token });\n          }\n          var user = new User();\n          user.foursquare = profile.id;\n          user.picture = profile.photo.prefix + '300x300' + profile.photo.suffix;\n          user.displayName = profile.firstName + ' ' + profile.lastName;\n          user.save(function() {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      }\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Twitch\n |--------------------------------------------------------------------------\n */\napp.post('/auth/twitch', function(req, res) {\n  var accessTokenUrl = 'https://api.twitch.tv/kraken/oauth2/token';\n  var profileUrl = 'https://api.twitch.tv/kraken/user';\n  var formData = {\n    code: req.body.code,\n    client_id: req.body.clientId,\n    client_secret: config.TWITCH_SECRET,\n    redirect_uri: req.body.redirectUri,\n    grant_type: 'authorization_code'\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.post({ url: accessTokenUrl, form: formData, json: true }, function(err, response, accessToken) {\n   var params = {\n     oauth_token: accessToken.access_token\n   };\n\n    // Step 2. Retrieve information about the current user.\n    request.get({ url: profileUrl, qs: params, json: true }, function(err, response, profile) {\n      // Step 3a. Link user accounts.\n      if (req.header('Authorization')) {\n        User.findOne({ twitch: profile._id }, function(err, existingUser) {\n          if (existingUser) {\n            return res.status(409).send({ message: 'There is already a Twitch account that belongs to you' });\n          }\n          var token = req.header('Authorization').split(' ')[1];\n          var payload = jwt.decode(token, config.TOKEN_SECRET);\n          User.findById(payload.sub, function(err, user) {\n            if (!user) {\n              return res.status(400).send({ message: 'User not found' });\n            }\n            user.twitch = profile._id;\n            user.picture = user.picture || profile.logo;\n            user.displayName = user.name || profile.name;\n            user.email = user.email || profile.email;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        });\n      } else {\n        // Step 3b. Create a new user account or return an existing one.\n        User.findOne({ twitch: profile._id }, function(err, existingUser) {\n          if (existingUser) {\n            var token = createJWT(existingUser);\n            return res.send({ token: token });\n          }\n          var user = new User();\n          user.twitch = profile._id;\n          user.picture = profile.logo;\n          user.displayName = profile.name;\n          user.email = profile.email;\n          user.save(function() {\n            var token = createJWT(user);\n            res.send({ token: token });\n          });\n        });\n      }\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Bitbucket\n |--------------------------------------------------------------------------\n */\napp.post('/auth/bitbucket', function(req, res) {\n  var accessTokenUrl = 'https://bitbucket.org/site/oauth2/access_token';\n  var userApiUrl = 'https://bitbucket.org/api/2.0/user';\n  var emailApiUrl = 'https://bitbucket.org/api/2.0/user/emails';\n\n  var headers = {\n    Authorization: 'Basic ' + new Buffer(req.body.clientId + ':' + config.BITBUCKET_SECRET).toString('base64')\n  };\n\n  var formData = {\n    code: req.body.code,\n    redirect_uri: req.body.redirectUri,\n    grant_type: 'authorization_code'\n  };\n\n  // Step 1. Exchange authorization code for access token.\n  request.post({ url: accessTokenUrl, form: formData, headers: headers, json: true }, function(err, response, body) {\n    if (body.error) {\n      return res.status(400).send({ message: body.error_description });\n    }\n\n    var params = {\n      access_token: body.access_token\n    };\n\n    // Step 2. Retrieve information about the current user.\n    request.get({ url: userApiUrl, qs: params, json: true }, function(err, response, profile) {\n\n      // Step 2.5. Retrieve current user's email.\n      request.get({ url: emailApiUrl, qs: params, json: true }, function(err, response, emails) {\n        var email = emails.values[0].email;\n\n        // Step 3a. Link user accounts.\n        if (req.header('Authorization')) {\n          User.findOne({ bitbucket: profile.uuid }, function(err, existingUser) {\n            if (existingUser) {\n              return res.status(409).send({ message: 'There is already a Bitbucket account that belongs to you' });\n            }\n            var token = req.header('Authorization').split(' ')[1];\n            var payload = jwt.decode(token, config.TOKEN_SECRET);\n            User.findById(payload.sub, function(err, user) {\n              if (!user) {\n                return res.status(400).send({ message: 'User not found' });\n              }\n              user.bitbucket = profile.uuid;\n              user.email = user.email || email;\n              user.picture = user.picture || profile.links.avatar.href;\n              user.displayName = user.displayName || profile.display_name;\n              user.save(function() {\n                var token = createJWT(user);\n                res.send({ token: token });\n              });\n            });\n          });\n        } else {\n          // Step 3b. Create a new user account or return an existing one.\n          User.findOne({ bitbucket: profile.id }, function(err, existingUser) {\n            if (existingUser) {\n              var token = createJWT(existingUser);\n              return res.send({ token: token });\n            }\n            var user = new User();\n            user.bitbucket = profile.uuid;\n            user.email = email;\n            user.picture = profile.links.avatar.href;\n            user.displayName = profile.display_name;\n            user.save(function() {\n              var token = createJWT(user);\n              res.send({ token: token });\n            });\n          });\n        }\n      });\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Login with Spotify\n |--------------------------------------------------------------------------\n */\n\n app.post('/auth/spotify', function(req, res) {\n   var tokenUrl = 'https://accounts.spotify.com/api/token';\n   var userUrl = 'https://api.spotify.com/v1/me';\n\n   var params = {\n     grant_type: 'authorization_code',\n     code: req.body.code,\n     redirect_uri: req.body.redirectUri\n   };\n\n   var headers = {\n     Authorization: 'Basic ' + new Buffer(req.body.clientId + ':' + config.SPOTIFY_SECRET).toString('base64')\n   };\n\n   request.post(tokenUrl, { json: true, form: params, headers: headers }, function(err, response, body) {\n     if (body.error) {\n       return res.status(400).send({ message: body.error_description });\n     }\n\n     request.get(userUrl, {json: true, headers: {Authorization: 'Bearer ' + body.access_token} }, function(err, response, profile){\n       // Step 3a. Link user accounts.\n       if (req.header('Authorization')) {\n         User.findOne({ spotify: profile.id }, function(err, existingUser) {\n           if (existingUser) {\n             return res.status(409).send({ message: 'There is already a Spotify account that belongs to you' });\n           }\n           var token = req.header('Authorization').split(' ')[1];\n           var payload = jwt.decode(token, config.TOKEN_SECRET);\n           User.findById(payload.sub, function(err, user) {\n             if (!user) {\n               return res.status(400).send({ message: 'User not found' });\n             }\n             user.spotify = profile.id;\n             user.email = user.email || profile.email;\n             user.picture = profile.images.length > 0 ? profile.images[0].url : '';\n             user.displayName = user.displayName || profile.displayName || profile.id;\n\n             user.save(function() {\n               var token = createJWT(user);\n               res.send({ token: token });\n             });\n           });\n         });\n       } else {\n         // Step 3b. Create a new user account or return an existing one.\n         User.findOne({ spotify: profile.id }, function(err, existingUser) {\n           if (existingUser) {\n             return res.send({ token: createJWT(existingUser) });\n           }\n           var user = new User();\n           user.spotify = profile.id;\n           user.email = profile.email;\n           user.picture = profile.images.length > 0 ? profile.images[0].url : '';\n           user.displayName = profile.displayName || profile.id;\n\n           user.save(function(err) {\n             var token = createJWT(user);\n             res.send({ token: token });\n           });\n         });\n       }\n     });\n   });\n });\n\n/*\n |--------------------------------------------------------------------------\n | Unlink Provider\n |--------------------------------------------------------------------------\n */\napp.post('/auth/unlink', ensureAuthenticated, function(req, res) {\n  var provider = req.body.provider;\n  var providers = ['facebook', 'foursquare', 'google', 'github', 'instagram',\n    'linkedin', 'live', 'twitter', 'twitch', 'yahoo', 'bitbucket', 'spotify'];\n\n  if (providers.indexOf(provider) === -1) {\n    return res.status(400).send({ message: 'Unknown OAuth Provider' });\n  }\n\n  User.findById(req.user, function(err, user) {\n    if (!user) {\n      return res.status(400).send({ message: 'User Not Found' });\n    }\n    user[provider] = undefined;\n    user.save(function() {\n      res.status(200).end();\n    });\n  });\n});\n\n/*\n |--------------------------------------------------------------------------\n | Start the Server\n |--------------------------------------------------------------------------\n */\napp.listen(app.get('port'), app.get('host'), function() {\n  console.log('Express server listening on port ' + app.get('port'));\n});\n"
  },
  {
    "path": "examples/server/php/.gitattributes",
    "content": "* text=auto\n*.css linguist-vendored\n*.less linguist-vendored\n"
  },
  {
    "path": "examples/server/php/.gitignore",
    "content": "/vendor\n/node_modules\n.env\n"
  },
  {
    "path": "examples/server/php/README.md",
    "content": "<img src=\"http://blog.legacyteam.info/wp-content/uploads/2014/10/laravel-logo-white.png\" width=\"280px\">\n\nLaravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable, creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in the majority of web projects, such as authentication, routing, sessions, queueing, and caching.\n\n## Usage\n\n1. Download and install [Composer](https://getcomposer.org/).\n2. Install [Laravel 5](http://laravel.com) via `composer global require \"laravel/installer=~1.1\"`.\n3. Install Mcrypt PHP Extension:\n - <img src=\"http://deluge-torrent.org/images/apple-logo.gif\" height=\"17\"> **Mac OS X**: `brew install php55-mcrypt`.\n - <img src=\"https://lh5.googleusercontent.com/-2YS1ceHWyys/AAAAAAAAAAI/AAAAAAAAAAc/0LCb_tsTvmU/s46-c-k/photo.jpg\" height=\"17\"> **Ubuntu**: `sudo apt-get install php5-mcrypt`.\n4. Install dependencies via `composer install`.\n5. Run `php artisan serve --port 3000`, then go to `http://localhost:3000`.\n\n### <img src=\"http://www.file-extensions.org/imgs/app-icon/128/10520/microsoft-windows-10-icon.png\" height=\"24\"> Windows Prerequisites\n\n1. After you download and install PHP 5.5 (or 5.6), inside its directory find a file *php.ini-development*.\n2. Rename *php.ini-development* to *php.ini*.\n3. Open *php.ini* with a text editor, then uncomment the following extensions by removing semicolon in front:\n - `extension=php_openssl.dll`\n - `extension=php_mbstring.dll`\n - `extension=php_exif.dll`\n4. You need above extensions to properly install Composer and Laravel.\n5. Install the latest [OpenSSL](https://slproweb.com/products/Win32OpenSSL.html) library (Win32 or Win64 depending on which PHP you downloaded).\n"
  },
  {
    "path": "examples/server/php/app/Commands/Command.php",
    "content": "<?php namespace App\\Commands;\n\nabstract class Command {\n\n\t//\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Console/Commands/Inspire.php",
    "content": "<?php namespace App\\Console\\Commands;\n\nuse Illuminate\\Console\\Command;\nuse Illuminate\\Foundation\\Inspiring;\n\nclass Inspire extends Command {\n\n\t/**\n\t * The console command name.\n\t *\n\t * @var string\n\t */\n\tprotected $name = 'inspire';\n\n\t/**\n\t * The console command description.\n\t *\n\t * @var string\n\t */\n\tprotected $description = 'Display an inspiring quote';\n\n\t/**\n\t * Execute the console command.\n\t *\n\t * @return mixed\n\t */\n\tpublic function handle()\n\t{\n\t\t$this->comment(PHP_EOL.Inspiring::quote().PHP_EOL);\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Console/Kernel.php",
    "content": "<?php namespace App\\Console;\n\nuse Illuminate\\Console\\Scheduling\\Schedule;\nuse Illuminate\\Foundation\\Console\\Kernel as ConsoleKernel;\n\nclass Kernel extends ConsoleKernel {\n\n\t/**\n\t * The Artisan commands provided by your application.\n\t *\n\t * @var array\n\t */\n\tprotected $commands = [\n\t\t'App\\Console\\Commands\\Inspire',\n\t];\n\n\t/**\n\t * Define the application's command schedule.\n\t *\n\t * @param  \\Illuminate\\Console\\Scheduling\\Schedule  $schedule\n\t * @return void\n\t */\n\tprotected function schedule(Schedule $schedule)\n\t{\n\t\t$schedule->command('inspire')\n\t\t\t\t ->hourly();\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Events/Event.php",
    "content": "<?php namespace App\\Events;\n\nabstract class Event {\n\n\t//\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Exceptions/Handler.php",
    "content": "<?php namespace App\\Exceptions;\n\nuse Exception;\nuse Illuminate\\Foundation\\Exceptions\\Handler as ExceptionHandler;\n\nclass Handler extends ExceptionHandler {\n\n\t/**\n\t * A list of the exception types that should not be reported.\n\t *\n\t * @var array\n\t */\n\tprotected $dontReport = [\n\t\t'Symfony\\Component\\HttpKernel\\Exception\\HttpException'\n\t];\n\n\t/**\n\t * Report or log an exception.\n\t *\n\t * This is a great spot to send exceptions to Sentry, Bugsnag, etc.\n\t *\n\t * @param  \\Exception  $e\n\t * @return void\n\t */\n\tpublic function report(Exception $e)\n\t{\n\t\treturn parent::report($e);\n\t}\n\n\t/**\n\t * Render an exception into an HTTP response.\n\t *\n\t * @param  \\Illuminate\\Http\\Request  $request\n\t * @param  \\Exception  $e\n\t * @return \\Illuminate\\Http\\Response\n\t */\n\tpublic function render($request, Exception $e)\n\t{\n\t\treturn parent::render($request, $e);\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Handlers/Commands/.gitkeep",
    "content": ""
  },
  {
    "path": "examples/server/php/app/Handlers/Events/.gitkeep",
    "content": ""
  },
  {
    "path": "examples/server/php/app/Http/Controllers/AuthController.php",
    "content": "<?php namespace App\\Http\\Controllers;\n\nuse Hash;\nuse Config;\nuse Validator;\nuse Firebase\\JWT\\JWT;\nuse Illuminate\\Http\\Request;\nuse GuzzleHttp;\nuse GuzzleHttp\\Subscriber\\Oauth\\Oauth1;\nuse App\\User;\n\nclass AuthController extends Controller {\n\n    /**\n     * Generate JSON Web Token.\n     */\n    protected function createToken($user)\n    {\n        $payload = [\n            'sub' => $user->id,\n            'iat' => time(),\n            'exp' => time() + (2 * 7 * 24 * 60 * 60)\n        ];\n        return JWT::encode($payload, Config::get('app.token_secret'));\n    }\n\n\n    /**\n     * Unlink provider.\n     */\n    public function unlink(Request $request, $provider)\n    {\n        $user = User::find($request['user']['sub']);\n\n        if (!$user)\n        {\n            return response()->json(['message' => 'User not found']);\n        }\n\n        $user->$provider = '';\n        $user->save();\n        \n        return response()->json(array('token' => $this->createToken($user)));\n    }\n\n    /**\n     * Log in with Email and Password.\n     */\n    public function login(Request $request)\n    {\n        $email = $request->input('email');\n        $password = $request->input('password');\n\n        $user = User::where('email', '=', $email)->first();\n\n        if (!$user)\n        {\n            return response()->json(['message' => 'Wrong email and/or password'], 401);\n        }\n\n        if (Hash::check($password, $user->password))\n        {\n            unset($user->password);\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n        else\n        {\n            return response()->json(['message' => 'Wrong email and/or password'], 401);\n        }\n    }\n\n    /**\n     * Create Email and Password Account.\n     */\n    public function signup(Request $request)\n    {\n        $validator = Validator::make($request->all(), [\n            'displayName' => 'required',\n            'email' => 'required|email|unique:users,email',\n            'password' => 'required'\n        ]);\n\n        if ($validator->fails()) {\n            return response()->json(['message' => $validator->messages()], 400);\n        }\n\n        $user = new User;\n        $user->displayName = $request->input('displayName');\n        $user->email = $request->input('email');\n        $user->password = Hash::make($request->input('password'));\n        $user->save();\n\n        return response()->json(['token' => $this->createToken($user)]);\n    }\n\n    /**\n     * Login with Facebook.\n     */\n    public function facebook(Request $request)\n    {\n        $client = new GuzzleHttp\\Client();\n\n        $params = [\n            'code' => $request->input('code'),\n            'client_id' => $request->input('clientId'),\n            'redirect_uri' => $request->input('redirectUri'),\n            'client_secret' => Config::get('app.facebook_secret')\n        ];\n\n        // Step 1. Exchange authorization code for access token.\n        $accessTokenResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/oauth/access_token', [\n            'query' => $params\n        ]);\n        $accessToken = json_decode($accessTokenResponse->getBody(), true);\n\n        // Step 2. Retrieve profile information about the current user.\n        $fields = 'id,email,first_name,last_name,link,name';\n        $profileResponse = $client->request('GET', 'https://graph.facebook.com/v2.5/me', [\n            'query' => [\n                'access_token' => $accessToken['access_token'],\n                'fields' => $fields\n            ]\n        ]);\n        $profile = json_decode($profileResponse->getBody(), true);\n\n        // Step 3a. If user is already signed in then link accounts.\n        if ($request->header('Authorization'))\n        {\n            $user = User::where('facebook', '=', $profile['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['message' => 'There is already a Facebook account that belongs to you'], 409);\n            }\n\n            $token = explode(' ', $request->header('Authorization'))[1];\n            $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n            $user = User::find($payload['sub']);\n            $user->facebook = $profile['id'];\n            $user->email = $user->email ?: $profile['email'];\n            $user->displayName = $user->displayName ?: $profile['name'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n        // Step 3b. Create a new user account or return an existing one.\n        else\n        {\n            $user = User::where('facebook', '=', $profile['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['token' => $this->createToken($user->first())]);\n            }\n\n            $user = new User;\n            $user->facebook = $profile['id'];\n            $user->email = $profile['email'];\n            $user->displayName = $profile['name'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n    }\n\n    /**\n     * Login with Google.\n     */\n    public function google(Request $request)\n    {\n        $client = new GuzzleHttp\\Client();\n\n        $params = [\n            'code' => $request->input('code'),\n            'client_id' => $request->input('clientId'),\n            'client_secret' => Config::get('app.google_secret'),\n            'redirect_uri' => $request->input('redirectUri'),\n            'grant_type' => 'authorization_code',\n        ];\n\n        // Step 1. Exchange authorization code for access token.\n        $accessTokenResponse = $client->request('POST', 'https://accounts.google.com/o/oauth2/token', [\n            'form_params' => $params\n        ]);\n        $accessToken = json_decode($accessTokenResponse->getBody(), true);\n\n        // Step 2. Retrieve profile information about the current user.\n        $profileResponse = $client->request('GET', 'https://www.googleapis.com/plus/v1/people/me/openIdConnect', [\n            'headers' => array('Authorization' => 'Bearer ' . $accessToken['access_token'])\n        ]);\n        $profile = json_decode($profileResponse->getBody(), true);\n\n        // Step 3a. If user is already signed in then link accounts.\n        if ($request->header('Authorization'))\n        {\n            $user = User::where('google', '=', $profile['sub']);\n\n            if ($user->first())\n            {\n                return response()->json(['message' => 'There is already a Google account that belongs to you'], 409);\n            }\n\n            $token = explode(' ', $request->header('Authorization'))[1];\n            $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n            $user = User::find($payload['sub']);\n            $user->google = $profile['sub'];\n            $user->displayName = $user->displayName ?: $profile['name'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n        // Step 3b. Create a new user account or return an existing one.\n        else\n        {\n            $user = User::where('google', '=', $profile['sub']);\n\n            if ($user->first())\n            {\n                return response()->json(['token' => $this->createToken($user->first())]);\n            }\n\n            $user = new User;\n            $user->google = $profile['sub'];\n            $user->displayName = $profile['name'];\n            $user->picture = $profile['picture'];\n            $user->email = $profile['email'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n    }\n\n    /**\n     * Login with LinkedIn.\n     */\n    public function linkedin(Request $request)\n    {\n        $client = new GuzzleHttp\\Client();\n\n        $params = [\n            'code' => $request->input('code'),\n            'client_id' => $request->input('clientId'),\n            'client_secret' => Config::get('app.linkedin_secret'),\n            'redirect_uri' => $request->input('redirectUri'),\n            'grant_type' => 'authorization_code',\n        ];\n\n        // Step 1. Exchange authorization code for access token.\n        $accessTokenResponse = $client->request('POST', 'https://www.linkedin.com/uas/oauth2/accessToken', [\n            'form_params' => $params\n        ]);\n        $accessToken = json_decode($accessTokenResponse->getBody(), true);\n\n        // Step 2. Retrieve profile information about the current user.\n        $profileResponse = $client->request('GET', 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)', [\n            'query' => [\n                'oauth2_access_token' => $accessToken['access_token'],\n                'format' => 'json'\n            ]\n        ]);\n        $profile = json_decode($profileResponse->getBody(), true);\n\n        // Step 3a. If user is already signed in then link accounts.\n        if ($request->header('Authorization'))\n        {\n            $user = User::where('linkedin', '=', $profile['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['message' => 'There is already a LinkedIn account that belongs to you'], 409);\n            }\n\n            $token = explode(' ', $request->header('Authorization'))[1];\n            $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n            $user = User::find($payload['sub']);\n            $user->linkedin = $profile['id'];\n            $user->displayName = $user->displayName ?: $profile['firstName'] . ' ' . $profile['lastName'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n        // Step 3b. Create a new user account or return an existing one.\n        else\n        {\n            $user = User::where('linkedin', '=', $profile['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['token' => $this->createToken($user->first())]);\n            }\n\n            $user = new User;\n            $user->linkedin = $profile['id'];\n            $user->displayName =  $profile['firstName'] . ' ' . $profile['lastName'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n    }\n\n    /**\n     * Login with Twitter.\n     */\n    public function twitter(Request $request)\n    {\n        $stack = GuzzleHttp\\HandlerStack::create();\n\n        // Part 1 of 2: Initial request from Satellizer.\n        if (!$request->input('oauth_token') || !$request->input('oauth_verifier'))\n        {\n            $stack = GuzzleHttp\\HandlerStack::create();\n\n            $requestTokenOauth = new Oauth1([\n              'consumer_key' => Config::get('app.twitter_key'),\n              'consumer_secret' => Config::get('app.twitter_secret'),\n              'callback' => $request->input('redirectUri'),\n              'token' => '',\n              'token_secret' => ''\n            ]);\n            $stack->push($requestTokenOauth);\n\n            $client = new GuzzleHttp\\Client([\n                'handler' => $stack\n            ]);\n\n            // Step 1. Obtain request token for the authorization popup.\n            $requestTokenResponse = $client->request('POST', 'https://api.twitter.com/oauth/request_token', [\n                'auth' => 'oauth'\n            ]);\n\n            $oauthToken = array();\n            parse_str($requestTokenResponse->getBody(), $oauthToken);\n\n            // Step 2. Send OAuth token back to open the authorization screen.\n            return response()->json($oauthToken);\n\n        }\n        // Part 2 of 2: Second request after Authorize app is clicked.\n        else\n        {\n            $accessTokenOauth = new Oauth1([\n                'consumer_key' => Config::get('app.twitter_key'),\n                'consumer_secret' => Config::get('app.twitter_secret'),\n                'token' => $request->input('oauth_token'),\n                'verifier' => $request->input('oauth_verifier'),\n                'token_secret' => ''\n            ]);\n            $stack->push($accessTokenOauth);\n\n            $client = new GuzzleHttp\\Client([\n                'handler' => $stack\n            ]);\n\n            // Step 3. Exchange oauth token and oauth verifier for access token.\n            $accessTokenResponse = $client->request('POST', 'https://api.twitter.com/oauth/access_token', [\n                'auth' => 'oauth'\n            ]);\n\n            $accessToken = array();\n            parse_str($accessTokenResponse->getBody(), $accessToken);\n\n            $profileOauth = new Oauth1([\n                'consumer_key' => Config::get('app.twitter_key'),\n                'consumer_secret' => Config::get('app.twitter_secret'),\n                'oauth_token' => $accessToken['oauth_token'],\n                'token_secret' => ''\n            ]);\n            $stack->push($profileOauth);\n\n            $client = new GuzzleHttp\\Client([\n                'handler' => $stack\n            ]);\n\n            // Step 4. Retrieve profile information about the current user.\n            $profileResponse = $client->request('GET', 'https://api.twitter.com/1.1/users/show.json?screen_name=' . $accessToken['screen_name'], [\n                'auth' => 'oauth'\n            ]);\n            $profile = json_decode($profileResponse->getBody(), true);\n\n            // Step 5a. Link user accounts.\n            if ($request->header('Authorization'))\n            {\n                $user = User::where('twitter', '=', $profile['id']);\n                if ($user->first())\n                {\n                    return response()->json(['message' => 'There is already a Twitter account that belongs to you'], 409);\n                }\n\n                $token = explode(' ', $request->header('Authorization'))[1];\n                $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n                $user = User::find($payload['sub']);\n                $user->twitter = $profile['id'];\n                $user->displayName = $user->displayName ?: $profile['screen_name'];\n                $user->save();\n\n                return response()->json(['token' => $this->createToken($user)]);\n            }\n            // Step 5b. Create a new user account or return an existing one.\n            else\n            {\n                $user = User::where('twitter', '=', $profile['id']);\n\n                if ($user->first())\n                {\n                    return response()->json(['token' => $this->createToken($user->first())]);\n                }\n\n                $user = new User;\n                $user->twitter = $profile['id'];\n                $user->displayName = $profile['screen_name'];\n                $user->save();\n\n                return response()->json(['token' => $this->createToken($user)]);\n            }\n        }\n    }\n\n    /**\n     * Login with Foursquare.\n     */\n    public function foursquare(Request $request)\n    {\n        $client = new GuzzleHttp\\Client();\n\n        $params = [\n            'code' => $request->input('code'),\n            'client_id' => $request->input('clientId'),\n            'client_secret' => Config::get('app.foursquare_secret'),\n            'redirect_uri' => $request->input('redirectUri'),\n            'grant_type' => 'authorization_code',\n        ];\n\n        // Step 1. Exchange authorization code for access token.\n        $accessTokenResponse = $client->request('POST', 'https://foursquare.com/oauth2/access_token', [\n            'form_params' => $params\n        ]);\n        $accessToken = json_decode($accessTokenResponse->getBody(), true);\n\n        // Step 2. Retrieve profile information about the current user.\n        $profileResponse = $client->request('GET', 'https://api.foursquare.com/v2/users/self', [\n            'query' => [\n                'v' => '20140806',\n                'oauth_token' => $accessToken['access_token']\n            ]\n        ]);\n\n        $profile = json_decode($profileResponse->getBody(), true)['response']['user'];\n\n        // Step 3a. If user is already signed in then link accounts.\n        if ($request->header('Authorization'))\n        {\n            $user = User::where('foursquare', '=', $profile['id']);\n            if ($user->first())\n            {\n                return response()->json(array('message' => 'There is already a Foursquare account that belongs to you'), 409);\n            }\n\n            $token = explode(' ', $request->header('Authorization'))[1];\n            $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n            $user = User::find($payload['sub']);\n            $user->foursquare = $profile['id'];\n            $user->displayName = $user->displayName ?: $profile['firstName'] . ' ' . $profile['lastName'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n        // Step 3b. Create a new user account or return an existing one.\n        else\n        {\n            $user = User::where('foursquare', '=', $profile['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['token' => $this->createToken($user->first())]);\n            }\n\n            $user = new User;\n            $user->foursquare = $profile['id'];\n            $user->displayName =  $profile['firstName'] . ' ' . $profile['lastName'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n    }\n\n    /**\n     * Login with Instagram.\n     */\n    public function instagram(Request $request)\n    {\n        $client = new GuzzleHttp\\Client();\n\n        $params = [\n            'code' => $request->input('code'),\n            'client_id' => $request->input('clientId'),\n            'client_secret' => Config::get('app.instagram_secret'),\n            'redirect_uri' => $request->input('redirectUri'),\n            'grant_type' => 'authorization_code',\n        ];\n\n        // Step 1. Exchange authorization code for access token.\n        $accessTokenResponse = $client->request('POST', 'https://api.instagram.com/oauth/access_token', [\n            'body' => $params\n        ]);\n        $accessToken = json_decode($accessTokenResponse->getBody(), true);\n\n        // Step 2a. If user is already signed in then link accounts.\n        if ($request->header('Authorization'))\n        {\n            $user = User::where('instagram', '=', $accessToken['user']['id']);\n            if ($user->first())\n            {\n                return response()->json(array('message' => 'There is already an Instagram account that belongs to you'), 409);\n            }\n\n            $token = explode(' ', $request->header('Authorization'))[1];\n            $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n            $user = User::find($payload['sub']);\n            $user->instagram = $accessToken['user']['id'];\n            $user->displayName = $user->displayName ?: $accessToken['user']['username'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n        // Step 2b. Create a new user account or return an existing one.\n        else\n        {\n            $user = User::where('instagram', '=', $accessToken['user']['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['token' => $this->createToken($user->first())]);\n            }\n\n            $user = new User;\n            $user->instagram = $accessToken['user']['id'];\n            $user->displayName =  $accessToken['user']['username'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n    }\n\n    /**\n     * Login with GitHub.\n     */\n    public function github(Request $request)\n    {\n        $client = new GuzzleHttp\\Client();\n\n        $params = [\n            'code' => $request->input('code'),\n            'client_id' => $request->input('clientId'),\n            'client_secret' => Config::get('app.github_secret'),\n            'redirect_uri' => $request->input('redirectUri')\n        ];\n\n        // Step 1. Exchange authorization code for access token.\n        $accessTokenResponse = $client->request('GET', 'https://github.com/login/oauth/access_token', [\n            'query' => $params\n        ]);\n\n        $accessToken = array();\n        parse_str($accessTokenResponse->getBody(), $accessToken);\n\n        // Step 2. Retrieve profile information about the current user.\n        $profileResponse = $client->request('GET', 'https://api.github.com/user', [\n            'headers' => ['User-Agent' => 'Satellizer'],\n            'query' => $accessToken\n        ]);\n        $profile = json_decode($profileResponse->getBody(), true);\n\n        // Step 3a. If user is already signed in then link accounts.\n        if ($request->header('Authorization'))\n        {\n            $user = User::where('github', '=', $profile['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['message' => 'There is already a GitHub account that belongs to you'], 409);\n            }\n\n            $token = explode(' ', $request->header('Authorization'))[1];\n            $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n            $user = User::find($payload['sub']);\n            $user->github = $profile['id'];\n            $user->displayName = $user->displayName ?: $profile['name'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n        // Step 3b. Create a new user account or return an existing one.\n        else\n        {\n            $user = User::where('github', '=', $profile['id']);\n\n            if ($user->first())\n            {\n                return response()->json(['token' => $this->createToken($user->first())]);\n            }\n\n            $user = new User;\n            $user->github = $profile['id'];\n            $user->displayName = $profile['name'];\n            $user->save();\n\n            return response()->json(['token' => $this->createToken($user)]);\n        }\n    }\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/Controllers/Controller.php",
    "content": "<?php namespace App\\Http\\Controllers;\n\nuse Illuminate\\Foundation\\Bus\\DispatchesJobs;\nuse Illuminate\\Routing\\Controller as BaseController;\nuse Illuminate\\Foundation\\Validation\\ValidatesRequests;\n\nabstract class Controller extends BaseController {\n\n\tuse DispatchesJobs, ValidatesRequests;\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/Controllers/HomeController.php",
    "content": "<?php namespace App\\Http\\Controllers;\n\nuse File;\n\nclass HomeController extends Controller {\n\n    public function index()\n    {\n        return File::get(public_path().'/index.html');\n    }\n\n}"
  },
  {
    "path": "examples/server/php/app/Http/Controllers/UserController.php",
    "content": "<?php namespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse Config;\nuse Firebase\\JWT\\JWT;\nuse App\\User;\n\nclass UserController extends Controller {\n\n    /**\n     * Generate JSON Web Token.\n     */\n    protected function createToken($user)\n    {\n        $payload = [\n            'sub' => $user->id,\n            'iat' => time(),\n            'exp' => time() + (2 * 7 * 24 * 60 * 60)\n        ];\n        return JWT::encode($payload, Config::get('app.token_secret'));\n    }\n\n    /**\n     * Get signed in user's profile.\n     */\n    public function getUser(Request $request)\n    {\n        $user = User::find($request['user']['sub']);\n\n        return $user;\n    }\n\n    /**\n     * Update signed in user's profile.\n     */\n    public function updateUser(Request $request)\n    {\n        $user = User::find($request['user']['sub']);\n\n        $user->displayName = $request->input('displayName');\n        $user->email = $request->input('email');\n        $user->save();\n\n        $token = $this->createToken($user);\n\n        return response()->json(['token' => $token]);\n    }\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/Kernel.php",
    "content": "<?php namespace App\\Http;\n\nuse Illuminate\\Foundation\\Http\\Kernel as HttpKernel;\n\nclass Kernel extends HttpKernel {\n\n\t/**\n\t * The application's global HTTP middleware stack.\n\t *\n\t * @var array\n\t */\n\tprotected $middleware = [\n\t\t'Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode',\n\t\t'Illuminate\\Cookie\\Middleware\\EncryptCookies',\n\t\t'Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse',\n\t\t'Illuminate\\Session\\Middleware\\StartSession',\n\t\t'Illuminate\\View\\Middleware\\ShareErrorsFromSession',\n//\t\t'App\\Http\\Middleware\\VerifyCsrfToken',\n\t];\n\n\t/**\n\t * The application's route middleware.\n\t *\n\t * @var array\n\t */\n\tprotected $routeMiddleware = [\n\t\t'auth' => 'App\\Http\\Middleware\\Authenticate',\n\t\t'auth.basic' => 'Illuminate\\Auth\\Middleware\\AuthenticateWithBasicAuth',\n\t\t'guest' => 'App\\Http\\Middleware\\RedirectIfAuthenticated',\n\t];\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/Middleware/Authenticate.php",
    "content": "<?php namespace App\\Http\\Middleware;\n\nuse Firebase\\JWT\\JWT;\nuse Config;\nuse Closure;\nuse Illuminate\\Contracts\\Auth\\Guard;\n\nclass Authenticate {\n\n\t/**\n\t * The Guard implementation.\n\t *\n\t * @var Guard\n\t */\n\tprotected $auth;\n\n\t/**\n\t * Create a new filter instance.\n\t *\n\t * @param  Guard  $auth\n\t * @return void\n\t */\n\tpublic function __construct(Guard $auth)\n\t{\n\t\t$this->auth = $auth;\n\t}\n\n\t/**\n\t * Handle an incoming request.\n\t *\n\t * @param  \\Illuminate\\Http\\Request  $request\n\t * @param  \\Closure  $next\n\t * @return mixed\n\t */\n\tpublic function handle($request, Closure $next)\n\t{\n\t\tif ($request->header('Authorization'))\n\t\t{\n\t\t\t$token = explode(' ', $request->header('Authorization'))[1];\n\t\t\t$payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));\n\n\t\t\tif ($payload['exp'] < time())\n\t\t\t{\n\t\t\t\treturn response()->json(['message' => 'Token has expired']);\n\t\t\t}\n\n\t\t\t$request['user'] = $payload;\n\n\t\t\treturn $next($request);\n\t\t}\n\t\telse\n\t\t{\n\t\t\treturn response()->json(['message' => 'Please make sure your request has an Authorization header'], 401);\n\t\t}\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/Middleware/RedirectIfAuthenticated.php",
    "content": "<?php namespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Contracts\\Auth\\Guard;\nuse Illuminate\\Http\\RedirectResponse;\n\nclass RedirectIfAuthenticated {\n\n\t/**\n\t * The Guard implementation.\n\t *\n\t * @var Guard\n\t */\n\tprotected $auth;\n\n\t/**\n\t * Create a new filter instance.\n\t *\n\t * @param  Guard  $auth\n\t * @return void\n\t */\n\tpublic function __construct(Guard $auth)\n\t{\n\t\t$this->auth = $auth;\n\t}\n\n\t/**\n\t * Handle an incoming request.\n\t *\n\t * @param  \\Illuminate\\Http\\Request  $request\n\t * @param  \\Closure  $next\n\t * @return mixed\n\t */\n\tpublic function handle($request, Closure $next)\n\t{\n\t\tif ($this->auth->check())\n\t\t{\n\t\t\treturn new RedirectResponse(url('/home'));\n\t\t}\n\n\t\treturn $next($request);\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/Middleware/VerifyCsrfToken.php",
    "content": "<?php namespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken as BaseVerifier;\n\nclass VerifyCsrfToken extends BaseVerifier {\n\n\t/**\n\t * Handle an incoming request.\n\t *\n\t * @param  \\Illuminate\\Http\\Request  $request\n\t * @param  \\Closure  $next\n\t * @return mixed\n\t */\n\tpublic function handle($request, Closure $next)\n\t{\n\t\treturn parent::handle($request, $next);\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/Requests/Request.php",
    "content": "<?php namespace App\\Http\\Requests;\n\nuse Illuminate\\Foundation\\Http\\FormRequest;\n\nabstract class Request extends FormRequest {\n\n\t//\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Http/routes.php",
    "content": "<?php\n\n/*\n|--------------------------------------------------------------------------\n| Application Routes\n|--------------------------------------------------------------------------\n|\n| Here is where you can register all of the routes for an application.\n| It's a breeze. Simply tell Laravel the URIs it should respond to\n| and give it the controller to call when that URI is requested.\n|\n*/\n\n// OAuth, Login and Signup Routes.\nRoute::post('auth/twitter', 'AuthController@twitter');\nRoute::post('auth/facebook', 'AuthController@facebook');\nRoute::post('auth/foursquare', 'AuthController@foursquare');\nRoute::post('auth/instagram', 'AuthController@instagram');\nRoute::post('auth/github', 'AuthController@github');\nRoute::post('auth/google', 'AuthController@google');\nRoute::post('auth/linkedin', 'AuthController@linkedin');\nRoute::post('auth/login', 'AuthController@login');\nRoute::post('auth/signup', 'AuthController@signup');\nRoute::get('auth/unlink/{provider}', ['middleware' => 'auth', 'uses' => 'AuthController@unlink']);\n\n// API Routes.\nRoute::get('api/me', ['middleware' => 'auth', 'uses' => 'UserController@getUser']);\nRoute::put('api/me', ['middleware' => 'auth', 'uses' => 'UserController@updateUser']);\n\n// Initialize Angular.js App Route.\nRoute::get('/', 'HomeController@index');"
  },
  {
    "path": "examples/server/php/app/Providers/AppServiceProvider.php",
    "content": "<?php namespace App\\Providers;\n\nuse Illuminate\\Support\\ServiceProvider;\n\nclass AppServiceProvider extends ServiceProvider {\n\n\t/**\n\t * Bootstrap any application services.\n\t *\n\t * @return void\n\t */\n\tpublic function boot()\n\t{\n\t\t//\n\t}\n\n\t/**\n\t * Register any application services.\n\t *\n\t * @return void\n\t */\n\tpublic function register()\n\t{\n\t\t//\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Providers/AuthServiceProvider.php",
    "content": "<?php\n\nnamespace App\\Providers;\n\nuse Illuminate\\Contracts\\Auth\\Access\\Gate as GateContract;\nuse Illuminate\\Foundation\\Support\\Providers\\AuthServiceProvider as ServiceProvider;\n\nclass AuthServiceProvider extends ServiceProvider\n{\n    /**\n     * The policy mappings for the application.\n     *\n     * @var array\n     */\n    protected $policies = [\n        'App\\Model' => 'App\\Policies\\ModelPolicy',\n    ];\n\n    /**\n     * Register any application authentication / authorization services.\n     *\n     * @param  \\Illuminate\\Contracts\\Auth\\Access\\Gate  $gate\n     * @return void\n     */\n    public function boot(GateContract $gate)\n    {\n        $this->registerPolicies($gate);\n\n        //\n    }\n}"
  },
  {
    "path": "examples/server/php/app/Providers/BusServiceProvider.php",
    "content": "<?php namespace App\\Providers;\n\nuse Illuminate\\Bus\\Dispatcher;\nuse Illuminate\\Support\\ServiceProvider;\n\nclass BusServiceProvider extends ServiceProvider {\n\n\t/**\n\t * Bootstrap any application services.\n\t *\n\t * @param  \\Illuminate\\Bus\\Dispatcher  $dispatcher\n\t * @return void\n\t */\n\tpublic function boot(Dispatcher $dispatcher)\n\t{\n\t\t$dispatcher->mapUsing(function($command)\n\t\t{\n\t\t\treturn Dispatcher::simpleMapping(\n\t\t\t\t$command, 'App\\Commands', 'App\\Handlers\\Commands'\n\t\t\t);\n\t\t});\n\t}\n\n\t/**\n\t * Register any application services.\n\t *\n\t * @return void\n\t */\n\tpublic function register()\n\t{\n\t\t//\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Providers/ConfigServiceProvider.php",
    "content": "<?php namespace App\\Providers;\n\nuse Illuminate\\Support\\ServiceProvider;\n\nclass ConfigServiceProvider extends ServiceProvider {\n\n\t/**\n\t * Overwrite any vendor / package configuration.\n\t *\n\t * This service provider is intended to provide a convenient location for you\n\t * to overwrite any \"vendor\" or package configuration that you may want to\n\t * modify before the application handles the incoming request / command.\n\t *\n\t * @return void\n\t */\n\tpublic function register()\n\t{\n\t\tconfig([\n\t\t\t//\n\t\t]);\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Providers/EventServiceProvider.php",
    "content": "<?php namespace App\\Providers;\n\nuse Illuminate\\Contracts\\Events\\Dispatcher as DispatcherContract;\nuse Illuminate\\Foundation\\Support\\Providers\\EventServiceProvider as ServiceProvider;\n\nclass EventServiceProvider extends ServiceProvider {\n\n\t/**\n\t * The event handler mappings for the application.\n\t *\n\t * @var array\n\t */\n\tprotected $listen = [\n\t\t'event.name' => [\n\t\t\t'EventListener',\n\t\t],\n\t];\n\n\t/**\n\t * Register any other events for your application.\n\t *\n\t * @param  \\Illuminate\\Contracts\\Events\\Dispatcher  $events\n\t * @return void\n\t */\n\tpublic function boot(DispatcherContract $events)\n\t{\n\t\tparent::boot($events);\n\n\t\t//\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/Providers/RouteServiceProvider.php",
    "content": "<?php namespace App\\Providers;\n\nuse Illuminate\\Routing\\Router;\nuse Illuminate\\Foundation\\Support\\Providers\\RouteServiceProvider as ServiceProvider;\n\nclass RouteServiceProvider extends ServiceProvider {\n\n\t/**\n\t * This namespace is applied to the controller routes in your routes file.\n\t *\n\t * In addition, it is set as the URL generator's root namespace.\n\t *\n\t * @var string\n\t */\n\tprotected $namespace = 'App\\Http\\Controllers';\n\n\t/**\n\t * Define your route model bindings, pattern filters, etc.\n\t *\n\t * @param  \\Illuminate\\Routing\\Router  $router\n\t * @return void\n\t */\n\tpublic function boot(Router $router)\n\t{\n\t\t//\n\t\t\n\t\tparent::boot($router);\n\t}\n\n\t/**\n\t * Define the routes for the application.\n\t *\n\t * @param  \\Illuminate\\Routing\\Router  $router\n\t * @return void\n\t */\n\tpublic function map(Router $router)\n\t{\n\t\t$router->group(['namespace' => $this->namespace], function($router)\n\t\t{\n\t\t\trequire app_path('Http/routes.php');\n\t\t});\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/app/User.php",
    "content": "<?php namespace App;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass User extends Model {\n\n\t/**\n\t * The database table used by the model.\n\t *\n\t * @var string\n\t */\n\tprotected $table = 'users';\n\n\t/**\n\t * The attributes excluded from the model's JSON form.\n\t *\n\t * @var array\n\t */\n\tprotected $hidden = ['password'];\n\n}\n"
  },
  {
    "path": "examples/server/php/artisan",
    "content": "#!/usr/bin/env php\n<?php\n\n/*\n|--------------------------------------------------------------------------\n| Register The Auto Loader\n|--------------------------------------------------------------------------\n|\n| Composer provides a convenient, automatically generated class loader\n| for our application. We just need to utilize it! We'll require it\n| into the script here so that we do not have to worry about the\n| loading of any our classes \"manually\". Feels great to relax.\n|\n*/\n\nrequire __DIR__.'/bootstrap/autoload.php';\n\n$app = require_once __DIR__.'/bootstrap/app.php';\n\n/*\n|--------------------------------------------------------------------------\n| Run The Artisan Application\n|--------------------------------------------------------------------------\n|\n| When we run the console application, the current CLI command will be\n| executed in this console and the response sent back to a terminal\n| or another output device for the developers. Here goes nothing!\n|\n*/\n\n$kernel = $app->make('Illuminate\\Contracts\\Console\\Kernel');\n\n$status = $kernel->handle(\n\t$input = new Symfony\\Component\\Console\\Input\\ArgvInput,\n\tnew Symfony\\Component\\Console\\Output\\ConsoleOutput\n);\n\n/*\n|--------------------------------------------------------------------------\n| Shutdown The Application\n|--------------------------------------------------------------------------\n|\n| Once Artisan has finished running. We will fire off the shutdown events\n| so that any final work may be done by the application before we shut\n| down the process. This is the last thing to happen to the request.\n|\n*/\n\n$kernel->terminate($input, $status);\n\nexit($status);\n"
  },
  {
    "path": "examples/server/php/bootstrap/app.php",
    "content": "<?php\n\n/*\n|--------------------------------------------------------------------------\n| Create The Application\n|--------------------------------------------------------------------------\n|\n| The first thing we will do is create a new Laravel application instance\n| which serves as the \"glue\" for all the components of Laravel, and is\n| the IoC container for the system binding all of the various parts.\n|\n*/\n\n$app = new Illuminate\\Foundation\\Application(\n\trealpath(__DIR__.'/../')\n);\n\n/*\n|--------------------------------------------------------------------------\n| Bind Important Interfaces\n|--------------------------------------------------------------------------\n|\n| Next, we need to bind some important interfaces into the container so\n| we will be able to resolve them when needed. The kernels serve the\n| incoming requests to this application from both the web and CLI.\n|\n*/\n\n$app->singleton(\n\t'Illuminate\\Contracts\\Http\\Kernel',\n\t'App\\Http\\Kernel'\n);\n\n$app->singleton(\n\t'Illuminate\\Contracts\\Console\\Kernel',\n\t'App\\Console\\Kernel'\n);\n\n$app->singleton(\n\t'Illuminate\\Contracts\\Debug\\ExceptionHandler',\n\t'App\\Exceptions\\Handler'\n);\n\n/*\n|--------------------------------------------------------------------------\n| Return The Application\n|--------------------------------------------------------------------------\n|\n| This script returns the application instance. The instance is given to\n| the calling script so we can separate the building of the instances\n| from the actual running of the application and sending responses.\n|\n*/\n\nreturn $app;\n"
  },
  {
    "path": "examples/server/php/bootstrap/autoload.php",
    "content": "<?php\n\ndefine('LARAVEL_START', microtime(true));\n\n/*\n|--------------------------------------------------------------------------\n| Register The Composer Auto Loader\n|--------------------------------------------------------------------------\n|\n| Composer provides a convenient, automatically generated class loader\n| for our application. We just need to utilize it! We'll require it\n| into the script here so that we do not have to worry about the\n| loading of any our classes \"manually\". Feels great to relax.\n|\n*/\n\nrequire __DIR__.'/../vendor/autoload.php';\n\n/*\n|--------------------------------------------------------------------------\n| Include The Compiled Class File\n|--------------------------------------------------------------------------\n|\n| To dramatically increase your application's performance, you may use a\n| compiled class file which contains all of the classes commonly used\n| by a request. The Artisan \"optimize\" is used to create this file.\n|\n*/\n\nif (file_exists($compiledPath = __DIR__.'/../vendor/compiled.php'))\n{\n\trequire $compiledPath;\n}\nelseif (file_exists($compiledPath = __DIR__.'/../storage/framework/compiled.php'))\n{\n\trequire $compiledPath;\n}\n"
  },
  {
    "path": "examples/server/php/bootstrap/cache/.gitignore",
    "content": "*\n!.gitignore"
  },
  {
    "path": "examples/server/php/composer.json",
    "content": "{\n\t\"name\": \"laravel/laravel\",\n\t\"description\": \"The Laravel Framework.\",\n\t\"keywords\": [\"framework\", \"laravel\"],\n\t\"license\": \"MIT\",\n\t\"type\": \"project\",\n\t\"require\": {\n\t\t\"laravel/framework\": \"5.2.*\",\n\t  \t\"firebase/php-jwt\": \"~3.0.0\",\n\t  \t\"guzzlehttp/guzzle\": \"~6.1.1\",\n\t  \t\"guzzlehttp/oauth-subscriber\": \"dev-master\"\n\t},\n\t\"require-dev\": {\n\t\t\"phpunit/phpunit\": \"~4.0\",\n\t\t\"phpspec/phpspec\": \"~2.1\",\n\t\t\"symfony/dom-crawler\": \"~3.0\",\n\t\t\"symfony/css-selector\": \"~3.0\"\n\t},\n\t\"autoload\": {\n\t\t\"classmap\": [\n\t\t\t\"database\"\n\t\t],\n\t\t\"psr-4\": {\n\t\t\t\"App\\\\\": \"app/\"\n\t\t}\n\t},\n\t\"autoload-dev\": {\n\t\t\"classmap\": [\n\t\t\t\"tests/TestCase.php\"\n\t\t]\n\t},\n\t\"scripts\": {\n\t\t\"post-install-cmd\": [\n\t\t\t\"php artisan clear-compiled\",\n\t\t\t\"php artisan optimize\"\n\t\t],\n\t\t\"post-update-cmd\": [\n\t\t\t\"php artisan clear-compiled\",\n\t\t\t\"php artisan optimize\"\n\t\t],\n\t\t\"post-create-project-cmd\": [\n\t\t\t\"php -r \\\"copy('.env.example', '.env');\\\"\",\n\t\t\t\"php artisan key:generate\"\n\t\t]\n\t},\n\t\"config\": {\n\t\t\"preferred-install\": \"dist\"\n\t}\n}\n"
  },
  {
    "path": "examples/server/php/config/app.php",
    "content": "<?php\n\nreturn [\n\n\t'token_secret' => 'some random string',\n\t'facebook_secret' => '',\n\t'foursquare_secret' => '',\n\t'google_secret' => '',\n\t'github_secret' => '',\n\t'instagram_secret' => '',\n\t'linkedin_secret' => '',\n\t'live_secret' => '',\n\t'yahoo_secret' => '',\n\t'twitter_key' => '',\n\t'twitter_secret' => '',\n\n\n\t/*\n    |--------------------------------------------------------------------------\n    | Application Environment\n    |--------------------------------------------------------------------------\n    |\n    | This value determines the \"environment\" your application is currently\n    | running in. This may determine how you prefer to configure various\n    | services your application utilizes. Set this in your \".env\" file.\n    |\n    */\n\n\t'env' => env('APP_ENV', 'development'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Application Debug Mode\n\t|--------------------------------------------------------------------------\n\t|\n\t| When your application is in debug mode, detailed error messages with\n\t| stack traces will be shown on every error that occurs within your\n\t| application. If disabled, a simple generic error page is shown.\n\t|\n\t*/\n\n\t'debug' => env('APP_DEBUG', true),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Application URL\n\t|--------------------------------------------------------------------------\n\t|\n\t| This URL is used by the console to properly generate URLs when using\n\t| the Artisan command line tool. You should set this to the root of\n\t| your application so that it is used when running Artisan tasks.\n\t|\n\t*/\n\n\t'url' => 'http://localhost',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Application Timezone\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may specify the default timezone for your application, which\n\t| will be used by the PHP date and date-time functions. We have gone\n\t| ahead and set this to a sensible default for you out of the box.\n\t|\n\t*/\n\n\t'timezone' => 'UTC',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Application Locale Configuration\n\t|--------------------------------------------------------------------------\n\t|\n\t| The application locale determines the default locale that will be used\n\t| by the translation service provider. You are free to set this value\n\t| to any of the locales which will be supported by the application.\n\t|\n\t*/\n\n\t'locale' => 'en',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Application Fallback Locale\n\t|--------------------------------------------------------------------------\n\t|\n\t| The fallback locale determines the locale to use when the current one\n\t| is not available. You may change the value to correspond to any of\n\t| the language folders that are provided through your application.\n\t|\n\t*/\n\n\t'fallback_locale' => 'en',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Encryption Key\n\t|--------------------------------------------------------------------------\n\t|\n\t| This key is used by the Illuminate encrypter service and should be set\n\t| to a random, 32 character string, otherwise these encrypted strings\n\t| will not be safe. Please do this before deploying an application!\n\t|\n\t*/\n\n\t'key' => env('APP_KEY', 'SomeRandomString'),\n\n\t'cipher' => MCRYPT_RIJNDAEL_128,\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Logging Configuration\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may configure the log settings for your application. Out of\n\t| the box, Laravel uses the Monolog PHP logging library. This gives\n\t| you a variety of powerful log handlers / formatters to utilize.\n\t|\n\t| Available Settings: \"single\", \"daily\", \"syslog\", \"errorlog\"\n\t|\n\t*/\n\n\t'log' => 'daily',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Autoloaded Service Providers\n\t|--------------------------------------------------------------------------\n\t|\n\t| The service providers listed here will be automatically loaded on the\n\t| request to your application. Feel free to add your own services to\n\t| this array to grant expanded functionality to your applications.\n\t|\n\t*/\n\n\t'providers' => [\n\n\t\t/*\n\t\t * Laravel Framework Service Providers...\n\t\t */\n\t\tIlluminate\\Auth\\AuthServiceProvider::class,\n\t\tIlluminate\\Broadcasting\\BroadcastServiceProvider::class,\n\t\tIlluminate\\Bus\\BusServiceProvider::class,\n\t\tIlluminate\\Cache\\CacheServiceProvider::class,\n\t\tIlluminate\\Foundation\\Providers\\ConsoleSupportServiceProvider::class,\n\t\tIlluminate\\Cookie\\CookieServiceProvider::class,\n\t\tIlluminate\\Database\\DatabaseServiceProvider::class,\n\t\tIlluminate\\Encryption\\EncryptionServiceProvider::class,\n\t\tIlluminate\\Filesystem\\FilesystemServiceProvider::class,\n\t\tIlluminate\\Foundation\\Providers\\FoundationServiceProvider::class,\n\t\tIlluminate\\Hashing\\HashServiceProvider::class,\n\t\tIlluminate\\Mail\\MailServiceProvider::class,\n\t\tIlluminate\\Pagination\\PaginationServiceProvider::class,\n\t\tIlluminate\\Pipeline\\PipelineServiceProvider::class,\n\t\tIlluminate\\Queue\\QueueServiceProvider::class,\n\t\tIlluminate\\Redis\\RedisServiceProvider::class,\n\t\tIlluminate\\Auth\\Passwords\\PasswordResetServiceProvider::class,\n\t\tIlluminate\\Session\\SessionServiceProvider::class,\n\t\tIlluminate\\Translation\\TranslationServiceProvider::class,\n\t\tIlluminate\\Validation\\ValidationServiceProvider::class,\n\t\tIlluminate\\View\\ViewServiceProvider::class,\n\n\t\t/*\n         * Application Service Providers...\n         */\n\t\tApp\\Providers\\AppServiceProvider::class,\n\t\tApp\\Providers\\AuthServiceProvider::class,\n\t\tApp\\Providers\\EventServiceProvider::class,\n\t\tApp\\Providers\\RouteServiceProvider::class,\n\n\t],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Class Aliases\n\t|--------------------------------------------------------------------------\n\t|\n\t| This array of class aliases will be registered when this application\n\t| is started. However, feel free to register as many as you wish as\n\t| the aliases are \"lazy\" loaded so they don't hinder performance.\n\t|\n\t*/\n\n\t'aliases' => [\n\n\t\t'App'       => Illuminate\\Support\\Facades\\App::class,\n\t\t'Artisan'   => Illuminate\\Support\\Facades\\Artisan::class,\n\t\t'AuthProvider'      => Illuminate\\Support\\Facades\\Auth::class,\n\t\t'Blade'     => Illuminate\\Support\\Facades\\Blade::class,\n\t\t'Cache'     => Illuminate\\Support\\Facades\\Cache::class,\n\t\t'Config'    => Illuminate\\Support\\Facades\\Config::class,\n\t\t'Cookie'    => Illuminate\\Support\\Facades\\Cookie::class,\n\t\t'Crypt'     => Illuminate\\Support\\Facades\\Crypt::class,\n\t\t'DB'        => Illuminate\\Support\\Facades\\DB::class,\n\t\t'Eloquent'  => Illuminate\\Database\\Eloquent\\Model::class,\n\t\t'Event'     => Illuminate\\Support\\Facades\\Event::class,\n\t\t'File'      => Illuminate\\Support\\Facades\\File::class,\n\t\t'Gate'      => Illuminate\\Support\\Facades\\Gate::class,\n\t\t'Hash'      => Illuminate\\Support\\Facades\\Hash::class,\n\t\t'Lang'      => Illuminate\\Support\\Facades\\Lang::class,\n\t\t'Log'       => Illuminate\\Support\\Facades\\Log::class,\n\t\t'Mail'      => Illuminate\\Support\\Facades\\Mail::class,\n\t\t'Password'  => Illuminate\\Support\\Facades\\Password::class,\n\t\t'Queue'     => Illuminate\\Support\\Facades\\Queue::class,\n\t\t'Redirect'  => Illuminate\\Support\\Facades\\Redirect::class,\n\t\t'Redis'     => Illuminate\\Support\\Facades\\Redis::class,\n\t\t'Request'   => Illuminate\\Support\\Facades\\Request::class,\n\t\t'Response'  => Illuminate\\Support\\Facades\\Response::class,\n\t\t'Route'     => Illuminate\\Support\\Facades\\Route::class,\n\t\t'Schema'    => Illuminate\\Support\\Facades\\Schema::class,\n\t\t'Session'   => Illuminate\\Support\\Facades\\Session::class,\n\t\t'Storage'   => Illuminate\\Support\\Facades\\Storage::class,\n\t\t'URL'       => Illuminate\\Support\\Facades\\URL::class,\n\t\t'Validator' => Illuminate\\Support\\Facades\\Validator::class,\n\t\t'View'      => Illuminate\\Support\\Facades\\View::class,\n\n\t],\n\n];\n"
  },
  {
    "path": "examples/server/php/config/auth.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n    |--------------------------------------------------------------------------\n    | Authentication Defaults\n    |--------------------------------------------------------------------------\n    |\n    | This option controls the default authentication \"guard\" and password\n    | reset options for your application. You may change these defaults\n    | as required, but they're a perfect start for most applications.\n    |\n    */\n\n\t\t'defaults' => [\n\t\t\t\t'guard' => 'web',\n\t\t\t\t'passwords' => 'users',\n\t\t],\n\n\t/*\n    |--------------------------------------------------------------------------\n    | Authentication Guards\n    |--------------------------------------------------------------------------\n    |\n    | Next, you may define every authentication guard for your application.\n    | Of course, a great default configuration has been defined for you\n    | here which uses session storage and the Eloquent user provider.\n    |\n    | All authentication drivers have a user provider. This defines how the\n    | users are actually retrieved out of your database or other storage\n    | mechanisms used by this application to persist your user's data.\n    |\n    | Supported: \"session\", \"token\"\n    |\n    */\n\n\t\t'guards' => [\n\t\t\t\t'web' => [\n\t\t\t\t\t\t'driver' => 'session',\n\t\t\t\t\t\t'provider' => 'users',\n\t\t\t\t],\n\n\t\t\t\t'api' => [\n\t\t\t\t\t\t'driver' => 'token',\n\t\t\t\t\t\t'provider' => 'users',\n\t\t\t\t],\n\t\t],\n\n\t/*\n    |--------------------------------------------------------------------------\n    | User Providers\n    |--------------------------------------------------------------------------\n    |\n    | All authentication drivers have a user provider. This defines how the\n    | users are actually retrieved out of your database or other storage\n    | mechanisms used by this application to persist your user's data.\n    |\n    | If you have multiple user tables or models you may configure multiple\n    | sources which represent each model / table. These sources may then\n    | be assigned to any extra authentication guards you have defined.\n    |\n    | Supported: \"database\", \"eloquent\"\n    |\n    */\n\n\t\t'providers' => [\n\t\t\t\t'users' => [\n\t\t\t\t\t\t'driver' => 'eloquent',\n\t\t\t\t\t\t'model' => App\\User::class,\n\t\t\t\t],\n\n\t\t\t// 'users' => [\n\t\t\t//     'driver' => 'database',\n\t\t\t//     'table' => 'users',\n\t\t\t// ],\n\t\t],\n\n\t/*\n    |--------------------------------------------------------------------------\n    | Resetting Passwords\n    |--------------------------------------------------------------------------\n    |\n    | Here you may set the options for resetting passwords including the view\n    | that is your password reset e-mail. You may also set the name of the\n    | table that maintains all of the reset tokens for your application.\n    |\n    | You may specify multiple password reset configurations if you have more\n    | than one user table or model in the application and you want to have\n    | separate password reset settings based on the specific user types.\n    |\n    | The expire time is the number of minutes that the reset token should be\n    | considered valid. This security feature keeps tokens short-lived so\n    | they have less time to be guessed. You may change this as needed.\n    |\n    */\n\n\t\t'passwords' => [\n\t\t\t\t'users' => [\n\t\t\t\t\t\t'provider' => 'users',\n\t\t\t\t\t\t'email' => 'auth.emails.password',\n\t\t\t\t\t\t'table' => 'password_resets',\n\t\t\t\t\t\t'expire' => 60,\n\t\t\t\t],\n\t\t],\n\n];"
  },
  {
    "path": "examples/server/php/config/cache.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Default Cache Store\n\t|--------------------------------------------------------------------------\n\t|\n\t| This option controls the default cache connection that gets used while\n\t| using this caching library. This connection is used when another is\n\t| not explicitly specified when executing a given caching function.\n\t|\n\t*/\n\n\t'default' => env('CACHE_DRIVER', 'file'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Cache Stores\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may define all of the cache \"stores\" for your application as\n\t| well as their drivers. You may even define multiple stores for the\n\t| same cache driver to group types of items stored in your caches.\n\t|\n\t*/\n\n\t'stores' => [\n\n\t\t'apc' => [\n\t\t\t'driver' => 'apc'\n\t\t],\n\n\t\t'array' => [\n\t\t\t'driver' => 'array'\n\t\t],\n\n\t\t'database' => [\n\t\t\t'driver' => 'database',\n\t\t\t'table'  => 'cache',\n\t\t\t'connection' => null,\n\t\t],\n\n\t\t'file' => [\n\t\t\t'driver' => 'file',\n\t\t\t'path'   => storage_path().'/framework/cache',\n\t\t],\n\n\t\t'memcached' => [\n\t\t\t'driver'  => 'memcached',\n\t\t\t'servers' => [\n\t\t\t\t[\n\t\t\t\t\t'host' => '127.0.0.1', 'port' => 11211, 'weight' => 100\n\t\t\t\t],\n\t\t\t],\n\t\t],\n\n\t\t'redis' => [\n\t\t\t'driver' => 'redis',\n\t\t\t'connection' => 'default',\n\t\t],\n\n\t],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Cache Key Prefix\n\t|--------------------------------------------------------------------------\n\t|\n\t| When utilizing a RAM based store such as APC or Memcached, there might\n\t| be other applications utilizing the same cache. So, we'll specify a\n\t| value to get prefixed to all our keys so we can avoid collisions.\n\t|\n\t*/\n\n\t'prefix' => 'laravel',\n\n];\n"
  },
  {
    "path": "examples/server/php/config/compile.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Additional Compiled Classes\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may specify additional classes to include in the compiled file\n\t| generated by the `artisan optimize` command. These should be classes\n\t| that are included on basically every request into the application.\n\t|\n\t*/\n\n\t'files' => [\n\n\t\trealpath(__DIR__.'/../app/Providers/AppServiceProvider.php'),\n\t\trealpath(__DIR__.'/../app/Providers/BusServiceProvider.php'),\n\t\trealpath(__DIR__.'/../app/Providers/ConfigServiceProvider.php'),\n\t\trealpath(__DIR__.'/../app/Providers/EventServiceProvider.php'),\n\t\trealpath(__DIR__.'/../app/Providers/RouteServiceProvider.php'),\n\n\t],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Compiled File Providers\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may list service providers which define a \"compiles\" function\n\t| that returns additional files that should be compiled, providing an\n\t| easy way to get common files from any packages you are utilizing.\n\t|\n\t*/\n\n\t'providers' => [\n\t\t//\n\t],\n\n];\n"
  },
  {
    "path": "examples/server/php/config/database.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| PDO Fetch Style\n\t|--------------------------------------------------------------------------\n\t|\n\t| By default, database results will be returned as instances of the PHP\n\t| stdClass object; however, you may desire to retrieve records in an\n\t| array format for simplicity. Here you can tweak the fetch style.\n\t|\n\t*/\n\n\t'fetch' => PDO::FETCH_CLASS,\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Default Database Connection Name\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may specify which of the database connections below you wish\n\t| to use as your default connection for all database work. Of course\n\t| you may use many connections at once using the Database library.\n\t|\n\t*/\n\n\t'default' => 'sqlite',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Database Connections\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here are each of the database connections setup for your application.\n\t| Of course, examples of configuring each database platform that is\n\t| supported by Laravel is shown below to make development simple.\n\t|\n\t|\n\t| All database work in Laravel is done through the PHP PDO facilities\n\t| so make sure you have the driver for your particular database of\n\t| choice installed on your machine before you begin development.\n\t|\n\t*/\n\n\t'connections' => [\n\n\t\t'sqlite' => [\n\t\t\t'driver'   => 'sqlite',\n\t\t\t'database' => storage_path().'/database.sqlite',\n\t\t\t'prefix'   => '',\n\t\t],\n\n\t\t'mysql' => [\n\t\t\t'driver'    => 'mysql',\n\t\t\t'host'      => env('DB_HOST', 'localhost'),\n\t\t\t'database'  => env('DB_DATABASE', 'forge'),\n\t\t\t'username'  => env('DB_USERNAME', 'forge'),\n\t\t\t'password'  => env('DB_PASSWORD', ''),\n\t\t\t'charset'   => 'utf8',\n\t\t\t'collation' => 'utf8_unicode_ci',\n\t\t\t'prefix'    => '',\n\t\t\t'strict'    => false,\n\t\t],\n\n\t\t'pgsql' => [\n\t\t\t'driver'   => 'pgsql',\n\t\t\t'host'     => env('DB_HOST', 'localhost'),\n\t\t\t'database' => env('DB_DATABASE', 'forge'),\n\t\t\t'username' => env('DB_USERNAME', 'forge'),\n\t\t\t'password' => env('DB_PASSWORD', ''),\n\t\t\t'charset'  => 'utf8',\n\t\t\t'prefix'   => '',\n\t\t\t'schema'   => 'public',\n\t\t],\n\n\t\t'sqlsrv' => [\n\t\t\t'driver'   => 'sqlsrv',\n\t\t\t'host'     => env('DB_HOST', 'localhost'),\n\t\t\t'database' => env('DB_DATABASE', 'forge'),\n\t\t\t'username' => env('DB_USERNAME', 'forge'),\n\t\t\t'password' => env('DB_PASSWORD', ''),\n\t\t\t'prefix'   => '',\n\t\t],\n\n\t],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Migration Repository Table\n\t|--------------------------------------------------------------------------\n\t|\n\t| This table keeps track of all the migrations that have already run for\n\t| your application. Using this information, we can determine which of\n\t| the migrations on disk haven't actually been run in the database.\n\t|\n\t*/\n\n\t'migrations' => 'migrations',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Redis Databases\n\t|--------------------------------------------------------------------------\n\t|\n\t| Redis is an open source, fast, and advanced key-value store that also\n\t| provides a richer set of commands than a typical key-value systems\n\t| such as APC or Memcached. Laravel makes it easy to dig right in.\n\t|\n\t*/\n\n\t'redis' => [\n\n\t\t'cluster' => false,\n\n\t\t'default' => [\n\t\t\t'host'     => '127.0.0.1',\n\t\t\t'port'     => 6379,\n\t\t\t'database' => 0,\n\t\t],\n\n\t],\n\n];\n"
  },
  {
    "path": "examples/server/php/config/filesystems.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Default Filesystem Disk\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may specify the default filesystem disk that should be used\n\t| by the framework. A \"local\" driver, as well as a variety of cloud\n\t| based drivers are available for your choosing. Just store away!\n\t|\n\t| Supported: \"local\", \"s3\", \"rackspace\"\n\t|\n\t*/\n\n\t'default' => 'local',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Default Cloud Filesystem Disk\n\t|--------------------------------------------------------------------------\n\t|\n\t| Many applications store files both locally and in the cloud. For this\n\t| reason, you may specify a default \"cloud\" driver here. This driver\n\t| will be bound as the Cloud disk implementation in the container.\n\t|\n\t*/\n\n\t'cloud' => 's3',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Filesystem Disks\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may configure as many filesystem \"disks\" as you wish, and you\n\t| may even configure multiple disks of the same driver. Defaults have\n\t| been setup for each driver as an example of the required options.\n\t|\n\t*/\n\n\t'disks' => [\n\n\t\t'local' => [\n\t\t\t'driver' => 'local',\n\t\t\t'root'   => storage_path().'/app',\n\t\t],\n\n\t\t's3' => [\n\t\t\t'driver' => 's3',\n\t\t\t'key'    => 'your-key',\n\t\t\t'secret' => 'your-secret',\n\t\t\t'region' => 'your-region',\n\t\t\t'bucket' => 'your-bucket',\n\t\t],\n\n\t\t'rackspace' => [\n\t\t\t'driver'    => 'rackspace',\n\t\t\t'username'  => 'your-username',\n\t\t\t'key'       => 'your-key',\n\t\t\t'container' => 'your-container',\n\t\t\t'endpoint'  => 'https://identity.api.rackspacecloud.com/v2.0/',\n\t\t\t'region'    => 'IAD',\n\t\t\t'url_type'  => 'publicURL'\n\t\t],\n\n\t],\n\n];\n"
  },
  {
    "path": "examples/server/php/config/mail.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Mail Driver\n\t|--------------------------------------------------------------------------\n\t|\n\t| Laravel supports both SMTP and PHP's \"mail\" function as drivers for the\n\t| sending of e-mail. You may specify which one you're using throughout\n\t| your application here. By default, Laravel is setup for SMTP mail.\n\t|\n\t| Supported: \"smtp\", \"mail\", \"sendmail\", \"mailgun\", \"mandrill\", \"log\"\n\t|\n\t*/\n\n\t'driver' => env('MAIL_DRIVER', 'smtp'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| SMTP Host Address\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may provide the host address of the SMTP server used by your\n\t| applications. A default option is provided that is compatible with\n\t| the Mailgun mail service which will provide reliable deliveries.\n\t|\n\t*/\n\n\t'host' => env('MAIL_HOST', 'smtp.mailgun.org'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| SMTP Host Port\n\t|--------------------------------------------------------------------------\n\t|\n\t| This is the SMTP port used by your application to deliver e-mails to\n\t| users of the application. Like the host we have set this value to\n\t| stay compatible with the Mailgun e-mail application by default.\n\t|\n\t*/\n\n\t'port' => env('MAIL_PORT', 587),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Global \"From\" Address\n\t|--------------------------------------------------------------------------\n\t|\n\t| You may wish for all e-mails sent by your application to be sent from\n\t| the same address. Here, you may specify a name and address that is\n\t| used globally for all e-mails that are sent by your application.\n\t|\n\t*/\n\n\t'from' => ['address' => null, 'name' => null],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| E-Mail Encryption Protocol\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may specify the encryption protocol that should be used when\n\t| the application send e-mail messages. A sensible default using the\n\t| transport layer security protocol should provide great security.\n\t|\n\t*/\n\n\t'encryption' => 'tls',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| SMTP Server Username\n\t|--------------------------------------------------------------------------\n\t|\n\t| If your SMTP server requires a username for authentication, you should\n\t| set it here. This will get used to authenticate with your server on\n\t| connection. You may also set the \"password\" value below this one.\n\t|\n\t*/\n\n\t'username' => env('MAIL_USERNAME'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| SMTP Server Password\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may set the password required by your SMTP server to send out\n\t| messages from your application. This will be given to the server on\n\t| connection so that the application will be able to send messages.\n\t|\n\t*/\n\n\t'password' => env('MAIL_PASSWORD'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Sendmail System Path\n\t|--------------------------------------------------------------------------\n\t|\n\t| When using the \"sendmail\" driver to send e-mails, we will need to know\n\t| the path to where Sendmail lives on this server. A default path has\n\t| been provided here, which will work well on most of your systems.\n\t|\n\t*/\n\n\t'sendmail' => '/usr/sbin/sendmail -bs',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Mail \"Pretend\"\n\t|--------------------------------------------------------------------------\n\t|\n\t| When this option is enabled, e-mail will not actually be sent over the\n\t| web and will instead be written to your application's logs files so\n\t| you may inspect the message. This is great for local development.\n\t|\n\t*/\n\n\t'pretend' => false,\n\n];\n"
  },
  {
    "path": "examples/server/php/config/queue.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Default Queue Driver\n\t|--------------------------------------------------------------------------\n\t|\n\t| The Laravel queue API supports a variety of back-ends via an unified\n\t| API, giving you convenient access to each back-end using the same\n\t| syntax for each one. Here you may set the default queue driver.\n\t|\n\t| Supported: \"null\", \"sync\", \"database\", \"beanstalkd\",\n\t|            \"sqs\", \"iron\", \"redis\"\n\t|\n\t*/\n\n\t'default' => env('QUEUE_DRIVER', 'sync'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Queue Connections\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may configure the connection information for each server that\n\t| is used by your application. A default configuration has been added\n\t| for each back-end shipped with Laravel. You are free to add more.\n\t|\n\t*/\n\n\t'connections' => [\n\n\t\t'sync' => [\n\t\t\t'driver' => 'sync',\n\t\t],\n\n\t\t'database' => [\n\t\t\t'driver' => 'database',\n\t\t\t'table' => 'jobs',\n\t\t\t'queue' => 'default',\n\t\t\t'expire' => 60,\n\t\t],\n\n\t\t'beanstalkd' => [\n\t\t\t'driver' => 'beanstalkd',\n\t\t\t'host'   => 'localhost',\n\t\t\t'queue'  => 'default',\n\t\t\t'ttr'    => 60,\n\t\t],\n\n\t\t'sqs' => [\n\t\t\t'driver' => 'sqs',\n\t\t\t'key'    => 'your-public-key',\n\t\t\t'secret' => 'your-secret-key',\n\t\t\t'queue'  => 'your-queue-url',\n\t\t\t'region' => 'us-east-1',\n\t\t],\n\n\t\t'iron' => [\n\t\t\t'driver'  => 'iron',\n\t\t\t'host'    => 'mq-aws-us-east-1.iron.io',\n\t\t\t'token'   => 'your-token',\n\t\t\t'project' => 'your-project-id',\n\t\t\t'queue'   => 'your-queue-name',\n\t\t\t'encrypt' => true,\n\t\t],\n\n\t\t'redis' => [\n\t\t\t'driver' => 'redis',\n\t\t\t'queue'  => 'default',\n\t\t\t'expire' => 60,\n\t\t],\n\n\t],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Failed Queue Jobs\n\t|--------------------------------------------------------------------------\n\t|\n\t| These options configure the behavior of failed queue job logging so you\n\t| can control which database and table are used to store the jobs that\n\t| have failed. You may change them to any database / table you wish.\n\t|\n\t*/\n\n\t'failed' => [\n\t\t'database' => 'mysql', 'table' => 'failed_jobs',\n\t],\n\n];\n"
  },
  {
    "path": "examples/server/php/config/services.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Third Party Services\n\t|--------------------------------------------------------------------------\n\t|\n\t| This file is for storing the credentials for third party services such\n\t| as Stripe, Mailgun, Mandrill, and others. This file provides a sane\n\t| default location for this type of information, allowing packages\n\t| to have a conventional place to find your various credentials.\n\t|\n\t*/\n\n\t'mailgun' => [\n\t\t'domain' => '',\n\t\t'secret' => '',\n\t],\n\n\t'mandrill' => [\n\t\t'secret' => '',\n\t],\n\n\t'ses' => [\n\t\t'key' => '',\n\t\t'secret' => '',\n\t\t'region' => 'us-east-1',\n\t],\n\n\t'stripe' => [\n\t\t'model'  => 'App\\User',\n\t\t'key' => '',\n\t\t'secret' => '',\n\t],\n\n];\n"
  },
  {
    "path": "examples/server/php/config/session.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Default Session Driver\n\t|--------------------------------------------------------------------------\n\t|\n\t| This option controls the default session \"driver\" that will be used on\n\t| requests. By default, we will use the lightweight native driver but\n\t| you may specify any of the other wonderful drivers provided here.\n\t|\n\t| Supported: \"file\", \"cookie\", \"database\", \"apc\",\n\t|            \"memcached\", \"redis\", \"array\"\n\t|\n\t*/\n\n\t'driver' => env('SESSION_DRIVER', 'file'),\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Lifetime\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may specify the number of minutes that you wish the session\n\t| to be allowed to remain idle before it expires. If you want them\n\t| to immediately expire on the browser closing, set that option.\n\t|\n\t*/\n\n\t'lifetime' => 120,\n\n\t'expire_on_close' => false,\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Encryption\n\t|--------------------------------------------------------------------------\n\t|\n\t| This option allows you to easily specify that all of your session data\n\t| should be encrypted before it is stored. All encryption will be run\n\t| automatically by Laravel and you can use the Session like normal.\n\t|\n\t*/\n\n\t'encrypt' => false,\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session File Location\n\t|--------------------------------------------------------------------------\n\t|\n\t| When using the native session driver, we need a location where session\n\t| files may be stored. A default has been set for you but a different\n\t| location may be specified. This is only needed for file sessions.\n\t|\n\t*/\n\n\t'files' => storage_path().'/framework/sessions',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Database Connection\n\t|--------------------------------------------------------------------------\n\t|\n\t| When using the \"database\" or \"redis\" session drivers, you may specify a\n\t| connection that should be used to manage these sessions. This should\n\t| correspond to a connection in your database configuration options.\n\t|\n\t*/\n\n\t'connection' => null,\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Database Table\n\t|--------------------------------------------------------------------------\n\t|\n\t| When using the \"database\" session driver, you may specify the table we\n\t| should use to manage the sessions. Of course, a sensible default is\n\t| provided for you; however, you are free to change this as needed.\n\t|\n\t*/\n\n\t'table' => 'sessions',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Sweeping Lottery\n\t|--------------------------------------------------------------------------\n\t|\n\t| Some session drivers must manually sweep their storage location to get\n\t| rid of old sessions from storage. Here are the chances that it will\n\t| happen on a given request. By default, the odds are 2 out of 100.\n\t|\n\t*/\n\n\t'lottery' => [2, 100],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Cookie Name\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may change the name of the cookie used to identify a session\n\t| instance by ID. The name specified here will get used every time a\n\t| new session cookie is created by the framework for every driver.\n\t|\n\t*/\n\n\t'cookie' => 'laravel_session',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Cookie Path\n\t|--------------------------------------------------------------------------\n\t|\n\t| The session cookie path determines the path for which the cookie will\n\t| be regarded as available. Typically, this will be the root path of\n\t| your application but you are free to change this when necessary.\n\t|\n\t*/\n\n\t'path' => '/',\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Session Cookie Domain\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may change the domain of the cookie used to identify a session\n\t| in your application. This will determine which domains the cookie is\n\t| available to in your application. A sensible default has been set.\n\t|\n\t*/\n\n\t'domain' => null,\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| HTTPS Only Cookies\n\t|--------------------------------------------------------------------------\n\t|\n\t| By setting this option to true, session cookies will only be sent back\n\t| to the server if the browser has a HTTPS connection. This will keep\n\t| the cookie from being sent to you if it can not be done securely.\n\t|\n\t*/\n\n\t'secure' => false,\n\n];\n"
  },
  {
    "path": "examples/server/php/config/view.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| View Storage Paths\n\t|--------------------------------------------------------------------------\n\t|\n\t| Most templating systems load templates from disk. Here you may specify\n\t| an array of paths that should be checked for your views. Of course\n\t| the usual Laravel view path has already been registered for you.\n\t|\n\t*/\n\n\t'paths' => [\n\t\trealpath(base_path('resources/views'))\n\t],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Compiled View Path\n\t|--------------------------------------------------------------------------\n\t|\n\t| This option determines where all the compiled Blade templates will be\n\t| stored for your application. Typically, this is within the storage\n\t| directory. However, as usual, you are free to change this value.\n\t|\n\t*/\n\n\t'compiled' => realpath(storage_path().'/framework/views'),\n\n];\n"
  },
  {
    "path": "examples/server/php/database/.gitignore",
    "content": "*.sqlite\n"
  },
  {
    "path": "examples/server/php/database/migrations/.gitkeep",
    "content": ""
  },
  {
    "path": "examples/server/php/database/migrations/2015_04_18_080047_create_users_table.php",
    "content": "<?php\n\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Database\\Migrations\\Migration;\n\nclass CreateUsersTable extends Migration {\n\n\t/**\n\t * Run the migrations.\n\t *\n\t * @return void\n\t */\n\tpublic function up()\n\t{\n\t\tSchema::create('users', function(Blueprint $table)\n\t\t{\n\t\t\t$table->increments('id');\n\t\t\t$table->string('email')->nullable();\n\t\t\t$table->string('password')->nullable();\n\t\t\t$table->string('displayName')->nullable();\n\t\t\t$table->string('facebook')->nullable();\n\t\t\t$table->string('foursquare')->nullable();\n\t\t\t$table->string('instagram')->nullable();\n\t\t\t$table->string('github')->nullable();\n\t\t\t$table->string('google')->nullable();\n\t\t\t$table->string('linkedin')->nullable();\n\t\t\t$table->string('twitter')->nullable();\n\t\t\t$table->string('picture')->nullable();\n\t\t\t$table->timestamps();\n\t\t});\n\t}\n\n\t/**\n\t * Reverse the migrations.\n\t *\n\t * @return void\n\t */\n\tpublic function down()\n\t{\n\t\tSchema::drop('users');\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/database/seeds/.gitkeep",
    "content": ""
  },
  {
    "path": "examples/server/php/database/seeds/DatabaseSeeder.php",
    "content": "<?php\n\nuse Illuminate\\Database\\Seeder;\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass DatabaseSeeder extends Seeder {\n\n\t/**\n\t * Run the database seeds.\n\t *\n\t * @return void\n\t */\n\tpublic function run()\n\t{\n\t\tModel::unguard();\n\n\t\t// $this->call('UserTableSeeder');\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/gulpfile.js",
    "content": "var elixir = require('laravel-elixir');\n\n/*\n |--------------------------------------------------------------------------\n | Elixir Asset Management\n |--------------------------------------------------------------------------\n |\n | Elixir provides a clean, fluent API for defining some basic Gulp tasks\n | for your Laravel application. By default, we are compiling the Less\n | file for our application, as well as publishing vendor resources.\n |\n */\n\nelixir(function(mix) {\n    mix.less('app.less');\n});\n"
  },
  {
    "path": "examples/server/php/package.json",
    "content": "{\n  \"private\": true,\n  \"devDependencies\": {\n    \"gulp\": \"^3.8.8\",\n    \"laravel-elixir\": \"*\"\n  }\n}\n"
  },
  {
    "path": "examples/server/php/phpspec.yml",
    "content": "suites:\n    main:\n        namespace: App\n        psr4_prefix: App\n        src_path: app"
  },
  {
    "path": "examples/server/php/phpunit.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit backupGlobals=\"false\"\n         backupStaticAttributes=\"false\"\n         bootstrap=\"bootstrap/autoload.php\"\n         colors=\"true\"\n         convertErrorsToExceptions=\"true\"\n         convertNoticesToExceptions=\"true\"\n         convertWarningsToExceptions=\"true\"\n         processIsolation=\"false\"\n         stopOnFailure=\"false\"\n         syntaxCheck=\"false\">\n    <testsuites>\n        <testsuite name=\"Application Test Suite\">\n            <directory>./tests/</directory>\n        </testsuite>\n    </testsuites>\n    <php>\n        <env name=\"APP_ENV\" value=\"testing\"/>\n        <env name=\"CACHE_DRIVER\" value=\"array\"/>\n        <env name=\"SESSION_DRIVER\" value=\"array\"/>\n        <env name=\"QUEUE_DRIVER\" value=\"sync\"/>\n    </php>\n</phpunit>\n"
  },
  {
    "path": "examples/server/php/public/.htaccess",
    "content": "<IfModule mod_rewrite.c>\n    <IfModule mod_negotiation.c>\n        Options -MultiViews\n    </IfModule>\n\n    RewriteEngine On\n\n    # Redirect Trailing Slashes...\n    RewriteRule ^(.*)/$ /$1 [L,R=301]\n\n    # Handle Front Controller...\n    RewriteCond %{REQUEST_FILENAME} !-d\n    RewriteCond %{REQUEST_FILENAME} !-f\n    RewriteRule ^ index.php [L]\n\n    # Include Authorization header in a request\n    RewriteCond %{HTTP:Authorization} ^(.+)$\n    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]\n</IfModule>\n"
  },
  {
    "path": "examples/server/php/public/app.js",
    "content": "angular.module('MyApp', ['ngResource', 'ngMessages', 'ngAnimate', 'toastr', 'ui.router', 'satellizer'])\n  .config(function($stateProvider, $urlRouterProvider, $authProvider) {\n\n    /**\n     * Helper auth functions\n     */\n    var skipIfLoggedIn = function($q, $auth) {\n      var deferred = $q.defer();\n      if ($auth.isAuthenticated()) {\n        deferred.reject();\n      } else {\n        deferred.resolve();\n      }\n      return deferred.promise;\n    };\n\n    var loginRequired = function($q, $location, $auth) {\n      var deferred = $q.defer();\n      if ($auth.isAuthenticated()) {\n        deferred.resolve();\n      } else {\n        $location.path('/login');\n      }\n      return deferred.promise;\n    };\n\n    /**\n     * App routes\n     */\n    $stateProvider\n      .state('home', {\n        url: '/',\n        controller: 'HomeCtrl',\n        templateUrl: 'partials/home.html'\n      })\n      .state('login', {\n        url: '/login',\n        templateUrl: 'partials/login.html',\n        controller: 'LoginCtrl',\n        resolve: {\n          skipIfLoggedIn: skipIfLoggedIn\n        }\n      })\n      .state('signup', {\n        url: '/signup',\n        templateUrl: 'partials/signup.html',\n        controller: 'SignupCtrl',\n        resolve: {\n          skipIfLoggedIn: skipIfLoggedIn\n        }\n      })\n      .state('logout', {\n        url: '/logout',\n        template: null,\n        controller: 'LogoutCtrl'\n      })\n      .state('profile', {\n        url: '/profile',\n        templateUrl: 'partials/profile.html',\n        controller: 'ProfileCtrl',\n        resolve: {\n          loginRequired: loginRequired\n        }\n      });\n    $urlRouterProvider.otherwise('/');\n\n    /**\n     *  Satellizer config\n     */\n    $authProvider.facebook({\n      clientId: '603122136500203'\n    });\n\n    $authProvider.google({\n      clientId: 'YOUR_GOOGLE_CLIENT_ID'\n    });\n\n    $authProvider.github({\n      clientId: 'YOUR_GITHUB_CLIENT_ID'\n    });\n\n    $authProvider.linkedin({\n      clientId: 'YOUR_LINKEDIN_CLIENT_ID'\n    });\n\n    $authProvider.instagram({\n      clientId: 'YOUR_INSTAGRAM_CLIENT_ID'\n    });\n\n    $authProvider.yahoo({\n      clientId: 'YOUR_YAHOO_CLIENT_ID'\n    });\n\n    $authProvider.live({\n      clientId: 'YOUR_MICROSOFT_CLIENT_ID'\n    });\n\n    $authProvider.twitch({\n      clientId: 'YOUR_TWITCH_CLIENT_ID'\n    });\n\n    $authProvider.bitbucket({\n      clientId: 'YOUR_BITBUCKET_CLIENT_ID'\n    });\n\n    $authProvider.spotify({\n      clientId: 'YOUR_SPOTIFY_CLIENT_ID'\n    });\n\n    $authProvider.twitter({\n      url: '/auth/twitter'\n    });\n\n    $authProvider.oauth2({\n      name: 'foursquare',\n      url: '/auth/foursquare',\n      clientId: 'MTCEJ3NGW2PNNB31WOSBFDSAD4MTHYVAZ1UKIULXZ2CVFC2K',\n      redirectUri: window.location.origin || window.location.protocol + '//' + window.location.host,\n      authorizationEndpoint: 'https://foursquare.com/oauth2/authenticate'\n    });\n  });\n"
  },
  {
    "path": "examples/server/php/public/controllers/home.js",
    "content": "angular.module('MyApp')\n  .controller('HomeCtrl', function($scope, $http) {\n    $http.jsonp('https://api.github.com/repos/sahat/satellizer?callback=JSON_CALLBACK')\n      .success(function(data) {\n        if (data) {\n          if (data.data.stargazers_count) {\n            $scope.stars = data.data.stargazers_count;\n          }\n          if (data.data.forks) {\n            $scope.forks = data.data.forks;\n          }\n          if (data.data.open_issues) {\n            $scope.issues = data.data.open_issues;\n          }\n        }\n      });\n  });\n"
  },
  {
    "path": "examples/server/php/public/controllers/login.js",
    "content": "angular.module('MyApp')\n  .controller('LoginCtrl', function($scope, $location, $auth, toastr) {\n    $scope.login = function() {\n      $auth.login($scope.user)\n        .then(function() {\n          toastr.success('You have successfully signed in!');\n          $location.path('/');\n        })\n        .catch(function(error) {\n          toastr.error(error.data.message, error.status);\n        });\n    };\n    $scope.authenticate = function(provider) {\n      $auth.authenticate(provider)\n        .then(function() {\n          toastr.success('You have successfully signed in with ' + provider + '!');\n          $location.path('/');\n        })\n        .catch(function(error) {\n          if (error.message) {\n            // Satellizer promise reject error.\n            toastr.error(error.message);\n          } else if (error.data) {\n            // HTTP response error from server\n            toastr.error(error.data.message, error.status);\n          } else {\n            toastr.error(error);\n          }\n        });\n    };\n  });\n"
  },
  {
    "path": "examples/server/php/public/controllers/logout.js",
    "content": "angular.module('MyApp')\n  .controller('LogoutCtrl', function($location, $auth, toastr) {\n    if (!$auth.isAuthenticated()) { return; }\n    $auth.logout()\n      .then(function() {\n        toastr.info('You have been logged out');\n        $location.path('/');\n      });\n  });"
  },
  {
    "path": "examples/server/php/public/controllers/navbar.js",
    "content": "angular.module('MyApp')\n  .controller('NavbarCtrl', function($scope, $auth) {\n    $scope.isAuthenticated = function() {\n      return $auth.isAuthenticated();\n    };\n  });\n"
  },
  {
    "path": "examples/server/php/public/controllers/profile.js",
    "content": "angular.module('MyApp')\n  .controller('ProfileCtrl', function($scope, $auth, toastr, Account) {\n    $scope.getProfile = function() {\n      Account.getProfile()\n        .then(function(response) {\n          $scope.user = response.data;\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message, response.status);\n        });\n    };\n    $scope.updateProfile = function() {\n      Account.updateProfile($scope.user)\n        .then(function() {\n          toastr.success('Profile has been updated');\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message, response.status);\n        });\n    };\n    $scope.link = function(provider) {\n      $auth.link(provider)\n        .then(function() {\n          toastr.success('You have successfully linked a ' + provider + ' account');\n          $scope.getProfile();\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message, response.status);\n        });\n    };\n    $scope.unlink = function(provider) {\n      $auth.unlink(provider)\n        .then(function() {\n          toastr.info('You have unlinked a ' + provider + ' account');\n          $scope.getProfile();\n        })\n        .catch(function(response) {\n          toastr.error(response.data ? response.data.message : 'Could not unlink ' + provider + ' account', response.status);\n        });\n    };\n\n    $scope.getProfile();\n  });\n"
  },
  {
    "path": "examples/server/php/public/controllers/signup.js",
    "content": "angular.module('MyApp')\n  .controller('SignupCtrl', function($scope, $location, $auth, toastr) {\n    $scope.signup = function() {\n      $auth.signup($scope.user)\n        .then(function(response) {\n          $auth.setToken(response);\n          $location.path('/');\n          toastr.info('You have successfully created a new account and have been signed-in');\n        })\n        .catch(function(response) {\n          toastr.error(response.data.message);\n        });\n    };\n  });"
  },
  {
    "path": "examples/server/php/public/directives/passwordMatch.js",
    "content": "angular.module('MyApp')\n  .directive('passwordMatch', function() {\n    return {\n      require: 'ngModel',\n      scope: {\n        otherModelValue: '=passwordMatch'\n      },\n      link: function(scope, element, attributes, ngModel) {\n        ngModel.$validators.compareTo = function(modelValue) {\n          return modelValue === scope.otherModelValue;\n        };\n        scope.$watch('otherModelValue', function() {\n          ngModel.$validate();\n        });\n      }\n    };\n  });\n\n"
  },
  {
    "path": "examples/server/php/public/directives/passwordStrength.js",
    "content": "angular.module('MyApp')\n  .directive('passwordStrength', function() {\n    return {\n      restrict: 'A',\n      require: 'ngModel',\n      link: function(scope, element, attrs, ngModel) {\n        var indicator = element.children();\n        var dots = Array.prototype.slice.call(indicator.children());\n        var weakest = dots.slice(-1)[0];\n        var weak = dots.slice(-2);\n        var strong = dots.slice(-3);\n        var strongest = dots.slice(-4);\n\n        element.after(indicator);\n\n        element.bind('keyup', function() {\n          var matches = {\n                positive: {},\n                negative: {}\n              },\n              counts = {\n                positive: {},\n                negative: {}\n              },\n              tmp,\n              strength = 0,\n              letters = 'abcdefghijklmnopqrstuvwxyz',\n              numbers = '01234567890',\n              symbols = '\\\\!@#$%&/()=?¿',\n              strValue;\n\n          angular.forEach(dots, function(el) {\n            el.style.backgroundColor = '#ebeef1';\n          });\n          \n          if (ngModel.$viewValue) {\n            // Increase strength level\n            matches.positive.lower = ngModel.$viewValue.match(/[a-z]/g);\n            matches.positive.upper = ngModel.$viewValue.match(/[A-Z]/g);\n            matches.positive.numbers = ngModel.$viewValue.match(/\\d/g);\n            matches.positive.symbols = ngModel.$viewValue.match(/[$-/:-?{-~!^_`\\[\\]]/g);\n            matches.positive.middleNumber = ngModel.$viewValue.slice(1, -1).match(/\\d/g);\n            matches.positive.middleSymbol = ngModel.$viewValue.slice(1, -1).match(/[$-/:-?{-~!^_`\\[\\]]/g);\n\n            counts.positive.lower = matches.positive.lower ? matches.positive.lower.length : 0;\n            counts.positive.upper = matches.positive.upper ? matches.positive.upper.length : 0;\n            counts.positive.numbers = matches.positive.numbers ? matches.positive.numbers.length : 0;\n            counts.positive.symbols = matches.positive.symbols ? matches.positive.symbols.length : 0;\n\n            counts.positive.numChars = ngModel.$viewValue.length;\n            tmp += (counts.positive.numChars >= 8) ? 1 : 0;\n\n            counts.positive.requirements = (tmp >= 3) ? tmp : 0;\n            counts.positive.middleNumber = matches.positive.middleNumber ? matches.positive.middleNumber.length : 0;\n            counts.positive.middleSymbol = matches.positive.middleSymbol ? matches.positive.middleSymbol.length : 0;\n\n            // Decrease strength level\n            matches.negative.consecLower = ngModel.$viewValue.match(/(?=([a-z]{2}))/g);\n            matches.negative.consecUpper = ngModel.$viewValue.match(/(?=([A-Z]{2}))/g);\n            matches.negative.consecNumbers = ngModel.$viewValue.match(/(?=(\\d{2}))/g);\n            matches.negative.onlyNumbers = ngModel.$viewValue.match(/^[0-9]*$/g);\n            matches.negative.onlyLetters = ngModel.$viewValue.match(/^([a-z]|[A-Z])*$/g);\n\n            counts.negative.consecLower = matches.negative.consecLower ? matches.negative.consecLower.length : 0;\n            counts.negative.consecUpper = matches.negative.consecUpper ? matches.negative.consecUpper.length : 0;\n            counts.negative.consecNumbers = matches.negative.consecNumbers ? matches.negative.consecNumbers.length : 0;\n\n            // Calculations\n            strength += counts.positive.numChars * 4;\n            if (counts.positive.upper) {\n              strength += (counts.positive.numChars - counts.positive.upper) * 2;\n            }\n            if (counts.positive.lower) {\n              strength += (counts.positive.numChars - counts.positive.lower) * 2;\n            }\n            if (counts.positive.upper || counts.positive.lower) {\n              strength += counts.positive.numbers * 4;\n            }\n            strength += counts.positive.symbols * 6;\n            strength += (counts.positive.middleSymbol + counts.positive.middleNumber) * 2;\n            strength += counts.positive.requirements * 2;\n\n            strength -= counts.negative.consecLower * 2;\n            strength -= counts.negative.consecUpper * 2;\n            strength -= counts.negative.consecNumbers * 2;\n\n            if (matches.negative.onlyNumbers) {\n              strength -= counts.positive.numChars;\n            }\n            if (matches.negative.onlyLetters) {\n              strength -= counts.positive.numChars;\n            }\n\n            strength = Math.max(0, Math.min(100, Math.round(strength)));\n\n            if (strength > 85) {\n              angular.forEach(strongest, function(el) {\n                el.style.backgroundColor = '#008cdd';\n              });\n            } else if (strength > 65) {\n              angular.forEach(strong, function(el) {\n                el.style.backgroundColor = '#6ead09';\n              });\n            } else if (strength > 30) {\n              angular.forEach(weak, function(el) {\n                el.style.backgroundColor = '#e09115';\n              });\n            } else {\n              weakest.style.backgroundColor = '#e01414';\n            }\n          }\n        });\n      },\n      template: '<span class=\"password-strength-indicator\"><span></span><span></span><span></span><span></span></span>'\n    };\n  });"
  },
  {
    "path": "examples/server/php/public/index.html",
    "content": "<!DOCTYPE html>\n<html ng-app=\"MyApp\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n  <title>Satellizer</title>\n  <link href=\"favicon.png\" rel=\"shortcut icon\">\n  <link href=\"//fonts.googleapis.com/css?family=Roboto|Montserrat:400,700|Open+Sans:400,300,600\" rel=\"stylesheet\">\n  <link href=\"//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n  <link href=\"//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css\" rel=\"stylesheet\">\n  <link href=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n  <link href=\"//cdn.jsdelivr.net/animatecss/3.2.0/animate.css\" rel=\"stylesheet\">\n  <link href=\"/stylesheets/angular-toastr.css\" rel=\"stylesheet\">\n  <link href=\"/stylesheets/styles.css\" rel=\"stylesheet\">\n</head>\n<body>\n<div ng-controller=\"NavbarCtrl\" class=\"navbar navbar-default navbar-static-top\">\n  <div class=\"navbar-header\">\n    <a class=\"navbar-brand\" href=\"/\"><i class=\"ion-ios7-pulse-strong\"></i> Satellizer</a>\n  </div>\n  <ul class=\"nav navbar-nav\">\n    <li><a href=\"/#/\">Home</a></li>\n    <li ng-if=\"isAuthenticated()\"><a href=\"/#/profile\">Profile</a></li>\n  </ul>\n  <ul ng-if=\"!isAuthenticated()\" class=\"nav navbar-nav pull-right\">\n    <li><a href=\"/#/login\">Login</a></li>\n    <li><a href=\"/#/signup\">Sign up</a></li>\n  </ul>\n  <ul ng-if=\"isAuthenticated()\" class=\"nav navbar-nav pull-right\">\n    <li><a href=\"/#/logout\">Logout</a></li>\n  </ul>\n</div>\n\n<div ui-view></div>\n\n<!-- Third-party Libraries -->\n<script src=\"/vendor/angular.js\"></script>\n<script src=\"/vendor/angular-animate.js\"></script>\n<script src=\"/vendor/angular-messages.js\"></script>\n<script src=\"/vendor/angular-resource.js\"></script>\n<script src=\"/vendor/angular-sanitize.js\"></script>\n<script src=\"/vendor/angular-ui-router.js\"></script>\n<script src=\"/vendor/angular-toastr.tpls.js\"></script>\n<script src=\"/vendor/satellizer.js\"></script>\n\n<!-- Application Code -->\n<script src=\"/app.js\"></script>\n<script src=\"/directives/passwordStrength.js\"></script>\n<script src=\"/directives/passwordMatch.js\"></script>\n<script src=\"/controllers/home.js\"></script>\n<script src=\"/controllers/login.js\"></script>\n<script src=\"/controllers/signup.js\"></script>\n<script src=\"/controllers/logout.js\"></script>\n<script src=\"/controllers/profile.js\"></script>\n<script src=\"/controllers/navbar.js\"></script>\n<script src=\"/services/account.js\"></script>\n</body>\n</html>\n"
  },
  {
    "path": "examples/server/php/public/index.php",
    "content": "<?php\n/**\n * Laravel - A PHP Framework For Web Artisans\n *\n * @package  Laravel\n * @author   Taylor Otwell <taylorotwell@gmail.com>\n */\n\n/*\n|--------------------------------------------------------------------------\n| Register The Auto Loader\n|--------------------------------------------------------------------------\n|\n| Composer provides a convenient, automatically generated class loader for\n| our application. We just need to utilize it! We'll simply require it\n| into the script here so that we don't have to worry about manual\n| loading any of our classes later on. It feels nice to relax.\n|\n*/\n\nrequire __DIR__.'/../bootstrap/autoload.php';\n\n/*\n|--------------------------------------------------------------------------\n| Turn On The Lights\n|--------------------------------------------------------------------------\n|\n| We need to illuminate PHP development, so let us turn on the lights.\n| This bootstraps the framework and gets it ready for use, then it\n| will load up this application so that we can run it and send\n| the responses back to the browser and delight our users.\n|\n*/\n\n$app = require_once __DIR__.'/../bootstrap/app.php';\n\n/*\n|--------------------------------------------------------------------------\n| Run The Application\n|--------------------------------------------------------------------------\n|\n| Once we have the application, we can handle the incoming request\n| through the kernel, and send the associated response back to\n| the client's browser allowing them to enjoy the creative\n| and wonderful application we have prepared for them.\n|\n*/\n\n$kernel = $app->make('Illuminate\\Contracts\\Http\\Kernel');\n\n$response = $kernel->handle(\n\t$request = Illuminate\\Http\\Request::capture()\n);\n\n$response->send();\n\n$kernel->terminate($request, $response);\n"
  },
  {
    "path": "examples/server/php/public/partials/home.html",
    "content": "<div class=\"container\">\n  <div class=\"panel panel-default\">\n    <div class=\"panel-heading\">Home Page</div>\n    <div class=\"panel-body\">\n      <div class=\"row\">\n        <div class=\"col-sm-6\">\n          <h2>Heading</h2>\n          <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus,\n            tellus ac cursus commodo, tortor mauris condimentum nibh, ut\n            fermentum massa justo sit amet risus. Etiam porta sem malesuada\n            magna mollis euismod. Donec sed odio dui.</p>\n          <p><a class=\"btn btn-primary\" href=\"#\">View details »</a></p>\n        </div>\n        <div class=\"col-sm-6\">\n          <h2>Heading</h2>\n          <p>Donec id elit non mi porta gravida at eget metus. Fusce dapibus,\n            tellus ac cursus commodo, tortor mauris condimentum nibh, ut\n            fermentum massa justo sit amet risus. Etiam porta sem malesuada\n            magna mollis euismod. Donec sed odio dui.</p>\n          <p><a class=\"btn btn-primary\" href=\"#\">View details »</a></p>\n        </div>\n      </div>\n    </div>\n    <div class=\"panel-footer text-center\">\n      <ul class=\"list-inline\">\n        <li><i class=\"ion-star\"></i> {{stars | number}} stars</li>\n        <li><i class=\"ion-fork-repo\"></i> {{forks | number}} forks</li>\n        <li><i class=\"ion-pull-request\"></i> {{issues | number}} issues</li>\n      </ul>\n    </div>\n  </div>\n</div>\n<div class=\"text-center\">\n  <a class=\"btn btn-default\" href=\"https://github.com/sahat/satellizer\"><i class=\"ion-social-github\"></i> GitHub project</a>\n  <a class=\"btn btn-default\" href=\"https://github.com/sahat/satellizer/issues/new\"><i class=\"ion-bug\"></i> Report issue</a>\n</div>\n</div>"
  },
  {
    "path": "examples/server/php/public/partials/login.html",
    "content": "<div class=\"container\">\n  <div class=\"row\">\n    <div class=\"center-form panel\">\n      <div class=\"panel-body\">\n        <h2 class=\"text-center\">Log in</h2>\n        <form method=\"post\" ng-submit=\"login()\" name=\"loginForm\">\n          <div class=\"form-group has-feedback\">\n            <input class=\"form-control input-lg\" type=\"text\" name=\"email\" ng-model=\"user.email\" placeholder=\"Email\" required autofocus>\n            <span class=\"ion-at form-control-feedback\"></span>\n          </div>\n          <div class=\"form-group has-feedback\">\n            <input class=\"form-control input-lg\" type=\"password\" name=\"password\" ng-model=\"user.password\" placeholder=\"Password\" required>\n            <span class=\"ion-key form-control-feedback\"></span>\n          </div>\n          <button type=\"submit\" ng-disabled=\"loginForm.$invalid\" class=\"btn btn-lg  btn-block btn-success\">Log in</button>\n          <br/>\n          <p class=\"text-center text-muted\">\n            <small>Don't have an account yet? <a href=\"/#/signup\">Sign up</a></small>\n          </p>\n          <div class=\"signup-or-separator\">\n            <h6 class=\"text\">or</h6>\n            <hr>\n          </div>\n        </form>\n        <button class=\"btn btn-block btn-facebook\" ng-click=\"authenticate('facebook')\">\n          <i class=\"ion-social-facebook\"></i> Sign in with Facebook\n        </button>\n        <button class=\"btn btn-block btn-google-plus\" ng-click=\"authenticate('google')\">\n          <span class=\"ion-social-googleplus\"></span>Sign in with Google\n        </button>\n        <button class=\"btn btn-block btn-linkedin\" ng-click=\"authenticate('linkedin')\">\n          <i class=\"ion-social-linkedin\"></i> Sign in with LinkedIn\n        </button>\n        <button class=\"btn btn-block btn-instagram\" ng-click=\"authenticate('instagram')\">\n          <i class=\"ion-social-instagram\"></i> Sign in with Instagram\n        </button>\n        <button class=\"btn btn-block btn-twitter\" ng-click=\"authenticate('twitter')\">\n          <i class=\"ion-social-twitter\"></i> Sign in with Twitter\n        </button>\n        <button class=\"btn btn-block btn-foursquare\" ng-click=\"authenticate('foursquare')\">\n          <i class=\"fa fa-foursquare\"></i> Sign in with Foursquare\n        </button>\n        <button class=\"btn btn-block btn-github\" ng-click=\"authenticate('github')\">\n          <i class=\"ion-social-github\"></i> Sign in with GitHub\n        </button>\n        <button class=\"btn btn-block btn-bitbucket\" ng-click=\"authenticate('bitbucket')\">\n          <i class=\"fa fa-bitbucket\"></i> Sign in with Bitbucket\n        </button>\n        <button class=\"btn btn-block btn-yahoo\" ng-click=\"authenticate('yahoo')\">\n          <i class=\"ion-social-yahoo\"></i> Sign in with Yahoo\n        </button>\n        <button class=\"btn btn-block btn-live\" ng-click=\"authenticate('live')\">\n          <i class=\"ion-social-windows\"></i> Sign in with Windows Live\n        </button>\n        <button class=\"btn btn-block btn-twitch\" ng-click=\"authenticate('twitch')\">\n          <i class=\"ion-social-twitch\"></i> Sign in with Twitch\n        </button>\n        <button class=\"btn btn-block btn-spotify\" ng-click=\"authenticate('spotify')\">\n          <i class=\"fa fa-spotify\"></i> Sign in with Spotify\n        </button>\n      </div>\n    </div>\n  </div>\n</div>\n"
  },
  {
    "path": "examples/server/php/public/partials/profile.html",
    "content": "<div class=\"container\">\n  <div class=\"panel panel-default\">\n    <div class=\"panel-heading\">Profile</div>\n    <div class=\"panel-body\">\n      <legend><i class=\"ion-clipboard\"></i> Edit My Profile</legend>\n      <form method=\"post\" ng-submit=\"updateProfile()\">\n        <div class=\"form-group\">\n          <label class=\"control-label\">Profile Picture</label>\n          <img class=\"profile-picture\" ng-src=\"{{user.picture || 'https://placehold.it/100x100'}}\">\n        </div>\n        <div class=\"form-group\">\n          <label class=\"control-label\"><i class=\"ion-person\"></i> Display Name</label>\n          <input type=\"text\" class=\"form-control\" ng-model=\"user.displayName\" />\n        </div>\n        <div class=\"form-group\">\n          <label class=\"control-label\"><i class=\"ion-at\"></i> Email Address</label>\n          <input type=\"email\" class=\"form-control\" ng-model=\"user.email\" />\n        </div>\n        <button class=\"btn btn-lg btn-success\">Update Information</button>\n      </form>\n    </div>\n  </div>\n\n  <div class=\"panel panel-default\">\n    <div class=\"panel-heading\">Accounts</div>\n    <div class=\"panel-body\">\n      <legend><i class=\"ion-link\"></i> Linked Accounts</legend>\n      <div class=\"btn-group-vertical\">\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.facebook\" ng-click=\"unlink('facebook')\">\n          <i class=\"ion-social-facebook\"></i> Unlink Facebook Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.facebook\" ng-click=\"link('facebook')\">\n          <i class=\"ion-social-facebook\"></i> Link Facebook Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.google\" ng-click=\"unlink('google')\">\n          <i class=\"ion-social-googleplus\"></i> Unlink Google Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.google\" ng-click=\"link('google')\">\n          <i class=\"ion-social-googleplus\"></i> Link Google Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.linkedin\" ng-click=\"unlink('linkedin')\">\n          <i class=\"ion-social-linkedin\"></i> Unlink LinkedIn Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.linkedin\" ng-click=\"link('linkedin')\">\n          <i class=\"ion-social-linkedin\"></i> Link LinkedIn Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.twitter\" ng-click=\"unlink('twitter')\">\n          <i class=\"ion-social-twitter\"></i> Unlink Twitter Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.twitter\" ng-click=\"link('twitter')\">\n          <i class=\"ion-social-twitter\"></i> Link Twitter Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.github\" ng-click=\"unlink('github')\">\n          <i class=\"ion-social-github\"></i> Unlink GitHub Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.github\" ng-click=\"link('github')\">\n          <i class=\"ion-social-github\"></i> Link GitHub Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.instagram\" ng-click=\"unlink('instagram')\">\n          <i class=\"ion-social-instagram\"></i> Unlink Instagram Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.instagram\" ng-click=\"link('instagram')\">\n          <i class=\"ion-social-instagram\"></i> Link Instagram Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.foursquare\" ng-click=\"unlink('foursquare')\">\n          <i class=\"ion-social-foursquare\"></i> Unlink Foursquare Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.foursquare\" ng-click=\"link('foursquare')\">\n          <i class=\"ion-social-foursquare\"></i> Link Foursquare Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.yahoo\" ng-click=\"unlink('yahoo')\">\n          <i class=\"ion-social-yahoo\"></i> Unlink Yahoo Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.yahoo\" ng-click=\"link('yahoo')\">\n          <i class=\"ion-social-yahoo\"></i> Link Yahoo Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.live\" ng-click=\"unlink('live')\">\n          <i class=\"ion-social-windows\"></i> Unlink Windows Live Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.live\" ng-click=\"link('live')\">\n          <i class=\"ion-social-windows\"></i> Link Windows Live Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.twitch\" ng-click=\"link('twitch')\">\n          <i class=\"ion-social-twitch\"></i> Unlink Twitch Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.twitch\" ng-click=\"link('twitch')\">\n          <i class=\"ion-social-twitch\"></i> Link Twitch Account\n        </button>\n\n        <button class=\"btn btn-sm btn-danger\" ng-if=\"user.twitch\" ng-click=\"link('bitbucket')\">\n          <i class=\"fa fa-bitbucket\"></i> Unlink Bitbucket Account\n        </button>\n        <button class=\"btn btn-sm btn-primary\" ng-if=\"!user.twitch\" ng-click=\"link('bitbucket')\">\n          <i class=\"fa fa-bitbucket\"></i> Link Bitbucket Account\n        </button>\n      </div>\n    </div>\n  </div>\n</div>\n"
  },
  {
    "path": "examples/server/php/public/partials/signup.html",
    "content": "<div class=\"container\">\n  <div class=\"row\">\n    <div class=\"center-form panel\">\n      <div class=\"panel-body\">\n        <h2 class=\"text-center\">Sign up</h2>\n        <form method=\"post\" ng-submit=\"signup()\" name=\"signupForm\">\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.displayName.$invalid && signupForm.displayName.$dirty }\">\n            <input class=\"form-control input-lg\" type=\"text\" name=\"displayName\" ng-model=\"user.displayName\" placeholder=\"Name\" required autofocus>\n            <span class=\"ion-person form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.displayName.$dirty\" ng-messages=\"signupForm.displayName.$error\">\n              <div ng-message=\"required\">You must enter your name.</div>\n            </div>\n          </div>\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.email.$invalid && signupForm.email.$dirty }\">\n            <input class=\"form-control input-lg\" type=\"email\" id=\"email\" name=\"email\" ng-model=\"user.email\" placeholder=\"Email\" required>\n            <span class=\"ion-at form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.email.$dirty\" ng-messages=\"signupForm.email.$error\">\n              <div ng-message=\"required\">Your email address is required.</div>\n              <div ng-message=\"pattern\">Your email address is invalid.</div>\n            </div>\n          </div>\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.password.$invalid && signupForm.password.$dirty }\">\n            <input password-strength class=\"form-control input-lg\" type=\"password\" name=\"password\" ng-model=\"user.password\" placeholder=\"Password\" required>\n            <span class=\"ion-key form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.password.$dirty\" ng-messages=\"signupForm.password.$error\">\n              <div ng-message=\"required\">Password is required.</div>\n            </div>\n          </div>\n          <div class=\"form-group has-feedback\" ng-class=\"{ 'has-error' : signupForm.confirmPassword.$invalid && signupForm.confirmPassword.$dirty }\">\n            <input password-match=\"user.password\" class=\"form-control input-lg\" type=\"password\" name=\"confirmPassword\" ng-model=\"confirmPassword\" placeholder=\"Confirm Password\">\n            <span class=\"ion-key form-control-feedback\"></span>\n            <div class=\"help-block text-danger\" ng-if=\"signupForm.confirmPassword.$dirty\" ng-messages=\"signupForm.confirmPassword.$error\">\n              <div ng-message=\"compareTo\">Password must match.</div>\n            </div>\n          </div>\n          <p class=\"text-center text-muted\"><small>By clicking on Sign up, you agree to <a href=\"#\">terms & conditions</a> and <a href=\"#\">privacy policy</a></small></p>\n          <button type=\"submit\" ng-disabled=\"signupForm.$invalid\" class=\"btn btn-lg btn-block btn-primary\">Sign up</button>\n          <br/>\n          <p class=\"text-center text-muted\">Already have an account? <a href=\"/#/login\">Log in now</a></p>\n        </form>\n      </div>\n    </div>\n  </div>\n</div>"
  },
  {
    "path": "examples/server/php/public/robots.txt",
    "content": "User-agent: *\nDisallow:\n"
  },
  {
    "path": "examples/server/php/public/services/account.js",
    "content": "angular.module('MyApp')\n  .factory('Account', function($http) {\n    return {\n      getProfile: function() {\n        return $http.get('/api/me');\n      },\n      updateProfile: function(profileData) {\n        return $http.put('/api/me', profileData);\n      }\n    };\n  });"
  },
  {
    "path": "examples/server/php/public/stylesheets/angular-toastr.css",
    "content": ".toast-title {\n  font-weight: bold;\n}\n.toast-message {\n  word-wrap: break-word;\n}\n.toast-message a,\n.toast-message label {\n  color: #ffffff;\n}\n.toast-message a:hover {\n  color: #cccccc;\n  text-decoration: none;\n}\n.toast-close-button {\n  position: relative;\n  right: -0.3em;\n  top: -0.3em;\n  float: right;\n  font-size: 20px;\n  font-weight: bold;\n  color: #ffffff;\n  -webkit-text-shadow: 0 1px 0 #ffffff;\n  text-shadow: 0 1px 0 #ffffff;\n  opacity: 0.8;\n}\n.toast-close-button:hover,\n.toast-close-button:focus {\n  color: #000000;\n  text-decoration: none;\n  cursor: pointer;\n  opacity: 0.4;\n}\n/*Additional properties for button version\n iOS requires the button element instead of an anchor tag.\n If you want the anchor version, it requires `href=\"#\"`.*/\nbutton.toast-close-button {\n  padding: 0;\n  cursor: pointer;\n  background: transparent;\n  border: 0;\n  -webkit-appearance: none;\n}\n.toast-top-center {\n  top: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-bottom-center {\n  bottom: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-top-full-width {\n  top: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-bottom-full-width {\n  bottom: 0;\n  right: 0;\n  width: 100%;\n}\n.toast-top-left {\n  top: 12px;\n  left: 12px;\n}\n.toast-top-right {\n  top: 12px;\n  right: 12px;\n}\n.toast-bottom-right {\n  right: 12px;\n  bottom: 12px;\n}\n.toast-bottom-left {\n  bottom: 12px;\n  left: 12px;\n}\n#toast-container {\n  position: fixed;\n  z-index: 999999;\n  /*overrides*/\n}\n#toast-container * {\n  -moz-box-sizing: border-box;\n  -webkit-box-sizing: border-box;\n  box-sizing: border-box;\n}\n#toast-container > div {\n  position: relative;\n  overflow: hidden;\n  margin: 0 0 6px;\n  padding: 15px 15px 15px 50px;\n  width: 300px;\n  -moz-border-radius: 3px 3px 3px 3px;\n  -webkit-border-radius: 3px 3px 3px 3px;\n  border-radius: 3px 3px 3px 3px;\n  background-position: 15px center;\n  background-repeat: no-repeat;\n  -moz-box-shadow: 0 0 12px #999999;\n  -webkit-box-shadow: 0 0 12px #999999;\n  box-shadow: 0 0 12px #999999;\n  color: #ffffff;\n  opacity: 0.8;\n}\n#toast-container > :hover {\n  -moz-box-shadow: 0 0 12px #000000;\n  -webkit-box-shadow: 0 0 12px #000000;\n  box-shadow: 0 0 12px #000000;\n  opacity: 1;\n  cursor: pointer;\n}\n#toast-container > .toast-info {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGwSURBVEhLtZa9SgNBEMc9sUxxRcoUKSzSWIhXpFMhhYWFhaBg4yPYiWCXZxBLERsLRS3EQkEfwCKdjWJAwSKCgoKCcudv4O5YLrt7EzgXhiU3/4+b2ckmwVjJSpKkQ6wAi4gwhT+z3wRBcEz0yjSseUTrcRyfsHsXmD0AmbHOC9Ii8VImnuXBPglHpQ5wwSVM7sNnTG7Za4JwDdCjxyAiH3nyA2mtaTJufiDZ5dCaqlItILh1NHatfN5skvjx9Z38m69CgzuXmZgVrPIGE763Jx9qKsRozWYw6xOHdER+nn2KkO+Bb+UV5CBN6WC6QtBgbRVozrahAbmm6HtUsgtPC19tFdxXZYBOfkbmFJ1VaHA1VAHjd0pp70oTZzvR+EVrx2Ygfdsq6eu55BHYR8hlcki+n+kERUFG8BrA0BwjeAv2M8WLQBtcy+SD6fNsmnB3AlBLrgTtVW1c2QN4bVWLATaIS60J2Du5y1TiJgjSBvFVZgTmwCU+dAZFoPxGEEs8nyHC9Bwe2GvEJv2WXZb0vjdyFT4Cxk3e/kIqlOGoVLwwPevpYHT+00T+hWwXDf4AJAOUqWcDhbwAAAAASUVORK5CYII=\") !important;\n}\n#toast-container > .toast-error {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHOSURBVEhLrZa/SgNBEMZzh0WKCClSCKaIYOED+AAKeQQLG8HWztLCImBrYadgIdY+gIKNYkBFSwu7CAoqCgkkoGBI/E28PdbLZmeDLgzZzcx83/zZ2SSXC1j9fr+I1Hq93g2yxH4iwM1vkoBWAdxCmpzTxfkN2RcyZNaHFIkSo10+8kgxkXIURV5HGxTmFuc75B2RfQkpxHG8aAgaAFa0tAHqYFfQ7Iwe2yhODk8+J4C7yAoRTWI3w/4klGRgR4lO7Rpn9+gvMyWp+uxFh8+H+ARlgN1nJuJuQAYvNkEnwGFck18Er4q3egEc/oO+mhLdKgRyhdNFiacC0rlOCbhNVz4H9FnAYgDBvU3QIioZlJFLJtsoHYRDfiZoUyIxqCtRpVlANq0EU4dApjrtgezPFad5S19Wgjkc0hNVnuF4HjVA6C7QrSIbylB+oZe3aHgBsqlNqKYH48jXyJKMuAbiyVJ8KzaB3eRc0pg9VwQ4niFryI68qiOi3AbjwdsfnAtk0bCjTLJKr6mrD9g8iq/S/B81hguOMlQTnVyG40wAcjnmgsCNESDrjme7wfftP4P7SP4N3CJZdvzoNyGq2c/HWOXJGsvVg+RA/k2MC/wN6I2YA2Pt8GkAAAAASUVORK5CYII=\") !important;\n}\n#toast-container > .toast-success {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADsSURBVEhLY2AYBfQMgf///3P8+/evAIgvA/FsIF+BavYDDWMBGroaSMMBiE8VC7AZDrIFaMFnii3AZTjUgsUUWUDA8OdAH6iQbQEhw4HyGsPEcKBXBIC4ARhex4G4BsjmweU1soIFaGg/WtoFZRIZdEvIMhxkCCjXIVsATV6gFGACs4Rsw0EGgIIH3QJYJgHSARQZDrWAB+jawzgs+Q2UO49D7jnRSRGoEFRILcdmEMWGI0cm0JJ2QpYA1RDvcmzJEWhABhD/pqrL0S0CWuABKgnRki9lLseS7g2AlqwHWQSKH4oKLrILpRGhEQCw2LiRUIa4lwAAAABJRU5ErkJggg==\") !important;\n}\n#toast-container > .toast-warning {\n  background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAGYSURBVEhL5ZSvTsNQFMbXZGICMYGYmJhAQIJAICYQPAACiSDB8AiICQQJT4CqQEwgJvYASAQCiZiYmJhAIBATCARJy+9rTsldd8sKu1M0+dLb057v6/lbq/2rK0mS/TRNj9cWNAKPYIJII7gIxCcQ51cvqID+GIEX8ASG4B1bK5gIZFeQfoJdEXOfgX4QAQg7kH2A65yQ87lyxb27sggkAzAuFhbbg1K2kgCkB1bVwyIR9m2L7PRPIhDUIXgGtyKw575yz3lTNs6X4JXnjV+LKM/m3MydnTbtOKIjtz6VhCBq4vSm3ncdrD2lk0VgUXSVKjVDJXJzijW1RQdsU7F77He8u68koNZTz8Oz5yGa6J3H3lZ0xYgXBK2QymlWWA+RWnYhskLBv2vmE+hBMCtbA7KX5drWyRT/2JsqZ2IvfB9Y4bWDNMFbJRFmC9E74SoS0CqulwjkC0+5bpcV1CZ8NMej4pjy0U+doDQsGyo1hzVJttIjhQ7GnBtRFN1UarUlH8F3xict+HY07rEzoUGPlWcjRFRr4/gChZgc3ZL2d8oAAAAASUVORK5CYII=\") !important;\n}\n#toast-container.toast-top-center > div,\n#toast-container.toast-bottom-center > div {\n  width: 300px;\n  margin: auto;\n}\n#toast-container.toast-top-full-width > div,\n#toast-container.toast-bottom-full-width > div {\n  width: 96%;\n  margin: auto;\n}\n.toast {\n  background-color: #030303;\n}\n.toast-success {\n  background-color: #51a351;\n}\n.toast-error {\n  background-color: #bd362f;\n}\n.toast-info {\n  background-color: #2f96b4;\n}\n.toast-warning {\n  background-color: #f89406;\n}\n.toast-progress {\n  position: absolute;\n  left: 0;\n  bottom: 0;\n  height: 4px;\n  background-color: #000000;\n  opacity: 0.4;\n}\n/*Animations*/\n.toast {\n  opacity: 1 !important;\n}\n.toast.ng-enter {\n  opacity: 0 !important;\n  transition: opacity .3s linear;\n}\n.toast.ng-enter.ng-enter-active {\n  opacity: 1 !important;\n}\n.toast.ng-leave {\n  opacity: 1;\n  transition: opacity .3s linear;\n}\n.toast.ng-leave.ng-leave-active {\n  opacity: 0 !important;\n}\n/*Responsive Design*/\n@media all and (max-width: 240px) {\n  #toast-container > div {\n    padding: 8px 8px 8px 50px;\n    width: 11em;\n  }\n  #toast-container .toast-close-button {\n    right: -0.2em;\n    top: -0.2em;\n  }\n}\n@media all and (min-width: 241px) and (max-width: 480px) {\n  #toast-container > div {\n    padding: 8px 8px 8px 50px;\n    width: 18em;\n  }\n  #toast-container .toast-close-button {\n    right: -0.2em;\n    top: -0.2em;\n  }\n}\n@media all and (min-width: 481px) and (max-width: 768px) {\n  #toast-container > div {\n    padding: 15px 15px 15px 50px;\n    width: 25em;\n  }\n}\n"
  },
  {
    "path": "examples/server/php/public/stylesheets/styles.css",
    "content": "body {\n  font-family: 'Open Sans', sans-serif;\n  background: #e4e7ec;\n}\n\nh1, h2, h3, h4, h5, h6 {\n  font-family: 'Montserrat', sans-serif;\n  font-weight: bold;\n}\n\na {\n  color: #000;\n}\n\nul {\n  margin-bottom: 0;\n}\n\n.list-inline > li {\n  padding-left: 15px;\n  padding-right: 15px;\n}\n\n.text-muted {\n  color: #90939a;\n}\n\n.navbar {\n  border: 0;\n  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .26);\n}\n\n.navbar-header {\n  float: left;\n  padding-left: 15px;\n}\n\n.navbar-nav {\n  float: left;\n  margin: 0;\n}\n\n.navbar-nav > li {\n  float: left;\n}\n\n.navbar-nav > li > a {\n  padding: 15px;\n}\n\n.navbar-default {\n  color: #fff;\n  background: #fff;\n}\n\n.navbar-default .navbar-brand {\n  color: #333;\n  background-color: #ffe939;\n}\n\n.navbar-default .navbar-brand:hover {\n  color: #ffe939;\n  background-color: #333;\n}\n\n.navbar-brand {\n  margin-left: -15px;\n  transition: 0.25s all;\n}\n\n.panel {\n  border-color: #cfd9D7;\n  border-radius: 2px;\n  box-shadow: 0 8px 17px rgba(0, 0, 0, .2);\n}\n\n.panel-default > .panel-heading {\n  font-size: 85%;\n  font-weight: bold;\n  color: #444;\n  text-transform: uppercase;\n  background-color: #f6f6f6;\n  border-color: #cfd9db;\n}\n\n.form-control {\n  border-radius: 0;\n}\n\n.center-form {\n  width: 330px;\n  margin: 12% auto;\n}\n\n.signup-or-separator {\n  position: relative;\n  height: 34px;\n  text-align: center;\n  background: none;\n}\n\n.signup-or-separator hr {\n  width: 90%;\n  margin: -16px auto 10px auto;\n  border-top: 1px solid #dce0e0;\n}\n\n.signup-or-separator .text {\n  display: inline-block;\n  padding: 8px;\n  margin: 0;\n  background-color: #fff;\n}\n\n.has-feedback .form-control-feedback {\n  top: 0;\n  left: 0;\n  width: 46px;\n  height: 46px;\n  line-height: 46px;\n  color: #555;\n}\n\n.password-strength-indicator {\n  position: absolute;\n  top: 10px;\n  right: 0;\n  width: 5px;\n  padding: 0 15px;\n}\n\n.password-strength-indicator span {\n  display: block;\n  width: 5px;\n  height: 5px;\n  margin-bottom: 2px;\n  background: #ebeef1;\n  border-radius: 5px;\n}\n\n[class^='ion-'] {\n  font-size: 1.2em;\n}\n\n.has-feedback .form-control {\n  padding-left: 42.5px;\n}\n\n.alert-material {\n  position: fixed;\n  right: 12px;\n  bottom: 12px;\n  z-index: 1;\n  display: inline-block;\n  min-height: 48px;\n  padding: 13px 24px 12px;\n  font-family: 'Roboto', sans-serif;\n  color: #f1f1f1;\n  cursor: default;\n  background: #323232;\n  border-radius: 2px;\n  outline: none;\n  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.26);\n}\n\n.profile-picture {\n  height: 100px;\n  display: block;\n}\n\n.btn {\n  font-weight: bold;\n  border-radius: 2px;\n  box-shadow: 0 2px 5px 0 rgba(0, 0, 0, .26);\n}\n\n.btn-primary {\n  background-color: #4285f4;\n}\n\n.btn-primary:hover {\n  background-color: #3367d6;\n}\n\n.btn-success {\n  background-color: #0f9d58;\n}\n\n.btn-success:hover {\n  background-color: #196c4a;\n}\n\n.btn-danger {\n  background-color: #db4437;\n}\n\n.btn-danger:hover {\n  background-color: #b04c3b;\n}\n\n.btn-group-vertical .btn {\n  margin-bottom: 10px;\n}\n\n.btn-group-vertical > .btn:first-child:not(:last-child) {\n  border-radius: 2px;\n}\n\n.btn-group-vertical > .btn:not(:first-child):not(:last-child) {\n  border-radius: 2px;\n}\n\n.btn-group-vertical > .btn:last-child:not(:first-child) {\n  border-radius: 2px;\n}\n\n.btn-lg {\n  font-size: 14px;\n}\n\n.btn [class^='ion-'] {\n  margin-right: 5px;\n}\n\n.btn .fa {\n  margin-right: 5px;\n}\n\n/*********************\n* Social Buttons\n*********************/\n\n.btn-google-plus {\n  color: #fff;\n  background-color: #dd4b39;\n  border: 1px solid #d54331;\n}\n\n.btn-google-plus:hover,\n.btn-google-plus:focus {\n  color: #fff;\n  background-color: #cb3927;\n}\n\n.btn-facebook {\n  color: #fff;\n  background-color: #3b5998;\n  border: 1px solid #335190;\n}\n\n.btn-facebook:hover,\n.btn-facebook:focus {\n  color: #fff;\n  background-color: #294786;\n}\n\n.btn-linkedin {\n  color: #fff;\n  background-color: #007bb6;\n  border: 1px solid #0073ae;\n}\n\n.btn-linkedin:hover,\n.btn-linkedin:focus {\n  color: #fff;\n  background-color: #0069a4;\n}\n\n.btn-twitter {\n  color: #fff;\n  background-color: #00aced;\n  border: 1px solid #009fdb;\n}\n\n.btn-twitter:hover,\n.btn-twitter:focus {\n  color: #fff;\n  background-color: #0090c7;\n}\n\n.btn-foursquare {\n  color: #fff;\n  background-color: #f94877;\n  border: 1px solid #f8215a;\n}\n\n.btn-foursquare:hover,\n.btn-foursquare:focus {\n  color: #fff;\n  background-color: #f71752;\n}\n\n.btn-github {\n  color: #fff;\n  background-color: #444;\n  border: 1px solid #3b3b3b;\n}\n\n.btn-github:hover,\n.btn-github:focus {\n  color: #fff;\n  background-color: #303030;\n}\n\n.btn-instagram {\n  color: #fff;\n  background-color: #3f729b;\n}\n\n.btn-instagram:hover,\n.btn-instagram:focus {\n  color: #fff;\n  background-color: #305777;\n}\n\n.btn-yahoo {\n  color: #fff;\n  background-color: #720e9e;\n}\n\n.btn-yahoo:hover,\n.btn-yahoo:focus {\n  color: #fff;\n  background-color: #600e85;\n}\n\n.btn-live {\n  color: #fff;\n  background-color: #2672ec;\n}\n\n.btn-live:hover,\n.btn-live:focus {\n  color: #fff;\n  background-color: #125acd;\n}\n\n.btn-twitch {\n  color: #fff;\n  background-color: #6441a5;\n}\n\n.btn-twitch:hover,\n.btn-twitch:focus {\n  color: #fff;\n  background-color: #7550ba;\n}\n\n.btn-bitbucket {\n  color: #fff;\n  background-color: #10375e;\n}\n\n.btn-bitbucket:hover,\n.btn-bitbucket:focus {\n  color: #fff;\n  background-color: #0d2c4a;\n}\n\n.btn-spotify {\n  color: #fff;\n  background-color: #2ebd59;\n}\n\n.btn-spotify:hover,\n.btn-spotify:focus {\n  color: #fff;\n  background-color: #29a34e;\n}\n\n/*********************\n* Animations\n*********************/\n\n.fadeZoom.ng-enter {\n  -webkit-animation-duration: 0.6s, 0.2s;\n  -moz-animation-duration: 0.2s, 0.2s;\n  -ms-animation-duration: 0.2s, 0.2s;\n  animation-duration: 0.2, 0.2s;\n  -webkit-animation-name: fadeIn, zoomIn;\n  -moz-animation-name: fadeIn, zoomIn;\n  -ms-animation-name: fadeIn, zoomIn;\n  animation-name: fadeIn, zoomIn;\n}\n\n.fadeZoomFadeDown.ng-enter {\n  -webkit-animation-duration: 0.2s, 0.2s;\n  -moz-animation-duration: 0.2s, 0.2s;\n  -ms-animation-duration: 0.2s, 0.2s;\n  animation-duration: 0.2s, 0.2s;\n  -webkit-animation-name: fadeIn, zoomIn;\n  -moz-animation-name: fadeIn, zoomIn;\n  -ms-animation-name: fadeIn, zoomIn;\n  animation-name: fadeIn, zoomIn;\n}\n\n.fadeZoomFadeDown.ng-leave {\n  -webkit-animation: fadeOutDown 0.2s;\n  -moz-animation: fadeOutDown 0.2s;\n  -ms-animation: fadeOutDown 0.2s;\n  animation: fadeOutDown 0.2s;\n}\n\n@-webkit-keyframes zoomIn {\n  0% {\n    opacity: 0;\n    -webkit-transform: scale3d(0.8, 0.8, 0.8);\n    -moz-transform: scale3d(0.8, 0.8, 0.8);\n    -ms-transform: scale3d(0.8, 0.8, 0.8);\n    transform: scale3d(0.8, 0.8, 0.8);\n  }\n\n  50% {\n    opacity: 1;\n  }\n}\n\n@keyframes zoomIn {\n  0% {\n    opacity: 0;\n    -webkit-transform: scale3d(0.8, 0.8, 0.8);\n    -moz-transform: scale3d(0.8, 0.8, 0.8);\n    -ms-transform: scale3d(0.8, 0.8, 0.8);\n    transform: scale3d(0.8, 0.8, 0.8);\n  }\n\n  50% {\n    opacity: 1;\n  }\n}\n"
  },
  {
    "path": "examples/server/php/public/vendor/angular-animate.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* jshint ignore:start */\nvar noop        = angular.noop;\nvar extend      = angular.extend;\nvar jqLite      = angular.element;\nvar forEach     = angular.forEach;\nvar isArray     = angular.isArray;\nvar isString    = angular.isString;\nvar isObject    = angular.isObject;\nvar isUndefined = angular.isUndefined;\nvar isDefined   = angular.isDefined;\nvar isFunction  = angular.isFunction;\nvar isElement   = angular.isElement;\n\nvar ELEMENT_NODE = 1;\nvar COMMENT_NODE = 8;\n\nvar ADD_CLASS_SUFFIX = '-add';\nvar REMOVE_CLASS_SUFFIX = '-remove';\nvar EVENT_CLASS_PREFIX = 'ng-';\nvar ACTIVE_CLASS_SUFFIX = '-active';\n\nvar NG_ANIMATE_CLASSNAME = 'ng-animate';\nvar NG_ANIMATE_CHILDREN_DATA = '$$ngAnimateChildren';\n\n// Detect proper transitionend/animationend event names.\nvar CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;\n\n// If unprefixed events are not supported but webkit-prefixed are, use the latter.\n// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.\n// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`\n// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.\n// Register both events in case `window.onanimationend` is not supported because of that,\n// do the same for `transitionend` as Safari is likely to exhibit similar behavior.\n// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit\n// therefore there is no reason to test anymore for other vendor prefixes:\n// http://caniuse.com/#search=transition\nif (isUndefined(window.ontransitionend) && isDefined(window.onwebkittransitionend)) {\n  CSS_PREFIX = '-webkit-';\n  TRANSITION_PROP = 'WebkitTransition';\n  TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';\n} else {\n  TRANSITION_PROP = 'transition';\n  TRANSITIONEND_EVENT = 'transitionend';\n}\n\nif (isUndefined(window.onanimationend) && isDefined(window.onwebkitanimationend)) {\n  CSS_PREFIX = '-webkit-';\n  ANIMATION_PROP = 'WebkitAnimation';\n  ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';\n} else {\n  ANIMATION_PROP = 'animation';\n  ANIMATIONEND_EVENT = 'animationend';\n}\n\nvar DURATION_KEY = 'Duration';\nvar PROPERTY_KEY = 'Property';\nvar DELAY_KEY = 'Delay';\nvar TIMING_KEY = 'TimingFunction';\nvar ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';\nvar ANIMATION_PLAYSTATE_KEY = 'PlayState';\nvar SAFE_FAST_FORWARD_DURATION_VALUE = 9999;\n\nvar ANIMATION_DELAY_PROP = ANIMATION_PROP + DELAY_KEY;\nvar ANIMATION_DURATION_PROP = ANIMATION_PROP + DURATION_KEY;\nvar TRANSITION_DELAY_PROP = TRANSITION_PROP + DELAY_KEY;\nvar TRANSITION_DURATION_PROP = TRANSITION_PROP + DURATION_KEY;\n\nvar isPromiseLike = function(p) {\n  return p && p.then ? true : false;\n};\n\nfunction assertArg(arg, name, reason) {\n  if (!arg) {\n    throw ngMinErr('areq', \"Argument '{0}' is {1}\", (name || '?'), (reason || \"required\"));\n  }\n  return arg;\n}\n\nfunction mergeClasses(a,b) {\n  if (!a && !b) return '';\n  if (!a) return b;\n  if (!b) return a;\n  if (isArray(a)) a = a.join(' ');\n  if (isArray(b)) b = b.join(' ');\n  return a + ' ' + b;\n}\n\nfunction packageStyles(options) {\n  var styles = {};\n  if (options && (options.to || options.from)) {\n    styles.to = options.to;\n    styles.from = options.from;\n  }\n  return styles;\n}\n\nfunction pendClasses(classes, fix, isPrefix) {\n  var className = '';\n  classes = isArray(classes)\n      ? classes\n      : classes && isString(classes) && classes.length\n          ? classes.split(/\\s+/)\n          : [];\n  forEach(classes, function(klass, i) {\n    if (klass && klass.length > 0) {\n      className += (i > 0) ? ' ' : '';\n      className += isPrefix ? fix + klass\n                            : klass + fix;\n    }\n  });\n  return className;\n}\n\nfunction removeFromArray(arr, val) {\n  var index = arr.indexOf(val);\n  if (val >= 0) {\n    arr.splice(index, 1);\n  }\n}\n\nfunction stripCommentsFromElement(element) {\n  if (element instanceof jqLite) {\n    switch (element.length) {\n      case 0:\n        return [];\n        break;\n\n      case 1:\n        // there is no point of stripping anything if the element\n        // is the only element within the jqLite wrapper.\n        // (it's important that we retain the element instance.)\n        if (element[0].nodeType === ELEMENT_NODE) {\n          return element;\n        }\n        break;\n\n      default:\n        return jqLite(extractElementNode(element));\n        break;\n    }\n  }\n\n  if (element.nodeType === ELEMENT_NODE) {\n    return jqLite(element);\n  }\n}\n\nfunction extractElementNode(element) {\n  if (!element[0]) return element;\n  for (var i = 0; i < element.length; i++) {\n    var elm = element[i];\n    if (elm.nodeType == ELEMENT_NODE) {\n      return elm;\n    }\n  }\n}\n\nfunction $$addClass($$jqLite, element, className) {\n  forEach(element, function(elm) {\n    $$jqLite.addClass(elm, className);\n  });\n}\n\nfunction $$removeClass($$jqLite, element, className) {\n  forEach(element, function(elm) {\n    $$jqLite.removeClass(elm, className);\n  });\n}\n\nfunction applyAnimationClassesFactory($$jqLite) {\n  return function(element, options) {\n    if (options.addClass) {\n      $$addClass($$jqLite, element, options.addClass);\n      options.addClass = null;\n    }\n    if (options.removeClass) {\n      $$removeClass($$jqLite, element, options.removeClass);\n      options.removeClass = null;\n    }\n  }\n}\n\nfunction prepareAnimationOptions(options) {\n  options = options || {};\n  if (!options.$$prepared) {\n    var domOperation = options.domOperation || noop;\n    options.domOperation = function() {\n      options.$$domOperationFired = true;\n      domOperation();\n      domOperation = noop;\n    };\n    options.$$prepared = true;\n  }\n  return options;\n}\n\nfunction applyAnimationStyles(element, options) {\n  applyAnimationFromStyles(element, options);\n  applyAnimationToStyles(element, options);\n}\n\nfunction applyAnimationFromStyles(element, options) {\n  if (options.from) {\n    element.css(options.from);\n    options.from = null;\n  }\n}\n\nfunction applyAnimationToStyles(element, options) {\n  if (options.to) {\n    element.css(options.to);\n    options.to = null;\n  }\n}\n\nfunction mergeAnimationOptions(element, target, newOptions) {\n  var toAdd = (target.addClass || '') + ' ' + (newOptions.addClass || '');\n  var toRemove = (target.removeClass || '') + ' ' + (newOptions.removeClass || '');\n  var classes = resolveElementClasses(element.attr('class'), toAdd, toRemove);\n\n  if (newOptions.preparationClasses) {\n    target.preparationClasses = concatWithSpace(newOptions.preparationClasses, target.preparationClasses);\n    delete newOptions.preparationClasses;\n  }\n\n  // noop is basically when there is no callback; otherwise something has been set\n  var realDomOperation = target.domOperation !== noop ? target.domOperation : null;\n\n  extend(target, newOptions);\n\n  // TODO(matsko or sreeramu): proper fix is to maintain all animation callback in array and call at last,but now only leave has the callback so no issue with this.\n  if (realDomOperation) {\n    target.domOperation = realDomOperation;\n  }\n\n  if (classes.addClass) {\n    target.addClass = classes.addClass;\n  } else {\n    target.addClass = null;\n  }\n\n  if (classes.removeClass) {\n    target.removeClass = classes.removeClass;\n  } else {\n    target.removeClass = null;\n  }\n\n  return target;\n}\n\nfunction resolveElementClasses(existing, toAdd, toRemove) {\n  var ADD_CLASS = 1;\n  var REMOVE_CLASS = -1;\n\n  var flags = {};\n  existing = splitClassesToLookup(existing);\n\n  toAdd = splitClassesToLookup(toAdd);\n  forEach(toAdd, function(value, key) {\n    flags[key] = ADD_CLASS;\n  });\n\n  toRemove = splitClassesToLookup(toRemove);\n  forEach(toRemove, function(value, key) {\n    flags[key] = flags[key] === ADD_CLASS ? null : REMOVE_CLASS;\n  });\n\n  var classes = {\n    addClass: '',\n    removeClass: ''\n  };\n\n  forEach(flags, function(val, klass) {\n    var prop, allow;\n    if (val === ADD_CLASS) {\n      prop = 'addClass';\n      allow = !existing[klass];\n    } else if (val === REMOVE_CLASS) {\n      prop = 'removeClass';\n      allow = existing[klass];\n    }\n    if (allow) {\n      if (classes[prop].length) {\n        classes[prop] += ' ';\n      }\n      classes[prop] += klass;\n    }\n  });\n\n  function splitClassesToLookup(classes) {\n    if (isString(classes)) {\n      classes = classes.split(' ');\n    }\n\n    var obj = {};\n    forEach(classes, function(klass) {\n      // sometimes the split leaves empty string values\n      // incase extra spaces were applied to the options\n      if (klass.length) {\n        obj[klass] = true;\n      }\n    });\n    return obj;\n  }\n\n  return classes;\n}\n\nfunction getDomNode(element) {\n  return (element instanceof angular.element) ? element[0] : element;\n}\n\nfunction applyGeneratedPreparationClasses(element, event, options) {\n  var classes = '';\n  if (event) {\n    classes = pendClasses(event, EVENT_CLASS_PREFIX, true);\n  }\n  if (options.addClass) {\n    classes = concatWithSpace(classes, pendClasses(options.addClass, ADD_CLASS_SUFFIX));\n  }\n  if (options.removeClass) {\n    classes = concatWithSpace(classes, pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX));\n  }\n  if (classes.length) {\n    options.preparationClasses = classes;\n    element.addClass(classes);\n  }\n}\n\nfunction clearGeneratedClasses(element, options) {\n  if (options.preparationClasses) {\n    element.removeClass(options.preparationClasses);\n    options.preparationClasses = null;\n  }\n  if (options.activeClasses) {\n    element.removeClass(options.activeClasses);\n    options.activeClasses = null;\n  }\n}\n\nfunction blockTransitions(node, duration) {\n  // we use a negative delay value since it performs blocking\n  // yet it doesn't kill any existing transitions running on the\n  // same element which makes this safe for class-based animations\n  var value = duration ? '-' + duration + 's' : '';\n  applyInlineStyle(node, [TRANSITION_DELAY_PROP, value]);\n  return [TRANSITION_DELAY_PROP, value];\n}\n\nfunction blockKeyframeAnimations(node, applyBlock) {\n  var value = applyBlock ? 'paused' : '';\n  var key = ANIMATION_PROP + ANIMATION_PLAYSTATE_KEY;\n  applyInlineStyle(node, [key, value]);\n  return [key, value];\n}\n\nfunction applyInlineStyle(node, styleTuple) {\n  var prop = styleTuple[0];\n  var value = styleTuple[1];\n  node.style[prop] = value;\n}\n\nfunction concatWithSpace(a,b) {\n  if (!a) return b;\n  if (!b) return a;\n  return a + ' ' + b;\n}\n\nvar $$rAFSchedulerFactory = ['$$rAF', function($$rAF) {\n  var queue, cancelFn;\n\n  function scheduler(tasks) {\n    // we make a copy since RAFScheduler mutates the state\n    // of the passed in array variable and this would be difficult\n    // to track down on the outside code\n    queue = queue.concat(tasks);\n    nextTick();\n  }\n\n  queue = scheduler.queue = [];\n\n  /* waitUntilQuiet does two things:\n   * 1. It will run the FINAL `fn` value only when an uncancelled RAF has passed through\n   * 2. It will delay the next wave of tasks from running until the quiet `fn` has run.\n   *\n   * The motivation here is that animation code can request more time from the scheduler\n   * before the next wave runs. This allows for certain DOM properties such as classes to\n   * be resolved in time for the next animation to run.\n   */\n  scheduler.waitUntilQuiet = function(fn) {\n    if (cancelFn) cancelFn();\n\n    cancelFn = $$rAF(function() {\n      cancelFn = null;\n      fn();\n      nextTick();\n    });\n  };\n\n  return scheduler;\n\n  function nextTick() {\n    if (!queue.length) return;\n\n    var items = queue.shift();\n    for (var i = 0; i < items.length; i++) {\n      items[i]();\n    }\n\n    if (!cancelFn) {\n      $$rAF(function() {\n        if (!cancelFn) nextTick();\n      });\n    }\n  }\n}];\n\nvar $$AnimateChildrenDirective = [function() {\n  return function(scope, element, attrs) {\n    var val = attrs.ngAnimateChildren;\n    if (angular.isString(val) && val.length === 0) { //empty attribute\n      element.data(NG_ANIMATE_CHILDREN_DATA, true);\n    } else {\n      attrs.$observe('ngAnimateChildren', function(value) {\n        value = value === 'on' || value === 'true';\n        element.data(NG_ANIMATE_CHILDREN_DATA, value);\n      });\n    }\n  };\n}];\n\nvar ANIMATE_TIMER_KEY = '$$animateCss';\n\n/**\n * @ngdoc service\n * @name $animateCss\n * @kind object\n *\n * @description\n * The `$animateCss` service is a useful utility to trigger customized CSS-based transitions/keyframes\n * from a JavaScript-based animation or directly from a directive. The purpose of `$animateCss` is NOT\n * to side-step how `$animate` and ngAnimate work, but the goal is to allow pre-existing animations or\n * directives to create more complex animations that can be purely driven using CSS code.\n *\n * Note that only browsers that support CSS transitions and/or keyframe animations are capable of\n * rendering animations triggered via `$animateCss` (bad news for IE9 and lower).\n *\n * ## Usage\n * Once again, `$animateCss` is designed to be used inside of a registered JavaScript animation that\n * is powered by ngAnimate. It is possible to use `$animateCss` directly inside of a directive, however,\n * any automatic control over cancelling animations and/or preventing animations from being run on\n * child elements will not be handled by Angular. For this to work as expected, please use `$animate` to\n * trigger the animation and then setup a JavaScript animation that injects `$animateCss` to trigger\n * the CSS animation.\n *\n * The example below shows how we can create a folding animation on an element using `ng-if`:\n *\n * ```html\n * <!-- notice the `fold-animation` CSS class -->\n * <div ng-if=\"onOff\" class=\"fold-animation\">\n *   This element will go BOOM\n * </div>\n * <button ng-click=\"onOff=true\">Fold In</button>\n * ```\n *\n * Now we create the **JavaScript animation** that will trigger the CSS transition:\n *\n * ```js\n * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n *       var height = element[0].offsetHeight;\n *       return $animateCss(element, {\n *         from: { height:'0px' },\n *         to: { height:height + 'px' },\n *         duration: 1 // one second\n *       });\n *     }\n *   }\n * }]);\n * ```\n *\n * ## More Advanced Uses\n *\n * `$animateCss` is the underlying code that ngAnimate uses to power **CSS-based animations** behind the scenes. Therefore CSS hooks\n * like `.ng-EVENT`, `.ng-EVENT-active`, `.ng-EVENT-stagger` are all features that can be triggered using `$animateCss` via JavaScript code.\n *\n * This also means that just about any combination of adding classes, removing classes, setting styles, dynamically setting a keyframe animation,\n * applying a hardcoded duration or delay value, changing the animation easing or applying a stagger animation are all options that work with\n * `$animateCss`. The service itself is smart enough to figure out the combination of options and examine the element styling properties in order\n * to provide a working animation that will run in CSS.\n *\n * The example below showcases a more advanced version of the `.fold-animation` from the example above:\n *\n * ```js\n * ngModule.animation('.fold-animation', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n *       var height = element[0].offsetHeight;\n *       return $animateCss(element, {\n *         addClass: 'red large-text pulse-twice',\n *         easing: 'ease-out',\n *         from: { height:'0px' },\n *         to: { height:height + 'px' },\n *         duration: 1 // one second\n *       });\n *     }\n *   }\n * }]);\n * ```\n *\n * Since we're adding/removing CSS classes then the CSS transition will also pick those up:\n *\n * ```css\n * /&#42; since a hardcoded duration value of 1 was provided in the JavaScript animation code,\n * the CSS classes below will be transitioned despite them being defined as regular CSS classes &#42;/\n * .red { background:red; }\n * .large-text { font-size:20px; }\n *\n * /&#42; we can also use a keyframe animation and $animateCss will make it work alongside the transition &#42;/\n * .pulse-twice {\n *   animation: 0.5s pulse linear 2;\n *   -webkit-animation: 0.5s pulse linear 2;\n * }\n *\n * @keyframes pulse {\n *   from { transform: scale(0.5); }\n *   to { transform: scale(1.5); }\n * }\n *\n * @-webkit-keyframes pulse {\n *   from { -webkit-transform: scale(0.5); }\n *   to { -webkit-transform: scale(1.5); }\n * }\n * ```\n *\n * Given this complex combination of CSS classes, styles and options, `$animateCss` will figure everything out and make the animation happen.\n *\n * ## How the Options are handled\n *\n * `$animateCss` is very versatile and intelligent when it comes to figuring out what configurations to apply to the element to ensure the animation\n * works with the options provided. Say for example we were adding a class that contained a keyframe value and we wanted to also animate some inline\n * styles using the `from` and `to` properties.\n *\n * ```js\n * var animator = $animateCss(element, {\n *   from: { background:'red' },\n *   to: { background:'blue' }\n * });\n * animator.start();\n * ```\n *\n * ```css\n * .rotating-animation {\n *   animation:0.5s rotate linear;\n *   -webkit-animation:0.5s rotate linear;\n * }\n *\n * @keyframes rotate {\n *   from { transform: rotate(0deg); }\n *   to { transform: rotate(360deg); }\n * }\n *\n * @-webkit-keyframes rotate {\n *   from { -webkit-transform: rotate(0deg); }\n *   to { -webkit-transform: rotate(360deg); }\n * }\n * ```\n *\n * The missing pieces here are that we do not have a transition set (within the CSS code nor within the `$animateCss` options) and the duration of the animation is\n * going to be detected from what the keyframe styles on the CSS class are. In this event, `$animateCss` will automatically create an inline transition\n * style matching the duration detected from the keyframe style (which is present in the CSS class that is being added) and then prepare both the transition\n * and keyframe animations to run in parallel on the element. Then when the animation is underway the provided `from` and `to` CSS styles will be applied\n * and spread across the transition and keyframe animation.\n *\n * ## What is returned\n *\n * `$animateCss` works in two stages: a preparation phase and an animation phase. Therefore when `$animateCss` is first called it will NOT actually\n * start the animation. All that is going on here is that the element is being prepared for the animation (which means that the generated CSS classes are\n * added and removed on the element). Once `$animateCss` is called it will return an object with the following properties:\n *\n * ```js\n * var animator = $animateCss(element, { ... });\n * ```\n *\n * Now what do the contents of our `animator` variable look like:\n *\n * ```js\n * {\n *   // starts the animation\n *   start: Function,\n *\n *   // ends (aborts) the animation\n *   end: Function\n * }\n * ```\n *\n * To actually start the animation we need to run `animation.start()` which will then return a promise that we can hook into to detect when the animation ends.\n * If we choose not to run the animation then we MUST run `animation.end()` to perform a cleanup on the element (since some CSS classes and stlyes may have been\n * applied to the element during the preparation phase). Note that all other properties such as duration, delay, transitions and keyframes are just properties\n * and that changing them will not reconfigure the parameters of the animation.\n *\n * ### runner.done() vs runner.then()\n * It is documented that `animation.start()` will return a promise object and this is true, however, there is also an additional method available on the\n * runner called `.done(callbackFn)`. The done method works the same as `.finally(callbackFn)`, however, it does **not trigger a digest to occur**.\n * Therefore, for performance reasons, it's always best to use `runner.done(callback)` instead of `runner.then()`, `runner.catch()` or `runner.finally()`\n * unless you really need a digest to kick off afterwards.\n *\n * Keep in mind that, to make this easier, ngAnimate has tweaked the JS animations API to recognize when a runner instance is returned from $animateCss\n * (so there is no need to call `runner.done(doneFn)` inside of your JavaScript animation code).\n * Check the {@link ngAnimate.$animateCss#usage animation code above} to see how this works.\n *\n * @param {DOMElement} element the element that will be animated\n * @param {object} options the animation-related options that will be applied during the animation\n *\n * * `event` - The DOM event (e.g. enter, leave, move). When used, a generated CSS class of `ng-EVENT` and `ng-EVENT-active` will be applied\n * to the element during the animation. Multiple events can be provided when spaces are used as a separator. (Note that this will not perform any DOM operation.)\n * * `easing` - The CSS easing value that will be applied to the transition or keyframe animation (or both).\n * * `transitionStyle` - The raw CSS transition style that will be used (e.g. `1s linear all`).\n * * `keyframeStyle` - The raw CSS keyframe animation style that will be used (e.g. `1s my_animation linear`).\n * * `from` - The starting CSS styles (a key/value object) that will be applied at the start of the animation.\n * * `to` - The ending CSS styles (a key/value object) that will be applied across the animation via a CSS transition.\n * * `addClass` - A space separated list of CSS classes that will be added to the element and spread across the animation.\n * * `removeClass` - A space separated list of CSS classes that will be removed from the element and spread across the animation.\n * * `duration` - A number value representing the total duration of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `0`\n * is provided then the animation will be skipped entirely.\n * * `delay` - A number value representing the total delay of the transition and/or keyframe (note that a value of 1 is 1000ms). If a value of `true` is\n * used then whatever delay value is detected from the CSS classes will be mirrored on the elements styles (e.g. by setting delay true then the style value\n * of the element will be `transition-delay: DETECTED_VALUE`). Using `true` is useful when you want the CSS classes and inline styles to all share the same\n * CSS delay value.\n * * `stagger` - A numeric time value representing the delay between successively animated elements\n * ({@link ngAnimate#css-staggering-animations Click here to learn how CSS-based staggering works in ngAnimate.})\n * * `staggerIndex` - The numeric index representing the stagger item (e.g. a value of 5 is equal to the sixth item in the stagger; therefore when a\n * * `stagger` option value of `0.1` is used then there will be a stagger delay of `600ms`)\n * * `applyClassesEarly` - Whether or not the classes being added or removed will be used when detecting the animation. This is set by `$animate` when enter/leave/move animations are fired to ensure that the CSS classes are resolved in time. (Note that this will prevent any transitions from occuring on the classes being added and removed.)\n * * `cleanupStyles` - Whether or not the provided `from` and `to` styles will be removed once\n *    the animation is closed. This is useful for when the styles are used purely for the sake of\n *    the animation and do not have a lasting visual effect on the element (e.g. a colapse and open animation).\n *    By default this value is set to `false`.\n *\n * @return {object} an object with start and end methods and details about the animation.\n *\n * * `start` - The method to start the animation. This will return a `Promise` when called.\n * * `end` - This method will cancel the animation and remove all applied CSS classes and styles.\n */\nvar ONE_SECOND = 1000;\nvar BASE_TEN = 10;\n\nvar ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;\nvar CLOSING_TIME_BUFFER = 1.5;\n\nvar DETECT_CSS_PROPERTIES = {\n  transitionDuration:      TRANSITION_DURATION_PROP,\n  transitionDelay:         TRANSITION_DELAY_PROP,\n  transitionProperty:      TRANSITION_PROP + PROPERTY_KEY,\n  animationDuration:       ANIMATION_DURATION_PROP,\n  animationDelay:          ANIMATION_DELAY_PROP,\n  animationIterationCount: ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY\n};\n\nvar DETECT_STAGGER_CSS_PROPERTIES = {\n  transitionDuration:      TRANSITION_DURATION_PROP,\n  transitionDelay:         TRANSITION_DELAY_PROP,\n  animationDuration:       ANIMATION_DURATION_PROP,\n  animationDelay:          ANIMATION_DELAY_PROP\n};\n\nfunction getCssKeyframeDurationStyle(duration) {\n  return [ANIMATION_DURATION_PROP, duration + 's'];\n}\n\nfunction getCssDelayStyle(delay, isKeyframeAnimation) {\n  var prop = isKeyframeAnimation ? ANIMATION_DELAY_PROP : TRANSITION_DELAY_PROP;\n  return [prop, delay + 's'];\n}\n\nfunction computeCssStyles($window, element, properties) {\n  var styles = Object.create(null);\n  var detectedStyles = $window.getComputedStyle(element) || {};\n  forEach(properties, function(formalStyleName, actualStyleName) {\n    var val = detectedStyles[formalStyleName];\n    if (val) {\n      var c = val.charAt(0);\n\n      // only numerical-based values have a negative sign or digit as the first value\n      if (c === '-' || c === '+' || c >= 0) {\n        val = parseMaxTime(val);\n      }\n\n      // by setting this to null in the event that the delay is not set or is set directly as 0\n      // then we can still allow for zegative values to be used later on and not mistake this\n      // value for being greater than any other negative value.\n      if (val === 0) {\n        val = null;\n      }\n      styles[actualStyleName] = val;\n    }\n  });\n\n  return styles;\n}\n\nfunction parseMaxTime(str) {\n  var maxValue = 0;\n  var values = str.split(/\\s*,\\s*/);\n  forEach(values, function(value) {\n    // it's always safe to consider only second values and omit `ms` values since\n    // getComputedStyle will always handle the conversion for us\n    if (value.charAt(value.length - 1) == 's') {\n      value = value.substring(0, value.length - 1);\n    }\n    value = parseFloat(value) || 0;\n    maxValue = maxValue ? Math.max(value, maxValue) : value;\n  });\n  return maxValue;\n}\n\nfunction truthyTimingValue(val) {\n  return val === 0 || val != null;\n}\n\nfunction getCssTransitionDurationStyle(duration, applyOnlyDuration) {\n  var style = TRANSITION_PROP;\n  var value = duration + 's';\n  if (applyOnlyDuration) {\n    style += DURATION_KEY;\n  } else {\n    value += ' linear all';\n  }\n  return [style, value];\n}\n\nfunction createLocalCacheLookup() {\n  var cache = Object.create(null);\n  return {\n    flush: function() {\n      cache = Object.create(null);\n    },\n\n    count: function(key) {\n      var entry = cache[key];\n      return entry ? entry.total : 0;\n    },\n\n    get: function(key) {\n      var entry = cache[key];\n      return entry && entry.value;\n    },\n\n    put: function(key, value) {\n      if (!cache[key]) {\n        cache[key] = { total: 1, value: value };\n      } else {\n        cache[key].total++;\n      }\n    }\n  };\n}\n\n// we do not reassign an already present style value since\n// if we detect the style property value again we may be\n// detecting styles that were added via the `from` styles.\n// We make use of `isDefined` here since an empty string\n// or null value (which is what getPropertyValue will return\n// for a non-existing style) will still be marked as a valid\n// value for the style (a falsy value implies that the style\n// is to be removed at the end of the animation). If we had a simple\n// \"OR\" statement then it would not be enough to catch that.\nfunction registerRestorableStyles(backup, node, properties) {\n  forEach(properties, function(prop) {\n    backup[prop] = isDefined(backup[prop])\n        ? backup[prop]\n        : node.style.getPropertyValue(prop);\n  });\n}\n\nvar $AnimateCssProvider = ['$animateProvider', function($animateProvider) {\n  var gcsLookup = createLocalCacheLookup();\n  var gcsStaggerLookup = createLocalCacheLookup();\n\n  this.$get = ['$window', '$$jqLite', '$$AnimateRunner', '$timeout',\n               '$$forceReflow', '$sniffer', '$$rAFScheduler', '$animate',\n       function($window,   $$jqLite,   $$AnimateRunner,   $timeout,\n                $$forceReflow,   $sniffer,   $$rAFScheduler, $animate) {\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    var parentCounter = 0;\n    function gcsHashFn(node, extraClasses) {\n      var KEY = \"$$ngAnimateParentKey\";\n      var parentNode = node.parentNode;\n      var parentID = parentNode[KEY] || (parentNode[KEY] = ++parentCounter);\n      return parentID + '-' + node.getAttribute('class') + '-' + extraClasses;\n    }\n\n    function computeCachedCssStyles(node, className, cacheKey, properties) {\n      var timings = gcsLookup.get(cacheKey);\n\n      if (!timings) {\n        timings = computeCssStyles($window, node, properties);\n        if (timings.animationIterationCount === 'infinite') {\n          timings.animationIterationCount = 1;\n        }\n      }\n\n      // we keep putting this in multiple times even though the value and the cacheKey are the same\n      // because we're keeping an interal tally of how many duplicate animations are detected.\n      gcsLookup.put(cacheKey, timings);\n      return timings;\n    }\n\n    function computeCachedCssStaggerStyles(node, className, cacheKey, properties) {\n      var stagger;\n\n      // if we have one or more existing matches of matching elements\n      // containing the same parent + CSS styles (which is how cacheKey works)\n      // then staggering is possible\n      if (gcsLookup.count(cacheKey) > 0) {\n        stagger = gcsStaggerLookup.get(cacheKey);\n\n        if (!stagger) {\n          var staggerClassName = pendClasses(className, '-stagger');\n\n          $$jqLite.addClass(node, staggerClassName);\n\n          stagger = computeCssStyles($window, node, properties);\n\n          // force the conversion of a null value to zero incase not set\n          stagger.animationDuration = Math.max(stagger.animationDuration, 0);\n          stagger.transitionDuration = Math.max(stagger.transitionDuration, 0);\n\n          $$jqLite.removeClass(node, staggerClassName);\n\n          gcsStaggerLookup.put(cacheKey, stagger);\n        }\n      }\n\n      return stagger || {};\n    }\n\n    var cancelLastRAFRequest;\n    var rafWaitQueue = [];\n    function waitUntilQuiet(callback) {\n      rafWaitQueue.push(callback);\n      $$rAFScheduler.waitUntilQuiet(function() {\n        gcsLookup.flush();\n        gcsStaggerLookup.flush();\n\n        // DO NOT REMOVE THIS LINE OR REFACTOR OUT THE `pageWidth` variable.\n        // PLEASE EXAMINE THE `$$forceReflow` service to understand why.\n        var pageWidth = $$forceReflow();\n\n        // we use a for loop to ensure that if the queue is changed\n        // during this looping then it will consider new requests\n        for (var i = 0; i < rafWaitQueue.length; i++) {\n          rafWaitQueue[i](pageWidth);\n        }\n        rafWaitQueue.length = 0;\n      });\n    }\n\n    function computeTimings(node, className, cacheKey) {\n      var timings = computeCachedCssStyles(node, className, cacheKey, DETECT_CSS_PROPERTIES);\n      var aD = timings.animationDelay;\n      var tD = timings.transitionDelay;\n      timings.maxDelay = aD && tD\n          ? Math.max(aD, tD)\n          : (aD || tD);\n      timings.maxDuration = Math.max(\n          timings.animationDuration * timings.animationIterationCount,\n          timings.transitionDuration);\n\n      return timings;\n    }\n\n    return function init(element, options) {\n      var restoreStyles = {};\n      var node = getDomNode(element);\n      if (!node\n          || !node.parentNode\n          || !$animate.enabled()) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      options = prepareAnimationOptions(options);\n\n      var temporaryStyles = [];\n      var classes = element.attr('class');\n      var styles = packageStyles(options);\n      var animationClosed;\n      var animationPaused;\n      var animationCompleted;\n      var runner;\n      var runnerHost;\n      var maxDelay;\n      var maxDelayTime;\n      var maxDuration;\n      var maxDurationTime;\n\n      if (options.duration === 0 || (!$sniffer.animations && !$sniffer.transitions)) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      var method = options.event && isArray(options.event)\n            ? options.event.join(' ')\n            : options.event;\n\n      var isStructural = method && options.structural;\n      var structuralClassName = '';\n      var addRemoveClassName = '';\n\n      if (isStructural) {\n        structuralClassName = pendClasses(method, EVENT_CLASS_PREFIX, true);\n      } else if (method) {\n        structuralClassName = method;\n      }\n\n      if (options.addClass) {\n        addRemoveClassName += pendClasses(options.addClass, ADD_CLASS_SUFFIX);\n      }\n\n      if (options.removeClass) {\n        if (addRemoveClassName.length) {\n          addRemoveClassName += ' ';\n        }\n        addRemoveClassName += pendClasses(options.removeClass, REMOVE_CLASS_SUFFIX);\n      }\n\n      // there may be a situation where a structural animation is combined together\n      // with CSS classes that need to resolve before the animation is computed.\n      // However this means that there is no explicit CSS code to block the animation\n      // from happening (by setting 0s none in the class name). If this is the case\n      // we need to apply the classes before the first rAF so we know to continue if\n      // there actually is a detected transition or keyframe animation\n      if (options.applyClassesEarly && addRemoveClassName.length) {\n        applyAnimationClasses(element, options);\n      }\n\n      var preparationClasses = [structuralClassName, addRemoveClassName].join(' ').trim();\n      var fullClassName = classes + ' ' + preparationClasses;\n      var activeClasses = pendClasses(preparationClasses, ACTIVE_CLASS_SUFFIX);\n      var hasToStyles = styles.to && Object.keys(styles.to).length > 0;\n      var containsKeyframeAnimation = (options.keyframeStyle || '').length > 0;\n\n      // there is no way we can trigger an animation if no styles and\n      // no classes are being applied which would then trigger a transition,\n      // unless there a is raw keyframe value that is applied to the element.\n      if (!containsKeyframeAnimation\n           && !hasToStyles\n           && !preparationClasses) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      var cacheKey, stagger;\n      if (options.stagger > 0) {\n        var staggerVal = parseFloat(options.stagger);\n        stagger = {\n          transitionDelay: staggerVal,\n          animationDelay: staggerVal,\n          transitionDuration: 0,\n          animationDuration: 0\n        };\n      } else {\n        cacheKey = gcsHashFn(node, fullClassName);\n        stagger = computeCachedCssStaggerStyles(node, preparationClasses, cacheKey, DETECT_STAGGER_CSS_PROPERTIES);\n      }\n\n      if (!options.$$skipPreparationClasses) {\n        $$jqLite.addClass(element, preparationClasses);\n      }\n\n      var applyOnlyDuration;\n\n      if (options.transitionStyle) {\n        var transitionStyle = [TRANSITION_PROP, options.transitionStyle];\n        applyInlineStyle(node, transitionStyle);\n        temporaryStyles.push(transitionStyle);\n      }\n\n      if (options.duration >= 0) {\n        applyOnlyDuration = node.style[TRANSITION_PROP].length > 0;\n        var durationStyle = getCssTransitionDurationStyle(options.duration, applyOnlyDuration);\n\n        // we set the duration so that it will be picked up by getComputedStyle later\n        applyInlineStyle(node, durationStyle);\n        temporaryStyles.push(durationStyle);\n      }\n\n      if (options.keyframeStyle) {\n        var keyframeStyle = [ANIMATION_PROP, options.keyframeStyle];\n        applyInlineStyle(node, keyframeStyle);\n        temporaryStyles.push(keyframeStyle);\n      }\n\n      var itemIndex = stagger\n          ? options.staggerIndex >= 0\n              ? options.staggerIndex\n              : gcsLookup.count(cacheKey)\n          : 0;\n\n      var isFirst = itemIndex === 0;\n\n      // this is a pre-emptive way of forcing the setup classes to be added and applied INSTANTLY\n      // without causing any combination of transitions to kick in. By adding a negative delay value\n      // it forces the setup class' transition to end immediately. We later then remove the negative\n      // transition delay to allow for the transition to naturally do it's thing. The beauty here is\n      // that if there is no transition defined then nothing will happen and this will also allow\n      // other transitions to be stacked on top of each other without any chopping them out.\n      if (isFirst && !options.skipBlocking) {\n        blockTransitions(node, SAFE_FAST_FORWARD_DURATION_VALUE);\n      }\n\n      var timings = computeTimings(node, fullClassName, cacheKey);\n      var relativeDelay = timings.maxDelay;\n      maxDelay = Math.max(relativeDelay, 0);\n      maxDuration = timings.maxDuration;\n\n      var flags = {};\n      flags.hasTransitions          = timings.transitionDuration > 0;\n      flags.hasAnimations           = timings.animationDuration > 0;\n      flags.hasTransitionAll        = flags.hasTransitions && timings.transitionProperty == 'all';\n      flags.applyTransitionDuration = hasToStyles && (\n                                        (flags.hasTransitions && !flags.hasTransitionAll)\n                                         || (flags.hasAnimations && !flags.hasTransitions));\n      flags.applyAnimationDuration  = options.duration && flags.hasAnimations;\n      flags.applyTransitionDelay    = truthyTimingValue(options.delay) && (flags.applyTransitionDuration || flags.hasTransitions);\n      flags.applyAnimationDelay     = truthyTimingValue(options.delay) && flags.hasAnimations;\n      flags.recalculateTimingStyles = addRemoveClassName.length > 0;\n\n      if (flags.applyTransitionDuration || flags.applyAnimationDuration) {\n        maxDuration = options.duration ? parseFloat(options.duration) : maxDuration;\n\n        if (flags.applyTransitionDuration) {\n          flags.hasTransitions = true;\n          timings.transitionDuration = maxDuration;\n          applyOnlyDuration = node.style[TRANSITION_PROP + PROPERTY_KEY].length > 0;\n          temporaryStyles.push(getCssTransitionDurationStyle(maxDuration, applyOnlyDuration));\n        }\n\n        if (flags.applyAnimationDuration) {\n          flags.hasAnimations = true;\n          timings.animationDuration = maxDuration;\n          temporaryStyles.push(getCssKeyframeDurationStyle(maxDuration));\n        }\n      }\n\n      if (maxDuration === 0 && !flags.recalculateTimingStyles) {\n        return closeAndReturnNoopAnimator();\n      }\n\n      if (options.delay != null) {\n        var delayStyle = parseFloat(options.delay);\n\n        if (flags.applyTransitionDelay) {\n          temporaryStyles.push(getCssDelayStyle(delayStyle));\n        }\n\n        if (flags.applyAnimationDelay) {\n          temporaryStyles.push(getCssDelayStyle(delayStyle, true));\n        }\n      }\n\n      // we need to recalculate the delay value since we used a pre-emptive negative\n      // delay value and the delay value is required for the final event checking. This\n      // property will ensure that this will happen after the RAF phase has passed.\n      if (options.duration == null && timings.transitionDuration > 0) {\n        flags.recalculateTimingStyles = flags.recalculateTimingStyles || isFirst;\n      }\n\n      maxDelayTime = maxDelay * ONE_SECOND;\n      maxDurationTime = maxDuration * ONE_SECOND;\n      if (!options.skipBlocking) {\n        flags.blockTransition = timings.transitionDuration > 0;\n        flags.blockKeyframeAnimation = timings.animationDuration > 0 &&\n                                       stagger.animationDelay > 0 &&\n                                       stagger.animationDuration === 0;\n      }\n\n      if (options.from) {\n        if (options.cleanupStyles) {\n          registerRestorableStyles(restoreStyles, node, Object.keys(options.from));\n        }\n        applyAnimationFromStyles(element, options);\n      }\n\n      if (flags.blockTransition || flags.blockKeyframeAnimation) {\n        applyBlocking(maxDuration);\n      } else if (!options.skipBlocking) {\n        blockTransitions(node, false);\n      }\n\n      // TODO(matsko): for 1.5 change this code to have an animator object for better debugging\n      return {\n        $$willAnimate: true,\n        end: endFn,\n        start: function() {\n          if (animationClosed) return;\n\n          runnerHost = {\n            end: endFn,\n            cancel: cancelFn,\n            resume: null, //this will be set during the start() phase\n            pause: null\n          };\n\n          runner = new $$AnimateRunner(runnerHost);\n\n          waitUntilQuiet(start);\n\n          // we don't have access to pause/resume the animation\n          // since it hasn't run yet. AnimateRunner will therefore\n          // set noop functions for resume and pause and they will\n          // later be overridden once the animation is triggered\n          return runner;\n        }\n      };\n\n      function endFn() {\n        close();\n      }\n\n      function cancelFn() {\n        close(true);\n      }\n\n      function close(rejected) { // jshint ignore:line\n        // if the promise has been called already then we shouldn't close\n        // the animation again\n        if (animationClosed || (animationCompleted && animationPaused)) return;\n        animationClosed = true;\n        animationPaused = false;\n\n        if (!options.$$skipPreparationClasses) {\n          $$jqLite.removeClass(element, preparationClasses);\n        }\n        $$jqLite.removeClass(element, activeClasses);\n\n        blockKeyframeAnimations(node, false);\n        blockTransitions(node, false);\n\n        forEach(temporaryStyles, function(entry) {\n          // There is only one way to remove inline style properties entirely from elements.\n          // By using `removeProperty` this works, but we need to convert camel-cased CSS\n          // styles down to hyphenated values.\n          node.style[entry[0]] = '';\n        });\n\n        applyAnimationClasses(element, options);\n        applyAnimationStyles(element, options);\n\n        if (Object.keys(restoreStyles).length) {\n          forEach(restoreStyles, function(value, prop) {\n            value ? node.style.setProperty(prop, value)\n                  : node.style.removeProperty(prop);\n          });\n        }\n\n        // the reason why we have this option is to allow a synchronous closing callback\n        // that is fired as SOON as the animation ends (when the CSS is removed) or if\n        // the animation never takes off at all. A good example is a leave animation since\n        // the element must be removed just after the animation is over or else the element\n        // will appear on screen for one animation frame causing an overbearing flicker.\n        if (options.onDone) {\n          options.onDone();\n        }\n\n        // if the preparation function fails then the promise is not setup\n        if (runner) {\n          runner.complete(!rejected);\n        }\n      }\n\n      function applyBlocking(duration) {\n        if (flags.blockTransition) {\n          blockTransitions(node, duration);\n        }\n\n        if (flags.blockKeyframeAnimation) {\n          blockKeyframeAnimations(node, !!duration);\n        }\n      }\n\n      function closeAndReturnNoopAnimator() {\n        runner = new $$AnimateRunner({\n          end: endFn,\n          cancel: cancelFn\n        });\n\n        // should flush the cache animation\n        waitUntilQuiet(noop);\n        close();\n\n        return {\n          $$willAnimate: false,\n          start: function() {\n            return runner;\n          },\n          end: endFn\n        };\n      }\n\n      function start() {\n        if (animationClosed) return;\n        if (!node.parentNode) {\n          close();\n          return;\n        }\n\n        var startTime, events = [];\n\n        // even though we only pause keyframe animations here the pause flag\n        // will still happen when transitions are used. Only the transition will\n        // not be paused since that is not possible. If the animation ends when\n        // paused then it will not complete until unpaused or cancelled.\n        var playPause = function(playAnimation) {\n          if (!animationCompleted) {\n            animationPaused = !playAnimation;\n            if (timings.animationDuration) {\n              var value = blockKeyframeAnimations(node, animationPaused);\n              animationPaused\n                  ? temporaryStyles.push(value)\n                  : removeFromArray(temporaryStyles, value);\n            }\n          } else if (animationPaused && playAnimation) {\n            animationPaused = false;\n            close();\n          }\n        };\n\n        // checking the stagger duration prevents an accidently cascade of the CSS delay style\n        // being inherited from the parent. If the transition duration is zero then we can safely\n        // rely that the delay value is an intential stagger delay style.\n        var maxStagger = itemIndex > 0\n                         && ((timings.transitionDuration && stagger.transitionDuration === 0) ||\n                            (timings.animationDuration && stagger.animationDuration === 0))\n                         && Math.max(stagger.animationDelay, stagger.transitionDelay);\n        if (maxStagger) {\n          $timeout(triggerAnimationStart,\n                   Math.floor(maxStagger * itemIndex * ONE_SECOND),\n                   false);\n        } else {\n          triggerAnimationStart();\n        }\n\n        // this will decorate the existing promise runner with pause/resume methods\n        runnerHost.resume = function() {\n          playPause(true);\n        };\n\n        runnerHost.pause = function() {\n          playPause(false);\n        };\n\n        function triggerAnimationStart() {\n          // just incase a stagger animation kicks in when the animation\n          // itself was cancelled entirely\n          if (animationClosed) return;\n\n          applyBlocking(false);\n\n          forEach(temporaryStyles, function(entry) {\n            var key = entry[0];\n            var value = entry[1];\n            node.style[key] = value;\n          });\n\n          applyAnimationClasses(element, options);\n          $$jqLite.addClass(element, activeClasses);\n\n          if (flags.recalculateTimingStyles) {\n            fullClassName = node.className + ' ' + preparationClasses;\n            cacheKey = gcsHashFn(node, fullClassName);\n\n            timings = computeTimings(node, fullClassName, cacheKey);\n            relativeDelay = timings.maxDelay;\n            maxDelay = Math.max(relativeDelay, 0);\n            maxDuration = timings.maxDuration;\n\n            if (maxDuration === 0) {\n              close();\n              return;\n            }\n\n            flags.hasTransitions = timings.transitionDuration > 0;\n            flags.hasAnimations = timings.animationDuration > 0;\n          }\n\n          if (flags.applyAnimationDelay) {\n            relativeDelay = typeof options.delay !== \"boolean\" && truthyTimingValue(options.delay)\n                  ? parseFloat(options.delay)\n                  : relativeDelay;\n\n            maxDelay = Math.max(relativeDelay, 0);\n            timings.animationDelay = relativeDelay;\n            delayStyle = getCssDelayStyle(relativeDelay, true);\n            temporaryStyles.push(delayStyle);\n            node.style[delayStyle[0]] = delayStyle[1];\n          }\n\n          maxDelayTime = maxDelay * ONE_SECOND;\n          maxDurationTime = maxDuration * ONE_SECOND;\n\n          if (options.easing) {\n            var easeProp, easeVal = options.easing;\n            if (flags.hasTransitions) {\n              easeProp = TRANSITION_PROP + TIMING_KEY;\n              temporaryStyles.push([easeProp, easeVal]);\n              node.style[easeProp] = easeVal;\n            }\n            if (flags.hasAnimations) {\n              easeProp = ANIMATION_PROP + TIMING_KEY;\n              temporaryStyles.push([easeProp, easeVal]);\n              node.style[easeProp] = easeVal;\n            }\n          }\n\n          if (timings.transitionDuration) {\n            events.push(TRANSITIONEND_EVENT);\n          }\n\n          if (timings.animationDuration) {\n            events.push(ANIMATIONEND_EVENT);\n          }\n\n          startTime = Date.now();\n          var timerTime = maxDelayTime + CLOSING_TIME_BUFFER * maxDurationTime;\n          var endTime = startTime + timerTime;\n\n          var animationsData = element.data(ANIMATE_TIMER_KEY) || [];\n          var setupFallbackTimer = true;\n          if (animationsData.length) {\n            var currentTimerData = animationsData[0];\n            setupFallbackTimer = endTime > currentTimerData.expectedEndTime;\n            if (setupFallbackTimer) {\n              $timeout.cancel(currentTimerData.timer);\n            } else {\n              animationsData.push(close);\n            }\n          }\n\n          if (setupFallbackTimer) {\n            var timer = $timeout(onAnimationExpired, timerTime, false);\n            animationsData[0] = {\n              timer: timer,\n              expectedEndTime: endTime\n            };\n            animationsData.push(close);\n            element.data(ANIMATE_TIMER_KEY, animationsData);\n          }\n\n          element.on(events.join(' '), onAnimationProgress);\n          if (options.to) {\n            if (options.cleanupStyles) {\n              registerRestorableStyles(restoreStyles, node, Object.keys(options.to));\n            }\n            applyAnimationToStyles(element, options);\n          }\n        }\n\n        function onAnimationExpired() {\n          var animationsData = element.data(ANIMATE_TIMER_KEY);\n\n          // this will be false in the event that the element was\n          // removed from the DOM (via a leave animation or something\n          // similar)\n          if (animationsData) {\n            for (var i = 1; i < animationsData.length; i++) {\n              animationsData[i]();\n            }\n            element.removeData(ANIMATE_TIMER_KEY);\n          }\n        }\n\n        function onAnimationProgress(event) {\n          event.stopPropagation();\n          var ev = event.originalEvent || event;\n          var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();\n\n          /* Firefox (or possibly just Gecko) likes to not round values up\n           * when a ms measurement is used for the animation */\n          var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));\n\n          /* $manualTimeStamp is a mocked timeStamp value which is set\n           * within browserTrigger(). This is only here so that tests can\n           * mock animations properly. Real events fallback to event.timeStamp,\n           * or, if they don't, then a timeStamp is automatically created for them.\n           * We're checking to see if the timeStamp surpasses the expected delay,\n           * but we're using elapsedTime instead of the timeStamp on the 2nd\n           * pre-condition since animations sometimes close off early */\n          if (Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {\n            // we set this flag to ensure that if the transition is paused then, when resumed,\n            // the animation will automatically close itself since transitions cannot be paused.\n            animationCompleted = true;\n            close();\n          }\n        }\n      }\n    };\n  }];\n}];\n\nvar $$AnimateCssDriverProvider = ['$$animationProvider', function($$animationProvider) {\n  $$animationProvider.drivers.push('$$animateCssDriver');\n\n  var NG_ANIMATE_SHIM_CLASS_NAME = 'ng-animate-shim';\n  var NG_ANIMATE_ANCHOR_CLASS_NAME = 'ng-anchor';\n\n  var NG_OUT_ANCHOR_CLASS_NAME = 'ng-anchor-out';\n  var NG_IN_ANCHOR_CLASS_NAME = 'ng-anchor-in';\n\n  function isDocumentFragment(node) {\n    return node.parentNode && node.parentNode.nodeType === 11;\n  }\n\n  this.$get = ['$animateCss', '$rootScope', '$$AnimateRunner', '$rootElement', '$sniffer', '$$jqLite', '$document',\n       function($animateCss,   $rootScope,   $$AnimateRunner,   $rootElement,   $sniffer,   $$jqLite,   $document) {\n\n    // only browsers that support these properties can render animations\n    if (!$sniffer.animations && !$sniffer.transitions) return noop;\n\n    var bodyNode = $document[0].body;\n    var rootNode = getDomNode($rootElement);\n\n    var rootBodyElement = jqLite(\n      // this is to avoid using something that exists outside of the body\n      // we also special case the doc fragement case because our unit test code\n      // appends the $rootElement to the body after the app has been bootstrapped\n      isDocumentFragment(rootNode) || bodyNode.contains(rootNode) ? rootNode : bodyNode\n    );\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    return function initDriverFn(animationDetails) {\n      return animationDetails.from && animationDetails.to\n          ? prepareFromToAnchorAnimation(animationDetails.from,\n                                         animationDetails.to,\n                                         animationDetails.classes,\n                                         animationDetails.anchors)\n          : prepareRegularAnimation(animationDetails);\n    };\n\n    function filterCssClasses(classes) {\n      //remove all the `ng-` stuff\n      return classes.replace(/\\bng-\\S+\\b/g, '');\n    }\n\n    function getUniqueValues(a, b) {\n      if (isString(a)) a = a.split(' ');\n      if (isString(b)) b = b.split(' ');\n      return a.filter(function(val) {\n        return b.indexOf(val) === -1;\n      }).join(' ');\n    }\n\n    function prepareAnchoredAnimation(classes, outAnchor, inAnchor) {\n      var clone = jqLite(getDomNode(outAnchor).cloneNode(true));\n      var startingClasses = filterCssClasses(getClassVal(clone));\n\n      outAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);\n      inAnchor.addClass(NG_ANIMATE_SHIM_CLASS_NAME);\n\n      clone.addClass(NG_ANIMATE_ANCHOR_CLASS_NAME);\n\n      rootBodyElement.append(clone);\n\n      var animatorIn, animatorOut = prepareOutAnimation();\n\n      // the user may not end up using the `out` animation and\n      // only making use of the `in` animation or vice-versa.\n      // In either case we should allow this and not assume the\n      // animation is over unless both animations are not used.\n      if (!animatorOut) {\n        animatorIn = prepareInAnimation();\n        if (!animatorIn) {\n          return end();\n        }\n      }\n\n      var startingAnimator = animatorOut || animatorIn;\n\n      return {\n        start: function() {\n          var runner;\n\n          var currentAnimation = startingAnimator.start();\n          currentAnimation.done(function() {\n            currentAnimation = null;\n            if (!animatorIn) {\n              animatorIn = prepareInAnimation();\n              if (animatorIn) {\n                currentAnimation = animatorIn.start();\n                currentAnimation.done(function() {\n                  currentAnimation = null;\n                  end();\n                  runner.complete();\n                });\n                return currentAnimation;\n              }\n            }\n            // in the event that there is no `in` animation\n            end();\n            runner.complete();\n          });\n\n          runner = new $$AnimateRunner({\n            end: endFn,\n            cancel: endFn\n          });\n\n          return runner;\n\n          function endFn() {\n            if (currentAnimation) {\n              currentAnimation.end();\n            }\n          }\n        }\n      };\n\n      function calculateAnchorStyles(anchor) {\n        var styles = {};\n\n        var coords = getDomNode(anchor).getBoundingClientRect();\n\n        // we iterate directly since safari messes up and doesn't return\n        // all the keys for the coods object when iterated\n        forEach(['width','height','top','left'], function(key) {\n          var value = coords[key];\n          switch (key) {\n            case 'top':\n              value += bodyNode.scrollTop;\n              break;\n            case 'left':\n              value += bodyNode.scrollLeft;\n              break;\n          }\n          styles[key] = Math.floor(value) + 'px';\n        });\n        return styles;\n      }\n\n      function prepareOutAnimation() {\n        var animator = $animateCss(clone, {\n          addClass: NG_OUT_ANCHOR_CLASS_NAME,\n          delay: true,\n          from: calculateAnchorStyles(outAnchor)\n        });\n\n        // read the comment within `prepareRegularAnimation` to understand\n        // why this check is necessary\n        return animator.$$willAnimate ? animator : null;\n      }\n\n      function getClassVal(element) {\n        return element.attr('class') || '';\n      }\n\n      function prepareInAnimation() {\n        var endingClasses = filterCssClasses(getClassVal(inAnchor));\n        var toAdd = getUniqueValues(endingClasses, startingClasses);\n        var toRemove = getUniqueValues(startingClasses, endingClasses);\n\n        var animator = $animateCss(clone, {\n          to: calculateAnchorStyles(inAnchor),\n          addClass: NG_IN_ANCHOR_CLASS_NAME + ' ' + toAdd,\n          removeClass: NG_OUT_ANCHOR_CLASS_NAME + ' ' + toRemove,\n          delay: true\n        });\n\n        // read the comment within `prepareRegularAnimation` to understand\n        // why this check is necessary\n        return animator.$$willAnimate ? animator : null;\n      }\n\n      function end() {\n        clone.remove();\n        outAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);\n        inAnchor.removeClass(NG_ANIMATE_SHIM_CLASS_NAME);\n      }\n    }\n\n    function prepareFromToAnchorAnimation(from, to, classes, anchors) {\n      var fromAnimation = prepareRegularAnimation(from, noop);\n      var toAnimation = prepareRegularAnimation(to, noop);\n\n      var anchorAnimations = [];\n      forEach(anchors, function(anchor) {\n        var outElement = anchor['out'];\n        var inElement = anchor['in'];\n        var animator = prepareAnchoredAnimation(classes, outElement, inElement);\n        if (animator) {\n          anchorAnimations.push(animator);\n        }\n      });\n\n      // no point in doing anything when there are no elements to animate\n      if (!fromAnimation && !toAnimation && anchorAnimations.length === 0) return;\n\n      return {\n        start: function() {\n          var animationRunners = [];\n\n          if (fromAnimation) {\n            animationRunners.push(fromAnimation.start());\n          }\n\n          if (toAnimation) {\n            animationRunners.push(toAnimation.start());\n          }\n\n          forEach(anchorAnimations, function(animation) {\n            animationRunners.push(animation.start());\n          });\n\n          var runner = new $$AnimateRunner({\n            end: endFn,\n            cancel: endFn // CSS-driven animations cannot be cancelled, only ended\n          });\n\n          $$AnimateRunner.all(animationRunners, function(status) {\n            runner.complete(status);\n          });\n\n          return runner;\n\n          function endFn() {\n            forEach(animationRunners, function(runner) {\n              runner.end();\n            });\n          }\n        }\n      };\n    }\n\n    function prepareRegularAnimation(animationDetails) {\n      var element = animationDetails.element;\n      var options = animationDetails.options || {};\n\n      if (animationDetails.structural) {\n        options.event = animationDetails.event;\n        options.structural = true;\n        options.applyClassesEarly = true;\n\n        // we special case the leave animation since we want to ensure that\n        // the element is removed as soon as the animation is over. Otherwise\n        // a flicker might appear or the element may not be removed at all\n        if (animationDetails.event === 'leave') {\n          options.onDone = options.domOperation;\n        }\n      }\n\n      // We assign the preparationClasses as the actual animation event since\n      // the internals of $animateCss will just suffix the event token values\n      // with `-active` to trigger the animation.\n      if (options.preparationClasses) {\n        options.event = concatWithSpace(options.event, options.preparationClasses);\n      }\n\n      var animator = $animateCss(element, options);\n\n      // the driver lookup code inside of $$animation attempts to spawn a\n      // driver one by one until a driver returns a.$$willAnimate animator object.\n      // $animateCss will always return an object, however, it will pass in\n      // a flag as a hint as to whether an animation was detected or not\n      return animator.$$willAnimate ? animator : null;\n    }\n  }];\n}];\n\n// TODO(matsko): use caching here to speed things up for detection\n// TODO(matsko): add documentation\n//  by the time...\n\nvar $$AnimateJsProvider = ['$animateProvider', function($animateProvider) {\n  this.$get = ['$injector', '$$AnimateRunner', '$$jqLite',\n       function($injector,   $$AnimateRunner,   $$jqLite) {\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n         // $animateJs(element, 'enter');\n    return function(element, event, classes, options) {\n      // the `classes` argument is optional and if it is not used\n      // then the classes will be resolved from the element's className\n      // property as well as options.addClass/options.removeClass.\n      if (arguments.length === 3 && isObject(classes)) {\n        options = classes;\n        classes = null;\n      }\n\n      options = prepareAnimationOptions(options);\n      if (!classes) {\n        classes = element.attr('class') || '';\n        if (options.addClass) {\n          classes += ' ' + options.addClass;\n        }\n        if (options.removeClass) {\n          classes += ' ' + options.removeClass;\n        }\n      }\n\n      var classesToAdd = options.addClass;\n      var classesToRemove = options.removeClass;\n\n      // the lookupAnimations function returns a series of animation objects that are\n      // matched up with one or more of the CSS classes. These animation objects are\n      // defined via the module.animation factory function. If nothing is detected then\n      // we don't return anything which then makes $animation query the next driver.\n      var animations = lookupAnimations(classes);\n      var before, after;\n      if (animations.length) {\n        var afterFn, beforeFn;\n        if (event == 'leave') {\n          beforeFn = 'leave';\n          afterFn = 'afterLeave'; // TODO(matsko): get rid of this\n        } else {\n          beforeFn = 'before' + event.charAt(0).toUpperCase() + event.substr(1);\n          afterFn = event;\n        }\n\n        if (event !== 'enter' && event !== 'move') {\n          before = packageAnimations(element, event, options, animations, beforeFn);\n        }\n        after  = packageAnimations(element, event, options, animations, afterFn);\n      }\n\n      // no matching animations\n      if (!before && !after) return;\n\n      function applyOptions() {\n        options.domOperation();\n        applyAnimationClasses(element, options);\n      }\n\n      return {\n        start: function() {\n          var closeActiveAnimations;\n          var chain = [];\n\n          if (before) {\n            chain.push(function(fn) {\n              closeActiveAnimations = before(fn);\n            });\n          }\n\n          if (chain.length) {\n            chain.push(function(fn) {\n              applyOptions();\n              fn(true);\n            });\n          } else {\n            applyOptions();\n          }\n\n          if (after) {\n            chain.push(function(fn) {\n              closeActiveAnimations = after(fn);\n            });\n          }\n\n          var animationClosed = false;\n          var runner = new $$AnimateRunner({\n            end: function() {\n              endAnimations();\n            },\n            cancel: function() {\n              endAnimations(true);\n            }\n          });\n\n          $$AnimateRunner.chain(chain, onComplete);\n          return runner;\n\n          function onComplete(success) {\n            animationClosed = true;\n            applyOptions();\n            applyAnimationStyles(element, options);\n            runner.complete(success);\n          }\n\n          function endAnimations(cancelled) {\n            if (!animationClosed) {\n              (closeActiveAnimations || noop)(cancelled);\n              onComplete(cancelled);\n            }\n          }\n        }\n      };\n\n      function executeAnimationFn(fn, element, event, options, onDone) {\n        var args;\n        switch (event) {\n          case 'animate':\n            args = [element, options.from, options.to, onDone];\n            break;\n\n          case 'setClass':\n            args = [element, classesToAdd, classesToRemove, onDone];\n            break;\n\n          case 'addClass':\n            args = [element, classesToAdd, onDone];\n            break;\n\n          case 'removeClass':\n            args = [element, classesToRemove, onDone];\n            break;\n\n          default:\n            args = [element, onDone];\n            break;\n        }\n\n        args.push(options);\n\n        var value = fn.apply(fn, args);\n        if (value) {\n          if (isFunction(value.start)) {\n            value = value.start();\n          }\n\n          if (value instanceof $$AnimateRunner) {\n            value.done(onDone);\n          } else if (isFunction(value)) {\n            // optional onEnd / onCancel callback\n            return value;\n          }\n        }\n\n        return noop;\n      }\n\n      function groupEventedAnimations(element, event, options, animations, fnName) {\n        var operations = [];\n        forEach(animations, function(ani) {\n          var animation = ani[fnName];\n          if (!animation) return;\n\n          // note that all of these animations will run in parallel\n          operations.push(function() {\n            var runner;\n            var endProgressCb;\n\n            var resolved = false;\n            var onAnimationComplete = function(rejected) {\n              if (!resolved) {\n                resolved = true;\n                (endProgressCb || noop)(rejected);\n                runner.complete(!rejected);\n              }\n            };\n\n            runner = new $$AnimateRunner({\n              end: function() {\n                onAnimationComplete();\n              },\n              cancel: function() {\n                onAnimationComplete(true);\n              }\n            });\n\n            endProgressCb = executeAnimationFn(animation, element, event, options, function(result) {\n              var cancelled = result === false;\n              onAnimationComplete(cancelled);\n            });\n\n            return runner;\n          });\n        });\n\n        return operations;\n      }\n\n      function packageAnimations(element, event, options, animations, fnName) {\n        var operations = groupEventedAnimations(element, event, options, animations, fnName);\n        if (operations.length === 0) {\n          var a,b;\n          if (fnName === 'beforeSetClass') {\n            a = groupEventedAnimations(element, 'removeClass', options, animations, 'beforeRemoveClass');\n            b = groupEventedAnimations(element, 'addClass', options, animations, 'beforeAddClass');\n          } else if (fnName === 'setClass') {\n            a = groupEventedAnimations(element, 'removeClass', options, animations, 'removeClass');\n            b = groupEventedAnimations(element, 'addClass', options, animations, 'addClass');\n          }\n\n          if (a) {\n            operations = operations.concat(a);\n          }\n          if (b) {\n            operations = operations.concat(b);\n          }\n        }\n\n        if (operations.length === 0) return;\n\n        // TODO(matsko): add documentation\n        return function startAnimation(callback) {\n          var runners = [];\n          if (operations.length) {\n            forEach(operations, function(animateFn) {\n              runners.push(animateFn());\n            });\n          }\n\n          runners.length ? $$AnimateRunner.all(runners, callback) : callback();\n\n          return function endFn(reject) {\n            forEach(runners, function(runner) {\n              reject ? runner.cancel() : runner.end();\n            });\n          };\n        };\n      }\n    };\n\n    function lookupAnimations(classes) {\n      classes = isArray(classes) ? classes : classes.split(' ');\n      var matches = [], flagMap = {};\n      for (var i=0; i < classes.length; i++) {\n        var klass = classes[i],\n            animationFactory = $animateProvider.$$registeredAnimations[klass];\n        if (animationFactory && !flagMap[klass]) {\n          matches.push($injector.get(animationFactory));\n          flagMap[klass] = true;\n        }\n      }\n      return matches;\n    }\n  }];\n}];\n\nvar $$AnimateJsDriverProvider = ['$$animationProvider', function($$animationProvider) {\n  $$animationProvider.drivers.push('$$animateJsDriver');\n  this.$get = ['$$animateJs', '$$AnimateRunner', function($$animateJs, $$AnimateRunner) {\n    return function initDriverFn(animationDetails) {\n      if (animationDetails.from && animationDetails.to) {\n        var fromAnimation = prepareAnimation(animationDetails.from);\n        var toAnimation = prepareAnimation(animationDetails.to);\n        if (!fromAnimation && !toAnimation) return;\n\n        return {\n          start: function() {\n            var animationRunners = [];\n\n            if (fromAnimation) {\n              animationRunners.push(fromAnimation.start());\n            }\n\n            if (toAnimation) {\n              animationRunners.push(toAnimation.start());\n            }\n\n            $$AnimateRunner.all(animationRunners, done);\n\n            var runner = new $$AnimateRunner({\n              end: endFnFactory(),\n              cancel: endFnFactory()\n            });\n\n            return runner;\n\n            function endFnFactory() {\n              return function() {\n                forEach(animationRunners, function(runner) {\n                  // at this point we cannot cancel animations for groups just yet. 1.5+\n                  runner.end();\n                });\n              };\n            }\n\n            function done(status) {\n              runner.complete(status);\n            }\n          }\n        };\n      } else {\n        return prepareAnimation(animationDetails);\n      }\n    };\n\n    function prepareAnimation(animationDetails) {\n      // TODO(matsko): make sure to check for grouped animations and delegate down to normal animations\n      var element = animationDetails.element;\n      var event = animationDetails.event;\n      var options = animationDetails.options;\n      var classes = animationDetails.classes;\n      return $$animateJs(element, event, classes, options);\n    }\n  }];\n}];\n\nvar NG_ANIMATE_ATTR_NAME = 'data-ng-animate';\nvar NG_ANIMATE_PIN_DATA = '$ngAnimatePin';\nvar $$AnimateQueueProvider = ['$animateProvider', function($animateProvider) {\n  var PRE_DIGEST_STATE = 1;\n  var RUNNING_STATE = 2;\n\n  var rules = this.rules = {\n    skip: [],\n    cancel: [],\n    join: []\n  };\n\n  function isAllowed(ruleType, element, currentAnimation, previousAnimation) {\n    return rules[ruleType].some(function(fn) {\n      return fn(element, currentAnimation, previousAnimation);\n    });\n  }\n\n  function hasAnimationClasses(options, and) {\n    options = options || {};\n    var a = (options.addClass || '').length > 0;\n    var b = (options.removeClass || '').length > 0;\n    return and ? a && b : a || b;\n  }\n\n  rules.join.push(function(element, newAnimation, currentAnimation) {\n    // if the new animation is class-based then we can just tack that on\n    return !newAnimation.structural && hasAnimationClasses(newAnimation.options);\n  });\n\n  rules.skip.push(function(element, newAnimation, currentAnimation) {\n    // there is no need to animate anything if no classes are being added and\n    // there is no structural animation that will be triggered\n    return !newAnimation.structural && !hasAnimationClasses(newAnimation.options);\n  });\n\n  rules.skip.push(function(element, newAnimation, currentAnimation) {\n    // why should we trigger a new structural animation if the element will\n    // be removed from the DOM anyway?\n    return currentAnimation.event == 'leave' && newAnimation.structural;\n  });\n\n  rules.skip.push(function(element, newAnimation, currentAnimation) {\n    // if there is an ongoing current animation then don't even bother running the class-based animation\n    return currentAnimation.structural && currentAnimation.state === RUNNING_STATE && !newAnimation.structural;\n  });\n\n  rules.cancel.push(function(element, newAnimation, currentAnimation) {\n    // there can never be two structural animations running at the same time\n    return currentAnimation.structural && newAnimation.structural;\n  });\n\n  rules.cancel.push(function(element, newAnimation, currentAnimation) {\n    // if the previous animation is already running, but the new animation will\n    // be triggered, but the new animation is structural\n    return currentAnimation.state === RUNNING_STATE && newAnimation.structural;\n  });\n\n  rules.cancel.push(function(element, newAnimation, currentAnimation) {\n    var nO = newAnimation.options;\n    var cO = currentAnimation.options;\n\n    // if the exact same CSS class is added/removed then it's safe to cancel it\n    return (nO.addClass && nO.addClass === cO.removeClass) || (nO.removeClass && nO.removeClass === cO.addClass);\n  });\n\n  this.$get = ['$$rAF', '$rootScope', '$rootElement', '$document', '$$HashMap',\n               '$$animation', '$$AnimateRunner', '$templateRequest', '$$jqLite', '$$forceReflow',\n       function($$rAF,   $rootScope,   $rootElement,   $document,   $$HashMap,\n                $$animation,   $$AnimateRunner,   $templateRequest,   $$jqLite,   $$forceReflow) {\n\n    var activeAnimationsLookup = new $$HashMap();\n    var disabledElementsLookup = new $$HashMap();\n    var animationsEnabled = null;\n\n    function postDigestTaskFactory() {\n      var postDigestCalled = false;\n      return function(fn) {\n        // we only issue a call to postDigest before\n        // it has first passed. This prevents any callbacks\n        // from not firing once the animation has completed\n        // since it will be out of the digest cycle.\n        if (postDigestCalled) {\n          fn();\n        } else {\n          $rootScope.$$postDigest(function() {\n            postDigestCalled = true;\n            fn();\n          });\n        }\n      };\n    }\n\n    // Wait until all directive and route-related templates are downloaded and\n    // compiled. The $templateRequest.totalPendingRequests variable keeps track of\n    // all of the remote templates being currently downloaded. If there are no\n    // templates currently downloading then the watcher will still fire anyway.\n    var deregisterWatch = $rootScope.$watch(\n      function() { return $templateRequest.totalPendingRequests === 0; },\n      function(isEmpty) {\n        if (!isEmpty) return;\n        deregisterWatch();\n\n        // Now that all templates have been downloaded, $animate will wait until\n        // the post digest queue is empty before enabling animations. By having two\n        // calls to $postDigest calls we can ensure that the flag is enabled at the\n        // very end of the post digest queue. Since all of the animations in $animate\n        // use $postDigest, it's important that the code below executes at the end.\n        // This basically means that the page is fully downloaded and compiled before\n        // any animations are triggered.\n        $rootScope.$$postDigest(function() {\n          $rootScope.$$postDigest(function() {\n            // we check for null directly in the event that the application already called\n            // .enabled() with whatever arguments that it provided it with\n            if (animationsEnabled === null) {\n              animationsEnabled = true;\n            }\n          });\n        });\n      }\n    );\n\n    var callbackRegistry = {};\n\n    // remember that the classNameFilter is set during the provider/config\n    // stage therefore we can optimize here and setup a helper function\n    var classNameFilter = $animateProvider.classNameFilter();\n    var isAnimatableClassName = !classNameFilter\n              ? function() { return true; }\n              : function(className) {\n                return classNameFilter.test(className);\n              };\n\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    function normalizeAnimationOptions(element, options) {\n      return mergeAnimationOptions(element, options, {});\n    }\n\n    function findCallbacks(element, event) {\n      var targetNode = getDomNode(element);\n\n      var matches = [];\n      var entries = callbackRegistry[event];\n      if (entries) {\n        forEach(entries, function(entry) {\n          if (entry.node.contains(targetNode)) {\n            matches.push(entry.callback);\n          }\n        });\n      }\n\n      return matches;\n    }\n\n    return {\n      on: function(event, container, callback) {\n        var node = extractElementNode(container);\n        callbackRegistry[event] = callbackRegistry[event] || [];\n        callbackRegistry[event].push({\n          node: node,\n          callback: callback\n        });\n      },\n\n      off: function(event, container, callback) {\n        var entries = callbackRegistry[event];\n        if (!entries) return;\n\n        callbackRegistry[event] = arguments.length === 1\n            ? null\n            : filterFromRegistry(entries, container, callback);\n\n        function filterFromRegistry(list, matchContainer, matchCallback) {\n          var containerNode = extractElementNode(matchContainer);\n          return list.filter(function(entry) {\n            var isMatch = entry.node === containerNode &&\n                            (!matchCallback || entry.callback === matchCallback);\n            return !isMatch;\n          });\n        }\n      },\n\n      pin: function(element, parentElement) {\n        assertArg(isElement(element), 'element', 'not an element');\n        assertArg(isElement(parentElement), 'parentElement', 'not an element');\n        element.data(NG_ANIMATE_PIN_DATA, parentElement);\n      },\n\n      push: function(element, event, options, domOperation) {\n        options = options || {};\n        options.domOperation = domOperation;\n        return queueAnimation(element, event, options);\n      },\n\n      // this method has four signatures:\n      //  () - global getter\n      //  (bool) - global setter\n      //  (element) - element getter\n      //  (element, bool) - element setter<F37>\n      enabled: function(element, bool) {\n        var argCount = arguments.length;\n\n        if (argCount === 0) {\n          // () - Global getter\n          bool = !!animationsEnabled;\n        } else {\n          var hasElement = isElement(element);\n\n          if (!hasElement) {\n            // (bool) - Global setter\n            bool = animationsEnabled = !!element;\n          } else {\n            var node = getDomNode(element);\n            var recordExists = disabledElementsLookup.get(node);\n\n            if (argCount === 1) {\n              // (element) - Element getter\n              bool = !recordExists;\n            } else {\n              // (element, bool) - Element setter\n              bool = !!bool;\n              if (!bool) {\n                disabledElementsLookup.put(node, true);\n              } else if (recordExists) {\n                disabledElementsLookup.remove(node);\n              }\n            }\n          }\n        }\n\n        return bool;\n      }\n    };\n\n    function queueAnimation(element, event, options) {\n      var node, parent;\n      element = stripCommentsFromElement(element);\n      if (element) {\n        node = getDomNode(element);\n        parent = element.parent();\n      }\n\n      options = prepareAnimationOptions(options);\n\n      // we create a fake runner with a working promise.\n      // These methods will become available after the digest has passed\n      var runner = new $$AnimateRunner();\n\n      // this is used to trigger callbacks in postDigest mode\n      var runInNextPostDigestOrNow = postDigestTaskFactory();\n\n      if (isArray(options.addClass)) {\n        options.addClass = options.addClass.join(' ');\n      }\n\n      if (options.addClass && !isString(options.addClass)) {\n        options.addClass = null;\n      }\n\n      if (isArray(options.removeClass)) {\n        options.removeClass = options.removeClass.join(' ');\n      }\n\n      if (options.removeClass && !isString(options.removeClass)) {\n        options.removeClass = null;\n      }\n\n      if (options.from && !isObject(options.from)) {\n        options.from = null;\n      }\n\n      if (options.to && !isObject(options.to)) {\n        options.to = null;\n      }\n\n      // there are situations where a directive issues an animation for\n      // a jqLite wrapper that contains only comment nodes... If this\n      // happens then there is no way we can perform an animation\n      if (!node) {\n        close();\n        return runner;\n      }\n\n      var className = [node.className, options.addClass, options.removeClass].join(' ');\n      if (!isAnimatableClassName(className)) {\n        close();\n        return runner;\n      }\n\n      var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;\n\n      // this is a hard disable of all animations for the application or on\n      // the element itself, therefore  there is no need to continue further\n      // past this point if not enabled\n      var skipAnimations = !animationsEnabled || disabledElementsLookup.get(node);\n      var existingAnimation = (!skipAnimations && activeAnimationsLookup.get(node)) || {};\n      var hasExistingAnimation = !!existingAnimation.state;\n\n      // there is no point in traversing the same collection of parent ancestors if a followup\n      // animation will be run on the same element that already did all that checking work\n      if (!skipAnimations && (!hasExistingAnimation || existingAnimation.state != PRE_DIGEST_STATE)) {\n        skipAnimations = !areAnimationsAllowed(element, parent, event);\n      }\n\n      if (skipAnimations) {\n        close();\n        return runner;\n      }\n\n      if (isStructural) {\n        closeChildAnimations(element);\n      }\n\n      var newAnimation = {\n        structural: isStructural,\n        element: element,\n        event: event,\n        close: close,\n        options: options,\n        runner: runner\n      };\n\n      if (hasExistingAnimation) {\n        var skipAnimationFlag = isAllowed('skip', element, newAnimation, existingAnimation);\n        if (skipAnimationFlag) {\n          if (existingAnimation.state === RUNNING_STATE) {\n            close();\n            return runner;\n          } else {\n            mergeAnimationOptions(element, existingAnimation.options, options);\n            return existingAnimation.runner;\n          }\n        }\n\n        var cancelAnimationFlag = isAllowed('cancel', element, newAnimation, existingAnimation);\n        if (cancelAnimationFlag) {\n          if (existingAnimation.state === RUNNING_STATE) {\n            // this will end the animation right away and it is safe\n            // to do so since the animation is already running and the\n            // runner callback code will run in async\n            existingAnimation.runner.end();\n          } else if (existingAnimation.structural) {\n            // this means that the animation is queued into a digest, but\n            // hasn't started yet. Therefore it is safe to run the close\n            // method which will call the runner methods in async.\n            existingAnimation.close();\n          } else {\n            // this will merge the new animation options into existing animation options\n            mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);\n            return existingAnimation.runner;\n          }\n        } else {\n          // a joined animation means that this animation will take over the existing one\n          // so an example would involve a leave animation taking over an enter. Then when\n          // the postDigest kicks in the enter will be ignored.\n          var joinAnimationFlag = isAllowed('join', element, newAnimation, existingAnimation);\n          if (joinAnimationFlag) {\n            if (existingAnimation.state === RUNNING_STATE) {\n              normalizeAnimationOptions(element, options);\n            } else {\n              applyGeneratedPreparationClasses(element, isStructural ? event : null, options);\n\n              event = newAnimation.event = existingAnimation.event;\n              options = mergeAnimationOptions(element, existingAnimation.options, newAnimation.options);\n\n              //we return the same runner since only the option values of this animation will\n              //be fed into the `existingAnimation`.\n              return existingAnimation.runner;\n            }\n          }\n        }\n      } else {\n        // normalization in this case means that it removes redundant CSS classes that\n        // already exist (addClass) or do not exist (removeClass) on the element\n        normalizeAnimationOptions(element, options);\n      }\n\n      // when the options are merged and cleaned up we may end up not having to do\n      // an animation at all, therefore we should check this before issuing a post\n      // digest callback. Structural animations will always run no matter what.\n      var isValidAnimation = newAnimation.structural;\n      if (!isValidAnimation) {\n        // animate (from/to) can be quickly checked first, otherwise we check if any classes are present\n        isValidAnimation = (newAnimation.event === 'animate' && Object.keys(newAnimation.options.to || {}).length > 0)\n                            || hasAnimationClasses(newAnimation.options);\n      }\n\n      if (!isValidAnimation) {\n        close();\n        clearElementAnimationState(element);\n        return runner;\n      }\n\n      // the counter keeps track of cancelled animations\n      var counter = (existingAnimation.counter || 0) + 1;\n      newAnimation.counter = counter;\n\n      markElementAnimationState(element, PRE_DIGEST_STATE, newAnimation);\n\n      $rootScope.$$postDigest(function() {\n        var animationDetails = activeAnimationsLookup.get(node);\n        var animationCancelled = !animationDetails;\n        animationDetails = animationDetails || {};\n\n        // if addClass/removeClass is called before something like enter then the\n        // registered parent element may not be present. The code below will ensure\n        // that a final value for parent element is obtained\n        var parentElement = element.parent() || [];\n\n        // animate/structural/class-based animations all have requirements. Otherwise there\n        // is no point in performing an animation. The parent node must also be set.\n        var isValidAnimation = parentElement.length > 0\n                                && (animationDetails.event === 'animate'\n                                    || animationDetails.structural\n                                    || hasAnimationClasses(animationDetails.options));\n\n        // this means that the previous animation was cancelled\n        // even if the follow-up animation is the same event\n        if (animationCancelled || animationDetails.counter !== counter || !isValidAnimation) {\n          // if another animation did not take over then we need\n          // to make sure that the domOperation and options are\n          // handled accordingly\n          if (animationCancelled) {\n            applyAnimationClasses(element, options);\n            applyAnimationStyles(element, options);\n          }\n\n          // if the event changed from something like enter to leave then we do\n          // it, otherwise if it's the same then the end result will be the same too\n          if (animationCancelled || (isStructural && animationDetails.event !== event)) {\n            options.domOperation();\n            runner.end();\n          }\n\n          // in the event that the element animation was not cancelled or a follow-up animation\n          // isn't allowed to animate from here then we need to clear the state of the element\n          // so that any future animations won't read the expired animation data.\n          if (!isValidAnimation) {\n            clearElementAnimationState(element);\n          }\n\n          return;\n        }\n\n        // this combined multiple class to addClass / removeClass into a setClass event\n        // so long as a structural event did not take over the animation\n        event = !animationDetails.structural && hasAnimationClasses(animationDetails.options, true)\n            ? 'setClass'\n            : animationDetails.event;\n\n        markElementAnimationState(element, RUNNING_STATE);\n        var realRunner = $$animation(element, event, animationDetails.options);\n\n        realRunner.done(function(status) {\n          close(!status);\n          var animationDetails = activeAnimationsLookup.get(node);\n          if (animationDetails && animationDetails.counter === counter) {\n            clearElementAnimationState(getDomNode(element));\n          }\n          notifyProgress(runner, event, 'close', {});\n        });\n\n        // this will update the runner's flow-control events based on\n        // the `realRunner` object.\n        runner.setHost(realRunner);\n        notifyProgress(runner, event, 'start', {});\n      });\n\n      return runner;\n\n      function notifyProgress(runner, event, phase, data) {\n        runInNextPostDigestOrNow(function() {\n          var callbacks = findCallbacks(element, event);\n          if (callbacks.length) {\n            // do not optimize this call here to RAF because\n            // we don't know how heavy the callback code here will\n            // be and if this code is buffered then this can\n            // lead to a performance regression.\n            $$rAF(function() {\n              forEach(callbacks, function(callback) {\n                callback(element, phase, data);\n              });\n            });\n          }\n        });\n        runner.progress(event, phase, data);\n      }\n\n      function close(reject) { // jshint ignore:line\n        clearGeneratedClasses(element, options);\n        applyAnimationClasses(element, options);\n        applyAnimationStyles(element, options);\n        options.domOperation();\n        runner.complete(!reject);\n      }\n    }\n\n    function closeChildAnimations(element) {\n      var node = getDomNode(element);\n      var children = node.querySelectorAll('[' + NG_ANIMATE_ATTR_NAME + ']');\n      forEach(children, function(child) {\n        var state = parseInt(child.getAttribute(NG_ANIMATE_ATTR_NAME));\n        var animationDetails = activeAnimationsLookup.get(child);\n        switch (state) {\n          case RUNNING_STATE:\n            animationDetails.runner.end();\n            /* falls through */\n          case PRE_DIGEST_STATE:\n            if (animationDetails) {\n              activeAnimationsLookup.remove(child);\n            }\n            break;\n        }\n      });\n    }\n\n    function clearElementAnimationState(element) {\n      var node = getDomNode(element);\n      node.removeAttribute(NG_ANIMATE_ATTR_NAME);\n      activeAnimationsLookup.remove(node);\n    }\n\n    function isMatchingElement(nodeOrElmA, nodeOrElmB) {\n      return getDomNode(nodeOrElmA) === getDomNode(nodeOrElmB);\n    }\n\n    function areAnimationsAllowed(element, parentElement, event) {\n      var bodyElement = jqLite($document[0].body);\n      var bodyElementDetected = isMatchingElement(element, bodyElement) || element[0].nodeName === 'HTML';\n      var rootElementDetected = isMatchingElement(element, $rootElement);\n      var parentAnimationDetected = false;\n      var animateChildren;\n\n      var parentHost = element.data(NG_ANIMATE_PIN_DATA);\n      if (parentHost) {\n        parentElement = parentHost;\n      }\n\n      while (parentElement && parentElement.length) {\n        if (!rootElementDetected) {\n          // angular doesn't want to attempt to animate elements outside of the application\n          // therefore we need to ensure that the rootElement is an ancestor of the current element\n          rootElementDetected = isMatchingElement(parentElement, $rootElement);\n        }\n\n        var parentNode = parentElement[0];\n        if (parentNode.nodeType !== ELEMENT_NODE) {\n          // no point in inspecting the #document element\n          break;\n        }\n\n        var details = activeAnimationsLookup.get(parentNode) || {};\n        // either an enter, leave or move animation will commence\n        // therefore we can't allow any animations to take place\n        // but if a parent animation is class-based then that's ok\n        if (!parentAnimationDetected) {\n          parentAnimationDetected = details.structural || disabledElementsLookup.get(parentNode);\n        }\n\n        if (isUndefined(animateChildren) || animateChildren === true) {\n          var value = parentElement.data(NG_ANIMATE_CHILDREN_DATA);\n          if (isDefined(value)) {\n            animateChildren = value;\n          }\n        }\n\n        // there is no need to continue traversing at this point\n        if (parentAnimationDetected && animateChildren === false) break;\n\n        if (!rootElementDetected) {\n          // angular doesn't want to attempt to animate elements outside of the application\n          // therefore we need to ensure that the rootElement is an ancestor of the current element\n          rootElementDetected = isMatchingElement(parentElement, $rootElement);\n          if (!rootElementDetected) {\n            parentHost = parentElement.data(NG_ANIMATE_PIN_DATA);\n            if (parentHost) {\n              parentElement = parentHost;\n            }\n          }\n        }\n\n        if (!bodyElementDetected) {\n          // we also need to ensure that the element is or will be apart of the body element\n          // otherwise it is pointless to even issue an animation to be rendered\n          bodyElementDetected = isMatchingElement(parentElement, bodyElement);\n        }\n\n        parentElement = parentElement.parent();\n      }\n\n      var allowAnimation = !parentAnimationDetected || animateChildren;\n      return allowAnimation && rootElementDetected && bodyElementDetected;\n    }\n\n    function markElementAnimationState(element, state, details) {\n      details = details || {};\n      details.state = state;\n\n      var node = getDomNode(element);\n      node.setAttribute(NG_ANIMATE_ATTR_NAME, state);\n\n      var oldValue = activeAnimationsLookup.get(node);\n      var newValue = oldValue\n          ? extend(oldValue, details)\n          : details;\n      activeAnimationsLookup.put(node, newValue);\n    }\n  }];\n}];\n\nvar $$AnimateAsyncRunFactory = ['$$rAF', function($$rAF) {\n  var waitQueue = [];\n\n  function waitForTick(fn) {\n    waitQueue.push(fn);\n    if (waitQueue.length > 1) return;\n    $$rAF(function() {\n      for (var i = 0; i < waitQueue.length; i++) {\n        waitQueue[i]();\n      }\n      waitQueue = [];\n    });\n  }\n\n  return function() {\n    var passed = false;\n    waitForTick(function() {\n      passed = true;\n    });\n    return function(callback) {\n      passed ? callback() : waitForTick(callback);\n    };\n  };\n}];\n\nvar $$AnimateRunnerFactory = ['$q', '$sniffer', '$$animateAsyncRun',\n                      function($q,   $sniffer,   $$animateAsyncRun) {\n\n  var INITIAL_STATE = 0;\n  var DONE_PENDING_STATE = 1;\n  var DONE_COMPLETE_STATE = 2;\n\n  AnimateRunner.chain = function(chain, callback) {\n    var index = 0;\n\n    next();\n    function next() {\n      if (index === chain.length) {\n        callback(true);\n        return;\n      }\n\n      chain[index](function(response) {\n        if (response === false) {\n          callback(false);\n          return;\n        }\n        index++;\n        next();\n      });\n    }\n  };\n\n  AnimateRunner.all = function(runners, callback) {\n    var count = 0;\n    var status = true;\n    forEach(runners, function(runner) {\n      runner.done(onProgress);\n    });\n\n    function onProgress(response) {\n      status = status && response;\n      if (++count === runners.length) {\n        callback(status);\n      }\n    }\n  };\n\n  function AnimateRunner(host) {\n    this.setHost(host);\n\n    this._doneCallbacks = [];\n    this._runInAnimationFrame = $$animateAsyncRun();\n    this._state = 0;\n  }\n\n  AnimateRunner.prototype = {\n    setHost: function(host) {\n      this.host = host || {};\n    },\n\n    done: function(fn) {\n      if (this._state === DONE_COMPLETE_STATE) {\n        fn();\n      } else {\n        this._doneCallbacks.push(fn);\n      }\n    },\n\n    progress: noop,\n\n    getPromise: function() {\n      if (!this.promise) {\n        var self = this;\n        this.promise = $q(function(resolve, reject) {\n          self.done(function(status) {\n            status === false ? reject() : resolve();\n          });\n        });\n      }\n      return this.promise;\n    },\n\n    then: function(resolveHandler, rejectHandler) {\n      return this.getPromise().then(resolveHandler, rejectHandler);\n    },\n\n    'catch': function(handler) {\n      return this.getPromise()['catch'](handler);\n    },\n\n    'finally': function(handler) {\n      return this.getPromise()['finally'](handler);\n    },\n\n    pause: function() {\n      if (this.host.pause) {\n        this.host.pause();\n      }\n    },\n\n    resume: function() {\n      if (this.host.resume) {\n        this.host.resume();\n      }\n    },\n\n    end: function() {\n      if (this.host.end) {\n        this.host.end();\n      }\n      this._resolve(true);\n    },\n\n    cancel: function() {\n      if (this.host.cancel) {\n        this.host.cancel();\n      }\n      this._resolve(false);\n    },\n\n    complete: function(response) {\n      var self = this;\n      if (self._state === INITIAL_STATE) {\n        self._state = DONE_PENDING_STATE;\n        self._runInAnimationFrame(function() {\n          self._resolve(response);\n        });\n      }\n    },\n\n    _resolve: function(response) {\n      if (this._state !== DONE_COMPLETE_STATE) {\n        forEach(this._doneCallbacks, function(fn) {\n          fn(response);\n        });\n        this._doneCallbacks.length = 0;\n        this._state = DONE_COMPLETE_STATE;\n      }\n    }\n  };\n\n  return AnimateRunner;\n}];\n\nvar $$AnimationProvider = ['$animateProvider', function($animateProvider) {\n  var NG_ANIMATE_REF_ATTR = 'ng-animate-ref';\n\n  var drivers = this.drivers = [];\n\n  var RUNNER_STORAGE_KEY = '$$animationRunner';\n\n  function setRunner(element, runner) {\n    element.data(RUNNER_STORAGE_KEY, runner);\n  }\n\n  function removeRunner(element) {\n    element.removeData(RUNNER_STORAGE_KEY);\n  }\n\n  function getRunner(element) {\n    return element.data(RUNNER_STORAGE_KEY);\n  }\n\n  this.$get = ['$$jqLite', '$rootScope', '$injector', '$$AnimateRunner', '$$HashMap', '$$rAFScheduler',\n       function($$jqLite,   $rootScope,   $injector,   $$AnimateRunner,   $$HashMap,   $$rAFScheduler) {\n\n    var animationQueue = [];\n    var applyAnimationClasses = applyAnimationClassesFactory($$jqLite);\n\n    function sortAnimations(animations) {\n      var tree = { children: [] };\n      var i, lookup = new $$HashMap();\n\n      // this is done first beforehand so that the hashmap\n      // is filled with a list of the elements that will be animated\n      for (i = 0; i < animations.length; i++) {\n        var animation = animations[i];\n        lookup.put(animation.domNode, animations[i] = {\n          domNode: animation.domNode,\n          fn: animation.fn,\n          children: []\n        });\n      }\n\n      for (i = 0; i < animations.length; i++) {\n        processNode(animations[i]);\n      }\n\n      return flatten(tree);\n\n      function processNode(entry) {\n        if (entry.processed) return entry;\n        entry.processed = true;\n\n        var elementNode = entry.domNode;\n        var parentNode = elementNode.parentNode;\n        lookup.put(elementNode, entry);\n\n        var parentEntry;\n        while (parentNode) {\n          parentEntry = lookup.get(parentNode);\n          if (parentEntry) {\n            if (!parentEntry.processed) {\n              parentEntry = processNode(parentEntry);\n            }\n            break;\n          }\n          parentNode = parentNode.parentNode;\n        }\n\n        (parentEntry || tree).children.push(entry);\n        return entry;\n      }\n\n      function flatten(tree) {\n        var result = [];\n        var queue = [];\n        var i;\n\n        for (i = 0; i < tree.children.length; i++) {\n          queue.push(tree.children[i]);\n        }\n\n        var remainingLevelEntries = queue.length;\n        var nextLevelEntries = 0;\n        var row = [];\n\n        for (i = 0; i < queue.length; i++) {\n          var entry = queue[i];\n          if (remainingLevelEntries <= 0) {\n            remainingLevelEntries = nextLevelEntries;\n            nextLevelEntries = 0;\n            result.push(row);\n            row = [];\n          }\n          row.push(entry.fn);\n          entry.children.forEach(function(childEntry) {\n            nextLevelEntries++;\n            queue.push(childEntry);\n          });\n          remainingLevelEntries--;\n        }\n\n        if (row.length) {\n          result.push(row);\n        }\n\n        return result;\n      }\n    }\n\n    // TODO(matsko): document the signature in a better way\n    return function(element, event, options) {\n      options = prepareAnimationOptions(options);\n      var isStructural = ['enter', 'move', 'leave'].indexOf(event) >= 0;\n\n      // there is no animation at the current moment, however\n      // these runner methods will get later updated with the\n      // methods leading into the driver's end/cancel methods\n      // for now they just stop the animation from starting\n      var runner = new $$AnimateRunner({\n        end: function() { close(); },\n        cancel: function() { close(true); }\n      });\n\n      if (!drivers.length) {\n        close();\n        return runner;\n      }\n\n      setRunner(element, runner);\n\n      var classes = mergeClasses(element.attr('class'), mergeClasses(options.addClass, options.removeClass));\n      var tempClasses = options.tempClasses;\n      if (tempClasses) {\n        classes += ' ' + tempClasses;\n        options.tempClasses = null;\n      }\n\n      animationQueue.push({\n        // this data is used by the postDigest code and passed into\n        // the driver step function\n        element: element,\n        classes: classes,\n        event: event,\n        structural: isStructural,\n        options: options,\n        beforeStart: beforeStart,\n        close: close\n      });\n\n      element.on('$destroy', handleDestroyedElement);\n\n      // we only want there to be one function called within the post digest\n      // block. This way we can group animations for all the animations that\n      // were apart of the same postDigest flush call.\n      if (animationQueue.length > 1) return runner;\n\n      $rootScope.$$postDigest(function() {\n        var animations = [];\n        forEach(animationQueue, function(entry) {\n          // the element was destroyed early on which removed the runner\n          // form its storage. This means we can't animate this element\n          // at all and it already has been closed due to destruction.\n          if (getRunner(entry.element)) {\n            animations.push(entry);\n          } else {\n            entry.close();\n          }\n        });\n\n        // now any future animations will be in another postDigest\n        animationQueue.length = 0;\n\n        var groupedAnimations = groupAnimations(animations);\n        var toBeSortedAnimations = [];\n\n        forEach(groupedAnimations, function(animationEntry) {\n          toBeSortedAnimations.push({\n            domNode: getDomNode(animationEntry.from ? animationEntry.from.element : animationEntry.element),\n            fn: function triggerAnimationStart() {\n              // it's important that we apply the `ng-animate` CSS class and the\n              // temporary classes before we do any driver invoking since these\n              // CSS classes may be required for proper CSS detection.\n              animationEntry.beforeStart();\n\n              var startAnimationFn, closeFn = animationEntry.close;\n\n              // in the event that the element was removed before the digest runs or\n              // during the RAF sequencing then we should not trigger the animation.\n              var targetElement = animationEntry.anchors\n                  ? (animationEntry.from.element || animationEntry.to.element)\n                  : animationEntry.element;\n\n              if (getRunner(targetElement)) {\n                var operation = invokeFirstDriver(animationEntry);\n                if (operation) {\n                  startAnimationFn = operation.start;\n                }\n              }\n\n              if (!startAnimationFn) {\n                closeFn();\n              } else {\n                var animationRunner = startAnimationFn();\n                animationRunner.done(function(status) {\n                  closeFn(!status);\n                });\n                updateAnimationRunners(animationEntry, animationRunner);\n              }\n            }\n          });\n        });\n\n        // we need to sort each of the animations in order of parent to child\n        // relationships. This ensures that the child classes are applied at the\n        // right time.\n        $$rAFScheduler(sortAnimations(toBeSortedAnimations));\n      });\n\n      return runner;\n\n      // TODO(matsko): change to reference nodes\n      function getAnchorNodes(node) {\n        var SELECTOR = '[' + NG_ANIMATE_REF_ATTR + ']';\n        var items = node.hasAttribute(NG_ANIMATE_REF_ATTR)\n              ? [node]\n              : node.querySelectorAll(SELECTOR);\n        var anchors = [];\n        forEach(items, function(node) {\n          var attr = node.getAttribute(NG_ANIMATE_REF_ATTR);\n          if (attr && attr.length) {\n            anchors.push(node);\n          }\n        });\n        return anchors;\n      }\n\n      function groupAnimations(animations) {\n        var preparedAnimations = [];\n        var refLookup = {};\n        forEach(animations, function(animation, index) {\n          var element = animation.element;\n          var node = getDomNode(element);\n          var event = animation.event;\n          var enterOrMove = ['enter', 'move'].indexOf(event) >= 0;\n          var anchorNodes = animation.structural ? getAnchorNodes(node) : [];\n\n          if (anchorNodes.length) {\n            var direction = enterOrMove ? 'to' : 'from';\n\n            forEach(anchorNodes, function(anchor) {\n              var key = anchor.getAttribute(NG_ANIMATE_REF_ATTR);\n              refLookup[key] = refLookup[key] || {};\n              refLookup[key][direction] = {\n                animationID: index,\n                element: jqLite(anchor)\n              };\n            });\n          } else {\n            preparedAnimations.push(animation);\n          }\n        });\n\n        var usedIndicesLookup = {};\n        var anchorGroups = {};\n        forEach(refLookup, function(operations, key) {\n          var from = operations.from;\n          var to = operations.to;\n\n          if (!from || !to) {\n            // only one of these is set therefore we can't have an\n            // anchor animation since all three pieces are required\n            var index = from ? from.animationID : to.animationID;\n            var indexKey = index.toString();\n            if (!usedIndicesLookup[indexKey]) {\n              usedIndicesLookup[indexKey] = true;\n              preparedAnimations.push(animations[index]);\n            }\n            return;\n          }\n\n          var fromAnimation = animations[from.animationID];\n          var toAnimation = animations[to.animationID];\n          var lookupKey = from.animationID.toString();\n          if (!anchorGroups[lookupKey]) {\n            var group = anchorGroups[lookupKey] = {\n              structural: true,\n              beforeStart: function() {\n                fromAnimation.beforeStart();\n                toAnimation.beforeStart();\n              },\n              close: function() {\n                fromAnimation.close();\n                toAnimation.close();\n              },\n              classes: cssClassesIntersection(fromAnimation.classes, toAnimation.classes),\n              from: fromAnimation,\n              to: toAnimation,\n              anchors: [] // TODO(matsko): change to reference nodes\n            };\n\n            // the anchor animations require that the from and to elements both have at least\n            // one shared CSS class which effictively marries the two elements together to use\n            // the same animation driver and to properly sequence the anchor animation.\n            if (group.classes.length) {\n              preparedAnimations.push(group);\n            } else {\n              preparedAnimations.push(fromAnimation);\n              preparedAnimations.push(toAnimation);\n            }\n          }\n\n          anchorGroups[lookupKey].anchors.push({\n            'out': from.element, 'in': to.element\n          });\n        });\n\n        return preparedAnimations;\n      }\n\n      function cssClassesIntersection(a,b) {\n        a = a.split(' ');\n        b = b.split(' ');\n        var matches = [];\n\n        for (var i = 0; i < a.length; i++) {\n          var aa = a[i];\n          if (aa.substring(0,3) === 'ng-') continue;\n\n          for (var j = 0; j < b.length; j++) {\n            if (aa === b[j]) {\n              matches.push(aa);\n              break;\n            }\n          }\n        }\n\n        return matches.join(' ');\n      }\n\n      function invokeFirstDriver(animationDetails) {\n        // we loop in reverse order since the more general drivers (like CSS and JS)\n        // may attempt more elements, but custom drivers are more particular\n        for (var i = drivers.length - 1; i >= 0; i--) {\n          var driverName = drivers[i];\n          if (!$injector.has(driverName)) continue; // TODO(matsko): remove this check\n\n          var factory = $injector.get(driverName);\n          var driver = factory(animationDetails);\n          if (driver) {\n            return driver;\n          }\n        }\n      }\n\n      function beforeStart() {\n        element.addClass(NG_ANIMATE_CLASSNAME);\n        if (tempClasses) {\n          $$jqLite.addClass(element, tempClasses);\n        }\n      }\n\n      function updateAnimationRunners(animation, newRunner) {\n        if (animation.from && animation.to) {\n          update(animation.from.element);\n          update(animation.to.element);\n        } else {\n          update(animation.element);\n        }\n\n        function update(element) {\n          getRunner(element).setHost(newRunner);\n        }\n      }\n\n      function handleDestroyedElement() {\n        var runner = getRunner(element);\n        if (runner && (event !== 'leave' || !options.$$domOperationFired)) {\n          runner.end();\n        }\n      }\n\n      function close(rejected) { // jshint ignore:line\n        element.off('$destroy', handleDestroyedElement);\n        removeRunner(element);\n\n        applyAnimationClasses(element, options);\n        applyAnimationStyles(element, options);\n        options.domOperation();\n\n        if (tempClasses) {\n          $$jqLite.removeClass(element, tempClasses);\n        }\n\n        element.removeClass(NG_ANIMATE_CLASSNAME);\n        runner.complete(!rejected);\n      }\n    };\n  }];\n}];\n\n/* global angularAnimateModule: true,\n\n   $$AnimateAsyncRunFactory,\n   $$rAFSchedulerFactory,\n   $$AnimateChildrenDirective,\n   $$AnimateRunnerFactory,\n   $$AnimateQueueProvider,\n   $$AnimationProvider,\n   $AnimateCssProvider,\n   $$AnimateCssDriverProvider,\n   $$AnimateJsProvider,\n   $$AnimateJsDriverProvider,\n*/\n\n/**\n * @ngdoc module\n * @name ngAnimate\n * @description\n *\n * The `ngAnimate` module provides support for CSS-based animations (keyframes and transitions) as well as JavaScript-based animations via\n * callback hooks. Animations are not enabled by default, however, by including `ngAnimate` the animation hooks are enabled for an Angular app.\n *\n * <div doc-module-components=\"ngAnimate\"></div>\n *\n * # Usage\n * Simply put, there are two ways to make use of animations when ngAnimate is used: by using **CSS** and **JavaScript**. The former works purely based\n * using CSS (by using matching CSS selectors/styles) and the latter triggers animations that are registered via `module.animation()`. For\n * both CSS and JS animations the sole requirement is to have a matching `CSS class` that exists both in the registered animation and within\n * the HTML element that the animation will be triggered on.\n *\n * ## Directive Support\n * The following directives are \"animation aware\":\n *\n * | Directive                                                                                                | Supported Animations                                                     |\n * |----------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|\n * | {@link ng.directive:ngRepeat#animations ngRepeat}                                                        | enter, leave and move                                                    |\n * | {@link ngRoute.directive:ngView#animations ngView}                                                       | enter and leave                                                          |\n * | {@link ng.directive:ngInclude#animations ngInclude}                                                      | enter and leave                                                          |\n * | {@link ng.directive:ngSwitch#animations ngSwitch}                                                        | enter and leave                                                          |\n * | {@link ng.directive:ngIf#animations ngIf}                                                                | enter and leave                                                          |\n * | {@link ng.directive:ngClass#animations ngClass}                                                          | add and remove (the CSS class(es) present)                               |\n * | {@link ng.directive:ngShow#animations ngShow} & {@link ng.directive:ngHide#animations ngHide}            | add and remove (the ng-hide class value)                                 |\n * | {@link ng.directive:form#animation-hooks form} & {@link ng.directive:ngModel#animation-hooks ngModel}    | add and remove (dirty, pristine, valid, invalid & all other validations) |\n * | {@link module:ngMessages#animations ngMessages}                                                          | add and remove (ng-active & ng-inactive)                                 |\n * | {@link module:ngMessages#animations ngMessage}                                                           | enter and leave                                                          |\n *\n * (More information can be found by visiting each the documentation associated with each directive.)\n *\n * ## CSS-based Animations\n *\n * CSS-based animations with ngAnimate are unique since they require no JavaScript code at all. By using a CSS class that we reference between our HTML\n * and CSS code we can create an animation that will be picked up by Angular when an the underlying directive performs an operation.\n *\n * The example below shows how an `enter` animation can be made possible on an element using `ng-if`:\n *\n * ```html\n * <div ng-if=\"bool\" class=\"fade\">\n *    Fade me in out\n * </div>\n * <button ng-click=\"bool=true\">Fade In!</button>\n * <button ng-click=\"bool=false\">Fade Out!</button>\n * ```\n *\n * Notice the CSS class **fade**? We can now create the CSS transition code that references this class:\n *\n * ```css\n * /&#42; The starting CSS styles for the enter animation &#42;/\n * .fade.ng-enter {\n *   transition:0.5s linear all;\n *   opacity:0;\n * }\n *\n * /&#42; The finishing CSS styles for the enter animation &#42;/\n * .fade.ng-enter.ng-enter-active {\n *   opacity:1;\n * }\n * ```\n *\n * The key thing to remember here is that, depending on the animation event (which each of the directives above trigger depending on what's going on) two\n * generated CSS classes will be applied to the element; in the example above we have `.ng-enter` and `.ng-enter-active`. For CSS transitions, the transition\n * code **must** be defined within the starting CSS class (in this case `.ng-enter`). The destination class is what the transition will animate towards.\n *\n * If for example we wanted to create animations for `leave` and `move` (ngRepeat triggers move) then we can do so using the same CSS naming conventions:\n *\n * ```css\n * /&#42; now the element will fade out before it is removed from the DOM &#42;/\n * .fade.ng-leave {\n *   transition:0.5s linear all;\n *   opacity:1;\n * }\n * .fade.ng-leave.ng-leave-active {\n *   opacity:0;\n * }\n * ```\n *\n * We can also make use of **CSS Keyframes** by referencing the keyframe animation within the starting CSS class:\n *\n * ```css\n * /&#42; there is no need to define anything inside of the destination\n * CSS class since the keyframe will take charge of the animation &#42;/\n * .fade.ng-leave {\n *   animation: my_fade_animation 0.5s linear;\n *   -webkit-animation: my_fade_animation 0.5s linear;\n * }\n *\n * @keyframes my_fade_animation {\n *   from { opacity:1; }\n *   to { opacity:0; }\n * }\n *\n * @-webkit-keyframes my_fade_animation {\n *   from { opacity:1; }\n *   to { opacity:0; }\n * }\n * ```\n *\n * Feel free also mix transitions and keyframes together as well as any other CSS classes on the same element.\n *\n * ### CSS Class-based Animations\n *\n * Class-based animations (animations that are triggered via `ngClass`, `ngShow`, `ngHide` and some other directives) have a slightly different\n * naming convention. Class-based animations are basic enough that a standard transition or keyframe can be referenced on the class being added\n * and removed.\n *\n * For example if we wanted to do a CSS animation for `ngHide` then we place an animation on the `.ng-hide` CSS class:\n *\n * ```html\n * <div ng-show=\"bool\" class=\"fade\">\n *   Show and hide me\n * </div>\n * <button ng-click=\"bool=true\">Toggle</button>\n *\n * <style>\n * .fade.ng-hide {\n *   transition:0.5s linear all;\n *   opacity:0;\n * }\n * </style>\n * ```\n *\n * All that is going on here with ngShow/ngHide behind the scenes is the `.ng-hide` class is added/removed (when the hidden state is valid). Since\n * ngShow and ngHide are animation aware then we can match up a transition and ngAnimate handles the rest.\n *\n * In addition the addition and removal of the CSS class, ngAnimate also provides two helper methods that we can use to further decorate the animation\n * with CSS styles.\n *\n * ```html\n * <div ng-class=\"{on:onOff}\" class=\"highlight\">\n *   Highlight this box\n * </div>\n * <button ng-click=\"onOff=!onOff\">Toggle</button>\n *\n * <style>\n * .highlight {\n *   transition:0.5s linear all;\n * }\n * .highlight.on-add {\n *   background:white;\n * }\n * .highlight.on {\n *   background:yellow;\n * }\n * .highlight.on-remove {\n *   background:black;\n * }\n * </style>\n * ```\n *\n * We can also make use of CSS keyframes by placing them within the CSS classes.\n *\n *\n * ### CSS Staggering Animations\n * A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a\n * curtain-like effect. The ngAnimate module (versions >=1.2) supports staggering animations and the stagger effect can be\n * performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for\n * the animation. The style property expected within the stagger class can either be a **transition-delay** or an\n * **animation-delay** property (or both if your animation contains both transitions and keyframe animations).\n *\n * ```css\n * .my-animation.ng-enter {\n *   /&#42; standard transition code &#42;/\n *   transition: 1s linear all;\n *   opacity:0;\n * }\n * .my-animation.ng-enter-stagger {\n *   /&#42; this will have a 100ms delay between each successive leave animation &#42;/\n *   transition-delay: 0.1s;\n *\n *   /&#42; As of 1.4.4, this must always be set: it signals ngAnimate\n *     to not accidentally inherit a delay property from another CSS class &#42;/\n *   transition-duration: 0s;\n * }\n * .my-animation.ng-enter.ng-enter-active {\n *   /&#42; standard transition styles &#42;/\n *   opacity:1;\n * }\n * ```\n *\n * Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations\n * on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this\n * are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation\n * will also be reset if one or more animation frames have passed since the multiple calls to `$animate` were fired.\n *\n * The following code will issue the **ng-leave-stagger** event on the element provided:\n *\n * ```js\n * var kids = parent.children();\n *\n * $animate.leave(kids[0]); //stagger index=0\n * $animate.leave(kids[1]); //stagger index=1\n * $animate.leave(kids[2]); //stagger index=2\n * $animate.leave(kids[3]); //stagger index=3\n * $animate.leave(kids[4]); //stagger index=4\n *\n * window.requestAnimationFrame(function() {\n *   //stagger has reset itself\n *   $animate.leave(kids[5]); //stagger index=0\n *   $animate.leave(kids[6]); //stagger index=1\n *\n *   $scope.$digest();\n * });\n * ```\n *\n * Stagger animations are currently only supported within CSS-defined animations.\n *\n * ### The `ng-animate` CSS class\n *\n * When ngAnimate is animating an element it will apply the `ng-animate` CSS class to the element for the duration of the animation.\n * This is a temporary CSS class and it will be removed once the animation is over (for both JavaScript and CSS-based animations).\n *\n * Therefore, animations can be applied to an element using this temporary class directly via CSS.\n *\n * ```css\n * .zipper.ng-animate {\n *   transition:0.5s linear all;\n * }\n * .zipper.ng-enter {\n *   opacity:0;\n * }\n * .zipper.ng-enter.ng-enter-active {\n *   opacity:1;\n * }\n * .zipper.ng-leave {\n *   opacity:1;\n * }\n * .zipper.ng-leave.ng-leave-active {\n *   opacity:0;\n * }\n * ```\n *\n * (Note that the `ng-animate` CSS class is reserved and it cannot be applied on an element directly since ngAnimate will always remove\n * the CSS class once an animation has completed.)\n *\n *\n * ## JavaScript-based Animations\n *\n * ngAnimate also allows for animations to be consumed by JavaScript code. The approach is similar to CSS-based animations (where there is a shared\n * CSS class that is referenced in our HTML code) but in addition we need to register the JavaScript animation on the module. By making use of the\n * `module.animation()` module function we can register the ainmation.\n *\n * Let's see an example of a enter/leave animation using `ngRepeat`:\n *\n * ```html\n * <div ng-repeat=\"item in items\" class=\"slide\">\n *   {{ item }}\n * </div>\n * ```\n *\n * See the **slide** CSS class? Let's use that class to define an animation that we'll structure in our module code by using `module.animation`:\n *\n * ```js\n * myModule.animation('.slide', [function() {\n *   return {\n *     // make note that other events (like addClass/removeClass)\n *     // have different function input parameters\n *     enter: function(element, doneFn) {\n *       jQuery(element).fadeIn(1000, doneFn);\n *\n *       // remember to call doneFn so that angular\n *       // knows that the animation has concluded\n *     },\n *\n *     move: function(element, doneFn) {\n *       jQuery(element).fadeIn(1000, doneFn);\n *     },\n *\n *     leave: function(element, doneFn) {\n *       jQuery(element).fadeOut(1000, doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * The nice thing about JS-based animations is that we can inject other services and make use of advanced animation libraries such as\n * greensock.js and velocity.js.\n *\n * If our animation code class-based (meaning that something like `ngClass`, `ngHide` and `ngShow` triggers it) then we can still define\n * our animations inside of the same registered animation, however, the function input arguments are a bit different:\n *\n * ```html\n * <div ng-class=\"color\" class=\"colorful\">\n *   this box is moody\n * </div>\n * <button ng-click=\"color='red'\">Change to red</button>\n * <button ng-click=\"color='blue'\">Change to blue</button>\n * <button ng-click=\"color='green'\">Change to green</button>\n * ```\n *\n * ```js\n * myModule.animation('.colorful', [function() {\n *   return {\n *     addClass: function(element, className, doneFn) {\n *       // do some cool animation and call the doneFn\n *     },\n *     removeClass: function(element, className, doneFn) {\n *       // do some cool animation and call the doneFn\n *     },\n *     setClass: function(element, addedClass, removedClass, doneFn) {\n *       // do some cool animation and call the doneFn\n *     }\n *   }\n * }]\n * ```\n *\n * ## CSS + JS Animations Together\n *\n * AngularJS 1.4 and higher has taken steps to make the amalgamation of CSS and JS animations more flexible. However, unlike earlier versions of Angular,\n * defining CSS and JS animations to work off of the same CSS class will not work anymore. Therefore the example below will only result in **JS animations taking\n * charge of the animation**:\n *\n * ```html\n * <div ng-if=\"bool\" class=\"slide\">\n *   Slide in and out\n * </div>\n * ```\n *\n * ```js\n * myModule.animation('.slide', [function() {\n *   return {\n *     enter: function(element, doneFn) {\n *       jQuery(element).slideIn(1000, doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * ```css\n * .slide.ng-enter {\n *   transition:0.5s linear all;\n *   transform:translateY(-100px);\n * }\n * .slide.ng-enter.ng-enter-active {\n *   transform:translateY(0);\n * }\n * ```\n *\n * Does this mean that CSS and JS animations cannot be used together? Do JS-based animations always have higher priority? We can make up for the\n * lack of CSS animations by using the `$animateCss` service to trigger our own tweaked-out, CSS-based animations directly from\n * our own JS-based animation code:\n *\n * ```js\n * myModule.animation('.slide', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n*        // this will trigger `.slide.ng-enter` and `.slide.ng-enter-active`.\n *       var runner = $animateCss(element, {\n *         event: 'enter',\n *         structural: true\n *       }).start();\n*        runner.done(doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * The nice thing here is that we can save bandwidth by sticking to our CSS-based animation code and we don't need to rely on a 3rd-party animation framework.\n *\n * The `$animateCss` service is very powerful since we can feed in all kinds of extra properties that will be evaluated and fed into a CSS transition or\n * keyframe animation. For example if we wanted to animate the height of an element while adding and removing classes then we can do so by providing that\n * data into `$animateCss` directly:\n *\n * ```js\n * myModule.animation('.slide', ['$animateCss', function($animateCss) {\n *   return {\n *     enter: function(element, doneFn) {\n *       var runner = $animateCss(element, {\n *         event: 'enter',\n *         structural: true,\n *         addClass: 'maroon-setting',\n *         from: { height:0 },\n *         to: { height: 200 }\n *       }).start();\n *\n *       runner.done(doneFn);\n *     }\n *   }\n * }]\n * ```\n *\n * Now we can fill in the rest via our transition CSS code:\n *\n * ```css\n * /&#42; the transition tells ngAnimate to make the animation happen &#42;/\n * .slide.ng-enter { transition:0.5s linear all; }\n *\n * /&#42; this extra CSS class will be absorbed into the transition\n * since the $animateCss code is adding the class &#42;/\n * .maroon-setting { background:red; }\n * ```\n *\n * And `$animateCss` will figure out the rest. Just make sure to have the `done()` callback fire the `doneFn` function to signal when the animation is over.\n *\n * To learn more about what's possible be sure to visit the {@link ngAnimate.$animateCss $animateCss service}.\n *\n * ## Animation Anchoring (via `ng-animate-ref`)\n *\n * ngAnimate in AngularJS 1.4 comes packed with the ability to cross-animate elements between\n * structural areas of an application (like views) by pairing up elements using an attribute\n * called `ng-animate-ref`.\n *\n * Let's say for example we have two views that are managed by `ng-view` and we want to show\n * that there is a relationship between two components situated in within these views. By using the\n * `ng-animate-ref` attribute we can identify that the two components are paired together and we\n * can then attach an animation, which is triggered when the view changes.\n *\n * Say for example we have the following template code:\n *\n * ```html\n * <!-- index.html -->\n * <div ng-view class=\"view-animation\">\n * </div>\n *\n * <!-- home.html -->\n * <a href=\"#/banner-page\">\n *   <img src=\"./banner.jpg\" class=\"banner\" ng-animate-ref=\"banner\">\n * </a>\n *\n * <!-- banner-page.html -->\n * <img src=\"./banner.jpg\" class=\"banner\" ng-animate-ref=\"banner\">\n * ```\n *\n * Now, when the view changes (once the link is clicked), ngAnimate will examine the\n * HTML contents to see if there is a match reference between any components in the view\n * that is leaving and the view that is entering. It will scan both the view which is being\n * removed (leave) and inserted (enter) to see if there are any paired DOM elements that\n * contain a matching ref value.\n *\n * The two images match since they share the same ref value. ngAnimate will now create a\n * transport element (which is a clone of the first image element) and it will then attempt\n * to animate to the position of the second image element in the next view. For the animation to\n * work a special CSS class called `ng-anchor` will be added to the transported element.\n *\n * We can now attach a transition onto the `.banner.ng-anchor` CSS class and then\n * ngAnimate will handle the entire transition for us as well as the addition and removal of\n * any changes of CSS classes between the elements:\n *\n * ```css\n * .banner.ng-anchor {\n *   /&#42; this animation will last for 1 second since there are\n *          two phases to the animation (an `in` and an `out` phase) &#42;/\n *   transition:0.5s linear all;\n * }\n * ```\n *\n * We also **must** include animations for the views that are being entered and removed\n * (otherwise anchoring wouldn't be possible since the new view would be inserted right away).\n *\n * ```css\n * .view-animation.ng-enter, .view-animation.ng-leave {\n *   transition:0.5s linear all;\n *   position:fixed;\n *   left:0;\n *   top:0;\n *   width:100%;\n * }\n * .view-animation.ng-enter {\n *   transform:translateX(100%);\n * }\n * .view-animation.ng-leave,\n * .view-animation.ng-enter.ng-enter-active {\n *   transform:translateX(0%);\n * }\n * .view-animation.ng-leave.ng-leave-active {\n *   transform:translateX(-100%);\n * }\n * ```\n *\n * Now we can jump back to the anchor animation. When the animation happens, there are two stages that occur:\n * an `out` and an `in` stage. The `out` stage happens first and that is when the element is animated away\n * from its origin. Once that animation is over then the `in` stage occurs which animates the\n * element to its destination. The reason why there are two animations is to give enough time\n * for the enter animation on the new element to be ready.\n *\n * The example above sets up a transition for both the in and out phases, but we can also target the out or\n * in phases directly via `ng-anchor-out` and `ng-anchor-in`.\n *\n * ```css\n * .banner.ng-anchor-out {\n *   transition: 0.5s linear all;\n *\n *   /&#42; the scale will be applied during the out animation,\n *          but will be animated away when the in animation runs &#42;/\n *   transform: scale(1.2);\n * }\n *\n * .banner.ng-anchor-in {\n *   transition: 1s linear all;\n * }\n * ```\n *\n *\n *\n *\n * ### Anchoring Demo\n *\n  <example module=\"anchoringExample\"\n           name=\"anchoringExample\"\n           id=\"anchoringExample\"\n           deps=\"angular-animate.js;angular-route.js\"\n           animations=\"true\">\n    <file name=\"index.html\">\n      <a href=\"#/\">Home</a>\n      <hr />\n      <div class=\"view-container\">\n        <div ng-view class=\"view\"></div>\n      </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('anchoringExample', ['ngAnimate', 'ngRoute'])\n        .config(['$routeProvider', function($routeProvider) {\n          $routeProvider.when('/', {\n            templateUrl: 'home.html',\n            controller: 'HomeController as home'\n          });\n          $routeProvider.when('/profile/:id', {\n            templateUrl: 'profile.html',\n            controller: 'ProfileController as profile'\n          });\n        }])\n        .run(['$rootScope', function($rootScope) {\n          $rootScope.records = [\n            { id:1, title: \"Miss Beulah Roob\" },\n            { id:2, title: \"Trent Morissette\" },\n            { id:3, title: \"Miss Ava Pouros\" },\n            { id:4, title: \"Rod Pouros\" },\n            { id:5, title: \"Abdul Rice\" },\n            { id:6, title: \"Laurie Rutherford Sr.\" },\n            { id:7, title: \"Nakia McLaughlin\" },\n            { id:8, title: \"Jordon Blanda DVM\" },\n            { id:9, title: \"Rhoda Hand\" },\n            { id:10, title: \"Alexandrea Sauer\" }\n          ];\n        }])\n        .controller('HomeController', [function() {\n          //empty\n        }])\n        .controller('ProfileController', ['$rootScope', '$routeParams', function($rootScope, $routeParams) {\n          var index = parseInt($routeParams.id, 10);\n          var record = $rootScope.records[index - 1];\n\n          this.title = record.title;\n          this.id = record.id;\n        }]);\n    </file>\n    <file name=\"home.html\">\n      <h2>Welcome to the home page</h1>\n      <p>Please click on an element</p>\n      <a class=\"record\"\n         ng-href=\"#/profile/{{ record.id }}\"\n         ng-animate-ref=\"{{ record.id }}\"\n         ng-repeat=\"record in records\">\n        {{ record.title }}\n      </a>\n    </file>\n    <file name=\"profile.html\">\n      <div class=\"profile record\" ng-animate-ref=\"{{ profile.id }}\">\n        {{ profile.title }}\n      </div>\n    </file>\n    <file name=\"animations.css\">\n      .record {\n        display:block;\n        font-size:20px;\n      }\n      .profile {\n        background:black;\n        color:white;\n        font-size:100px;\n      }\n      .view-container {\n        position:relative;\n      }\n      .view-container > .view.ng-animate {\n        position:absolute;\n        top:0;\n        left:0;\n        width:100%;\n        min-height:500px;\n      }\n      .view.ng-enter, .view.ng-leave,\n      .record.ng-anchor {\n        transition:0.5s linear all;\n      }\n      .view.ng-enter {\n        transform:translateX(100%);\n      }\n      .view.ng-enter.ng-enter-active, .view.ng-leave {\n        transform:translateX(0%);\n      }\n      .view.ng-leave.ng-leave-active {\n        transform:translateX(-100%);\n      }\n      .record.ng-anchor-out {\n        background:red;\n      }\n    </file>\n  </example>\n *\n * ### How is the element transported?\n *\n * When an anchor animation occurs, ngAnimate will clone the starting element and position it exactly where the starting\n * element is located on screen via absolute positioning. The cloned element will be placed inside of the root element\n * of the application (where ng-app was defined) and all of the CSS classes of the starting element will be applied. The\n * element will then animate into the `out` and `in` animations and will eventually reach the coordinates and match\n * the dimensions of the destination element. During the entire animation a CSS class of `.ng-animate-shim` will be applied\n * to both the starting and destination elements in order to hide them from being visible (the CSS styling for the class\n * is: `visibility:hidden`). Once the anchor reaches its destination then it will be removed and the destination element\n * will become visible since the shim class will be removed.\n *\n * ### How is the morphing handled?\n *\n * CSS Anchoring relies on transitions and keyframes and the internal code is intelligent enough to figure out\n * what CSS classes differ between the starting element and the destination element. These different CSS classes\n * will be added/removed on the anchor element and a transition will be applied (the transition that is provided\n * in the anchor class). Long story short, ngAnimate will figure out what classes to add and remove which will\n * make the transition of the element as smooth and automatic as possible. Be sure to use simple CSS classes that\n * do not rely on DOM nesting structure so that the anchor element appears the same as the starting element (since\n * the cloned element is placed inside of root element which is likely close to the body element).\n *\n * Note that if the root element is on the `<html>` element then the cloned node will be placed inside of body.\n *\n *\n * ## Using $animate in your directive code\n *\n * So far we've explored how to feed in animations into an Angular application, but how do we trigger animations within our own directives in our application?\n * By injecting the `$animate` service into our directive code, we can trigger structural and class-based hooks which can then be consumed by animations. Let's\n * imagine we have a greeting box that shows and hides itself when the data changes\n *\n * ```html\n * <greeting-box active=\"onOrOff\">Hi there</greeting-box>\n * ```\n *\n * ```js\n * ngModule.directive('greetingBox', ['$animate', function($animate) {\n *   return function(scope, element, attrs) {\n *     attrs.$observe('active', function(value) {\n *       value ? $animate.addClass(element, 'on') : $animate.removeClass(element, 'on');\n *     });\n *   });\n * }]);\n * ```\n *\n * Now the `on` CSS class is added and removed on the greeting box component. Now if we add a CSS class on top of the greeting box element\n * in our HTML code then we can trigger a CSS or JS animation to happen.\n *\n * ```css\n * /&#42; normally we would create a CSS class to reference on the element &#42;/\n * greeting-box.on { transition:0.5s linear all; background:green; color:white; }\n * ```\n *\n * The `$animate` service contains a variety of other methods like `enter`, `leave`, `animate` and `setClass`. To learn more about what's\n * possible be sure to visit the {@link ng.$animate $animate service API page}.\n *\n *\n * ### Preventing Collisions With Third Party Libraries\n *\n * Some third-party frameworks place animation duration defaults across many element or className\n * selectors in order to make their code small and reuseable. This can lead to issues with ngAnimate, which\n * is expecting actual animations on these elements and has to wait for their completion.\n *\n * You can prevent this unwanted behavior by using a prefix on all your animation classes:\n *\n * ```css\n * /&#42; prefixed with animate- &#42;/\n * .animate-fade-add.animate-fade-add-active {\n *   transition:1s linear all;\n *   opacity:0;\n * }\n * ```\n *\n * You then configure `$animate` to enforce this prefix:\n *\n * ```js\n * $animateProvider.classNameFilter(/animate-/);\n * ```\n *\n * This also may provide your application with a speed boost since only specific elements containing CSS class prefix\n * will be evaluated for animation when any DOM changes occur in the application.\n *\n * ## Callbacks and Promises\n *\n * When `$animate` is called it returns a promise that can be used to capture when the animation has ended. Therefore if we were to trigger\n * an animation (within our directive code) then we can continue performing directive and scope related activities after the animation has\n * ended by chaining onto the returned promise that animation method returns.\n *\n * ```js\n * // somewhere within the depths of the directive\n * $animate.enter(element, parent).then(function() {\n *   //the animation has completed\n * });\n * ```\n *\n * (Note that earlier versions of Angular prior to v1.4 required the promise code to be wrapped using `$scope.$apply(...)`. This is not the case\n * anymore.)\n *\n * In addition to the animation promise, we can also make use of animation-related callbacks within our directives and controller code by registering\n * an event listener using the `$animate` service. Let's say for example that an animation was triggered on our view\n * routing controller to hook into that:\n *\n * ```js\n * ngModule.controller('HomePageController', ['$animate', function($animate) {\n *   $animate.on('enter', ngViewElement, function(element) {\n *     // the animation for this route has completed\n *   }]);\n * }])\n * ```\n *\n * (Note that you will need to trigger a digest within the callback to get angular to notice any scope-related changes.)\n */\n\n/**\n * @ngdoc service\n * @name $animate\n * @kind object\n *\n * @description\n * The ngAnimate `$animate` service documentation is the same for the core `$animate` service.\n *\n * Click here {@link ng.$animate to learn more about animations with `$animate`}.\n */\nangular.module('ngAnimate', [])\n  .directive('ngAnimateChildren', $$AnimateChildrenDirective)\n  .factory('$$rAFScheduler', $$rAFSchedulerFactory)\n\n  .factory('$$AnimateRunner', $$AnimateRunnerFactory)\n  .factory('$$animateAsyncRun', $$AnimateAsyncRunFactory)\n\n  .provider('$$animateQueue', $$AnimateQueueProvider)\n  .provider('$$animation', $$AnimationProvider)\n\n  .provider('$animateCss', $AnimateCssProvider)\n  .provider('$$animateCssDriver', $$AnimateCssDriverProvider)\n\n  .provider('$$animateJs', $$AnimateJsProvider)\n  .provider('$$animateJsDriver', $$AnimateJsDriverProvider);\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/server/php/public/vendor/angular-messages.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* jshint ignore:start */\n// this code is in the core, but not in angular-messages.js\nvar isArray = angular.isArray;\nvar forEach = angular.forEach;\nvar isString = angular.isString;\nvar jqLite = angular.element;\n/* jshint ignore:end */\n\n/**\n * @ngdoc module\n * @name ngMessages\n * @description\n *\n * The `ngMessages` module provides enhanced support for displaying messages within templates\n * (typically within forms or when rendering message objects that return key/value data).\n * Instead of relying on JavaScript code and/or complex ng-if statements within your form template to\n * show and hide error messages specific to the state of an input field, the `ngMessages` and\n * `ngMessage` directives are designed to handle the complexity, inheritance and priority\n * sequencing based on the order of how the messages are defined in the template.\n *\n * Currently, the ngMessages module only contains the code for the `ngMessages`, `ngMessagesInclude`\n * `ngMessage` and `ngMessageExp` directives.\n *\n * # Usage\n * The `ngMessages` directive listens on a key/value collection which is set on the ngMessages attribute.\n * Since the {@link ngModel ngModel} directive exposes an `$error` object, this error object can be\n * used with `ngMessages` to display control error messages in an easier way than with just regular angular\n * template directives.\n *\n * ```html\n * <form name=\"myForm\">\n *   <label>\n *     Enter text:\n *     <input type=\"text\" ng-model=\"field\" name=\"myField\" required minlength=\"5\" />\n *   </label>\n *   <div ng-messages=\"myForm.myField.$error\" role=\"alert\">\n *     <div ng-message=\"required\">You did not enter a field</div>\n *     <div ng-message=\"minlength, maxlength\">\n *       Your email must be between 5 and 100 characters long\n *     </div>\n *   </div>\n * </form>\n * ```\n *\n * Now whatever key/value entries are present within the provided object (in this case `$error`) then\n * the ngMessages directive will render the inner first ngMessage directive (depending if the key values\n * match the attribute value present on each ngMessage directive). In other words, if your errors\n * object contains the following data:\n *\n * ```javascript\n * <!-- keep in mind that ngModel automatically sets these error flags -->\n * myField.$error = { minlength : true, required : true };\n * ```\n *\n * Then the `required` message will be displayed first. When required is false then the `minlength` message\n * will be displayed right after (since these messages are ordered this way in the template HTML code).\n * The prioritization of each message is determined by what order they're present in the DOM.\n * Therefore, instead of having custom JavaScript code determine the priority of what errors are\n * present before others, the presentation of the errors are handled within the template.\n *\n * By default, ngMessages will only display one error at a time. However, if you wish to display all\n * messages then the `ng-messages-multiple` attribute flag can be used on the element containing the\n * ngMessages directive to make this happen.\n *\n * ```html\n * <!-- attribute-style usage -->\n * <div ng-messages=\"myForm.myField.$error\" ng-messages-multiple>...</div>\n *\n * <!-- element-style usage -->\n * <ng-messages for=\"myForm.myField.$error\" multiple>...</ng-messages>\n * ```\n *\n * ## Reusing and Overriding Messages\n * In addition to prioritization, ngMessages also allows for including messages from a remote or an inline\n * template. This allows for generic collection of messages to be reused across multiple parts of an\n * application.\n *\n * ```html\n * <script type=\"text/ng-template\" id=\"error-messages\">\n *   <div ng-message=\"required\">This field is required</div>\n *   <div ng-message=\"minlength\">This field is too short</div>\n * </script>\n *\n * <div ng-messages=\"myForm.myField.$error\" role=\"alert\">\n *   <div ng-messages-include=\"error-messages\"></div>\n * </div>\n * ```\n *\n * However, including generic messages may not be useful enough to match all input fields, therefore,\n * `ngMessages` provides the ability to override messages defined in the remote template by redefining\n * them within the directive container.\n *\n * ```html\n * <!-- a generic template of error messages known as \"my-custom-messages\" -->\n * <script type=\"text/ng-template\" id=\"my-custom-messages\">\n *   <div ng-message=\"required\">This field is required</div>\n *   <div ng-message=\"minlength\">This field is too short</div>\n * </script>\n *\n * <form name=\"myForm\">\n *   <label>\n *     Email address\n *     <input type=\"email\"\n *            id=\"email\"\n *            name=\"myEmail\"\n *            ng-model=\"email\"\n *            minlength=\"5\"\n *            required />\n *   </label>\n *   <!-- any ng-message elements that appear BEFORE the ng-messages-include will\n *        override the messages present in the ng-messages-include template -->\n *   <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *     <!-- this required message has overridden the template message -->\n *     <div ng-message=\"required\">You did not enter your email address</div>\n *\n *     <!-- this is a brand new message and will appear last in the prioritization -->\n *     <div ng-message=\"email\">Your email address is invalid</div>\n *\n *     <!-- and here are the generic error messages -->\n *     <div ng-messages-include=\"my-custom-messages\"></div>\n *   </div>\n * </form>\n * ```\n *\n * In the example HTML code above the message that is set on required will override the corresponding\n * required message defined within the remote template. Therefore, with particular input fields (such\n * email addresses, date fields, autocomplete inputs, etc...), specialized error messages can be applied\n * while more generic messages can be used to handle other, more general input errors.\n *\n * ## Dynamic Messaging\n * ngMessages also supports using expressions to dynamically change key values. Using arrays and\n * repeaters to list messages is also supported. This means that the code below will be able to\n * fully adapt itself and display the appropriate message when any of the expression data changes:\n *\n * ```html\n * <form name=\"myForm\">\n *   <label>\n *     Email address\n *     <input type=\"email\"\n *            name=\"myEmail\"\n *            ng-model=\"email\"\n *            minlength=\"5\"\n *            required />\n *   </label>\n *   <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *     <div ng-message=\"required\">You did not enter your email address</div>\n *     <div ng-repeat=\"errorMessage in errorMessages\">\n *       <!-- use ng-message-exp for a message whose key is given by an expression -->\n *       <div ng-message-exp=\"errorMessage.type\">{{ errorMessage.text }}</div>\n *     </div>\n *   </div>\n * </form>\n * ```\n *\n * The `errorMessage.type` expression can be a string value or it can be an array so\n * that multiple errors can be associated with a single error message:\n *\n * ```html\n *   <label>\n *     Email address\n *     <input type=\"email\"\n *            ng-model=\"data.email\"\n *            name=\"myEmail\"\n *            ng-minlength=\"5\"\n *            ng-maxlength=\"100\"\n *            required />\n *   </label>\n *   <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *     <div ng-message-exp=\"'required'\">You did not enter your email address</div>\n *     <div ng-message-exp=\"['minlength', 'maxlength']\">\n *       Your email must be between 5 and 100 characters long\n *     </div>\n *   </div>\n * ```\n *\n * Feel free to use other structural directives such as ng-if and ng-switch to further control\n * what messages are active and when. Be careful, if you place ng-message on the same element\n * as these structural directives, Angular may not be able to determine if a message is active\n * or not. Therefore it is best to place the ng-message on a child element of the structural\n * directive.\n *\n * ```html\n * <div ng-messages=\"myForm.myEmail.$error\" role=\"alert\">\n *   <div ng-if=\"showRequiredError\">\n *     <div ng-message=\"required\">Please enter something</div>\n *   </div>\n * </div>\n * ```\n *\n * ## Animations\n * If the `ngAnimate` module is active within the application then the `ngMessages`, `ngMessage` and\n * `ngMessageExp` directives will trigger animations whenever any messages are added and removed from\n * the DOM by the `ngMessages` directive.\n *\n * Whenever the `ngMessages` directive contains one or more visible messages then the `.ng-active` CSS\n * class will be added to the element. The `.ng-inactive` CSS class will be applied when there are no\n * messages present. Therefore, CSS transitions and keyframes as well as JavaScript animations can\n * hook into the animations whenever these classes are added/removed.\n *\n * Let's say that our HTML code for our messages container looks like so:\n *\n * ```html\n * <div ng-messages=\"myMessages\" class=\"my-messages\" role=\"alert\">\n *   <div ng-message=\"alert\" class=\"some-message\">...</div>\n *   <div ng-message=\"fail\" class=\"some-message\">...</div>\n * </div>\n * ```\n *\n * Then the CSS animation code for the message container looks like so:\n *\n * ```css\n * .my-messages {\n *   transition:1s linear all;\n * }\n * .my-messages.ng-active {\n *   // messages are visible\n * }\n * .my-messages.ng-inactive {\n *   // messages are hidden\n * }\n * ```\n *\n * Whenever an inner message is attached (becomes visible) or removed (becomes hidden) then the enter\n * and leave animation is triggered for each particular element bound to the `ngMessage` directive.\n *\n * Therefore, the CSS code for the inner messages looks like so:\n *\n * ```css\n * .some-message {\n *   transition:1s linear all;\n * }\n *\n * .some-message.ng-enter {}\n * .some-message.ng-enter.ng-enter-active {}\n *\n * .some-message.ng-leave {}\n * .some-message.ng-leave.ng-leave-active {}\n * ```\n *\n * {@link ngAnimate Click here} to learn how to use JavaScript animations or to learn more about ngAnimate.\n */\nangular.module('ngMessages', [])\n\n   /**\n    * @ngdoc directive\n    * @module ngMessages\n    * @name ngMessages\n    * @restrict AE\n    *\n    * @description\n    * `ngMessages` is a directive that is designed to show and hide messages based on the state\n    * of a key/value object that it listens on. The directive itself complements error message\n    * reporting with the `ngModel` $error object (which stores a key/value state of validation errors).\n    *\n    * `ngMessages` manages the state of internal messages within its container element. The internal\n    * messages use the `ngMessage` directive and will be inserted/removed from the page depending\n    * on if they're present within the key/value object. By default, only one message will be displayed\n    * at a time and this depends on the prioritization of the messages within the template. (This can\n    * be changed by using the `ng-messages-multiple` or `multiple` attribute on the directive container.)\n    *\n    * A remote template can also be used to promote message reusability and messages can also be\n    * overridden.\n    *\n    * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\" role=\"alert\">\n    *   <ANY ng-message=\"stringValue\">...</ANY>\n    *   <ANY ng-message=\"stringValue1, stringValue2, ...\">...</ANY>\n    *   <ANY ng-message-exp=\"expressionValue\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\" role=\"alert\">\n    *   <ng-message when=\"stringValue\">...</ng-message>\n    *   <ng-message when=\"stringValue1, stringValue2, ...\">...</ng-message>\n    *   <ng-message when-exp=\"expressionValue\">...</ng-message>\n    * </ng-messages>\n    * ```\n    *\n    * @param {string} ngMessages an angular expression evaluating to a key/value object\n    *                 (this is typically the $error object on an ngModel instance).\n    * @param {string=} ngMessagesMultiple|multiple when set, all messages will be displayed with true\n    *\n    * @example\n    * <example name=\"ngMessages-directive\" module=\"ngMessagesExample\"\n    *          deps=\"angular-messages.js\"\n    *          animations=\"true\" fixBase=\"true\">\n    *   <file name=\"index.html\">\n    *     <form name=\"myForm\">\n    *       <label>\n    *         Enter your name:\n    *         <input type=\"text\"\n    *                name=\"myName\"\n    *                ng-model=\"name\"\n    *                ng-minlength=\"5\"\n    *                ng-maxlength=\"20\"\n    *                required />\n    *       </label>\n    *       <pre>myForm.myName.$error = {{ myForm.myName.$error | json }}</pre>\n    *\n    *       <div ng-messages=\"myForm.myName.$error\" style=\"color:maroon\" role=\"alert\">\n    *         <div ng-message=\"required\">You did not enter a field</div>\n    *         <div ng-message=\"minlength\">Your field is too short</div>\n    *         <div ng-message=\"maxlength\">Your field is too long</div>\n    *       </div>\n    *     </form>\n    *   </file>\n    *   <file name=\"script.js\">\n    *     angular.module('ngMessagesExample', ['ngMessages']);\n    *   </file>\n    * </example>\n    */\n   .directive('ngMessages', ['$animate', function($animate) {\n     var ACTIVE_CLASS = 'ng-active';\n     var INACTIVE_CLASS = 'ng-inactive';\n\n     return {\n       require: 'ngMessages',\n       restrict: 'AE',\n       controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {\n         var ctrl = this;\n         var latestKey = 0;\n         var nextAttachId = 0;\n\n         this.getAttachId = function getAttachId() { return nextAttachId++; };\n\n         var messages = this.messages = {};\n         var renderLater, cachedCollection;\n\n         this.render = function(collection) {\n           collection = collection || {};\n\n           renderLater = false;\n           cachedCollection = collection;\n\n           // this is true if the attribute is empty or if the attribute value is truthy\n           var multiple = isAttrTruthy($scope, $attrs.ngMessagesMultiple) ||\n                          isAttrTruthy($scope, $attrs.multiple);\n\n           var unmatchedMessages = [];\n           var matchedKeys = {};\n           var messageItem = ctrl.head;\n           var messageFound = false;\n           var totalMessages = 0;\n\n           // we use != instead of !== to allow for both undefined and null values\n           while (messageItem != null) {\n             totalMessages++;\n             var messageCtrl = messageItem.message;\n\n             var messageUsed = false;\n             if (!messageFound) {\n               forEach(collection, function(value, key) {\n                 if (!messageUsed && truthy(value) && messageCtrl.test(key)) {\n                   // this is to prevent the same error name from showing up twice\n                   if (matchedKeys[key]) return;\n                   matchedKeys[key] = true;\n\n                   messageUsed = true;\n                   messageCtrl.attach();\n                 }\n               });\n             }\n\n             if (messageUsed) {\n               // unless we want to display multiple messages then we should\n               // set a flag here to avoid displaying the next message in the list\n               messageFound = !multiple;\n             } else {\n               unmatchedMessages.push(messageCtrl);\n             }\n\n             messageItem = messageItem.next;\n           }\n\n           forEach(unmatchedMessages, function(messageCtrl) {\n             messageCtrl.detach();\n           });\n\n           unmatchedMessages.length !== totalMessages\n              ? $animate.setClass($element, ACTIVE_CLASS, INACTIVE_CLASS)\n              : $animate.setClass($element, INACTIVE_CLASS, ACTIVE_CLASS);\n         };\n\n         $scope.$watchCollection($attrs.ngMessages || $attrs['for'], ctrl.render);\n\n         this.reRender = function() {\n           if (!renderLater) {\n             renderLater = true;\n             $scope.$evalAsync(function() {\n               if (renderLater) {\n                 cachedCollection && ctrl.render(cachedCollection);\n               }\n             });\n           }\n         };\n\n         this.register = function(comment, messageCtrl) {\n           var nextKey = latestKey.toString();\n           messages[nextKey] = {\n             message: messageCtrl\n           };\n           insertMessageNode($element[0], comment, nextKey);\n           comment.$$ngMessageNode = nextKey;\n           latestKey++;\n\n           ctrl.reRender();\n         };\n\n         this.deregister = function(comment) {\n           var key = comment.$$ngMessageNode;\n           delete comment.$$ngMessageNode;\n           removeMessageNode($element[0], comment, key);\n           delete messages[key];\n           ctrl.reRender();\n         };\n\n         function findPreviousMessage(parent, comment) {\n           var prevNode = comment;\n           var parentLookup = [];\n           while (prevNode && prevNode !== parent) {\n             var prevKey = prevNode.$$ngMessageNode;\n             if (prevKey && prevKey.length) {\n               return messages[prevKey];\n             }\n\n             // dive deeper into the DOM and examine its children for any ngMessage\n             // comments that may be in an element that appears deeper in the list\n             if (prevNode.childNodes.length && parentLookup.indexOf(prevNode) == -1) {\n               parentLookup.push(prevNode);\n               prevNode = prevNode.childNodes[prevNode.childNodes.length - 1];\n             } else {\n               prevNode = prevNode.previousSibling || prevNode.parentNode;\n             }\n           }\n         }\n\n         function insertMessageNode(parent, comment, key) {\n           var messageNode = messages[key];\n           if (!ctrl.head) {\n             ctrl.head = messageNode;\n           } else {\n             var match = findPreviousMessage(parent, comment);\n             if (match) {\n               messageNode.next = match.next;\n               match.next = messageNode;\n             } else {\n               messageNode.next = ctrl.head;\n               ctrl.head = messageNode;\n             }\n           }\n         }\n\n         function removeMessageNode(parent, comment, key) {\n           var messageNode = messages[key];\n\n           var match = findPreviousMessage(parent, comment);\n           if (match) {\n             match.next = messageNode.next;\n           } else {\n             ctrl.head = messageNode.next;\n           }\n         }\n       }]\n     };\n\n     function isAttrTruthy(scope, attr) {\n      return (isString(attr) && attr.length === 0) || //empty attribute\n             truthy(scope.$eval(attr));\n     }\n\n     function truthy(val) {\n       return isString(val) ? val.length : !!val;\n     }\n   }])\n\n   /**\n    * @ngdoc directive\n    * @name ngMessagesInclude\n    * @restrict AE\n    * @scope\n    *\n    * @description\n    * `ngMessagesInclude` is a directive with the purpose to import existing ngMessage template\n    * code from a remote template and place the downloaded template code into the exact spot\n    * that the ngMessagesInclude directive is placed within the ngMessages container. This allows\n    * for a series of pre-defined messages to be reused and also allows for the developer to\n    * determine what messages are overridden due to the placement of the ngMessagesInclude directive.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\" role=\"alert\">\n    *   <ANY ng-messages-include=\"remoteTplString\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\" role=\"alert\">\n    *   <ng-messages-include src=\"expressionValue1\">...</ng-messages-include>\n    * </ng-messages>\n    * ```\n    *\n    * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.\n    *\n    * @param {string} ngMessagesInclude|src a string value corresponding to the remote template.\n    */\n   .directive('ngMessagesInclude',\n     ['$templateRequest', '$document', '$compile', function($templateRequest, $document, $compile) {\n\n     return {\n       restrict: 'AE',\n       require: '^^ngMessages', // we only require this for validation sake\n       link: function($scope, element, attrs) {\n         var src = attrs.ngMessagesInclude || attrs.src;\n         $templateRequest(src).then(function(html) {\n           $compile(html)($scope, function(contents) {\n             element.after(contents);\n\n             // the anchor is placed for debugging purposes\n             var anchor = jqLite($document[0].createComment(' ngMessagesInclude: ' + src + ' '));\n             element.after(anchor);\n\n             // we don't want to pollute the DOM anymore by keeping an empty directive element\n             element.remove();\n           });\n         });\n       }\n     };\n   }])\n\n   /**\n    * @ngdoc directive\n    * @name ngMessage\n    * @restrict AE\n    * @scope\n    *\n    * @description\n    * `ngMessage` is a directive with the purpose to show and hide a particular message.\n    * For `ngMessage` to operate, a parent `ngMessages` directive on a parent DOM element\n    * must be situated since it determines which messages are visible based on the state\n    * of the provided key/value map that `ngMessages` listens on.\n    *\n    * More information about using `ngMessage` can be found in the\n    * {@link module:ngMessages `ngMessages` module documentation}.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\" role=\"alert\">\n    *   <ANY ng-message=\"stringValue\">...</ANY>\n    *   <ANY ng-message=\"stringValue1, stringValue2, ...\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\" role=\"alert\">\n    *   <ng-message when=\"stringValue\">...</ng-message>\n    *   <ng-message when=\"stringValue1, stringValue2, ...\">...</ng-message>\n    * </ng-messages>\n    * ```\n    *\n    * @param {expression} ngMessage|when a string value corresponding to the message key.\n    */\n  .directive('ngMessage', ngMessageDirectiveFactory('AE'))\n\n\n   /**\n    * @ngdoc directive\n    * @name ngMessageExp\n    * @restrict AE\n    * @scope\n    *\n    * @description\n    * `ngMessageExp` is a directive with the purpose to show and hide a particular message.\n    * For `ngMessageExp` to operate, a parent `ngMessages` directive on a parent DOM element\n    * must be situated since it determines which messages are visible based on the state\n    * of the provided key/value map that `ngMessages` listens on.\n    *\n    * @usage\n    * ```html\n    * <!-- using attribute directives -->\n    * <ANY ng-messages=\"expression\">\n    *   <ANY ng-message-exp=\"expressionValue\">...</ANY>\n    * </ANY>\n    *\n    * <!-- or by using element directives -->\n    * <ng-messages for=\"expression\">\n    *   <ng-message when-exp=\"expressionValue\">...</ng-message>\n    * </ng-messages>\n    * ```\n    *\n    * {@link module:ngMessages Click here} to learn more about `ngMessages` and `ngMessage`.\n    *\n    * @param {expression} ngMessageExp|whenExp an expression value corresponding to the message key.\n    */\n  .directive('ngMessageExp', ngMessageDirectiveFactory('A'));\n\nfunction ngMessageDirectiveFactory(restrict) {\n  return ['$animate', function($animate) {\n    return {\n      restrict: 'AE',\n      transclude: 'element',\n      terminal: true,\n      require: '^^ngMessages',\n      link: function(scope, element, attrs, ngMessagesCtrl, $transclude) {\n        var commentNode = element[0];\n\n        var records;\n        var staticExp = attrs.ngMessage || attrs.when;\n        var dynamicExp = attrs.ngMessageExp || attrs.whenExp;\n        var assignRecords = function(items) {\n          records = items\n              ? (isArray(items)\n                    ? items\n                    : items.split(/[\\s,]+/))\n              : null;\n          ngMessagesCtrl.reRender();\n        };\n\n        if (dynamicExp) {\n          assignRecords(scope.$eval(dynamicExp));\n          scope.$watchCollection(dynamicExp, assignRecords);\n        } else {\n          assignRecords(staticExp);\n        }\n\n        var currentElement, messageCtrl;\n        ngMessagesCtrl.register(commentNode, messageCtrl = {\n          test: function(name) {\n            return contains(records, name);\n          },\n          attach: function() {\n            if (!currentElement) {\n              $transclude(scope, function(elm) {\n                $animate.enter(elm, null, element);\n                currentElement = elm;\n\n                // Each time we attach this node to a message we get a new id that we can match\n                // when we are destroying the node later.\n                var $$attachId = currentElement.$$attachId = ngMessagesCtrl.getAttachId();\n\n                // in the event that the parent element is destroyed\n                // by any other structural directive then it's time\n                // to deregister the message from the controller\n                currentElement.on('$destroy', function() {\n                  if (currentElement && currentElement.$$attachId === $$attachId) {\n                    ngMessagesCtrl.deregister(commentNode);\n                    messageCtrl.detach();\n                  }\n                });\n              });\n            }\n          },\n          detach: function() {\n            if (currentElement) {\n              var elm = currentElement;\n              currentElement = null;\n              $animate.leave(elm);\n            }\n          }\n        });\n      }\n    };\n  }];\n\n  function contains(collection, key) {\n    if (collection) {\n      return isArray(collection)\n          ? collection.indexOf(key) >= 0\n          : collection.hasOwnProperty(key);\n    }\n  }\n}\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/server/php/public/vendor/angular-mocks.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {\n\n'use strict';\n\n/**\n * @ngdoc object\n * @name angular.mock\n * @description\n *\n * Namespace from 'angular-mocks.js' which contains testing related code.\n */\nangular.mock = {};\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n *\n * @description\n * This service is a mock implementation of {@link ng.$browser}. It provides fake\n * implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,\n * cookies, etc...\n *\n * The api of this service is the same as that of the real {@link ng.$browser $browser}, except\n * that there are several helper methods available which can be used in tests.\n */\nangular.mock.$BrowserProvider = function() {\n  this.$get = function() {\n    return new angular.mock.$Browser();\n  };\n};\n\nangular.mock.$Browser = function() {\n  var self = this;\n\n  this.isMock = true;\n  self.$$url = \"http://server/\";\n  self.$$lastUrl = self.$$url; // used by url polling fn\n  self.pollFns = [];\n\n  // TODO(vojta): remove this temporary api\n  self.$$completeOutstandingRequest = angular.noop;\n  self.$$incOutstandingRequestCount = angular.noop;\n\n\n  // register url polling fn\n\n  self.onUrlChange = function(listener) {\n    self.pollFns.push(\n      function() {\n        if (self.$$lastUrl !== self.$$url || self.$$state !== self.$$lastState) {\n          self.$$lastUrl = self.$$url;\n          self.$$lastState = self.$$state;\n          listener(self.$$url, self.$$state);\n        }\n      }\n    );\n\n    return listener;\n  };\n\n  self.$$applicationDestroyed = angular.noop;\n  self.$$checkUrlChange = angular.noop;\n\n  self.deferredFns = [];\n  self.deferredNextId = 0;\n\n  self.defer = function(fn, delay) {\n    delay = delay || 0;\n    self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});\n    self.deferredFns.sort(function(a, b) { return a.time - b.time;});\n    return self.deferredNextId++;\n  };\n\n\n  /**\n   * @name $browser#defer.now\n   *\n   * @description\n   * Current milliseconds mock time.\n   */\n  self.defer.now = 0;\n\n\n  self.defer.cancel = function(deferId) {\n    var fnIndex;\n\n    angular.forEach(self.deferredFns, function(fn, index) {\n      if (fn.id === deferId) fnIndex = index;\n    });\n\n    if (angular.isDefined(fnIndex)) {\n      self.deferredFns.splice(fnIndex, 1);\n      return true;\n    }\n\n    return false;\n  };\n\n\n  /**\n   * @name $browser#defer.flush\n   *\n   * @description\n   * Flushes all pending requests and executes the defer callbacks.\n   *\n   * @param {number=} number of milliseconds to flush. See {@link #defer.now}\n   */\n  self.defer.flush = function(delay) {\n    if (angular.isDefined(delay)) {\n      self.defer.now += delay;\n    } else {\n      if (self.deferredFns.length) {\n        self.defer.now = self.deferredFns[self.deferredFns.length - 1].time;\n      } else {\n        throw new Error('No deferred tasks to be flushed');\n      }\n    }\n\n    while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {\n      self.deferredFns.shift().fn();\n    }\n  };\n\n  self.$$baseHref = '/';\n  self.baseHref = function() {\n    return this.$$baseHref;\n  };\n};\nangular.mock.$Browser.prototype = {\n\n/**\n  * @name $browser#poll\n  *\n  * @description\n  * run all fns in pollFns\n  */\n  poll: function poll() {\n    angular.forEach(this.pollFns, function(pollFn) {\n      pollFn();\n    });\n  },\n\n  url: function(url, replace, state) {\n    if (angular.isUndefined(state)) {\n      state = null;\n    }\n    if (url) {\n      this.$$url = url;\n      // Native pushState serializes & copies the object; simulate it.\n      this.$$state = angular.copy(state);\n      return this;\n    }\n\n    return this.$$url;\n  },\n\n  state: function() {\n    return this.$$state;\n  },\n\n  notifyWhenNoOutstandingRequests: function(fn) {\n    fn();\n  }\n};\n\n\n/**\n * @ngdoc provider\n * @name $exceptionHandlerProvider\n *\n * @description\n * Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors\n * passed to the `$exceptionHandler`.\n */\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n *\n * @description\n * Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed\n * to it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration\n * information.\n *\n *\n * ```js\n *   describe('$exceptionHandlerProvider', function() {\n *\n *     it('should capture log messages and exceptions', function() {\n *\n *       module(function($exceptionHandlerProvider) {\n *         $exceptionHandlerProvider.mode('log');\n *       });\n *\n *       inject(function($log, $exceptionHandler, $timeout) {\n *         $timeout(function() { $log.log(1); });\n *         $timeout(function() { $log.log(2); throw 'banana peel'; });\n *         $timeout(function() { $log.log(3); });\n *         expect($exceptionHandler.errors).toEqual([]);\n *         expect($log.assertEmpty());\n *         $timeout.flush();\n *         expect($exceptionHandler.errors).toEqual(['banana peel']);\n *         expect($log.log.logs).toEqual([[1], [2], [3]]);\n *       });\n *     });\n *   });\n * ```\n */\n\nangular.mock.$ExceptionHandlerProvider = function() {\n  var handler;\n\n  /**\n   * @ngdoc method\n   * @name $exceptionHandlerProvider#mode\n   *\n   * @description\n   * Sets the logging mode.\n   *\n   * @param {string} mode Mode of operation, defaults to `rethrow`.\n   *\n   *   - `log`: Sometimes it is desirable to test that an error is thrown, for this case the `log`\n   *            mode stores an array of errors in `$exceptionHandler.errors`, to allow later\n   *            assertion of them. See {@link ngMock.$log#assertEmpty assertEmpty()} and\n   *            {@link ngMock.$log#reset reset()}\n   *   - `rethrow`: If any errors are passed to the handler in tests, it typically means that there\n   *                is a bug in the application or test, so this mock will make these tests fail.\n   *                For any implementations that expect exceptions to be thrown, the `rethrow` mode\n   *                will also maintain a log of thrown errors.\n   */\n  this.mode = function(mode) {\n\n    switch (mode) {\n      case 'log':\n      case 'rethrow':\n        var errors = [];\n        handler = function(e) {\n          if (arguments.length == 1) {\n            errors.push(e);\n          } else {\n            errors.push([].slice.call(arguments, 0));\n          }\n          if (mode === \"rethrow\") {\n            throw e;\n          }\n        };\n        handler.errors = errors;\n        break;\n      default:\n        throw new Error(\"Unknown mode '\" + mode + \"', only 'log'/'rethrow' modes are allowed!\");\n    }\n  };\n\n  this.$get = function() {\n    return handler;\n  };\n\n  this.mode('rethrow');\n};\n\n\n/**\n * @ngdoc service\n * @name $log\n *\n * @description\n * Mock implementation of {@link ng.$log} that gathers all logged messages in arrays\n * (one array per logging level). These arrays are exposed as `logs` property of each of the\n * level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.\n *\n */\nangular.mock.$LogProvider = function() {\n  var debug = true;\n\n  function concat(array1, array2, index) {\n    return array1.concat(Array.prototype.slice.call(array2, index));\n  }\n\n  this.debugEnabled = function(flag) {\n    if (angular.isDefined(flag)) {\n      debug = flag;\n      return this;\n    } else {\n      return debug;\n    }\n  };\n\n  this.$get = function() {\n    var $log = {\n      log: function() { $log.log.logs.push(concat([], arguments, 0)); },\n      warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },\n      info: function() { $log.info.logs.push(concat([], arguments, 0)); },\n      error: function() { $log.error.logs.push(concat([], arguments, 0)); },\n      debug: function() {\n        if (debug) {\n          $log.debug.logs.push(concat([], arguments, 0));\n        }\n      }\n    };\n\n    /**\n     * @ngdoc method\n     * @name $log#reset\n     *\n     * @description\n     * Reset all of the logging arrays to empty.\n     */\n    $log.reset = function() {\n      /**\n       * @ngdoc property\n       * @name $log#log.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#log `log()`}.\n       *\n       * @example\n       * ```js\n       * $log.log('Some Log');\n       * var first = $log.log.logs.unshift();\n       * ```\n       */\n      $log.log.logs = [];\n      /**\n       * @ngdoc property\n       * @name $log#info.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#info `info()`}.\n       *\n       * @example\n       * ```js\n       * $log.info('Some Info');\n       * var first = $log.info.logs.unshift();\n       * ```\n       */\n      $log.info.logs = [];\n      /**\n       * @ngdoc property\n       * @name $log#warn.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#warn `warn()`}.\n       *\n       * @example\n       * ```js\n       * $log.warn('Some Warning');\n       * var first = $log.warn.logs.unshift();\n       * ```\n       */\n      $log.warn.logs = [];\n      /**\n       * @ngdoc property\n       * @name $log#error.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#error `error()`}.\n       *\n       * @example\n       * ```js\n       * $log.error('Some Error');\n       * var first = $log.error.logs.unshift();\n       * ```\n       */\n      $log.error.logs = [];\n        /**\n       * @ngdoc property\n       * @name $log#debug.logs\n       *\n       * @description\n       * Array of messages logged using {@link ng.$log#debug `debug()`}.\n       *\n       * @example\n       * ```js\n       * $log.debug('Some Error');\n       * var first = $log.debug.logs.unshift();\n       * ```\n       */\n      $log.debug.logs = [];\n    };\n\n    /**\n     * @ngdoc method\n     * @name $log#assertEmpty\n     *\n     * @description\n     * Assert that all of the logging methods have no logged messages. If any messages are present,\n     * an exception is thrown.\n     */\n    $log.assertEmpty = function() {\n      var errors = [];\n      angular.forEach(['error', 'warn', 'info', 'log', 'debug'], function(logLevel) {\n        angular.forEach($log[logLevel].logs, function(log) {\n          angular.forEach(log, function(logItem) {\n            errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\\n' +\n                        (logItem.stack || ''));\n          });\n        });\n      });\n      if (errors.length) {\n        errors.unshift(\"Expected $log to be empty! Either a message was logged unexpectedly, or \" +\n          \"an expected log message was not checked and removed:\");\n        errors.push('');\n        throw new Error(errors.join('\\n---------\\n'));\n      }\n    };\n\n    $log.reset();\n    return $log;\n  };\n};\n\n\n/**\n * @ngdoc service\n * @name $interval\n *\n * @description\n * Mock implementation of the $interval service.\n *\n * Use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n * time.\n *\n * @param {function()} fn A function that should be called repeatedly.\n * @param {number} delay Number of milliseconds between each function call.\n * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n *   indefinitely.\n * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n * @param {...*=} Pass additional parameters to the executed function.\n * @returns {promise} A promise which will be notified on each iteration.\n */\nangular.mock.$IntervalProvider = function() {\n  this.$get = ['$browser', '$rootScope', '$q', '$$q',\n       function($browser,   $rootScope,   $q,   $$q) {\n    var repeatFns = [],\n        nextRepeatId = 0,\n        now = 0;\n\n    var $interval = function(fn, delay, count, invokeApply) {\n      var hasParams = arguments.length > 4,\n          args = hasParams ? Array.prototype.slice.call(arguments, 4) : [],\n          iteration = 0,\n          skipApply = (angular.isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise;\n\n      count = (angular.isDefined(count)) ? count : 0;\n      promise.then(null, null, (!hasParams) ? fn : function() {\n        fn.apply(null, args);\n      });\n\n      promise.$$intervalId = nextRepeatId;\n\n      function tick() {\n        deferred.notify(iteration++);\n\n        if (count > 0 && iteration >= count) {\n          var fnIndex;\n          deferred.resolve(iteration);\n\n          angular.forEach(repeatFns, function(fn, index) {\n            if (fn.id === promise.$$intervalId) fnIndex = index;\n          });\n\n          if (angular.isDefined(fnIndex)) {\n            repeatFns.splice(fnIndex, 1);\n          }\n        }\n\n        if (skipApply) {\n          $browser.defer.flush();\n        } else {\n          $rootScope.$apply();\n        }\n      }\n\n      repeatFns.push({\n        nextTime:(now + delay),\n        delay: delay,\n        fn: tick,\n        id: nextRepeatId,\n        deferred: deferred\n      });\n      repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});\n\n      nextRepeatId++;\n      return promise;\n    };\n    /**\n     * @ngdoc method\n     * @name $interval#cancel\n     *\n     * @description\n     * Cancels a task associated with the `promise`.\n     *\n     * @param {promise} promise A promise from calling the `$interval` function.\n     * @returns {boolean} Returns `true` if the task was successfully cancelled.\n     */\n    $interval.cancel = function(promise) {\n      if (!promise) return false;\n      var fnIndex;\n\n      angular.forEach(repeatFns, function(fn, index) {\n        if (fn.id === promise.$$intervalId) fnIndex = index;\n      });\n\n      if (angular.isDefined(fnIndex)) {\n        repeatFns[fnIndex].deferred.reject('canceled');\n        repeatFns.splice(fnIndex, 1);\n        return true;\n      }\n\n      return false;\n    };\n\n    /**\n     * @ngdoc method\n     * @name $interval#flush\n     * @description\n     *\n     * Runs interval tasks scheduled to be run in the next `millis` milliseconds.\n     *\n     * @param {number=} millis maximum timeout amount to flush up until.\n     *\n     * @return {number} The amount of time moved forward.\n     */\n    $interval.flush = function(millis) {\n      now += millis;\n      while (repeatFns.length && repeatFns[0].nextTime <= now) {\n        var task = repeatFns[0];\n        task.fn();\n        task.nextTime += task.delay;\n        repeatFns.sort(function(a, b) { return a.nextTime - b.nextTime;});\n      }\n      return millis;\n    };\n\n    return $interval;\n  }];\n};\n\n\n/* jshint -W101 */\n/* The R_ISO8061_STR regex is never going to fit into the 100 char limit!\n * This directive should go inside the anonymous function but a bug in JSHint means that it would\n * not be enacted early enough to prevent the warning.\n */\nvar R_ISO8061_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?:\\:?(\\d\\d)(?:\\:?(\\d\\d)(?:\\.(\\d{3}))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d)))?$/;\n\nfunction jsonStringToDate(string) {\n  var match;\n  if (match = string.match(R_ISO8061_STR)) {\n    var date = new Date(0),\n        tzHour = 0,\n        tzMin  = 0;\n    if (match[9]) {\n      tzHour = toInt(match[9] + match[10]);\n      tzMin = toInt(match[9] + match[11]);\n    }\n    date.setUTCFullYear(toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));\n    date.setUTCHours(toInt(match[4] || 0) - tzHour,\n                     toInt(match[5] || 0) - tzMin,\n                     toInt(match[6] || 0),\n                     toInt(match[7] || 0));\n    return date;\n  }\n  return string;\n}\n\nfunction toInt(str) {\n  return parseInt(str, 10);\n}\n\nfunction padNumber(num, digits, trim) {\n  var neg = '';\n  if (num < 0) {\n    neg =  '-';\n    num = -num;\n  }\n  num = '' + num;\n  while (num.length < digits) num = '0' + num;\n  if (trim) {\n    num = num.substr(num.length - digits);\n  }\n  return neg + num;\n}\n\n\n/**\n * @ngdoc type\n * @name angular.mock.TzDate\n * @description\n *\n * *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.\n *\n * Mock of the Date type which has its timezone specified via constructor arg.\n *\n * The main purpose is to create Date-like instances with timezone fixed to the specified timezone\n * offset, so that we can test code that depends on local timezone settings without dependency on\n * the time zone settings of the machine where the code is running.\n *\n * @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)\n * @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*\n *\n * @example\n * !!!! WARNING !!!!!\n * This is not a complete Date object so only methods that were implemented can be called safely.\n * To make matters worse, TzDate instances inherit stuff from Date via a prototype.\n *\n * We do our best to intercept calls to \"unimplemented\" methods, but since the list of methods is\n * incomplete we might be missing some non-standard methods. This can result in errors like:\n * \"Date.prototype.foo called on incompatible Object\".\n *\n * ```js\n * var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');\n * newYearInBratislava.getTimezoneOffset() => -60;\n * newYearInBratislava.getFullYear() => 2010;\n * newYearInBratislava.getMonth() => 0;\n * newYearInBratislava.getDate() => 1;\n * newYearInBratislava.getHours() => 0;\n * newYearInBratislava.getMinutes() => 0;\n * newYearInBratislava.getSeconds() => 0;\n * ```\n *\n */\nangular.mock.TzDate = function(offset, timestamp) {\n  var self = new Date(0);\n  if (angular.isString(timestamp)) {\n    var tsStr = timestamp;\n\n    self.origDate = jsonStringToDate(timestamp);\n\n    timestamp = self.origDate.getTime();\n    if (isNaN(timestamp)) {\n      throw {\n        name: \"Illegal Argument\",\n        message: \"Arg '\" + tsStr + \"' passed into TzDate constructor is not a valid date string\"\n      };\n    }\n  } else {\n    self.origDate = new Date(timestamp);\n  }\n\n  var localOffset = new Date(timestamp).getTimezoneOffset();\n  self.offsetDiff = localOffset * 60 * 1000 - offset * 1000 * 60 * 60;\n  self.date = new Date(timestamp + self.offsetDiff);\n\n  self.getTime = function() {\n    return self.date.getTime() - self.offsetDiff;\n  };\n\n  self.toLocaleDateString = function() {\n    return self.date.toLocaleDateString();\n  };\n\n  self.getFullYear = function() {\n    return self.date.getFullYear();\n  };\n\n  self.getMonth = function() {\n    return self.date.getMonth();\n  };\n\n  self.getDate = function() {\n    return self.date.getDate();\n  };\n\n  self.getHours = function() {\n    return self.date.getHours();\n  };\n\n  self.getMinutes = function() {\n    return self.date.getMinutes();\n  };\n\n  self.getSeconds = function() {\n    return self.date.getSeconds();\n  };\n\n  self.getMilliseconds = function() {\n    return self.date.getMilliseconds();\n  };\n\n  self.getTimezoneOffset = function() {\n    return offset * 60;\n  };\n\n  self.getUTCFullYear = function() {\n    return self.origDate.getUTCFullYear();\n  };\n\n  self.getUTCMonth = function() {\n    return self.origDate.getUTCMonth();\n  };\n\n  self.getUTCDate = function() {\n    return self.origDate.getUTCDate();\n  };\n\n  self.getUTCHours = function() {\n    return self.origDate.getUTCHours();\n  };\n\n  self.getUTCMinutes = function() {\n    return self.origDate.getUTCMinutes();\n  };\n\n  self.getUTCSeconds = function() {\n    return self.origDate.getUTCSeconds();\n  };\n\n  self.getUTCMilliseconds = function() {\n    return self.origDate.getUTCMilliseconds();\n  };\n\n  self.getDay = function() {\n    return self.date.getDay();\n  };\n\n  // provide this method only on browsers that already have it\n  if (self.toISOString) {\n    self.toISOString = function() {\n      return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +\n            padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +\n            padNumber(self.origDate.getUTCDate(), 2) + 'T' +\n            padNumber(self.origDate.getUTCHours(), 2) + ':' +\n            padNumber(self.origDate.getUTCMinutes(), 2) + ':' +\n            padNumber(self.origDate.getUTCSeconds(), 2) + '.' +\n            padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z';\n    };\n  }\n\n  //hide all methods not implemented in this mock that the Date prototype exposes\n  var unimplementedMethods = ['getUTCDay',\n      'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',\n      'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',\n      'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',\n      'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',\n      'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];\n\n  angular.forEach(unimplementedMethods, function(methodName) {\n    self[methodName] = function() {\n      throw new Error(\"Method '\" + methodName + \"' is not implemented in the TzDate mock\");\n    };\n  });\n\n  return self;\n};\n\n//make \"tzDateInstance instanceof Date\" return true\nangular.mock.TzDate.prototype = Date.prototype;\n/* jshint +W101 */\n\nangular.mock.animate = angular.module('ngAnimateMock', ['ng'])\n\n  .config(['$provide', function($provide) {\n\n    $provide.factory('$$forceReflow', function() {\n      function reflowFn() {\n        reflowFn.totalReflows++;\n      }\n      reflowFn.totalReflows = 0;\n      return reflowFn;\n    });\n\n    $provide.factory('$$animateAsyncRun', function() {\n      var queue = [];\n      var queueFn = function() {\n        return function(fn) {\n          queue.push(fn);\n        };\n      };\n      queueFn.flush = function() {\n        if (queue.length === 0) return false;\n\n        for (var i = 0; i < queue.length; i++) {\n          queue[i]();\n        }\n        queue = [];\n\n        return true;\n      };\n      return queueFn;\n    });\n\n    $provide.decorator('$animate', ['$delegate', '$timeout', '$browser', '$$rAF',\n                                    '$$forceReflow', '$$animateAsyncRun', '$rootScope',\n                            function($delegate,   $timeout,   $browser,   $$rAF,\n                                     $$forceReflow,   $$animateAsyncRun,  $rootScope) {\n      var animate = {\n        queue: [],\n        cancel: $delegate.cancel,\n        on: $delegate.on,\n        off: $delegate.off,\n        pin: $delegate.pin,\n        get reflows() {\n          return $$forceReflow.totalReflows;\n        },\n        enabled: $delegate.enabled,\n        flush: function() {\n          $rootScope.$digest();\n\n          var doNextRun, somethingFlushed = false;\n          do {\n            doNextRun = false;\n\n            if ($$rAF.queue.length) {\n              $$rAF.flush();\n              doNextRun = somethingFlushed = true;\n            }\n\n            if ($$animateAsyncRun.flush()) {\n              doNextRun = somethingFlushed = true;\n            }\n          } while (doNextRun);\n\n          if (!somethingFlushed) {\n            throw new Error('No pending animations ready to be closed or flushed');\n          }\n\n          $rootScope.$digest();\n        }\n      };\n\n      angular.forEach(\n        ['animate','enter','leave','move','addClass','removeClass','setClass'], function(method) {\n        animate[method] = function() {\n          animate.queue.push({\n            event: method,\n            element: arguments[0],\n            options: arguments[arguments.length - 1],\n            args: arguments\n          });\n          return $delegate[method].apply($delegate, arguments);\n        };\n      });\n\n      return animate;\n    }]);\n\n  }]);\n\n\n/**\n * @ngdoc function\n * @name angular.mock.dump\n * @description\n *\n * *NOTE*: this is not an injectable instance, just a globally available function.\n *\n * Method for serializing common angular objects (scope, elements, etc..) into strings, useful for\n * debugging.\n *\n * This method is also available on window, where it can be used to display objects on debug\n * console.\n *\n * @param {*} object - any object to turn into string.\n * @return {string} a serialized string of the argument\n */\nangular.mock.dump = function(object) {\n  return serialize(object);\n\n  function serialize(object) {\n    var out;\n\n    if (angular.isElement(object)) {\n      object = angular.element(object);\n      out = angular.element('<div></div>');\n      angular.forEach(object, function(element) {\n        out.append(angular.element(element).clone());\n      });\n      out = out.html();\n    } else if (angular.isArray(object)) {\n      out = [];\n      angular.forEach(object, function(o) {\n        out.push(serialize(o));\n      });\n      out = '[ ' + out.join(', ') + ' ]';\n    } else if (angular.isObject(object)) {\n      if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {\n        out = serializeScope(object);\n      } else if (object instanceof Error) {\n        out = object.stack || ('' + object.name + ': ' + object.message);\n      } else {\n        // TODO(i): this prevents methods being logged,\n        // we should have a better way to serialize objects\n        out = angular.toJson(object, true);\n      }\n    } else {\n      out = String(object);\n    }\n\n    return out;\n  }\n\n  function serializeScope(scope, offset) {\n    offset = offset ||  '  ';\n    var log = [offset + 'Scope(' + scope.$id + '): {'];\n    for (var key in scope) {\n      if (Object.prototype.hasOwnProperty.call(scope, key) && !key.match(/^(\\$|this)/)) {\n        log.push('  ' + key + ': ' + angular.toJson(scope[key]));\n      }\n    }\n    var child = scope.$$childHead;\n    while (child) {\n      log.push(serializeScope(child, offset + '  '));\n      child = child.$$nextSibling;\n    }\n    log.push('}');\n    return log.join('\\n' + offset);\n  }\n};\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @description\n * Fake HTTP backend implementation suitable for unit testing applications that use the\n * {@link ng.$http $http service}.\n *\n * *Note*: For fake HTTP backend implementation suitable for end-to-end testing or backend-less\n * development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.\n *\n * During unit testing, we want our unit tests to run quickly and have no external dependencies so\n * we don’t want to send [XHR](https://developer.mozilla.org/en/xmlhttprequest) or\n * [JSONP](http://en.wikipedia.org/wiki/JSONP) requests to a real server. All we really need is\n * to verify whether a certain request has been sent or not, or alternatively just let the\n * application make requests, respond with pre-trained responses and assert that the end result is\n * what we expect it to be.\n *\n * This mock implementation can be used to respond with static or dynamic responses via the\n * `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).\n *\n * When an Angular application needs some data from a server, it calls the $http service, which\n * sends the request to a real server using $httpBackend service. With dependency injection, it is\n * easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify\n * the requests and respond with some testing data without sending a request to a real server.\n *\n * There are two ways to specify what test data should be returned as http responses by the mock\n * backend when the code under test makes http requests:\n *\n * - `$httpBackend.expect` - specifies a request expectation\n * - `$httpBackend.when` - specifies a backend definition\n *\n *\n * # Request Expectations vs Backend Definitions\n *\n * Request expectations provide a way to make assertions about requests made by the application and\n * to define responses for those requests. The test will fail if the expected requests are not made\n * or they are made in the wrong order.\n *\n * Backend definitions allow you to define a fake backend for your application which doesn't assert\n * if a particular request was made or not, it just returns a trained response if a request is made.\n * The test will pass whether or not the request gets made during testing.\n *\n *\n * <table class=\"table\">\n *   <tr><th width=\"220px\"></th><th>Request expectations</th><th>Backend definitions</th></tr>\n *   <tr>\n *     <th>Syntax</th>\n *     <td>.expect(...).respond(...)</td>\n *     <td>.when(...).respond(...)</td>\n *   </tr>\n *   <tr>\n *     <th>Typical usage</th>\n *     <td>strict unit tests</td>\n *     <td>loose (black-box) unit testing</td>\n *   </tr>\n *   <tr>\n *     <th>Fulfills multiple requests</th>\n *     <td>NO</td>\n *     <td>YES</td>\n *   </tr>\n *   <tr>\n *     <th>Order of requests matters</th>\n *     <td>YES</td>\n *     <td>NO</td>\n *   </tr>\n *   <tr>\n *     <th>Request required</th>\n *     <td>YES</td>\n *     <td>NO</td>\n *   </tr>\n *   <tr>\n *     <th>Response required</th>\n *     <td>optional (see below)</td>\n *     <td>YES</td>\n *   </tr>\n * </table>\n *\n * In cases where both backend definitions and request expectations are specified during unit\n * testing, the request expectations are evaluated first.\n *\n * If a request expectation has no response specified, the algorithm will search your backend\n * definitions for an appropriate response.\n *\n * If a request didn't match any expectation or if the expectation doesn't have the response\n * defined, the backend definitions are evaluated in sequential order to see if any of them match\n * the request. The response from the first matched definition is returned.\n *\n *\n * # Flushing HTTP requests\n *\n * The $httpBackend used in production always responds to requests asynchronously. If we preserved\n * this behavior in unit testing, we'd have to create async unit tests, which are hard to write,\n * to follow and to maintain. But neither can the testing mock respond synchronously; that would\n * change the execution of the code under test. For this reason, the mock $httpBackend has a\n * `flush()` method, which allows the test to explicitly flush pending requests. This preserves\n * the async api of the backend, while allowing the test to execute synchronously.\n *\n *\n * # Unit testing with mock $httpBackend\n * The following code shows how to setup and use the mock backend when unit testing a controller.\n * First we create the controller under test:\n *\n  ```js\n  // The module code\n  angular\n    .module('MyApp', [])\n    .controller('MyController', MyController);\n\n  // The controller code\n  function MyController($scope, $http) {\n    var authToken;\n\n    $http.get('/auth.py').success(function(data, status, headers) {\n      authToken = headers('A-Token');\n      $scope.user = data;\n    });\n\n    $scope.saveMessage = function(message) {\n      var headers = { 'Authorization': authToken };\n      $scope.status = 'Saving...';\n\n      $http.post('/add-msg.py', message, { headers: headers } ).success(function(response) {\n        $scope.status = '';\n      }).error(function() {\n        $scope.status = 'Failed...';\n      });\n    };\n  }\n  ```\n *\n * Now we setup the mock backend and create the test specs:\n *\n  ```js\n    // testing controller\n    describe('MyController', function() {\n       var $httpBackend, $rootScope, createController, authRequestHandler;\n\n       // Set up the module\n       beforeEach(module('MyApp'));\n\n       beforeEach(inject(function($injector) {\n         // Set up the mock http service responses\n         $httpBackend = $injector.get('$httpBackend');\n         // backend definition common for all tests\n         authRequestHandler = $httpBackend.when('GET', '/auth.py')\n                                .respond({userId: 'userX'}, {'A-Token': 'xxx'});\n\n         // Get hold of a scope (i.e. the root scope)\n         $rootScope = $injector.get('$rootScope');\n         // The $controller service is used to create instances of controllers\n         var $controller = $injector.get('$controller');\n\n         createController = function() {\n           return $controller('MyController', {'$scope' : $rootScope });\n         };\n       }));\n\n\n       afterEach(function() {\n         $httpBackend.verifyNoOutstandingExpectation();\n         $httpBackend.verifyNoOutstandingRequest();\n       });\n\n\n       it('should fetch authentication token', function() {\n         $httpBackend.expectGET('/auth.py');\n         var controller = createController();\n         $httpBackend.flush();\n       });\n\n\n       it('should fail authentication', function() {\n\n         // Notice how you can change the response even after it was set\n         authRequestHandler.respond(401, '');\n\n         $httpBackend.expectGET('/auth.py');\n         var controller = createController();\n         $httpBackend.flush();\n         expect($rootScope.status).toBe('Failed...');\n       });\n\n\n       it('should send msg to server', function() {\n         var controller = createController();\n         $httpBackend.flush();\n\n         // now you don’t care about the authentication, but\n         // the controller will still send the request and\n         // $httpBackend will respond without you having to\n         // specify the expectation and response for this request\n\n         $httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');\n         $rootScope.saveMessage('message content');\n         expect($rootScope.status).toBe('Saving...');\n         $httpBackend.flush();\n         expect($rootScope.status).toBe('');\n       });\n\n\n       it('should send auth header', function() {\n         var controller = createController();\n         $httpBackend.flush();\n\n         $httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {\n           // check if the header was sent, if it wasn't the expectation won't\n           // match the request and the test will fail\n           return headers['Authorization'] == 'xxx';\n         }).respond(201, '');\n\n         $rootScope.saveMessage('whatever');\n         $httpBackend.flush();\n       });\n    });\n   ```\n */\nangular.mock.$HttpBackendProvider = function() {\n  this.$get = ['$rootScope', '$timeout', createHttpBackendMock];\n};\n\n/**\n * General factory function for $httpBackend mock.\n * Returns instance for unit testing (when no arguments specified):\n *   - passing through is disabled\n *   - auto flushing is disabled\n *\n * Returns instance for e2e testing (when `$delegate` and `$browser` specified):\n *   - passing through (delegating request to real backend) is enabled\n *   - auto flushing is enabled\n *\n * @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)\n * @param {Object=} $browser Auto-flushing enabled if specified\n * @return {Object} Instance of $httpBackend mock\n */\nfunction createHttpBackendMock($rootScope, $timeout, $delegate, $browser) {\n  var definitions = [],\n      expectations = [],\n      responses = [],\n      responsesPush = angular.bind(responses, responses.push),\n      copy = angular.copy;\n\n  function createResponse(status, data, headers, statusText) {\n    if (angular.isFunction(status)) return status;\n\n    return function() {\n      return angular.isNumber(status)\n          ? [status, data, headers, statusText]\n          : [200, status, data, headers];\n    };\n  }\n\n  // TODO(vojta): change params to: method, url, data, headers, callback\n  function $httpBackend(method, url, data, callback, headers, timeout, withCredentials) {\n    var xhr = new MockXhr(),\n        expectation = expectations[0],\n        wasExpected = false;\n\n    function prettyPrint(data) {\n      return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)\n          ? data\n          : angular.toJson(data);\n    }\n\n    function wrapResponse(wrapped) {\n      if (!$browser && timeout) {\n        timeout.then ? timeout.then(handleTimeout) : $timeout(handleTimeout, timeout);\n      }\n\n      return handleResponse;\n\n      function handleResponse() {\n        var response = wrapped.response(method, url, data, headers);\n        xhr.$$respHeaders = response[2];\n        callback(copy(response[0]), copy(response[1]), xhr.getAllResponseHeaders(),\n                 copy(response[3] || ''));\n      }\n\n      function handleTimeout() {\n        for (var i = 0, ii = responses.length; i < ii; i++) {\n          if (responses[i] === handleResponse) {\n            responses.splice(i, 1);\n            callback(-1, undefined, '');\n            break;\n          }\n        }\n      }\n    }\n\n    if (expectation && expectation.match(method, url)) {\n      if (!expectation.matchData(data)) {\n        throw new Error('Expected ' + expectation + ' with different data\\n' +\n            'EXPECTED: ' + prettyPrint(expectation.data) + '\\nGOT:      ' + data);\n      }\n\n      if (!expectation.matchHeaders(headers)) {\n        throw new Error('Expected ' + expectation + ' with different headers\\n' +\n                        'EXPECTED: ' + prettyPrint(expectation.headers) + '\\nGOT:      ' +\n                        prettyPrint(headers));\n      }\n\n      expectations.shift();\n\n      if (expectation.response) {\n        responses.push(wrapResponse(expectation));\n        return;\n      }\n      wasExpected = true;\n    }\n\n    var i = -1, definition;\n    while ((definition = definitions[++i])) {\n      if (definition.match(method, url, data, headers || {})) {\n        if (definition.response) {\n          // if $browser specified, we do auto flush all requests\n          ($browser ? $browser.defer : responsesPush)(wrapResponse(definition));\n        } else if (definition.passThrough) {\n          $delegate(method, url, data, callback, headers, timeout, withCredentials);\n        } else throw new Error('No response defined !');\n        return;\n      }\n    }\n    throw wasExpected ?\n        new Error('No response defined !') :\n        new Error('Unexpected request: ' + method + ' ' + url + '\\n' +\n                  (expectation ? 'Expected ' + expectation : 'No more request expected'));\n  }\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#when\n   * @description\n   * Creates a new backend definition.\n   *\n   * @param {string} method HTTP method.\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives\n   *   data string and returns true if the data is as expected.\n   * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header\n   *   object and returns true if the headers match the current definition.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   *\n   *  - respond –\n   *      `{function([status,] data[, headers, statusText])\n   *      | function(function(method, url, data, headers)}`\n   *    – The respond method takes a set of static data to be returned or a function that can\n   *    return an array containing response status (number), response data (string), response\n   *    headers (Object), and the text for the status (string). The respond method returns the\n   *    `requestHandler` object for possible overrides.\n   */\n  $httpBackend.when = function(method, url, data, headers) {\n    var definition = new MockHttpExpectation(method, url, data, headers),\n        chain = {\n          respond: function(status, data, headers, statusText) {\n            definition.passThrough = undefined;\n            definition.response = createResponse(status, data, headers, statusText);\n            return chain;\n          }\n        };\n\n    if ($browser) {\n      chain.passThrough = function() {\n        definition.response = undefined;\n        definition.passThrough = true;\n        return chain;\n      };\n    }\n\n    definitions.push(definition);\n    return chain;\n  };\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenGET\n   * @description\n   * Creates a new backend definition for GET requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenHEAD\n   * @description\n   * Creates a new backend definition for HEAD requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenDELETE\n   * @description\n   * Creates a new backend definition for DELETE requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenPOST\n   * @description\n   * Creates a new backend definition for POST requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives\n   *   data string and returns true if the data is as expected.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenPUT\n   * @description\n   * Creates a new backend definition for PUT requests.  For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string))=} data HTTP request body or function that receives\n   *   data string and returns true if the data is as expected.\n   * @param {(Object|function(Object))=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#whenJSONP\n   * @description\n   * Creates a new backend definition for JSONP requests. For more info see `when()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled.\n   */\n  createShortMethods('when');\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expect\n   * @description\n   * Creates a new request expectation.\n   *\n   * @param {string} method HTTP method.\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header\n   *   object and returns true if the headers match the current expectation.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *  request is handled. You can save this object for later use and invoke `respond` again in\n   *  order to change how a matched request is handled.\n   *\n   *  - respond –\n   *    `{function([status,] data[, headers, statusText])\n   *    | function(function(method, url, data, headers)}`\n   *    – The respond method takes a set of static data to be returned or a function that can\n   *    return an array containing response status (number), response data (string), response\n   *    headers (Object), and the text for the status (string). The respond method returns the\n   *    `requestHandler` object for possible overrides.\n   */\n  $httpBackend.expect = function(method, url, data, headers) {\n    var expectation = new MockHttpExpectation(method, url, data, headers),\n        chain = {\n          respond: function(status, data, headers, statusText) {\n            expectation.response = createResponse(status, data, headers, statusText);\n            return chain;\n          }\n        };\n\n    expectations.push(expectation);\n    return chain;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectGET\n   * @description\n   * Creates a new request expectation for GET requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   * request is handled. You can save this object for later use and invoke `respond` again in\n   * order to change how a matched request is handled. See #expect for more info.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectHEAD\n   * @description\n   * Creates a new request expectation for HEAD requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectDELETE\n   * @description\n   * Creates a new request expectation for DELETE requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectPOST\n   * @description\n   * Creates a new request expectation for POST requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectPUT\n   * @description\n   * Creates a new request expectation for PUT requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectPATCH\n   * @description\n   * Creates a new request expectation for PATCH requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n   *   and returns true if the url matches the current definition.\n   * @param {(string|RegExp|function(string)|Object)=} data HTTP request body or function that\n   *  receives data string and returns true if the data is as expected, or Object if request body\n   *  is in JSON format.\n   * @param {Object=} headers HTTP headers.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#expectJSONP\n   * @description\n   * Creates a new request expectation for JSONP requests. For more info see `expect()`.\n   *\n   * @param {string|RegExp|function(string)} url HTTP url or function that receives an url\n   *   and returns true if the url matches the current definition.\n   * @returns {requestHandler} Returns an object with `respond` method that controls how a matched\n   *   request is handled. You can save this object for later use and invoke `respond` again in\n   *   order to change how a matched request is handled.\n   */\n  createShortMethods('expect');\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#flush\n   * @description\n   * Flushes all pending requests using the trained responses.\n   *\n   * @param {number=} count Number of responses to flush (in the order they arrived). If undefined,\n   *   all pending requests will be flushed. If there are no pending requests when the flush method\n   *   is called an exception is thrown (as this typically a sign of programming error).\n   */\n  $httpBackend.flush = function(count, digest) {\n    if (digest !== false) $rootScope.$digest();\n    if (!responses.length) throw new Error('No pending request to flush !');\n\n    if (angular.isDefined(count) && count !== null) {\n      while (count--) {\n        if (!responses.length) throw new Error('No more pending request to flush !');\n        responses.shift()();\n      }\n    } else {\n      while (responses.length) {\n        responses.shift()();\n      }\n    }\n    $httpBackend.verifyNoOutstandingExpectation(digest);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#verifyNoOutstandingExpectation\n   * @description\n   * Verifies that all of the requests defined via the `expect` api were made. If any of the\n   * requests were not made, verifyNoOutstandingExpectation throws an exception.\n   *\n   * Typically, you would call this method following each test case that asserts requests using an\n   * \"afterEach\" clause.\n   *\n   * ```js\n   *   afterEach($httpBackend.verifyNoOutstandingExpectation);\n   * ```\n   */\n  $httpBackend.verifyNoOutstandingExpectation = function(digest) {\n    if (digest !== false) $rootScope.$digest();\n    if (expectations.length) {\n      throw new Error('Unsatisfied requests: ' + expectations.join(', '));\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#verifyNoOutstandingRequest\n   * @description\n   * Verifies that there are no outstanding requests that need to be flushed.\n   *\n   * Typically, you would call this method following each test case that asserts requests using an\n   * \"afterEach\" clause.\n   *\n   * ```js\n   *   afterEach($httpBackend.verifyNoOutstandingRequest);\n   * ```\n   */\n  $httpBackend.verifyNoOutstandingRequest = function() {\n    if (responses.length) {\n      throw new Error('Unflushed requests: ' + responses.length);\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $httpBackend#resetExpectations\n   * @description\n   * Resets all request expectations, but preserves all backend definitions. Typically, you would\n   * call resetExpectations during a multiple-phase test when you want to reuse the same instance of\n   * $httpBackend mock.\n   */\n  $httpBackend.resetExpectations = function() {\n    expectations.length = 0;\n    responses.length = 0;\n  };\n\n  return $httpBackend;\n\n\n  function createShortMethods(prefix) {\n    angular.forEach(['GET', 'DELETE', 'JSONP', 'HEAD'], function(method) {\n     $httpBackend[prefix + method] = function(url, headers) {\n       return $httpBackend[prefix](method, url, undefined, headers);\n     };\n    });\n\n    angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {\n      $httpBackend[prefix + method] = function(url, data, headers) {\n        return $httpBackend[prefix](method, url, data, headers);\n      };\n    });\n  }\n}\n\nfunction MockHttpExpectation(method, url, data, headers) {\n\n  this.data = data;\n  this.headers = headers;\n\n  this.match = function(m, u, d, h) {\n    if (method != m) return false;\n    if (!this.matchUrl(u)) return false;\n    if (angular.isDefined(d) && !this.matchData(d)) return false;\n    if (angular.isDefined(h) && !this.matchHeaders(h)) return false;\n    return true;\n  };\n\n  this.matchUrl = function(u) {\n    if (!url) return true;\n    if (angular.isFunction(url.test)) return url.test(u);\n    if (angular.isFunction(url)) return url(u);\n    return url == u;\n  };\n\n  this.matchHeaders = function(h) {\n    if (angular.isUndefined(headers)) return true;\n    if (angular.isFunction(headers)) return headers(h);\n    return angular.equals(headers, h);\n  };\n\n  this.matchData = function(d) {\n    if (angular.isUndefined(data)) return true;\n    if (data && angular.isFunction(data.test)) return data.test(d);\n    if (data && angular.isFunction(data)) return data(d);\n    if (data && !angular.isString(data)) {\n      return angular.equals(angular.fromJson(angular.toJson(data)), angular.fromJson(d));\n    }\n    return data == d;\n  };\n\n  this.toString = function() {\n    return method + ' ' + url;\n  };\n}\n\nfunction createMockXhr() {\n  return new MockXhr();\n}\n\nfunction MockXhr() {\n\n  // hack for testing $http, $httpBackend\n  MockXhr.$$lastInstance = this;\n\n  this.open = function(method, url, async) {\n    this.$$method = method;\n    this.$$url = url;\n    this.$$async = async;\n    this.$$reqHeaders = {};\n    this.$$respHeaders = {};\n  };\n\n  this.send = function(data) {\n    this.$$data = data;\n  };\n\n  this.setRequestHeader = function(key, value) {\n    this.$$reqHeaders[key] = value;\n  };\n\n  this.getResponseHeader = function(name) {\n    // the lookup must be case insensitive,\n    // that's why we try two quick lookups first and full scan last\n    var header = this.$$respHeaders[name];\n    if (header) return header;\n\n    name = angular.lowercase(name);\n    header = this.$$respHeaders[name];\n    if (header) return header;\n\n    header = undefined;\n    angular.forEach(this.$$respHeaders, function(headerVal, headerName) {\n      if (!header && angular.lowercase(headerName) == name) header = headerVal;\n    });\n    return header;\n  };\n\n  this.getAllResponseHeaders = function() {\n    var lines = [];\n\n    angular.forEach(this.$$respHeaders, function(value, key) {\n      lines.push(key + ': ' + value);\n    });\n    return lines.join('\\n');\n  };\n\n  this.abort = angular.noop;\n}\n\n\n/**\n * @ngdoc service\n * @name $timeout\n * @description\n *\n * This service is just a simple decorator for {@link ng.$timeout $timeout} service\n * that adds a \"flush\" and \"verifyNoPendingTasks\" methods.\n */\n\nangular.mock.$TimeoutDecorator = ['$delegate', '$browser', function($delegate, $browser) {\n\n  /**\n   * @ngdoc method\n   * @name $timeout#flush\n   * @description\n   *\n   * Flushes the queue of pending tasks.\n   *\n   * @param {number=} delay maximum timeout amount to flush up until\n   */\n  $delegate.flush = function(delay) {\n    $browser.defer.flush(delay);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $timeout#verifyNoPendingTasks\n   * @description\n   *\n   * Verifies that there are no pending tasks that need to be flushed.\n   */\n  $delegate.verifyNoPendingTasks = function() {\n    if ($browser.deferredFns.length) {\n      throw new Error('Deferred tasks to flush (' + $browser.deferredFns.length + '): ' +\n          formatPendingTasksAsString($browser.deferredFns));\n    }\n  };\n\n  function formatPendingTasksAsString(tasks) {\n    var result = [];\n    angular.forEach(tasks, function(task) {\n      result.push('{id: ' + task.id + ', ' + 'time: ' + task.time + '}');\n    });\n\n    return result.join(', ');\n  }\n\n  return $delegate;\n}];\n\nangular.mock.$RAFDecorator = ['$delegate', function($delegate) {\n  var rafFn = function(fn) {\n    var index = rafFn.queue.length;\n    rafFn.queue.push(fn);\n    return function() {\n      rafFn.queue.splice(index, 1);\n    };\n  };\n\n  rafFn.queue = [];\n  rafFn.supported = $delegate.supported;\n\n  rafFn.flush = function() {\n    if (rafFn.queue.length === 0) {\n      throw new Error('No rAF callbacks present');\n    }\n\n    var length = rafFn.queue.length;\n    for (var i = 0; i < length; i++) {\n      rafFn.queue[i]();\n    }\n\n    rafFn.queue = rafFn.queue.slice(i);\n  };\n\n  return rafFn;\n}];\n\n/**\n *\n */\nangular.mock.$RootElementProvider = function() {\n  this.$get = function() {\n    return angular.element('<div ng-app></div>');\n  };\n};\n\n/**\n * @ngdoc service\n * @name $controller\n * @description\n * A decorator for {@link ng.$controller} with additional `bindings` parameter, useful when testing\n * controllers of directives that use {@link $compile#-bindtocontroller- `bindToController`}.\n *\n *\n * ## Example\n *\n * ```js\n *\n * // Directive definition ...\n *\n * myMod.directive('myDirective', {\n *   controller: 'MyDirectiveController',\n *   bindToController: {\n *     name: '@'\n *   }\n * });\n *\n *\n * // Controller definition ...\n *\n * myMod.controller('MyDirectiveController', ['log', function($log) {\n *   $log.info(this.name);\n * })];\n *\n *\n * // In a test ...\n *\n * describe('myDirectiveController', function() {\n *   it('should write the bound name to the log', inject(function($controller, $log) {\n *     var ctrl = $controller('MyDirectiveController', { /* no locals &#42;/ }, { name: 'Clark Kent' });\n *     expect(ctrl.name).toEqual('Clark Kent');\n *     expect($log.info.logs).toEqual(['Clark Kent']);\n *   });\n * });\n *\n * ```\n *\n * @param {Function|string} constructor If called with a function then it's considered to be the\n *    controller constructor function. Otherwise it's considered to be a string which is used\n *    to retrieve the controller constructor using the following steps:\n *\n *    * check if a controller with given name is registered via `$controllerProvider`\n *    * check if evaluating the string on the current scope returns a constructor\n *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\n *      `window` object (not recommended)\n *\n *    The string can use the `controller as property` syntax, where the controller instance is published\n *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n *    to work correctly.\n *\n * @param {Object} locals Injection locals for Controller.\n * @param {Object=} bindings Properties to add to the controller before invoking the constructor. This is used\n *                           to simulate the `bindToController` feature and simplify certain kinds of tests.\n * @return {Object} Instance of given controller.\n */\nangular.mock.$ControllerDecorator = ['$delegate', function($delegate) {\n  return function(expression, locals, later, ident) {\n    if (later && typeof later === 'object') {\n      var create = $delegate(expression, locals, true, ident);\n      angular.extend(create.instance, later);\n      return create();\n    }\n    return $delegate(expression, locals, later, ident);\n  };\n}];\n\n\n/**\n * @ngdoc module\n * @name ngMock\n * @packageName angular-mocks\n * @description\n *\n * # ngMock\n *\n * The `ngMock` module provides support to inject and mock Angular services into unit tests.\n * In addition, ngMock also extends various core ng services such that they can be\n * inspected and controlled in a synchronous manner within test code.\n *\n *\n * <div doc-module-components=\"ngMock\"></div>\n *\n */\nangular.module('ngMock', ['ng']).provider({\n  $browser: angular.mock.$BrowserProvider,\n  $exceptionHandler: angular.mock.$ExceptionHandlerProvider,\n  $log: angular.mock.$LogProvider,\n  $interval: angular.mock.$IntervalProvider,\n  $httpBackend: angular.mock.$HttpBackendProvider,\n  $rootElement: angular.mock.$RootElementProvider\n}).config(['$provide', function($provide) {\n  $provide.decorator('$timeout', angular.mock.$TimeoutDecorator);\n  $provide.decorator('$$rAF', angular.mock.$RAFDecorator);\n  $provide.decorator('$rootScope', angular.mock.$RootScopeDecorator);\n  $provide.decorator('$controller', angular.mock.$ControllerDecorator);\n}]);\n\n/**\n * @ngdoc module\n * @name ngMockE2E\n * @module ngMockE2E\n * @packageName angular-mocks\n * @description\n *\n * The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.\n * Currently there is only one mock present in this module -\n * the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.\n */\nangular.module('ngMockE2E', ['ng']).config(['$provide', function($provide) {\n  $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);\n}]);\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @module ngMockE2E\n * @description\n * Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of\n * applications that use the {@link ng.$http $http service}.\n *\n * *Note*: For fake http backend implementation suitable for unit testing please see\n * {@link ngMock.$httpBackend unit-testing $httpBackend mock}.\n *\n * This implementation can be used to respond with static or dynamic responses via the `when` api\n * and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the\n * real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch\n * templates from a webserver).\n *\n * As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application\n * is being developed with the real backend api replaced with a mock, it is often desirable for\n * certain category of requests to bypass the mock and issue a real http request (e.g. to fetch\n * templates or static files from the webserver). To configure the backend with this behavior\n * use the `passThrough` request handler of `when` instead of `respond`.\n *\n * Additionally, we don't want to manually have to flush mocked out requests like we do during unit\n * testing. For this reason the e2e $httpBackend flushes mocked out requests\n * automatically, closely simulating the behavior of the XMLHttpRequest object.\n *\n * To setup the application to run with this http backend, you have to create a module that depends\n * on the `ngMockE2E` and your application modules and defines the fake backend:\n *\n * ```js\n *   myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);\n *   myAppDev.run(function($httpBackend) {\n *     phones = [{name: 'phone1'}, {name: 'phone2'}];\n *\n *     // returns the current list of phones\n *     $httpBackend.whenGET('/phones').respond(phones);\n *\n *     // adds a new phone to the phones array\n *     $httpBackend.whenPOST('/phones').respond(function(method, url, data) {\n *       var phone = angular.fromJson(data);\n *       phones.push(phone);\n *       return [200, phone, {}];\n *     });\n *     $httpBackend.whenGET(/^\\/templates\\//).passThrough();\n *     //...\n *   });\n * ```\n *\n * Afterwards, bootstrap your app with this new module.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#when\n * @module ngMockE2E\n * @description\n * Creates a new backend definition.\n *\n * @param {string} method HTTP method.\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers or function that receives http header\n *   object and returns true if the headers match the current definition.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n *\n *  - respond –\n *    `{function([status,] data[, headers, statusText])\n *    | function(function(method, url, data, headers)}`\n *    – The respond method takes a set of static data to be returned or a function that can return\n *    an array containing response status (number), response data (string), response headers\n *    (Object), and the text for the status (string).\n *  - passThrough – `{function()}` – Any request matching a backend definition with\n *    `passThrough` handler will be passed through to the real backend (an XHR request will be made\n *    to the server.)\n *  - Both methods return the `requestHandler` object for possible overrides.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenGET\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for GET requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenHEAD\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for HEAD requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenDELETE\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for DELETE requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenPOST\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for POST requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenPUT\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for PUT requests.  For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenPATCH\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for PATCH requests.  For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @param {(string|RegExp)=} data HTTP request body.\n * @param {(Object|function(Object))=} headers HTTP headers.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\n\n/**\n * @ngdoc method\n * @name $httpBackend#whenJSONP\n * @module ngMockE2E\n * @description\n * Creates a new backend definition for JSONP requests. For more info see `when()`.\n *\n * @param {string|RegExp|function(string)} url HTTP url or function that receives a url\n *   and returns true if the url matches the current definition.\n * @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that\n *   control how a matched request is handled. You can save this object for later use and invoke\n *   `respond` or `passThrough` again in order to change how a matched request is handled.\n */\nangular.mock.e2e = {};\nangular.mock.e2e.$httpBackendDecorator =\n  ['$rootScope', '$timeout', '$delegate', '$browser', createHttpBackendMock];\n\n\n/**\n * @ngdoc type\n * @name $rootScope.Scope\n * @module ngMock\n * @description\n * {@link ng.$rootScope.Scope Scope} type decorated with helper methods useful for testing. These\n * methods are automatically available on any {@link ng.$rootScope.Scope Scope} instance when\n * `ngMock` module is loaded.\n *\n * In addition to all the regular `Scope` methods, the following helper methods are available:\n */\nangular.mock.$RootScopeDecorator = ['$delegate', function($delegate) {\n\n  var $rootScopePrototype = Object.getPrototypeOf($delegate);\n\n  $rootScopePrototype.$countChildScopes = countChildScopes;\n  $rootScopePrototype.$countWatchers = countWatchers;\n\n  return $delegate;\n\n  // ------------------------------------------------------------------------------------------ //\n\n  /**\n   * @ngdoc method\n   * @name $rootScope.Scope#$countChildScopes\n   * @module ngMock\n   * @description\n   * Counts all the direct and indirect child scopes of the current scope.\n   *\n   * The current scope is excluded from the count. The count includes all isolate child scopes.\n   *\n   * @returns {number} Total number of child scopes.\n   */\n  function countChildScopes() {\n    // jshint validthis: true\n    var count = 0; // exclude the current scope\n    var pendingChildHeads = [this.$$childHead];\n    var currentScope;\n\n    while (pendingChildHeads.length) {\n      currentScope = pendingChildHeads.shift();\n\n      while (currentScope) {\n        count += 1;\n        pendingChildHeads.push(currentScope.$$childHead);\n        currentScope = currentScope.$$nextSibling;\n      }\n    }\n\n    return count;\n  }\n\n\n  /**\n   * @ngdoc method\n   * @name $rootScope.Scope#$countWatchers\n   * @module ngMock\n   * @description\n   * Counts all the watchers of direct and indirect child scopes of the current scope.\n   *\n   * The watchers of the current scope are included in the count and so are all the watchers of\n   * isolate child scopes.\n   *\n   * @returns {number} Total number of watchers.\n   */\n  function countWatchers() {\n    // jshint validthis: true\n    var count = this.$$watchers ? this.$$watchers.length : 0; // include the current scope\n    var pendingChildHeads = [this.$$childHead];\n    var currentScope;\n\n    while (pendingChildHeads.length) {\n      currentScope = pendingChildHeads.shift();\n\n      while (currentScope) {\n        count += currentScope.$$watchers ? currentScope.$$watchers.length : 0;\n        pendingChildHeads.push(currentScope.$$childHead);\n        currentScope = currentScope.$$nextSibling;\n      }\n    }\n\n    return count;\n  }\n}];\n\n\nif (window.jasmine || window.mocha) {\n\n  var currentSpec = null,\n      annotatedFunctions = [],\n      isSpecRunning = function() {\n        return !!currentSpec;\n      };\n\n  angular.mock.$$annotate = angular.injector.$$annotate;\n  angular.injector.$$annotate = function(fn) {\n    if (typeof fn === 'function' && !fn.$inject) {\n      annotatedFunctions.push(fn);\n    }\n    return angular.mock.$$annotate.apply(this, arguments);\n  };\n\n\n  (window.beforeEach || window.setup)(function() {\n    annotatedFunctions = [];\n    currentSpec = this;\n  });\n\n  (window.afterEach || window.teardown)(function() {\n    var injector = currentSpec.$injector;\n\n    annotatedFunctions.forEach(function(fn) {\n      delete fn.$inject;\n    });\n\n    angular.forEach(currentSpec.$modules, function(module) {\n      if (module && module.$$hashKey) {\n        module.$$hashKey = undefined;\n      }\n    });\n\n    currentSpec.$injector = null;\n    currentSpec.$modules = null;\n    currentSpec = null;\n\n    if (injector) {\n      injector.get('$rootElement').off();\n    }\n\n    // clean up jquery's fragment cache\n    angular.forEach(angular.element.fragments, function(val, key) {\n      delete angular.element.fragments[key];\n    });\n\n    MockXhr.$$lastInstance = null;\n\n    angular.forEach(angular.callbacks, function(val, key) {\n      delete angular.callbacks[key];\n    });\n    angular.callbacks.counter = 0;\n  });\n\n  /**\n   * @ngdoc function\n   * @name angular.mock.module\n   * @description\n   *\n   * *NOTE*: This function is also published on window for easy access.<br>\n   * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha\n   *\n   * This function registers a module configuration code. It collects the configuration information\n   * which will be used when the injector is created by {@link angular.mock.inject inject}.\n   *\n   * See {@link angular.mock.inject inject} for usage example\n   *\n   * @param {...(string|Function|Object)} fns any number of modules which are represented as string\n   *        aliases or as anonymous module initialization functions. The modules are used to\n   *        configure the injector. The 'ng' and 'ngMock' modules are automatically loaded. If an\n   *        object literal is passed they will be registered as values in the module, the key being\n   *        the module name and the value being what is returned.\n   */\n  window.module = angular.mock.module = function() {\n    var moduleFns = Array.prototype.slice.call(arguments, 0);\n    return isSpecRunning() ? workFn() : workFn;\n    /////////////////////\n    function workFn() {\n      if (currentSpec.$injector) {\n        throw new Error('Injector already created, can not register a module!');\n      } else {\n        var modules = currentSpec.$modules || (currentSpec.$modules = []);\n        angular.forEach(moduleFns, function(module) {\n          if (angular.isObject(module) && !angular.isArray(module)) {\n            modules.push(function($provide) {\n              angular.forEach(module, function(value, key) {\n                $provide.value(key, value);\n              });\n            });\n          } else {\n            modules.push(module);\n          }\n        });\n      }\n    }\n  };\n\n  /**\n   * @ngdoc function\n   * @name angular.mock.inject\n   * @description\n   *\n   * *NOTE*: This function is also published on window for easy access.<br>\n   * *NOTE*: This function is declared ONLY WHEN running tests with jasmine or mocha\n   *\n   * The inject function wraps a function into an injectable function. The inject() creates new\n   * instance of {@link auto.$injector $injector} per test, which is then used for\n   * resolving references.\n   *\n   *\n   * ## Resolving References (Underscore Wrapping)\n   * Often, we would like to inject a reference once, in a `beforeEach()` block and reuse this\n   * in multiple `it()` clauses. To be able to do this we must assign the reference to a variable\n   * that is declared in the scope of the `describe()` block. Since we would, most likely, want\n   * the variable to have the same name of the reference we have a problem, since the parameter\n   * to the `inject()` function would hide the outer variable.\n   *\n   * To help with this, the injected parameters can, optionally, be enclosed with underscores.\n   * These are ignored by the injector when the reference name is resolved.\n   *\n   * For example, the parameter `_myService_` would be resolved as the reference `myService`.\n   * Since it is available in the function body as _myService_, we can then assign it to a variable\n   * defined in an outer scope.\n   *\n   * ```\n   * // Defined out reference variable outside\n   * var myService;\n   *\n   * // Wrap the parameter in underscores\n   * beforeEach( inject( function(_myService_){\n   *   myService = _myService_;\n   * }));\n   *\n   * // Use myService in a series of tests.\n   * it('makes use of myService', function() {\n   *   myService.doStuff();\n   * });\n   *\n   * ```\n   *\n   * See also {@link angular.mock.module angular.mock.module}\n   *\n   * ## Example\n   * Example of what a typical jasmine tests looks like with the inject method.\n   * ```js\n   *\n   *   angular.module('myApplicationModule', [])\n   *       .value('mode', 'app')\n   *       .value('version', 'v1.0.1');\n   *\n   *\n   *   describe('MyApp', function() {\n   *\n   *     // You need to load modules that you want to test,\n   *     // it loads only the \"ng\" module by default.\n   *     beforeEach(module('myApplicationModule'));\n   *\n   *\n   *     // inject() is used to inject arguments of all given functions\n   *     it('should provide a version', inject(function(mode, version) {\n   *       expect(version).toEqual('v1.0.1');\n   *       expect(mode).toEqual('app');\n   *     }));\n   *\n   *\n   *     // The inject and module method can also be used inside of the it or beforeEach\n   *     it('should override a version and test the new version is injected', function() {\n   *       // module() takes functions or strings (module aliases)\n   *       module(function($provide) {\n   *         $provide.value('version', 'overridden'); // override version here\n   *       });\n   *\n   *       inject(function(version) {\n   *         expect(version).toEqual('overridden');\n   *       });\n   *     });\n   *   });\n   *\n   * ```\n   *\n   * @param {...Function} fns any number of functions which will be injected using the injector.\n   */\n\n\n\n  var ErrorAddingDeclarationLocationStack = function(e, errorForStack) {\n    this.message = e.message;\n    this.name = e.name;\n    if (e.line) this.line = e.line;\n    if (e.sourceId) this.sourceId = e.sourceId;\n    if (e.stack && errorForStack)\n      this.stack = e.stack + '\\n' + errorForStack.stack;\n    if (e.stackArray) this.stackArray = e.stackArray;\n  };\n  ErrorAddingDeclarationLocationStack.prototype.toString = Error.prototype.toString;\n\n  window.inject = angular.mock.inject = function() {\n    var blockFns = Array.prototype.slice.call(arguments, 0);\n    var errorForStack = new Error('Declaration Location');\n    return isSpecRunning() ? workFn.call(currentSpec) : workFn;\n    /////////////////////\n    function workFn() {\n      var modules = currentSpec.$modules || [];\n      var strictDi = !!currentSpec.$injectorStrict;\n      modules.unshift('ngMock');\n      modules.unshift('ng');\n      var injector = currentSpec.$injector;\n      if (!injector) {\n        if (strictDi) {\n          // If strictDi is enabled, annotate the providerInjector blocks\n          angular.forEach(modules, function(moduleFn) {\n            if (typeof moduleFn === \"function\") {\n              angular.injector.$$annotate(moduleFn);\n            }\n          });\n        }\n        injector = currentSpec.$injector = angular.injector(modules, strictDi);\n        currentSpec.$injectorStrict = strictDi;\n      }\n      for (var i = 0, ii = blockFns.length; i < ii; i++) {\n        if (currentSpec.$injectorStrict) {\n          // If the injector is strict / strictDi, and the spec wants to inject using automatic\n          // annotation, then annotate the function here.\n          injector.annotate(blockFns[i]);\n        }\n        try {\n          /* jshint -W040 *//* Jasmine explicitly provides a `this` object when calling functions */\n          injector.invoke(blockFns[i] || angular.noop, this);\n          /* jshint +W040 */\n        } catch (e) {\n          if (e.stack && errorForStack) {\n            throw new ErrorAddingDeclarationLocationStack(e, errorForStack);\n          }\n          throw e;\n        } finally {\n          errorForStack = null;\n        }\n      }\n    }\n  };\n\n\n  angular.mock.inject.strictDi = function(value) {\n    value = arguments.length ? !!value : true;\n    return isSpecRunning() ? workFn() : workFn;\n\n    function workFn() {\n      if (value !== currentSpec.$injectorStrict) {\n        if (currentSpec.$injector) {\n          throw new Error('Injector already created, can not modify strict annotations');\n        } else {\n          currentSpec.$injectorStrict = value;\n        }\n      }\n    }\n  };\n}\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/server/php/public/vendor/angular-resource.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\nvar $resourceMinErr = angular.$$minErr('$resource');\n\n// Helper functions and regex to lookup a dotted path on an object\n// stopping at undefined/null.  The path must be composed of ASCII\n// identifiers (just like $parse)\nvar MEMBER_NAME_REGEX = /^(\\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;\n\nfunction isValidDottedPath(path) {\n  return (path != null && path !== '' && path !== 'hasOwnProperty' &&\n      MEMBER_NAME_REGEX.test('.' + path));\n}\n\nfunction lookupDottedPath(obj, path) {\n  if (!isValidDottedPath(path)) {\n    throw $resourceMinErr('badmember', 'Dotted member path \"@{0}\" is invalid.', path);\n  }\n  var keys = path.split('.');\n  for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {\n    var key = keys[i];\n    obj = (obj !== null) ? obj[key] : undefined;\n  }\n  return obj;\n}\n\n/**\n * Create a shallow copy of an object and clear other fields from the destination\n */\nfunction shallowClearAndCopy(src, dst) {\n  dst = dst || {};\n\n  angular.forEach(dst, function(value, key) {\n    delete dst[key];\n  });\n\n  for (var key in src) {\n    if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n      dst[key] = src[key];\n    }\n  }\n\n  return dst;\n}\n\n/**\n * @ngdoc module\n * @name ngResource\n * @description\n *\n * # ngResource\n *\n * The `ngResource` module provides interaction support with RESTful services\n * via the $resource service.\n *\n *\n * <div doc-module-components=\"ngResource\"></div>\n *\n * See {@link ngResource.$resource `$resource`} for usage.\n */\n\n/**\n * @ngdoc service\n * @name $resource\n * @requires $http\n *\n * @description\n * A factory which creates a resource object that lets you interact with\n * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.\n *\n * The returned resource object has action methods which provide high-level behaviors without\n * the need to interact with the low level {@link ng.$http $http} service.\n *\n * Requires the {@link ngResource `ngResource`} module to be installed.\n *\n * By default, trailing slashes will be stripped from the calculated URLs,\n * which can pose problems with server backends that do not expect that\n * behavior.  This can be disabled by configuring the `$resourceProvider` like\n * this:\n *\n * ```js\n     app.config(['$resourceProvider', function($resourceProvider) {\n       // Don't strip trailing slashes from calculated URLs\n       $resourceProvider.defaults.stripTrailingSlashes = false;\n     }]);\n * ```\n *\n * @param {string} url A parameterized URL template with parameters prefixed by `:` as in\n *   `/user/:username`. If you are using a URL with a port number (e.g.\n *   `http://example.com:8080/api`), it will be respected.\n *\n *   If you are using a url with a suffix, just add the suffix, like this:\n *   `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`\n *   or even `$resource('http://example.com/resource/:resource_id.:format')`\n *   If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be\n *   collapsed down to a single `.`.  If you need this sequence to appear and not collapse then you\n *   can escape it with `/\\.`.\n *\n * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in\n *   `actions` methods. If any of the parameter value is a function, it will be executed every time\n *   when a param value needs to be obtained for a request (unless the param was overridden).\n *\n *   Each key value in the parameter object is first bound to url template if present and then any\n *   excess keys are appended to the url search query after the `?`.\n *\n *   Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in\n *   URL `/path/greet?salutation=Hello`.\n *\n *   If the parameter value is prefixed with `@` then the value for that parameter will be extracted\n *   from the corresponding property on the `data` object (provided when calling an action method).  For\n *   example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam`\n *   will be `data.someProp`.\n *\n * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend\n *   the default set of resource actions. The declaration should be created in the format of {@link\n *   ng.$http#usage $http.config}:\n *\n *       {action1: {method:?, params:?, isArray:?, headers:?, ...},\n *        action2: {method:?, params:?, isArray:?, headers:?, ...},\n *        ...}\n *\n *   Where:\n *\n *   - **`action`** – {string} – The name of action. This name becomes the name of the method on\n *     your resource object.\n *   - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,\n *     `DELETE`, `JSONP`, etc).\n *   - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of\n *     the parameter value is a function, it will be executed every time when a param value needs to\n *     be obtained for a request (unless the param was overridden).\n *   - **`url`** – {string} – action specific `url` override. The url templating is supported just\n *     like for the resource-level urls.\n *   - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,\n *     see `returns` section.\n *   - **`transformRequest`** –\n *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n *     transform function or an array of such functions. The transform function takes the http\n *     request body and headers and returns its transformed (typically serialized) version.\n *     By default, transformRequest will contain one function that checks if the request data is\n *     an object and serializes to using `angular.toJson`. To prevent this behavior, set\n *     `transformRequest` to an empty array: `transformRequest: []`\n *   - **`transformResponse`** –\n *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n *     transform function or an array of such functions. The transform function takes the http\n *     response body and headers and returns its transformed (typically deserialized) version.\n *     By default, transformResponse will contain one function that checks if the response looks like\n *     a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, set\n *     `transformResponse` to an empty array: `transformResponse: []`\n *   - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\n *     GET request, otherwise if a cache instance built with\n *     {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\n *     caching.\n *   - **`timeout`** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise} that\n *     should abort the request when resolved.\n *   - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the\n *     XHR object. See\n *     [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)\n *     for more information.\n *   - **`responseType`** - `{string}` - see\n *     [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).\n *   - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -\n *     `response` and `responseError`. Both `response` and `responseError` interceptors get called\n *     with `http response` object. See {@link ng.$http $http interceptors}.\n *\n * @param {Object} options Hash with custom settings that should extend the\n *   default `$resourceProvider` behavior.  The only supported option is\n *\n *   Where:\n *\n *   - **`stripTrailingSlashes`** – {boolean} – If true then the trailing\n *   slashes from any calculated URL will be stripped. (Defaults to true.)\n *\n * @returns {Object} A resource \"class\" object with methods for the default set of resource actions\n *   optionally extended with custom `actions`. The default set contains these actions:\n *   ```js\n *   { 'get':    {method:'GET'},\n *     'save':   {method:'POST'},\n *     'query':  {method:'GET', isArray:true},\n *     'remove': {method:'DELETE'},\n *     'delete': {method:'DELETE'} };\n *   ```\n *\n *   Calling these methods invoke an {@link ng.$http} with the specified http method,\n *   destination and parameters. When the data is returned from the server then the object is an\n *   instance of the resource class. The actions `save`, `remove` and `delete` are available on it\n *   as  methods with the `$` prefix. This allows you to easily perform CRUD operations (create,\n *   read, update, delete) on server-side data like this:\n *   ```js\n *   var User = $resource('/user/:userId', {userId:'@id'});\n *   var user = User.get({userId:123}, function() {\n *     user.abc = true;\n *     user.$save();\n *   });\n *   ```\n *\n *   It is important to realize that invoking a $resource object method immediately returns an\n *   empty reference (object or array depending on `isArray`). Once the data is returned from the\n *   server the existing reference is populated with the actual data. This is a useful trick since\n *   usually the resource is assigned to a model which is then rendered by the view. Having an empty\n *   object results in no rendering, once the data arrives from the server then the object is\n *   populated with the data and the view automatically re-renders itself showing the new data. This\n *   means that in most cases one never has to write a callback function for the action methods.\n *\n *   The action methods on the class object or instance object can be invoked with the following\n *   parameters:\n *\n *   - HTTP GET \"class\" actions: `Resource.action([parameters], [success], [error])`\n *   - non-GET \"class\" actions: `Resource.action([parameters], postData, [success], [error])`\n *   - non-GET instance actions:  `instance.$action([parameters], [success], [error])`\n *\n *\n *   Success callback is called with (value, responseHeaders) arguments, where the value is\n *   the populated resource instance or collection object. The error callback is called\n *   with (httpResponse) argument.\n *\n *   Class actions return empty instance (with additional properties below).\n *   Instance actions return promise of the action.\n *\n *   The Resource instances and collection have these additional properties:\n *\n *   - `$promise`: the {@link ng.$q promise} of the original server interaction that created this\n *     instance or collection.\n *\n *     On success, the promise is resolved with the same resource instance or collection object,\n *     updated with data from server. This makes it easy to use in\n *     {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view\n *     rendering until the resource(s) are loaded.\n *\n *     On failure, the promise is resolved with the {@link ng.$http http response} object, without\n *     the `resource` property.\n *\n *     If an interceptor object was provided, the promise will instead be resolved with the value\n *     returned by the interceptor.\n *\n *   - `$resolved`: `true` after first server interaction is completed (either with success or\n *      rejection), `false` before that. Knowing if the Resource has been resolved is useful in\n *      data-binding.\n *\n * @example\n *\n * # Credit card resource\n *\n * ```js\n     // Define CreditCard class\n     var CreditCard = $resource('/user/:userId/card/:cardId',\n      {userId:123, cardId:'@id'}, {\n       charge: {method:'POST', params:{charge:true}}\n      });\n\n     // We can retrieve a collection from the server\n     var cards = CreditCard.query(function() {\n       // GET: /user/123/card\n       // server returns: [ {id:456, number:'1234', name:'Smith'} ];\n\n       var card = cards[0];\n       // each item is an instance of CreditCard\n       expect(card instanceof CreditCard).toEqual(true);\n       card.name = \"J. Smith\";\n       // non GET methods are mapped onto the instances\n       card.$save();\n       // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}\n       // server returns: {id:456, number:'1234', name: 'J. Smith'};\n\n       // our custom method is mapped as well.\n       card.$charge({amount:9.99});\n       // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}\n     });\n\n     // we can create an instance as well\n     var newCard = new CreditCard({number:'0123'});\n     newCard.name = \"Mike Smith\";\n     newCard.$save();\n     // POST: /user/123/card {number:'0123', name:'Mike Smith'}\n     // server returns: {id:789, number:'0123', name: 'Mike Smith'};\n     expect(newCard.id).toEqual(789);\n * ```\n *\n * The object returned from this function execution is a resource \"class\" which has \"static\" method\n * for each action in the definition.\n *\n * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and\n * `headers`.\n * When the data is returned from the server then the object is an instance of the resource type and\n * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD\n * operations (create, read, update, delete) on server-side data.\n\n   ```js\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123}, function(user) {\n       user.abc = true;\n       user.$save();\n     });\n   ```\n *\n * It's worth noting that the success callback for `get`, `query` and other methods gets passed\n * in the response that came from the server as well as $http header getter function, so one\n * could rewrite the above example and get access to http headers as:\n *\n   ```js\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123}, function(u, getResponseHeaders){\n       u.abc = true;\n       u.$save(function(u, putResponseHeaders) {\n         //u => saved user object\n         //putResponseHeaders => $http header getter\n       });\n     });\n   ```\n *\n * You can also access the raw `$http` promise via the `$promise` property on the object returned\n *\n   ```\n     var User = $resource('/user/:userId', {userId:'@id'});\n     User.get({userId:123})\n         .$promise.then(function(user) {\n           $scope.user = user;\n         });\n   ```\n\n * # Creating a custom 'PUT' request\n * In this example we create a custom method on our resource to make a PUT request\n * ```js\n *    var app = angular.module('app', ['ngResource', 'ngRoute']);\n *\n *    // Some APIs expect a PUT request in the format URL/object/ID\n *    // Here we are creating an 'update' method\n *    app.factory('Notes', ['$resource', function($resource) {\n *    return $resource('/notes/:id', null,\n *        {\n *            'update': { method:'PUT' }\n *        });\n *    }]);\n *\n *    // In our controller we get the ID from the URL using ngRoute and $routeParams\n *    // We pass in $routeParams and our Notes factory along with $scope\n *    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',\n                                      function($scope, $routeParams, Notes) {\n *    // First get a note object from the factory\n *    var note = Notes.get({ id:$routeParams.id });\n *    $id = note.id;\n *\n *    // Now call update passing in the ID first then the object you are updating\n *    Notes.update({ id:$id }, note);\n *\n *    // This will PUT /notes/ID with the note object in the request payload\n *    }]);\n * ```\n */\nangular.module('ngResource', ['ng']).\n  provider('$resource', function() {\n    var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\\/\\/[^\\/]*/;\n    var provider = this;\n\n    this.defaults = {\n      // Strip slashes by default\n      stripTrailingSlashes: true,\n\n      // Default actions configuration\n      actions: {\n        'get': {method: 'GET'},\n        'save': {method: 'POST'},\n        'query': {method: 'GET', isArray: true},\n        'remove': {method: 'DELETE'},\n        'delete': {method: 'DELETE'}\n      }\n    };\n\n    this.$get = ['$http', '$q', function($http, $q) {\n\n      var noop = angular.noop,\n        forEach = angular.forEach,\n        extend = angular.extend,\n        copy = angular.copy,\n        isFunction = angular.isFunction;\n\n      /**\n       * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n       * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set\n       * (pchar) allowed in path segments:\n       *    segment       = *pchar\n       *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n       *    pct-encoded   = \"%\" HEXDIG HEXDIG\n       *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n       *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n       *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n       */\n      function encodeUriSegment(val) {\n        return encodeUriQuery(val, true).\n          replace(/%26/gi, '&').\n          replace(/%3D/gi, '=').\n          replace(/%2B/gi, '+');\n      }\n\n\n      /**\n       * This method is intended for encoding *key* or *value* parts of query component. We need a\n       * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't\n       * have to be encoded per http://tools.ietf.org/html/rfc3986:\n       *    query       = *( pchar / \"/\" / \"?\" )\n       *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n       *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n       *    pct-encoded   = \"%\" HEXDIG HEXDIG\n       *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n       *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n       */\n      function encodeUriQuery(val, pctEncodeSpaces) {\n        return encodeURIComponent(val).\n          replace(/%40/gi, '@').\n          replace(/%3A/gi, ':').\n          replace(/%24/g, '$').\n          replace(/%2C/gi, ',').\n          replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n      }\n\n      function Route(template, defaults) {\n        this.template = template;\n        this.defaults = extend({}, provider.defaults, defaults);\n        this.urlParams = {};\n      }\n\n      Route.prototype = {\n        setUrlParams: function(config, params, actionUrl) {\n          var self = this,\n            url = actionUrl || self.template,\n            val,\n            encodedVal,\n            protocolAndDomain = '';\n\n          var urlParams = self.urlParams = {};\n          forEach(url.split(/\\W/), function(param) {\n            if (param === 'hasOwnProperty') {\n              throw $resourceMinErr('badname', \"hasOwnProperty is not a valid parameter name.\");\n            }\n            if (!(new RegExp(\"^\\\\d+$\").test(param)) && param &&\n              (new RegExp(\"(^|[^\\\\\\\\]):\" + param + \"(\\\\W|$)\").test(url))) {\n              urlParams[param] = true;\n            }\n          });\n          url = url.replace(/\\\\:/g, ':');\n          url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {\n            protocolAndDomain = match;\n            return '';\n          });\n\n          params = params || {};\n          forEach(self.urlParams, function(_, urlParam) {\n            val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];\n            if (angular.isDefined(val) && val !== null) {\n              encodedVal = encodeUriSegment(val);\n              url = url.replace(new RegExp(\":\" + urlParam + \"(\\\\W|$)\", \"g\"), function(match, p1) {\n                return encodedVal + p1;\n              });\n            } else {\n              url = url.replace(new RegExp(\"(\\/?):\" + urlParam + \"(\\\\W|$)\", \"g\"), function(match,\n                  leadingSlashes, tail) {\n                if (tail.charAt(0) == '/') {\n                  return tail;\n                } else {\n                  return leadingSlashes + tail;\n                }\n              });\n            }\n          });\n\n          // strip trailing slashes and set the url (unless this behavior is specifically disabled)\n          if (self.defaults.stripTrailingSlashes) {\n            url = url.replace(/\\/+$/, '') || '/';\n          }\n\n          // then replace collapse `/.` if found in the last URL path segment before the query\n          // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`\n          url = url.replace(/\\/\\.(?=\\w+($|\\?))/, '.');\n          // replace escaped `/\\.` with `/.`\n          config.url = protocolAndDomain + url.replace(/\\/\\\\\\./, '/.');\n\n\n          // set params - delegate param encoding to $http\n          forEach(params, function(value, key) {\n            if (!self.urlParams[key]) {\n              config.params = config.params || {};\n              config.params[key] = value;\n            }\n          });\n        }\n      };\n\n\n      function resourceFactory(url, paramDefaults, actions, options) {\n        var route = new Route(url, options);\n\n        actions = extend({}, provider.defaults.actions, actions);\n\n        function extractParams(data, actionParams) {\n          var ids = {};\n          actionParams = extend({}, paramDefaults, actionParams);\n          forEach(actionParams, function(value, key) {\n            if (isFunction(value)) { value = value(); }\n            ids[key] = value && value.charAt && value.charAt(0) == '@' ?\n              lookupDottedPath(data, value.substr(1)) : value;\n          });\n          return ids;\n        }\n\n        function defaultResponseInterceptor(response) {\n          return response.resource;\n        }\n\n        function Resource(value) {\n          shallowClearAndCopy(value || {}, this);\n        }\n\n        Resource.prototype.toJSON = function() {\n          var data = extend({}, this);\n          delete data.$promise;\n          delete data.$resolved;\n          return data;\n        };\n\n        forEach(actions, function(action, name) {\n          var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);\n\n          Resource[name] = function(a1, a2, a3, a4) {\n            var params = {}, data, success, error;\n\n            /* jshint -W086 */ /* (purposefully fall through case statements) */\n            switch (arguments.length) {\n              case 4:\n                error = a4;\n                success = a3;\n              //fallthrough\n              case 3:\n              case 2:\n                if (isFunction(a2)) {\n                  if (isFunction(a1)) {\n                    success = a1;\n                    error = a2;\n                    break;\n                  }\n\n                  success = a2;\n                  error = a3;\n                  //fallthrough\n                } else {\n                  params = a1;\n                  data = a2;\n                  success = a3;\n                  break;\n                }\n              case 1:\n                if (isFunction(a1)) success = a1;\n                else if (hasBody) data = a1;\n                else params = a1;\n                break;\n              case 0: break;\n              default:\n                throw $resourceMinErr('badargs',\n                  \"Expected up to 4 arguments [params, data, success, error], got {0} arguments\",\n                  arguments.length);\n            }\n            /* jshint +W086 */ /* (purposefully fall through case statements) */\n\n            var isInstanceCall = this instanceof Resource;\n            var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));\n            var httpConfig = {};\n            var responseInterceptor = action.interceptor && action.interceptor.response ||\n              defaultResponseInterceptor;\n            var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||\n              undefined;\n\n            forEach(action, function(value, key) {\n              if (key != 'params' && key != 'isArray' && key != 'interceptor') {\n                httpConfig[key] = copy(value);\n              }\n            });\n\n            if (hasBody) httpConfig.data = data;\n            route.setUrlParams(httpConfig,\n              extend({}, extractParams(data, action.params || {}), params),\n              action.url);\n\n            var promise = $http(httpConfig).then(function(response) {\n              var data = response.data,\n                promise = value.$promise;\n\n              if (data) {\n                // Need to convert action.isArray to boolean in case it is undefined\n                // jshint -W018\n                if (angular.isArray(data) !== (!!action.isArray)) {\n                  throw $resourceMinErr('badcfg',\n                      'Error in resource configuration for action `{0}`. Expected response to ' +\n                      'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',\n                    angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);\n                }\n                // jshint +W018\n                if (action.isArray) {\n                  value.length = 0;\n                  forEach(data, function(item) {\n                    if (typeof item === \"object\") {\n                      value.push(new Resource(item));\n                    } else {\n                      // Valid JSON values may be string literals, and these should not be converted\n                      // into objects. These items will not have access to the Resource prototype\n                      // methods, but unfortunately there\n                      value.push(item);\n                    }\n                  });\n                } else {\n                  shallowClearAndCopy(data, value);\n                  value.$promise = promise;\n                }\n              }\n\n              value.$resolved = true;\n\n              response.resource = value;\n\n              return response;\n            }, function(response) {\n              value.$resolved = true;\n\n              (error || noop)(response);\n\n              return $q.reject(response);\n            });\n\n            promise = promise.then(\n              function(response) {\n                var value = responseInterceptor(response);\n                (success || noop)(value, response.headers);\n                return value;\n              },\n              responseErrorInterceptor);\n\n            if (!isInstanceCall) {\n              // we are creating instance / collection\n              // - set the initial promise\n              // - return the instance / collection\n              value.$promise = promise;\n              value.$resolved = false;\n\n              return value;\n            }\n\n            // instance call\n            return promise;\n          };\n\n\n          Resource.prototype['$' + name] = function(params, success, error) {\n            if (isFunction(params)) {\n              error = success; success = params; params = {};\n            }\n            var result = Resource[name].call(this, params, this, success, error);\n            return result.$promise || result;\n          };\n        });\n\n        Resource.bind = function(additionalParamDefaults) {\n          return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);\n        };\n\n        return Resource;\n      }\n\n      return resourceFactory;\n    }];\n  });\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/server/php/public/vendor/angular-sanitize.js",
    "content": "/**\n * @license AngularJS v1.4.7\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, angular, undefined) {'use strict';\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $sanitizeMinErr = angular.$$minErr('$sanitize');\n\n/**\n * @ngdoc module\n * @name ngSanitize\n * @description\n *\n * # ngSanitize\n *\n * The `ngSanitize` module provides functionality to sanitize HTML.\n *\n *\n * <div doc-module-components=\"ngSanitize\"></div>\n *\n * See {@link ngSanitize.$sanitize `$sanitize`} for usage.\n */\n\n/*\n * HTML Parser By Misko Hevery (misko@hevery.com)\n * based on:  HTML Parser By John Resig (ejohn.org)\n * Original code by Erik Arvidsson, Mozilla Public License\n * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js\n *\n * // Use like so:\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n */\n\n\n/**\n * @ngdoc service\n * @name $sanitize\n * @kind function\n *\n * @description\n *   The input is sanitized by parsing the HTML into tokens. All safe tokens (from a whitelist) are\n *   then serialized back to properly escaped html string. This means that no unsafe input can make\n *   it into the returned string, however, since our parser is more strict than a typical browser\n *   parser, it's possible that some obscure input, which would be recognized as valid HTML by a\n *   browser, won't make it through the sanitizer. The input may also contain SVG markup.\n *   The whitelist is configured using the functions `aHrefSanitizationWhitelist` and\n *   `imgSrcSanitizationWhitelist` of {@link ng.$compileProvider `$compileProvider`}.\n *\n * @param {string} html HTML input.\n * @returns {string} Sanitized HTML.\n *\n * @example\n   <example module=\"sanitizeExample\" deps=\"angular-sanitize.js\">\n   <file name=\"index.html\">\n     <script>\n         angular.module('sanitizeExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {\n             $scope.snippet =\n               '<p style=\"color:blue\">an html\\n' +\n               '<em onmouseover=\"this.textContent=\\'PWN3D!\\'\">click here</em>\\n' +\n               'snippet</p>';\n             $scope.deliberatelyTrustDangerousSnippet = function() {\n               return $sce.trustAsHtml($scope.snippet);\n             };\n           }]);\n     </script>\n     <div ng-controller=\"ExampleController\">\n        Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Directive</td>\n           <td>How</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"bind-html-with-sanitize\">\n           <td>ng-bind-html</td>\n           <td>Automatically uses $sanitize</td>\n           <td><pre>&lt;div ng-bind-html=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind-html=\"snippet\"></div></td>\n         </tr>\n         <tr id=\"bind-html-with-trust\">\n           <td>ng-bind-html</td>\n           <td>Bypass $sanitize by explicitly trusting the dangerous value</td>\n           <td>\n           <pre>&lt;div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"&gt;\n&lt;/div&gt;</pre>\n           </td>\n           <td><div ng-bind-html=\"deliberatelyTrustDangerousSnippet()\"></div></td>\n         </tr>\n         <tr id=\"bind-default\">\n           <td>ng-bind</td>\n           <td>Automatically escapes</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br/>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n       </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should sanitize the html snippet by default', function() {\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('<p>an html\\n<em>click here</em>\\nsnippet</p>');\n     });\n\n     it('should inline raw snippet if bound to a trusted value', function() {\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).\n         toBe(\"<p style=\\\"color:blue\\\">an html\\n\" +\n              \"<em onmouseover=\\\"this.textContent='PWN3D!'\\\">click here</em>\\n\" +\n              \"snippet</p>\");\n     });\n\n     it('should escape snippet without any filter', function() {\n       expect(element(by.css('#bind-default div')).getInnerHtml()).\n         toBe(\"&lt;p style=\\\"color:blue\\\"&gt;an html\\n\" +\n              \"&lt;em onmouseover=\\\"this.textContent='PWN3D!'\\\"&gt;click here&lt;/em&gt;\\n\" +\n              \"snippet&lt;/p&gt;\");\n     });\n\n     it('should update', function() {\n       element(by.model('snippet')).clear();\n       element(by.model('snippet')).sendKeys('new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).\n         toBe('new <b>text</b>');\n       expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(\n         'new <b onclick=\"alert(1)\">text</b>');\n       expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(\n         \"new &lt;b onclick=\\\"alert(1)\\\"&gt;text&lt;/b&gt;\");\n     });\n   </file>\n   </example>\n */\nfunction $SanitizeProvider() {\n  this.$get = ['$$sanitizeUri', function($$sanitizeUri) {\n    return function(html) {\n      var buf = [];\n      htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {\n        return !/^unsafe/.test($$sanitizeUri(uri, isImage));\n      }));\n      return buf.join('');\n    };\n  }];\n}\n\nfunction sanitizeText(chars) {\n  var buf = [];\n  var writer = htmlSanitizeWriter(buf, angular.noop);\n  writer.chars(chars);\n  return buf.join('');\n}\n\n\n// Regular Expressions for parsing tags and attributes\nvar START_TAG_REGEXP =\n       /^<((?:[a-zA-Z])[\\w:-]*)((?:\\s+[\\w:-]+(?:\\s*=\\s*(?:(?:\"[^\"]*\")|(?:'[^']*')|[^>\\s]+))?)*)\\s*(\\/?)\\s*(>?)/,\n  END_TAG_REGEXP = /^<\\/\\s*([\\w:-]+)[^>]*>/,\n  ATTR_REGEXP = /([\\w:-]+)(?:\\s*=\\s*(?:(?:\"((?:[^\"])*)\")|(?:'((?:[^'])*)')|([^>\\s]+)))?/g,\n  BEGIN_TAG_REGEXP = /^</,\n  BEGING_END_TAGE_REGEXP = /^<\\//,\n  COMMENT_REGEXP = /<!--(.*?)-->/g,\n  DOCTYPE_REGEXP = /<!DOCTYPE([^>]*?)>/i,\n  CDATA_REGEXP = /<!\\[CDATA\\[(.*?)]]>/g,\n  SURROGATE_PAIR_REGEXP = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g,\n  // Match everything outside of normal chars and \" (quote character)\n  NON_ALPHANUMERIC_REGEXP = /([^\\#-~| |!])/g;\n\n\n// Good source of info about elements and attributes\n// http://dev.w3.org/html5/spec/Overview.html#semantics\n// http://simon.html5.org/html-elements\n\n// Safe Void Elements - HTML5\n// http://dev.w3.org/html5/spec/Overview.html#void-elements\nvar voidElements = makeMap(\"area,br,col,hr,img,wbr\");\n\n// Elements that you can, intentionally, leave open (and which close themselves)\n// http://dev.w3.org/html5/spec/Overview.html#optional-tags\nvar optionalEndTagBlockElements = makeMap(\"colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr\"),\n    optionalEndTagInlineElements = makeMap(\"rp,rt\"),\n    optionalEndTagElements = angular.extend({},\n                                            optionalEndTagInlineElements,\n                                            optionalEndTagBlockElements);\n\n// Safe Block Elements - HTML5\nvar blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap(\"address,article,\" +\n        \"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,\" +\n        \"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul\"));\n\n// Inline Elements - HTML5\nvar inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap(\"a,abbr,acronym,b,\" +\n        \"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,\" +\n        \"samp,small,span,strike,strong,sub,sup,time,tt,u,var\"));\n\n// SVG Elements\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements\n// Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.\n// They can potentially allow for arbitrary javascript to be executed. See #11290\nvar svgElements = makeMap(\"circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,\" +\n        \"hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,\" +\n        \"radialGradient,rect,stop,svg,switch,text,title,tspan,use\");\n\n// Special Elements (can contain anything)\nvar specialElements = makeMap(\"script,style\");\n\nvar validElements = angular.extend({},\n                                   voidElements,\n                                   blockElements,\n                                   inlineElements,\n                                   optionalEndTagElements,\n                                   svgElements);\n\n//Attributes that have href and hence need to be sanitized\nvar uriAttrs = makeMap(\"background,cite,href,longdesc,src,usemap,xlink:href\");\n\nvar htmlAttrs = makeMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +\n    'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +\n    'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +\n    'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +\n    'valign,value,vspace,width');\n\n// SVG attributes (without \"id\" and \"name\" attributes)\n// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes\nvar svgAttrs = makeMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +\n    'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +\n    'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +\n    'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +\n    'height,horiz-adv-x,horiz-origin-x,ideographic,k,keyPoints,keySplines,keyTimes,lang,' +\n    'marker-end,marker-mid,marker-start,markerHeight,markerUnits,markerWidth,mathematical,' +\n    'max,min,offset,opacity,orient,origin,overline-position,overline-thickness,panose-1,' +\n    'path,pathLength,points,preserveAspectRatio,r,refX,refY,repeatCount,repeatDur,' +\n    'requiredExtensions,requiredFeatures,restart,rotate,rx,ry,slope,stemh,stemv,stop-color,' +\n    'stop-opacity,strikethrough-position,strikethrough-thickness,stroke,stroke-dasharray,' +\n    'stroke-dashoffset,stroke-linecap,stroke-linejoin,stroke-miterlimit,stroke-opacity,' +\n    'stroke-width,systemLanguage,target,text-anchor,to,transform,type,u1,u2,underline-position,' +\n    'underline-thickness,unicode,unicode-range,units-per-em,values,version,viewBox,visibility,' +\n    'width,widths,x,x-height,x1,x2,xlink:actuate,xlink:arcrole,xlink:role,xlink:show,xlink:title,' +\n    'xlink:type,xml:base,xml:lang,xml:space,xmlns,xmlns:xlink,y,y1,y2,zoomAndPan', true);\n\nvar validAttrs = angular.extend({},\n                                uriAttrs,\n                                svgAttrs,\n                                htmlAttrs);\n\nfunction makeMap(str, lowercaseKeys) {\n  var obj = {}, items = str.split(','), i;\n  for (i = 0; i < items.length; i++) {\n    obj[lowercaseKeys ? angular.lowercase(items[i]) : items[i]] = true;\n  }\n  return obj;\n}\n\n\n/**\n * @example\n * htmlParser(htmlString, {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * });\n *\n * @param {string} html string\n * @param {object} handler\n */\nfunction htmlParser(html, handler) {\n  if (typeof html !== 'string') {\n    if (html === null || typeof html === 'undefined') {\n      html = '';\n    } else {\n      html = '' + html;\n    }\n  }\n  var index, chars, match, stack = [], last = html, text;\n  stack.last = function() { return stack[stack.length - 1]; };\n\n  while (html) {\n    text = '';\n    chars = true;\n\n    // Make sure we're not in a script or style element\n    if (!stack.last() || !specialElements[stack.last()]) {\n\n      // Comment\n      if (html.indexOf(\"<!--\") === 0) {\n        // comments containing -- are not allowed unless they terminate the comment\n        index = html.indexOf(\"--\", 4);\n\n        if (index >= 0 && html.lastIndexOf(\"-->\", index) === index) {\n          if (handler.comment) handler.comment(html.substring(4, index));\n          html = html.substring(index + 3);\n          chars = false;\n        }\n      // DOCTYPE\n      } else if (DOCTYPE_REGEXP.test(html)) {\n        match = html.match(DOCTYPE_REGEXP);\n\n        if (match) {\n          html = html.replace(match[0], '');\n          chars = false;\n        }\n      // end tag\n      } else if (BEGING_END_TAGE_REGEXP.test(html)) {\n        match = html.match(END_TAG_REGEXP);\n\n        if (match) {\n          html = html.substring(match[0].length);\n          match[0].replace(END_TAG_REGEXP, parseEndTag);\n          chars = false;\n        }\n\n      // start tag\n      } else if (BEGIN_TAG_REGEXP.test(html)) {\n        match = html.match(START_TAG_REGEXP);\n\n        if (match) {\n          // We only have a valid start-tag if there is a '>'.\n          if (match[4]) {\n            html = html.substring(match[0].length);\n            match[0].replace(START_TAG_REGEXP, parseStartTag);\n          }\n          chars = false;\n        } else {\n          // no ending tag found --- this piece should be encoded as an entity.\n          text += '<';\n          html = html.substring(1);\n        }\n      }\n\n      if (chars) {\n        index = html.indexOf(\"<\");\n\n        text += index < 0 ? html : html.substring(0, index);\n        html = index < 0 ? \"\" : html.substring(index);\n\n        if (handler.chars) handler.chars(decodeEntities(text));\n      }\n\n    } else {\n      // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\\W\\w].\n      html = html.replace(new RegExp(\"([\\\\W\\\\w]*)<\\\\s*\\\\/\\\\s*\" + stack.last() + \"[^>]*>\", 'i'),\n        function(all, text) {\n          text = text.replace(COMMENT_REGEXP, \"$1\").replace(CDATA_REGEXP, \"$1\");\n\n          if (handler.chars) handler.chars(decodeEntities(text));\n\n          return \"\";\n      });\n\n      parseEndTag(\"\", stack.last());\n    }\n\n    if (html == last) {\n      throw $sanitizeMinErr('badparse', \"The sanitizer was unable to parse the following block \" +\n                                        \"of html: {0}\", html);\n    }\n    last = html;\n  }\n\n  // Clean up any remaining tags\n  parseEndTag();\n\n  function parseStartTag(tag, tagName, rest, unary) {\n    tagName = angular.lowercase(tagName);\n    if (blockElements[tagName]) {\n      while (stack.last() && inlineElements[stack.last()]) {\n        parseEndTag(\"\", stack.last());\n      }\n    }\n\n    if (optionalEndTagElements[tagName] && stack.last() == tagName) {\n      parseEndTag(\"\", tagName);\n    }\n\n    unary = voidElements[tagName] || !!unary;\n\n    if (!unary) {\n      stack.push(tagName);\n    }\n\n    var attrs = {};\n\n    rest.replace(ATTR_REGEXP,\n      function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {\n        var value = doubleQuotedValue\n          || singleQuotedValue\n          || unquotedValue\n          || '';\n\n        attrs[name] = decodeEntities(value);\n    });\n    if (handler.start) handler.start(tagName, attrs, unary);\n  }\n\n  function parseEndTag(tag, tagName) {\n    var pos = 0, i;\n    tagName = angular.lowercase(tagName);\n    if (tagName) {\n      // Find the closest opened tag of the same type\n      for (pos = stack.length - 1; pos >= 0; pos--) {\n        if (stack[pos] == tagName) break;\n      }\n    }\n\n    if (pos >= 0) {\n      // Close all the open elements, up the stack\n      for (i = stack.length - 1; i >= pos; i--)\n        if (handler.end) handler.end(stack[i]);\n\n      // Remove the open elements from the stack\n      stack.length = pos;\n    }\n  }\n}\n\nvar hiddenPre=document.createElement(\"pre\");\n/**\n * decodes all entities into regular string\n * @param value\n * @returns {string} A string with decoded entities.\n */\nfunction decodeEntities(value) {\n  if (!value) { return ''; }\n\n  hiddenPre.innerHTML = value.replace(/</g,\"&lt;\");\n  // innerText depends on styling as it doesn't display hidden elements.\n  // Therefore, it's better to use textContent not to cause unnecessary reflows.\n  return hiddenPre.textContent;\n}\n\n/**\n * Escapes all potentially dangerous characters, so that the\n * resulting string can be safely inserted into attribute or\n * element text.\n * @param value\n * @returns {string} escaped text\n */\nfunction encodeEntities(value) {\n  return value.\n    replace(/&/g, '&amp;').\n    replace(SURROGATE_PAIR_REGEXP, function(value) {\n      var hi = value.charCodeAt(0);\n      var low = value.charCodeAt(1);\n      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';\n    }).\n    replace(NON_ALPHANUMERIC_REGEXP, function(value) {\n      return '&#' + value.charCodeAt(0) + ';';\n    }).\n    replace(/</g, '&lt;').\n    replace(/>/g, '&gt;');\n}\n\n/**\n * create an HTML/XML writer which writes to buffer\n * @param {Array} buf use buf.jain('') to get out sanitized html string\n * @returns {object} in the form of {\n *     start: function(tag, attrs, unary) {},\n *     end: function(tag) {},\n *     chars: function(text) {},\n *     comment: function(text) {}\n * }\n */\nfunction htmlSanitizeWriter(buf, uriValidator) {\n  var ignore = false;\n  var out = angular.bind(buf, buf.push);\n  return {\n    start: function(tag, attrs, unary) {\n      tag = angular.lowercase(tag);\n      if (!ignore && specialElements[tag]) {\n        ignore = tag;\n      }\n      if (!ignore && validElements[tag] === true) {\n        out('<');\n        out(tag);\n        angular.forEach(attrs, function(value, key) {\n          var lkey=angular.lowercase(key);\n          var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');\n          if (validAttrs[lkey] === true &&\n            (uriAttrs[lkey] !== true || uriValidator(value, isImage))) {\n            out(' ');\n            out(key);\n            out('=\"');\n            out(encodeEntities(value));\n            out('\"');\n          }\n        });\n        out(unary ? '/>' : '>');\n      }\n    },\n    end: function(tag) {\n        tag = angular.lowercase(tag);\n        if (!ignore && validElements[tag] === true) {\n          out('</');\n          out(tag);\n          out('>');\n        }\n        if (tag == ignore) {\n          ignore = false;\n        }\n      },\n    chars: function(chars) {\n        if (!ignore) {\n          out(encodeEntities(chars));\n        }\n      }\n  };\n}\n\n\n// define ngSanitize module and register $sanitize service\nangular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);\n\n/* global sanitizeText: false */\n\n/**\n * @ngdoc filter\n * @name linky\n * @kind function\n *\n * @description\n * Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and\n * plain email address links.\n *\n * Requires the {@link ngSanitize `ngSanitize`} module to be installed.\n *\n * @param {string} text Input text.\n * @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.\n * @returns {string} Html-linkified text.\n *\n * @usage\n   <span ng-bind-html=\"linky_expression | linky\"></span>\n *\n * @example\n   <example module=\"linkyExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('linkyExample', ['ngSanitize'])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.snippet =\n               'Pretty text with some links:\\n'+\n               'http://angularjs.org/,\\n'+\n               'mailto:us@somewhere.org,\\n'+\n               'another@somewhere.org,\\n'+\n               'and one more: ftp://127.0.0.1/.';\n             $scope.snippetWithTarget = 'http://angularjs.org/';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n       Snippet: <textarea ng-model=\"snippet\" cols=\"60\" rows=\"3\"></textarea>\n       <table>\n         <tr>\n           <td>Filter</td>\n           <td>Source</td>\n           <td>Rendered</td>\n         </tr>\n         <tr id=\"linky-filter\">\n           <td>linky filter</td>\n           <td>\n             <pre>&lt;div ng-bind-html=\"snippet | linky\"&gt;<br>&lt;/div&gt;</pre>\n           </td>\n           <td>\n             <div ng-bind-html=\"snippet | linky\"></div>\n           </td>\n         </tr>\n         <tr id=\"linky-target\">\n          <td>linky target</td>\n          <td>\n            <pre>&lt;div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"&gt;<br>&lt;/div&gt;</pre>\n          </td>\n          <td>\n            <div ng-bind-html=\"snippetWithTarget | linky:'_blank'\"></div>\n          </td>\n         </tr>\n         <tr id=\"escaped-html\">\n           <td>no filter</td>\n           <td><pre>&lt;div ng-bind=\"snippet\"&gt;<br>&lt;/div&gt;</pre></td>\n           <td><div ng-bind=\"snippet\"></div></td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should linkify the snippet with urls', function() {\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(4);\n       });\n\n       it('should not linkify snippet without the linky filter', function() {\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText()).\n             toBe('Pretty text with some links: http://angularjs.org/, mailto:us@somewhere.org, ' +\n                  'another@somewhere.org, and one more: ftp://127.0.0.1/.');\n         expect(element.all(by.css('#escaped-html a')).count()).toEqual(0);\n       });\n\n       it('should update', function() {\n         element(by.model('snippet')).clear();\n         element(by.model('snippet')).sendKeys('new http://link.');\n         expect(element(by.id('linky-filter')).element(by.binding('snippet | linky')).getText()).\n             toBe('new http://link.');\n         expect(element.all(by.css('#linky-filter a')).count()).toEqual(1);\n         expect(element(by.id('escaped-html')).element(by.binding('snippet')).getText())\n             .toBe('new http://link.');\n       });\n\n       it('should work with the target property', function() {\n        expect(element(by.id('linky-target')).\n            element(by.binding(\"snippetWithTarget | linky:'_blank'\")).getText()).\n            toBe('http://angularjs.org/');\n        expect(element(by.css('#linky-target a')).getAttribute('target')).toEqual('_blank');\n       });\n     </file>\n   </example>\n */\nangular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {\n  var LINKY_URL_REGEXP =\n        /((ftp|https?):\\/\\/|(www\\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\\S*[^\\s.;,(){}<>\"\\u201d\\u2019]/i,\n      MAILTO_REGEXP = /^mailto:/i;\n\n  return function(text, target) {\n    if (!text) return text;\n    var match;\n    var raw = text;\n    var html = [];\n    var url;\n    var i;\n    while ((match = raw.match(LINKY_URL_REGEXP))) {\n      // We can not end in these as they are sometimes found at the end of the sentence\n      url = match[0];\n      // if we did not match ftp/http/www/mailto then assume mailto\n      if (!match[2] && !match[4]) {\n        url = (match[3] ? 'http://' : 'mailto:') + url;\n      }\n      i = match.index;\n      addText(raw.substr(0, i));\n      addLink(url, match[0].replace(MAILTO_REGEXP, ''));\n      raw = raw.substring(i + match[0].length);\n    }\n    addText(raw);\n    return $sanitize(html.join(''));\n\n    function addText(text) {\n      if (!text) {\n        return;\n      }\n      html.push(sanitizeText(text));\n    }\n\n    function addLink(url, text) {\n      html.push('<a ');\n      if (angular.isDefined(target)) {\n        html.push('target=\"',\n                  target,\n                  '\" ');\n      }\n      html.push('href=\"',\n                url.replace(/\"/g, '&quot;'),\n                '\">');\n      addText(text);\n      html.push('</a>');\n    }\n  };\n}]);\n\n\n})(window, window.angular);\n"
  },
  {
    "path": "examples/server/php/public/vendor/angular-toastr.js",
    "content": "(function() {\n  'use strict';\n\n  angular.module('toastr', [])\n    .factory('toastr', toastr);\n\n  toastr.$inject = ['$animate', '$injector', '$document', '$rootScope', '$sce', 'toastrConfig', '$q'];\n\n  function toastr($animate, $injector, $document, $rootScope, $sce, toastrConfig, $q) {\n    var container;\n    var index = 0;\n    var toasts = [];\n\n    var previousToastMessage = '';\n    var openToasts = {};\n\n    var containerDefer = $q.defer();\n\n    var toast = {\n      clear: clear,\n      error: error,\n      info: info,\n      remove: remove,\n      success: success,\n      warning: warning\n    };\n\n    return toast;\n\n    /* Public API */\n    function clear(toast) {\n      if (toast) {\n        remove(toast.toastId);\n      } else {\n        for (var i = 0; i < toasts.length; i++) {\n          remove(toasts[i].toastId);\n        }\n      }\n    }\n\n    function error(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.error;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function info(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.info;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function success(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.success;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function warning(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.warning;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function remove(toastId, wasClicked) {\n      var toast = findToast(toastId);\n\n      if (toast && ! toast.deleting) { // Avoid clicking when fading out\n        toast.deleting = true;\n        toast.isOpened = false;\n        $animate.leave(toast.el).then(function() {\n          if (toast.scope.options.onHidden) {\n            toast.scope.options.onHidden(wasClicked);\n          }\n          toast.scope.$destroy();\n          var index = toasts.indexOf(toast);\n          delete openToasts[toast.scope.message];\n          toasts.splice(index, 1);\n          var maxOpened = toastrConfig.maxOpened;\n          if (maxOpened && toasts.length >= maxOpened) {\n            toasts[maxOpened - 1].open.resolve();\n          }\n          if (lastToast()) {\n            container.remove();\n            container = null;\n            containerDefer = $q.defer();\n          }\n        });\n      }\n\n      function findToast(toastId) {\n        for (var i = 0; i < toasts.length; i++) {\n          if (toasts[i].toastId === toastId) {\n            return toasts[i];\n          }\n        }\n      }\n\n      function lastToast() {\n        return !toasts.length;\n      }\n    }\n\n    /* Internal functions */\n    function _buildNotification(type, message, title, optionsOverride)\n    {\n      if (angular.isObject(title)) {\n        optionsOverride = title;\n        title = null;\n      }\n\n      return _notify({\n        iconClass: type,\n        message: message,\n        optionsOverride: optionsOverride,\n        title: title\n      });\n    }\n\n    function _getOptions() {\n      return angular.extend({}, toastrConfig);\n    }\n\n    function _createOrGetContainer(options) {\n      if(container) { return containerDefer.promise; }\n\n      container = angular.element('<div></div>');\n      container.attr('id', options.containerId);\n      container.addClass(options.positionClass);\n      container.css({'pointer-events': 'auto'});\n\n      var target = angular.element(document.querySelector(options.target));\n\n      if ( ! target || ! target.length) {\n        throw 'Target for toasts doesn\\'t exist';\n      }\n\n      $animate.enter(container, target).then(function() {\n        containerDefer.resolve();\n      });\n\n      return containerDefer.promise;\n    }\n\n    function _notify(map) {\n      var options = _getOptions();\n\n      if (shouldExit()) { return; }\n\n      var newToast = createToast();\n\n      toasts.push(newToast);\n\n      if (options.autoDismiss && options.maxOpened > 0) {\n        var oldToasts = toasts.slice(0, (toasts.length - options.maxOpened));\n        for (var i = 0, len = oldToasts.length; i < len; i++) {\n          remove(oldToasts[i].toastId);\n        }\n      }\n\n      if (maxOpenedNotReached()) {\n        newToast.open.resolve();\n      }\n\n      newToast.open.promise.then(function() {\n        _createOrGetContainer(options).then(function() {\n          newToast.isOpened = true;\n          if (options.newestOnTop) {\n            $animate.enter(newToast.el, container).then(function() {\n              newToast.scope.init();\n            });\n          } else {\n            var sibling = container[0].lastChild ? angular.element(container[0].lastChild) : null;\n            $animate.enter(newToast.el, container, sibling).then(function() {\n              newToast.scope.init();\n            });\n          }\n        });\n      });\n\n      return newToast;\n\n      function createScope(toast, map, options) {\n        if (options.allowHtml) {\n          toast.scope.allowHtml = true;\n          toast.scope.title = $sce.trustAsHtml(map.title);\n          toast.scope.message = $sce.trustAsHtml(map.message);\n        } else {\n          toast.scope.title = map.title;\n          toast.scope.message = map.message;\n        }\n\n        toast.scope.toastType = toast.iconClass;\n        toast.scope.toastId = toast.toastId;\n\n        toast.scope.options = {\n          extendedTimeOut: options.extendedTimeOut,\n          messageClass: options.messageClass,\n          onHidden: options.onHidden,\n          onShown: options.onShown,\n          progressBar: options.progressBar,\n          tapToDismiss: options.tapToDismiss,\n          timeOut: options.timeOut,\n          titleClass: options.titleClass,\n          toastClass: options.toastClass\n        };\n\n        if (options.closeButton) {\n          toast.scope.options.closeHtml = options.closeHtml;\n        }\n      }\n\n      function createToast() {\n        var newToast = {\n          toastId: index++,\n          isOpened: false,\n          scope: $rootScope.$new(),\n          open: $q.defer()\n        };\n        newToast.iconClass = map.iconClass;\n        if (map.optionsOverride) {\n          options = angular.extend(options, cleanOptionsOverride(map.optionsOverride));\n          newToast.iconClass = map.optionsOverride.iconClass || newToast.iconClass;\n        }\n\n        createScope(newToast, map, options);\n\n        newToast.el = createToastEl(newToast.scope);\n\n        return newToast;\n\n        function cleanOptionsOverride(options) {\n          var badOptions = ['containerId', 'iconClasses', 'maxOpened', 'newestOnTop',\n                            'positionClass', 'preventDuplicates', 'preventOpenDuplicates', 'templates'];\n          for (var i = 0, l = badOptions.length; i < l; i++) {\n            delete options[badOptions[i]];\n          }\n\n          return options;\n        }\n      }\n\n      function createToastEl(scope) {\n        var angularDomEl = angular.element('<div toast></div>'),\n          $compile = $injector.get('$compile');\n        return $compile(angularDomEl)(scope);\n      }\n\n      function maxOpenedNotReached() {\n        return options.maxOpened && toasts.length <= options.maxOpened || !options.maxOpened;\n      }\n\n      function shouldExit() {\n        var isDuplicateOfLast = options.preventDuplicates && map.message === previousToastMessage;\n        var isDuplicateOpen = options.preventOpenDuplicates && openToasts[map.message];\n\n        if (isDuplicateOfLast || isDuplicateOpen) {\n          return true;\n        }\n\n        previousToastMessage = map.message;\n        openToasts[map.message] = true;\n\n        return false;\n      }\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .constant('toastrConfig', {\n      allowHtml: false,\n      autoDismiss: false,\n      closeButton: false,\n      closeHtml: '<button>&times;</button>',\n      containerId: 'toast-container',\n      extendedTimeOut: 1000,\n      iconClasses: {\n        error: 'toast-error',\n        info: 'toast-info',\n        success: 'toast-success',\n        warning: 'toast-warning'\n      },\n      maxOpened: 0,\n      messageClass: 'toast-message',\n      newestOnTop: true,\n      onHidden: null,\n      onShown: null,\n      positionClass: 'toast-top-right',\n      preventDuplicates: false,\n      preventOpenDuplicates: false,\n      progressBar: false,\n      tapToDismiss: true,\n      target: 'body',\n      templates: {\n        toast: 'directives/toast/toast.html',\n        progressbar: 'directives/progressbar/progressbar.html'\n      },\n      timeOut: 5000,\n      titleClass: 'toast-title',\n      toastClass: 'toast'\n    });\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('progressBar', progressBar);\n\n  progressBar.$inject = ['toastrConfig'];\n\n  function progressBar(toastrConfig) {\n    return {\n      replace: true,\n      require: '^toast',\n      templateUrl: function() {\n        return toastrConfig.templates.progressbar;\n      },\n      link: linkFunction\n    };\n\n    function linkFunction(scope, element, attrs, toastCtrl) {\n      var intervalId, currentTimeOut, hideTime;\n\n      toastCtrl.progressBar = scope;\n\n      scope.start = function(duration) {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n\n        currentTimeOut = parseFloat(duration);\n        hideTime = new Date().getTime() + currentTimeOut;\n        intervalId = setInterval(updateProgress, 10);\n      };\n\n      scope.stop = function() {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n      };\n\n      function updateProgress() {\n        var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100;\n        element.css('width', percentage + '%');\n      }\n\n      scope.$on('$destroy', function() {\n        // Failsafe stop\n        clearInterval(intervalId);\n      });\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .controller('ToastController', ToastController);\n\n  function ToastController() {\n    this.progressBar = null;\n\n    this.startProgressBar = function(duration) {\n      if (this.progressBar) {\n        this.progressBar.start(duration);\n      }\n    };\n\n    this.stopProgressBar = function() {\n      if (this.progressBar) {\n        this.progressBar.stop();\n      }\n    };\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('toast', toast);\n\n  toast.$inject = ['$injector', '$interval', 'toastrConfig', 'toastr'];\n\n  function toast($injector, $interval, toastrConfig, toastr) {\n    return {\n      replace: true,\n      templateUrl: function() {\n        return toastrConfig.templates.toast;\n      },\n      controller: 'ToastController',\n      link: toastLinkFunction\n    };\n\n    function toastLinkFunction(scope, element, attrs, toastCtrl) {\n      var timeout;\n\n      scope.toastClass = scope.options.toastClass;\n      scope.titleClass = scope.options.titleClass;\n      scope.messageClass = scope.options.messageClass;\n      scope.progressBar = scope.options.progressBar;\n\n      if (wantsCloseButton()) {\n        var button = angular.element(scope.options.closeHtml),\n          $compile = $injector.get('$compile');\n        button.addClass('toast-close-button');\n        button.attr('ng-click', 'close()');\n        $compile(button)(scope);\n        element.prepend(button);\n      }\n\n      scope.init = function() {\n        if (scope.options.timeOut) {\n          timeout = createTimeout(scope.options.timeOut);\n        }\n        if (scope.options.onShown) {\n          scope.options.onShown();\n        }\n      };\n\n      element.on('mouseenter', function() {\n        hideAndStopProgressBar();\n        if (timeout) {\n          $interval.cancel(timeout);\n        }\n      });\n\n      scope.tapToast = function () {\n        if (scope.options.tapToDismiss) {\n          scope.close(true);\n        }\n      };\n\n      scope.close = function (wasClicked) {\n        toastr.remove(scope.toastId, wasClicked);\n      };\n\n      element.on('mouseleave', function() {\n        if (scope.options.timeOut === 0 && scope.options.extendedTimeOut === 0) { return; }\n        scope.$apply(function() {\n          scope.progressBar = scope.options.progressBar;\n        });\n        timeout = createTimeout(scope.options.extendedTimeOut);\n      });\n\n      function createTimeout(time) {\n        toastCtrl.startProgressBar(time);\n        return $interval(function() {\n          toastCtrl.stopProgressBar();\n          toastr.remove(scope.toastId);\n        }, time, 1);\n      }\n\n      function hideAndStopProgressBar() {\n        scope.progressBar = false;\n        toastCtrl.stopProgressBar();\n      }\n\n      function wantsCloseButton() {\n        return scope.options.closeHtml;\n      }\n    }\n  }\n}());\n"
  },
  {
    "path": "examples/server/php/public/vendor/angular-toastr.tpls.js",
    "content": "(function() {\n  'use strict';\n\n  angular.module('toastr', [])\n    .factory('toastr', toastr);\n\n  toastr.$inject = ['$animate', '$injector', '$document', '$rootScope', '$sce', 'toastrConfig', '$q'];\n\n  function toastr($animate, $injector, $document, $rootScope, $sce, toastrConfig, $q) {\n    var container;\n    var index = 0;\n    var toasts = [];\n\n    var previousToastMessage = '';\n    var openToasts = {};\n\n    var containerDefer = $q.defer();\n\n    var toast = {\n      clear: clear,\n      error: error,\n      info: info,\n      remove: remove,\n      success: success,\n      warning: warning\n    };\n\n    return toast;\n\n    /* Public API */\n    function clear(toast) {\n      if (toast) {\n        remove(toast.toastId);\n      } else {\n        for (var i = 0; i < toasts.length; i++) {\n          remove(toasts[i].toastId);\n        }\n      }\n    }\n\n    function error(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.error;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function info(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.info;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function success(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.success;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function warning(message, title, optionsOverride) {\n      var type = _getOptions().iconClasses.warning;\n      return _buildNotification(type, message, title, optionsOverride);\n    }\n\n    function remove(toastId, wasClicked) {\n      var toast = findToast(toastId);\n\n      if (toast && ! toast.deleting) { // Avoid clicking when fading out\n        toast.deleting = true;\n        toast.isOpened = false;\n        $animate.leave(toast.el).then(function() {\n          if (toast.scope.options.onHidden) {\n            toast.scope.options.onHidden(wasClicked);\n          }\n          toast.scope.$destroy();\n          var index = toasts.indexOf(toast);\n          delete openToasts[toast.scope.message];\n          toasts.splice(index, 1);\n          var maxOpened = toastrConfig.maxOpened;\n          if (maxOpened && toasts.length >= maxOpened) {\n            toasts[maxOpened - 1].open.resolve();\n          }\n          if (lastToast()) {\n            container.remove();\n            container = null;\n            containerDefer = $q.defer();\n          }\n        });\n      }\n\n      function findToast(toastId) {\n        for (var i = 0; i < toasts.length; i++) {\n          if (toasts[i].toastId === toastId) {\n            return toasts[i];\n          }\n        }\n      }\n\n      function lastToast() {\n        return !toasts.length;\n      }\n    }\n\n    /* Internal functions */\n    function _buildNotification(type, message, title, optionsOverride)\n    {\n      if (angular.isObject(title)) {\n        optionsOverride = title;\n        title = null;\n      }\n\n      return _notify({\n        iconClass: type,\n        message: message,\n        optionsOverride: optionsOverride,\n        title: title\n      });\n    }\n\n    function _getOptions() {\n      return angular.extend({}, toastrConfig);\n    }\n\n    function _createOrGetContainer(options) {\n      if(container) { return containerDefer.promise; }\n\n      container = angular.element('<div></div>');\n      container.attr('id', options.containerId);\n      container.addClass(options.positionClass);\n      container.css({'pointer-events': 'auto'});\n\n      var target = angular.element(document.querySelector(options.target));\n\n      if ( ! target || ! target.length) {\n        throw 'Target for toasts doesn\\'t exist';\n      }\n\n      $animate.enter(container, target).then(function() {\n        containerDefer.resolve();\n      });\n\n      return containerDefer.promise;\n    }\n\n    function _notify(map) {\n      var options = _getOptions();\n\n      if (shouldExit()) { return; }\n\n      var newToast = createToast();\n\n      toasts.push(newToast);\n\n      if (options.autoDismiss && options.maxOpened > 0) {\n        var oldToasts = toasts.slice(0, (toasts.length - options.maxOpened));\n        for (var i = 0, len = oldToasts.length; i < len; i++) {\n          remove(oldToasts[i].toastId);\n        }\n      }\n\n      if (maxOpenedNotReached()) {\n        newToast.open.resolve();\n      }\n\n      newToast.open.promise.then(function() {\n        _createOrGetContainer(options).then(function() {\n          newToast.isOpened = true;\n          if (options.newestOnTop) {\n            $animate.enter(newToast.el, container).then(function() {\n              newToast.scope.init();\n            });\n          } else {\n            var sibling = container[0].lastChild ? angular.element(container[0].lastChild) : null;\n            $animate.enter(newToast.el, container, sibling).then(function() {\n              newToast.scope.init();\n            });\n          }\n        });\n      });\n\n      return newToast;\n\n      function createScope(toast, map, options) {\n        if (options.allowHtml) {\n          toast.scope.allowHtml = true;\n          toast.scope.title = $sce.trustAsHtml(map.title);\n          toast.scope.message = $sce.trustAsHtml(map.message);\n        } else {\n          toast.scope.title = map.title;\n          toast.scope.message = map.message;\n        }\n\n        toast.scope.toastType = toast.iconClass;\n        toast.scope.toastId = toast.toastId;\n\n        toast.scope.options = {\n          extendedTimeOut: options.extendedTimeOut,\n          messageClass: options.messageClass,\n          onHidden: options.onHidden,\n          onShown: options.onShown,\n          progressBar: options.progressBar,\n          tapToDismiss: options.tapToDismiss,\n          timeOut: options.timeOut,\n          titleClass: options.titleClass,\n          toastClass: options.toastClass\n        };\n\n        if (options.closeButton) {\n          toast.scope.options.closeHtml = options.closeHtml;\n        }\n      }\n\n      function createToast() {\n        var newToast = {\n          toastId: index++,\n          isOpened: false,\n          scope: $rootScope.$new(),\n          open: $q.defer()\n        };\n        newToast.iconClass = map.iconClass;\n        if (map.optionsOverride) {\n          options = angular.extend(options, cleanOptionsOverride(map.optionsOverride));\n          newToast.iconClass = map.optionsOverride.iconClass || newToast.iconClass;\n        }\n\n        createScope(newToast, map, options);\n\n        newToast.el = createToastEl(newToast.scope);\n\n        return newToast;\n\n        function cleanOptionsOverride(options) {\n          var badOptions = ['containerId', 'iconClasses', 'maxOpened', 'newestOnTop',\n                            'positionClass', 'preventDuplicates', 'preventOpenDuplicates', 'templates'];\n          for (var i = 0, l = badOptions.length; i < l; i++) {\n            delete options[badOptions[i]];\n          }\n\n          return options;\n        }\n      }\n\n      function createToastEl(scope) {\n        var angularDomEl = angular.element('<div toast></div>'),\n          $compile = $injector.get('$compile');\n        return $compile(angularDomEl)(scope);\n      }\n\n      function maxOpenedNotReached() {\n        return options.maxOpened && toasts.length <= options.maxOpened || !options.maxOpened;\n      }\n\n      function shouldExit() {\n        var isDuplicateOfLast = options.preventDuplicates && map.message === previousToastMessage;\n        var isDuplicateOpen = options.preventOpenDuplicates && openToasts[map.message];\n\n        if (isDuplicateOfLast || isDuplicateOpen) {\n          return true;\n        }\n\n        previousToastMessage = map.message;\n        openToasts[map.message] = true;\n\n        return false;\n      }\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .constant('toastrConfig', {\n      allowHtml: false,\n      autoDismiss: false,\n      closeButton: false,\n      closeHtml: '<button>&times;</button>',\n      containerId: 'toast-container',\n      extendedTimeOut: 1000,\n      iconClasses: {\n        error: 'toast-error',\n        info: 'toast-info',\n        success: 'toast-success',\n        warning: 'toast-warning'\n      },\n      maxOpened: 0,\n      messageClass: 'toast-message',\n      newestOnTop: true,\n      onHidden: null,\n      onShown: null,\n      positionClass: 'toast-top-right',\n      preventDuplicates: false,\n      preventOpenDuplicates: false,\n      progressBar: false,\n      tapToDismiss: true,\n      target: 'body',\n      templates: {\n        toast: 'directives/toast/toast.html',\n        progressbar: 'directives/progressbar/progressbar.html'\n      },\n      timeOut: 5000,\n      titleClass: 'toast-title',\n      toastClass: 'toast'\n    });\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('progressBar', progressBar);\n\n  progressBar.$inject = ['toastrConfig'];\n\n  function progressBar(toastrConfig) {\n    return {\n      replace: true,\n      require: '^toast',\n      templateUrl: function() {\n        return toastrConfig.templates.progressbar;\n      },\n      link: linkFunction\n    };\n\n    function linkFunction(scope, element, attrs, toastCtrl) {\n      var intervalId, currentTimeOut, hideTime;\n\n      toastCtrl.progressBar = scope;\n\n      scope.start = function(duration) {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n\n        currentTimeOut = parseFloat(duration);\n        hideTime = new Date().getTime() + currentTimeOut;\n        intervalId = setInterval(updateProgress, 10);\n      };\n\n      scope.stop = function() {\n        if (intervalId) {\n          clearInterval(intervalId);\n        }\n      };\n\n      function updateProgress() {\n        var percentage = ((hideTime - (new Date().getTime())) / currentTimeOut) * 100;\n        element.css('width', percentage + '%');\n      }\n\n      scope.$on('$destroy', function() {\n        // Failsafe stop\n        clearInterval(intervalId);\n      });\n    }\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .controller('ToastController', ToastController);\n\n  function ToastController() {\n    this.progressBar = null;\n\n    this.startProgressBar = function(duration) {\n      if (this.progressBar) {\n        this.progressBar.start(duration);\n      }\n    };\n\n    this.stopProgressBar = function() {\n      if (this.progressBar) {\n        this.progressBar.stop();\n      }\n    };\n  }\n}());\n\n(function() {\n  'use strict';\n\n  angular.module('toastr')\n    .directive('toast', toast);\n\n  toast.$inject = ['$injector', '$interval', 'toastrConfig', 'toastr'];\n\n  function toast($injector, $interval, toastrConfig, toastr) {\n    return {\n      replace: true,\n      templateUrl: function() {\n        return toastrConfig.templates.toast;\n      },\n      controller: 'ToastController',\n      link: toastLinkFunction\n    };\n\n    function toastLinkFunction(scope, element, attrs, toastCtrl) {\n      var timeout;\n\n      scope.toastClass = scope.options.toastClass;\n      scope.titleClass = scope.options.titleClass;\n      scope.messageClass = scope.options.messageClass;\n      scope.progressBar = scope.options.progressBar;\n\n      if (wantsCloseButton()) {\n        var button = angular.element(scope.options.closeHtml),\n          $compile = $injector.get('$compile');\n        button.addClass('toast-close-button');\n        button.attr('ng-click', 'close()');\n        $compile(button)(scope);\n        element.prepend(button);\n      }\n\n      scope.init = function() {\n        if (scope.options.timeOut) {\n          timeout = createTimeout(scope.options.timeOut);\n        }\n        if (scope.options.onShown) {\n          scope.options.onShown();\n        }\n      };\n\n      element.on('mouseenter', function() {\n        hideAndStopProgressBar();\n        if (timeout) {\n          $interval.cancel(timeout);\n        }\n      });\n\n      scope.tapToast = function () {\n        if (scope.options.tapToDismiss) {\n          scope.close(true);\n        }\n      };\n\n      scope.close = function (wasClicked) {\n        toastr.remove(scope.toastId, wasClicked);\n      };\n\n      element.on('mouseleave', function() {\n        if (scope.options.timeOut === 0 && scope.options.extendedTimeOut === 0) { return; }\n        scope.$apply(function() {\n          scope.progressBar = scope.options.progressBar;\n        });\n        timeout = createTimeout(scope.options.extendedTimeOut);\n      });\n\n      function createTimeout(time) {\n        toastCtrl.startProgressBar(time);\n        return $interval(function() {\n          toastCtrl.stopProgressBar();\n          toastr.remove(scope.toastId);\n        }, time, 1);\n      }\n\n      function hideAndStopProgressBar() {\n        scope.progressBar = false;\n        toastCtrl.stopProgressBar();\n      }\n\n      function wantsCloseButton() {\n        return scope.options.closeHtml;\n      }\n    }\n  }\n}());\n\nangular.module(\"toastr\").run([\"$templateCache\", function($templateCache) {$templateCache.put(\"directives/progressbar/progressbar.html\",\"<div class=\\\"toast-progress\\\"></div>\\n\");\n$templateCache.put(\"directives/toast/toast.html\",\"<div class=\\\"{{toastClass}} {{toastType}}\\\" ng-click=\\\"tapToast()\\\">\\n  <div ng-switch on=\\\"allowHtml\\\">\\n    <div ng-switch-default ng-if=\\\"title\\\" class=\\\"{{titleClass}}\\\">{{title}}</div>\\n    <div ng-switch-default class=\\\"{{messageClass}}\\\">{{message}}</div>\\n    <div ng-switch-when=\\\"true\\\" ng-if=\\\"title\\\" class=\\\"{{titleClass}}\\\" ng-bind-html=\\\"title\\\"></div>\\n    <div ng-switch-when=\\\"true\\\" class=\\\"{{messageClass}}\\\" ng-bind-html=\\\"message\\\"></div>\\n  </div>\\n  <progress-bar ng-if=\\\"progressBar\\\"></progress-bar>\\n</div>\\n\");}]);"
  },
  {
    "path": "examples/server/php/public/vendor/angular-ui-router.js",
    "content": "/**\n * State-based routing for AngularJS\n * @version v0.2.15\n * @link http://angular-ui.github.com/\n * @license MIT License, http://www.opensource.org/licenses/MIT\n */\n\n/* commonjs package manager support (eg componentjs) */\nif (typeof module !== \"undefined\" && typeof exports !== \"undefined\" && module.exports === exports){\n  module.exports = 'ui.router';\n}\n\n(function (window, angular, undefined) {\n/*jshint globalstrict:true*/\n/*global angular:false*/\n'use strict';\n\nvar isDefined = angular.isDefined,\n    isFunction = angular.isFunction,\n    isString = angular.isString,\n    isObject = angular.isObject,\n    isArray = angular.isArray,\n    forEach = angular.forEach,\n    extend = angular.extend,\n    copy = angular.copy;\n\nfunction inherit(parent, extra) {\n  return extend(new (extend(function() {}, { prototype: parent }))(), extra);\n}\n\nfunction merge(dst) {\n  forEach(arguments, function(obj) {\n    if (obj !== dst) {\n      forEach(obj, function(value, key) {\n        if (!dst.hasOwnProperty(key)) dst[key] = value;\n      });\n    }\n  });\n  return dst;\n}\n\n/**\n * Finds the common ancestor path between two states.\n *\n * @param {Object} first The first state.\n * @param {Object} second The second state.\n * @return {Array} Returns an array of state names in descending order, not including the root.\n */\nfunction ancestors(first, second) {\n  var path = [];\n\n  for (var n in first.path) {\n    if (first.path[n] !== second.path[n]) break;\n    path.push(first.path[n]);\n  }\n  return path;\n}\n\n/**\n * IE8-safe wrapper for `Object.keys()`.\n *\n * @param {Object} object A JavaScript object.\n * @return {Array} Returns the keys of the object as an array.\n */\nfunction objectKeys(object) {\n  if (Object.keys) {\n    return Object.keys(object);\n  }\n  var result = [];\n\n  forEach(object, function(val, key) {\n    result.push(key);\n  });\n  return result;\n}\n\n/**\n * IE8-safe wrapper for `Array.prototype.indexOf()`.\n *\n * @param {Array} array A JavaScript array.\n * @param {*} value A value to search the array for.\n * @return {Number} Returns the array index value of `value`, or `-1` if not present.\n */\nfunction indexOf(array, value) {\n  if (Array.prototype.indexOf) {\n    return array.indexOf(value, Number(arguments[2]) || 0);\n  }\n  var len = array.length >>> 0, from = Number(arguments[2]) || 0;\n  from = (from < 0) ? Math.ceil(from) : Math.floor(from);\n\n  if (from < 0) from += len;\n\n  for (; from < len; from++) {\n    if (from in array && array[from] === value) return from;\n  }\n  return -1;\n}\n\n/**\n * Merges a set of parameters with all parameters inherited between the common parents of the\n * current state and a given destination state.\n *\n * @param {Object} currentParams The value of the current state parameters ($stateParams).\n * @param {Object} newParams The set of parameters which will be composited with inherited params.\n * @param {Object} $current Internal definition of object representing the current state.\n * @param {Object} $to Internal definition of object representing state to transition to.\n */\nfunction inheritParams(currentParams, newParams, $current, $to) {\n  var parents = ancestors($current, $to), parentParams, inherited = {}, inheritList = [];\n\n  for (var i in parents) {\n    if (!parents[i].params) continue;\n    parentParams = objectKeys(parents[i].params);\n    if (!parentParams.length) continue;\n\n    for (var j in parentParams) {\n      if (indexOf(inheritList, parentParams[j]) >= 0) continue;\n      inheritList.push(parentParams[j]);\n      inherited[parentParams[j]] = currentParams[parentParams[j]];\n    }\n  }\n  return extend({}, inherited, newParams);\n}\n\n/**\n * Performs a non-strict comparison of the subset of two objects, defined by a list of keys.\n *\n * @param {Object} a The first object.\n * @param {Object} b The second object.\n * @param {Array} keys The list of keys within each object to compare. If the list is empty or not specified,\n *                     it defaults to the list of keys in `a`.\n * @return {Boolean} Returns `true` if the keys match, otherwise `false`.\n */\nfunction equalForKeys(a, b, keys) {\n  if (!keys) {\n    keys = [];\n    for (var n in a) keys.push(n); // Used instead of Object.keys() for IE8 compatibility\n  }\n\n  for (var i=0; i<keys.length; i++) {\n    var k = keys[i];\n    if (a[k] != b[k]) return false; // Not '===', values aren't necessarily normalized\n  }\n  return true;\n}\n\n/**\n * Returns the subset of an object, based on a list of keys.\n *\n * @param {Array} keys\n * @param {Object} values\n * @return {Boolean} Returns a subset of `values`.\n */\nfunction filterByKeys(keys, values) {\n  var filtered = {};\n\n  forEach(keys, function (name) {\n    filtered[name] = values[name];\n  });\n  return filtered;\n}\n\n// like _.indexBy\n// when you know that your index values will be unique, or you want last-one-in to win\nfunction indexBy(array, propName) {\n  var result = {};\n  forEach(array, function(item) {\n    result[item[propName]] = item;\n  });\n  return result;\n}\n\n// extracted from underscore.js\n// Return a copy of the object only containing the whitelisted properties.\nfunction pick(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  forEach(keys, function(key) {\n    if (key in obj) copy[key] = obj[key];\n  });\n  return copy;\n}\n\n// extracted from underscore.js\n// Return a copy of the object omitting the blacklisted properties.\nfunction omit(obj) {\n  var copy = {};\n  var keys = Array.prototype.concat.apply(Array.prototype, Array.prototype.slice.call(arguments, 1));\n  for (var key in obj) {\n    if (indexOf(keys, key) == -1) copy[key] = obj[key];\n  }\n  return copy;\n}\n\nfunction pluck(collection, key) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = isFunction(key) ? key(val) : val[key];\n  });\n  return result;\n}\n\nfunction filter(collection, callback) {\n  var array = isArray(collection);\n  var result = array ? [] : {};\n  forEach(collection, function(val, i) {\n    if (callback(val, i)) {\n      result[array ? result.length : i] = val;\n    }\n  });\n  return result;\n}\n\nfunction map(collection, callback) {\n  var result = isArray(collection) ? [] : {};\n\n  forEach(collection, function(val, i) {\n    result[i] = callback(val, i);\n  });\n  return result;\n}\n\n/**\n * @ngdoc overview\n * @name ui.router.util\n *\n * @description\n * # ui.router.util sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n *\n */\nangular.module('ui.router.util', ['ng']);\n\n/**\n * @ngdoc overview\n * @name ui.router.router\n * \n * @requires ui.router.util\n *\n * @description\n * # ui.router.router sub-module\n *\n * This module is a dependency of other sub-modules. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n */\nangular.module('ui.router.router', ['ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router.state\n * \n * @requires ui.router.router\n * @requires ui.router.util\n *\n * @description\n * # ui.router.state sub-module\n *\n * This module is a dependency of the main ui.router module. Do not include this module as a dependency\n * in your angular app (use {@link ui.router} module instead).\n * \n */\nangular.module('ui.router.state', ['ui.router.router', 'ui.router.util']);\n\n/**\n * @ngdoc overview\n * @name ui.router\n *\n * @requires ui.router.state\n *\n * @description\n * # ui.router\n * \n * ## The main module for ui.router \n * There are several sub-modules included with the ui.router module, however only this module is needed\n * as a dependency within your angular app. The other modules are for organization purposes. \n *\n * The modules are:\n * * ui.router - the main \"umbrella\" module\n * * ui.router.router - \n * \n * *You'll need to include **only** this module as the dependency within your angular app.*\n * \n * <pre>\n * <!doctype html>\n * <html ng-app=\"myApp\">\n * <head>\n *   <script src=\"js/angular.js\"></script>\n *   <!-- Include the ui-router script -->\n *   <script src=\"js/angular-ui-router.min.js\"></script>\n *   <script>\n *     // ...and add 'ui.router' as a dependency\n *     var myApp = angular.module('myApp', ['ui.router']);\n *   </script>\n * </head>\n * <body>\n * </body>\n * </html>\n * </pre>\n */\nangular.module('ui.router', ['ui.router.state']);\n\nangular.module('ui.router.compat', ['ui.router']);\n\n/**\n * @ngdoc object\n * @name ui.router.util.$resolve\n *\n * @requires $q\n * @requires $injector\n *\n * @description\n * Manages resolution of (acyclic) graphs of promises.\n */\n$Resolve.$inject = ['$q', '$injector'];\nfunction $Resolve(  $q,    $injector) {\n  \n  var VISIT_IN_PROGRESS = 1,\n      VISIT_DONE = 2,\n      NOTHING = {},\n      NO_DEPENDENCIES = [],\n      NO_LOCALS = NOTHING,\n      NO_PARENT = extend($q.when(NOTHING), { $$promises: NOTHING, $$values: NOTHING });\n  \n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#study\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Studies a set of invocables that are likely to be used multiple times.\n   * <pre>\n   * $resolve.study(invocables)(locals, parent, self)\n   * </pre>\n   * is equivalent to\n   * <pre>\n   * $resolve.resolve(invocables, locals, parent, self)\n   * </pre>\n   * but the former is more efficient (in fact `resolve` just calls `study` \n   * internally).\n   *\n   * @param {object} invocables Invocable objects\n   * @return {function} a function to pass in locals, parent and self\n   */\n  this.study = function (invocables) {\n    if (!isObject(invocables)) throw new Error(\"'invocables' must be an object\");\n    var invocableKeys = objectKeys(invocables || {});\n    \n    // Perform a topological sort of invocables to build an ordered plan\n    var plan = [], cycle = [], visited = {};\n    function visit(value, key) {\n      if (visited[key] === VISIT_DONE) return;\n      \n      cycle.push(key);\n      if (visited[key] === VISIT_IN_PROGRESS) {\n        cycle.splice(0, indexOf(cycle, key));\n        throw new Error(\"Cyclic dependency: \" + cycle.join(\" -> \"));\n      }\n      visited[key] = VISIT_IN_PROGRESS;\n      \n      if (isString(value)) {\n        plan.push(key, [ function() { return $injector.get(value); }], NO_DEPENDENCIES);\n      } else {\n        var params = $injector.annotate(value);\n        forEach(params, function (param) {\n          if (param !== key && invocables.hasOwnProperty(param)) visit(invocables[param], param);\n        });\n        plan.push(key, value, params);\n      }\n      \n      cycle.pop();\n      visited[key] = VISIT_DONE;\n    }\n    forEach(invocables, visit);\n    invocables = cycle = visited = null; // plan is all that's required\n    \n    function isResolve(value) {\n      return isObject(value) && value.then && value.$$promises;\n    }\n    \n    return function (locals, parent, self) {\n      if (isResolve(locals) && self === undefined) {\n        self = parent; parent = locals; locals = null;\n      }\n      if (!locals) locals = NO_LOCALS;\n      else if (!isObject(locals)) {\n        throw new Error(\"'locals' must be an object\");\n      }       \n      if (!parent) parent = NO_PARENT;\n      else if (!isResolve(parent)) {\n        throw new Error(\"'parent' must be a promise returned by $resolve.resolve()\");\n      }\n      \n      // To complete the overall resolution, we have to wait for the parent\n      // promise and for the promise for each invokable in our plan.\n      var resolution = $q.defer(),\n          result = resolution.promise,\n          promises = result.$$promises = {},\n          values = extend({}, locals),\n          wait = 1 + plan.length/3,\n          merged = false;\n          \n      function done() {\n        // Merge parent values we haven't got yet and publish our own $$values\n        if (!--wait) {\n          if (!merged) merge(values, parent.$$values); \n          result.$$values = values;\n          result.$$promises = result.$$promises || true; // keep for isResolve()\n          delete result.$$inheritedValues;\n          resolution.resolve(values);\n        }\n      }\n      \n      function fail(reason) {\n        result.$$failure = reason;\n        resolution.reject(reason);\n      }\n\n      // Short-circuit if parent has already failed\n      if (isDefined(parent.$$failure)) {\n        fail(parent.$$failure);\n        return result;\n      }\n      \n      if (parent.$$inheritedValues) {\n        merge(values, omit(parent.$$inheritedValues, invocableKeys));\n      }\n\n      // Merge parent values if the parent has already resolved, or merge\n      // parent promises and wait if the parent resolve is still in progress.\n      extend(promises, parent.$$promises);\n      if (parent.$$values) {\n        merged = merge(values, omit(parent.$$values, invocableKeys));\n        result.$$inheritedValues = omit(parent.$$values, invocableKeys);\n        done();\n      } else {\n        if (parent.$$inheritedValues) {\n          result.$$inheritedValues = omit(parent.$$inheritedValues, invocableKeys);\n        }        \n        parent.then(done, fail);\n      }\n      \n      // Process each invocable in the plan, but ignore any where a local of the same name exists.\n      for (var i=0, ii=plan.length; i<ii; i+=3) {\n        if (locals.hasOwnProperty(plan[i])) done();\n        else invoke(plan[i], plan[i+1], plan[i+2]);\n      }\n      \n      function invoke(key, invocable, params) {\n        // Create a deferred for this invocation. Failures will propagate to the resolution as well.\n        var invocation = $q.defer(), waitParams = 0;\n        function onfailure(reason) {\n          invocation.reject(reason);\n          fail(reason);\n        }\n        // Wait for any parameter that we have a promise for (either from parent or from this\n        // resolve; in that case study() will have made sure it's ordered before us in the plan).\n        forEach(params, function (dep) {\n          if (promises.hasOwnProperty(dep) && !locals.hasOwnProperty(dep)) {\n            waitParams++;\n            promises[dep].then(function (result) {\n              values[dep] = result;\n              if (!(--waitParams)) proceed();\n            }, onfailure);\n          }\n        });\n        if (!waitParams) proceed();\n        function proceed() {\n          if (isDefined(result.$$failure)) return;\n          try {\n            invocation.resolve($injector.invoke(invocable, self, values));\n            invocation.promise.then(function (result) {\n              values[key] = result;\n              done();\n            }, onfailure);\n          } catch (e) {\n            onfailure(e);\n          }\n        }\n        // Publish promise synchronously; invocations further down in the plan may depend on it.\n        promises[key] = invocation.promise;\n      }\n      \n      return result;\n    };\n  };\n  \n  /**\n   * @ngdoc function\n   * @name ui.router.util.$resolve#resolve\n   * @methodOf ui.router.util.$resolve\n   *\n   * @description\n   * Resolves a set of invocables. An invocable is a function to be invoked via \n   * `$injector.invoke()`, and can have an arbitrary number of dependencies. \n   * An invocable can either return a value directly,\n   * or a `$q` promise. If a promise is returned it will be resolved and the \n   * resulting value will be used instead. Dependencies of invocables are resolved \n   * (in this order of precedence)\n   *\n   * - from the specified `locals`\n   * - from another invocable that is part of this `$resolve` call\n   * - from an invocable that is inherited from a `parent` call to `$resolve` \n   *   (or recursively\n   * - from any ancestor `$resolve` of that parent).\n   *\n   * The return value of `$resolve` is a promise for an object that contains \n   * (in this order of precedence)\n   *\n   * - any `locals` (if specified)\n   * - the resolved return values of all injectables\n   * - any values inherited from a `parent` call to `$resolve` (if specified)\n   *\n   * The promise will resolve after the `parent` promise (if any) and all promises \n   * returned by injectables have been resolved. If any invocable \n   * (or `$injector.invoke`) throws an exception, or if a promise returned by an \n   * invocable is rejected, the `$resolve` promise is immediately rejected with the \n   * same error. A rejection of a `parent` promise (if specified) will likewise be \n   * propagated immediately. Once the `$resolve` promise has been rejected, no \n   * further invocables will be called.\n   * \n   * Cyclic dependencies between invocables are not permitted and will caues `$resolve`\n   * to throw an error. As a special case, an injectable can depend on a parameter \n   * with the same name as the injectable, which will be fulfilled from the `parent` \n   * injectable of the same name. This allows inherited values to be decorated. \n   * Note that in this case any other injectable in the same `$resolve` with the same\n   * dependency would see the decorated value, not the inherited value.\n   *\n   * Note that missing dependencies -- unlike cyclic dependencies -- will cause an \n   * (asynchronous) rejection of the `$resolve` promise rather than a (synchronous) \n   * exception.\n   *\n   * Invocables are invoked eagerly as soon as all dependencies are available. \n   * This is true even for dependencies inherited from a `parent` call to `$resolve`.\n   *\n   * As a special case, an invocable can be a string, in which case it is taken to \n   * be a service name to be passed to `$injector.get()`. This is supported primarily \n   * for backwards-compatibility with the `resolve` property of `$routeProvider` \n   * routes.\n   *\n   * @param {object} invocables functions to invoke or \n   * `$injector` services to fetch.\n   * @param {object} locals  values to make available to the injectables\n   * @param {object} parent  a promise returned by another call to `$resolve`.\n   * @param {object} self  the `this` for the invoked methods\n   * @return {object} Promise for an object that contains the resolved return value\n   * of all invocables, as well as any inherited and local values.\n   */\n  this.resolve = function (invocables, locals, parent, self) {\n    return this.study(invocables)(locals, parent, self);\n  };\n}\n\nangular.module('ui.router.util').service('$resolve', $Resolve);\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$templateFactory\n *\n * @requires $http\n * @requires $templateCache\n * @requires $injector\n *\n * @description\n * Service. Manages loading of templates.\n */\n$TemplateFactory.$inject = ['$http', '$templateCache', '$injector'];\nfunction $TemplateFactory(  $http,   $templateCache,   $injector) {\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromConfig\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a configuration object. \n   *\n   * @param {object} config Configuration object for which to load a template. \n   * The following properties are search in the specified order, and the first one \n   * that is defined is used to create the template:\n   *\n   * @param {string|object} config.template html string template or function to \n   * load via {@link ui.router.util.$templateFactory#fromString fromString}.\n   * @param {string|object} config.templateUrl url to load or a function returning \n   * the url to load via {@link ui.router.util.$templateFactory#fromUrl fromUrl}.\n   * @param {Function} config.templateProvider function to invoke via \n   * {@link ui.router.util.$templateFactory#fromProvider fromProvider}.\n   * @param {object} params  Parameters to pass to the template function.\n   * @param {object} locals Locals to pass to `invoke` if the template is loaded \n   * via a `templateProvider`. Defaults to `{ params: params }`.\n   *\n   * @return {string|object}  The template html as a string, or a promise for \n   * that string,or `null` if no template is configured.\n   */\n  this.fromConfig = function (config, params, locals) {\n    return (\n      isDefined(config.template) ? this.fromString(config.template, params) :\n      isDefined(config.templateUrl) ? this.fromUrl(config.templateUrl, params) :\n      isDefined(config.templateProvider) ? this.fromProvider(config.templateProvider, params, locals) :\n      null\n    );\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromString\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template from a string or a function returning a string.\n   *\n   * @param {string|object} template html template as a string or function that \n   * returns an html template as a string.\n   * @param {object} params Parameters to pass to the template function.\n   *\n   * @return {string|object} The template html as a string, or a promise for that \n   * string.\n   */\n  this.fromString = function (template, params) {\n    return isFunction(template) ? template(params) : template;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromUrl\n   * @methodOf ui.router.util.$templateFactory\n   * \n   * @description\n   * Loads a template from the a URL via `$http` and `$templateCache`.\n   *\n   * @param {string|Function} url url of the template to load, or a function \n   * that returns a url.\n   * @param {Object} params Parameters to pass to the url function.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromUrl = function (url, params) {\n    if (isFunction(url)) url = url(params);\n    if (url == null) return null;\n    else return $http\n        .get(url, { cache: $templateCache, headers: { Accept: 'text/html' }})\n        .then(function(response) { return response.data; });\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$templateFactory#fromProvider\n   * @methodOf ui.router.util.$templateFactory\n   *\n   * @description\n   * Creates a template by invoking an injectable provider function.\n   *\n   * @param {Function} provider Function to invoke via `$injector.invoke`\n   * @param {Object} params Parameters for the template.\n   * @param {Object} locals Locals to pass to `invoke`. Defaults to \n   * `{ params: params }`.\n   * @return {string|Promise.<string>} The template html as a string, or a promise \n   * for that string.\n   */\n  this.fromProvider = function (provider, params, locals) {\n    return $injector.invoke(provider, null, locals || { params: params });\n  };\n}\n\nangular.module('ui.router.util').service('$templateFactory', $TemplateFactory);\n\nvar $$UMFP; // reference to $UrlMatcherFactoryProvider\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:UrlMatcher\n *\n * @description\n * Matches URLs against patterns and extracts named parameters from the path or the search\n * part of the URL. A URL pattern consists of a path pattern, optionally followed by '?' and a list\n * of search parameters. Multiple search parameter names are separated by '&'. Search parameters\n * do not influence whether or not a URL is matched, but their values are passed through into\n * the matched parameters returned by {@link ui.router.util.type:UrlMatcher#methods_exec exec}.\n *\n * Path parameter placeholders can be specified using simple colon/catch-all syntax or curly brace\n * syntax, which optionally allows a regular expression for the parameter to be specified:\n *\n * * `':'` name - colon placeholder\n * * `'*'` name - catch-all placeholder\n * * `'{' name '}'` - curly placeholder\n * * `'{' name ':' regexp|type '}'` - curly placeholder with regexp or type name. Should the\n *   regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.\n *\n * Parameter names may contain only word characters (latin letters, digits, and underscore) and\n * must be unique within the pattern (across both path and search parameters). For colon\n * placeholders or curly placeholders without an explicit regexp, a path parameter matches any\n * number of characters other than '/'. For catch-all placeholders the path parameter matches\n * any number of characters.\n *\n * Examples:\n *\n * * `'/hello/'` - Matches only if the path is exactly '/hello/'. There is no special treatment for\n *   trailing slashes, and patterns have to match the entire path, not just a prefix.\n * * `'/user/:id'` - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or\n *   '/user/bob/details'. The second path segment will be captured as the parameter 'id'.\n * * `'/user/{id}'` - Same as the previous example, but using curly brace syntax.\n * * `'/user/{id:[^/]*}'` - Same as the previous example.\n * * `'/user/{id:[0-9a-fA-F]{1,8}}'` - Similar to the previous example, but only matches if the id\n *   parameter consists of 1 to 8 hex digits.\n * * `'/files/{path:.*}'` - Matches any URL starting with '/files/' and captures the rest of the\n *   path into the parameter 'path'.\n * * `'/files/*path'` - ditto.\n * * `'/calendar/{start:date}'` - Matches \"/calendar/2014-11-12\" (because the pattern defined\n *   in the built-in  `date` Type matches `2014-11-12`) and provides a Date object in $stateParams.start\n *\n * @param {string} pattern  The pattern to compile into a matcher.\n * @param {Object} config  A configuration object hash:\n * @param {Object=} parentMatcher Used to concatenate the pattern/config onto\n *   an existing UrlMatcher\n *\n * * `caseInsensitive` - `true` if URL matching should be case insensitive, otherwise `false`, the default value (for backward compatibility) is `false`.\n * * `strict` - `false` if matching against a URL with a trailing slash should be treated as equivalent to a URL without a trailing slash, the default value is `true`.\n *\n * @property {string} prefix  A static prefix of this pattern. The matcher guarantees that any\n *   URL matching this matcher (i.e. any string for which {@link ui.router.util.type:UrlMatcher#methods_exec exec()} returns\n *   non-null) will start with this prefix.\n *\n * @property {string} source  The pattern that was passed into the constructor\n *\n * @property {string} sourcePath  The path portion of the source property\n *\n * @property {string} sourceSearch  The search portion of the source property\n *\n * @property {string} regex  The constructed regex that will be used to match against the url when\n *   it is time to determine which url will match.\n *\n * @returns {Object}  New `UrlMatcher` object\n */\nfunction UrlMatcher(pattern, config, parentMatcher) {\n  config = extend({ params: {} }, isObject(config) ? config : {});\n\n  // Find all placeholders and create a compiled pattern, using either classic or curly syntax:\n  //   '*' name\n  //   ':' name\n  //   '{' name '}'\n  //   '{' name ':' regexp '}'\n  // The regular expression is somewhat complicated due to the need to allow curly braces\n  // inside the regular expression. The placeholder regexp breaks down as follows:\n  //    ([:*])([\\w\\[\\]]+)              - classic placeholder ($1 / $2) (search version has - for snake-case)\n  //    \\{([\\w\\[\\]]+)(?:\\:( ... ))?\\}  - curly brace placeholder ($3) with optional regexp/type ... ($4) (search version has - for snake-case\n  //    (?: ... | ... | ... )+         - the regexp consists of any number of atoms, an atom being either\n  //    [^{}\\\\]+                       - anything other than curly braces or backslash\n  //    \\\\.                            - a backslash escape\n  //    \\{(?:[^{}\\\\]+|\\\\.)*\\}          - a matched set of curly braces containing other atoms\n  var placeholder       = /([:*])([\\w\\[\\]]+)|\\{([\\w\\[\\]]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      searchPlaceholder = /([:]?)([\\w\\[\\]-]+)|\\{([\\w\\[\\]-]+)(?:\\:((?:[^{}\\\\]+|\\\\.|\\{(?:[^{}\\\\]+|\\\\.)*\\})+))?\\}/g,\n      compiled = '^', last = 0, m,\n      segments = this.segments = [],\n      parentParams = parentMatcher ? parentMatcher.params : {},\n      params = this.params = parentMatcher ? parentMatcher.params.$$new() : new $$UMFP.ParamSet(),\n      paramNames = [];\n\n  function addParameter(id, type, config, location) {\n    paramNames.push(id);\n    if (parentParams[id]) return parentParams[id];\n    if (!/^\\w+(-+\\w+)*(?:\\[\\])?$/.test(id)) throw new Error(\"Invalid parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    if (params[id]) throw new Error(\"Duplicate parameter name '\" + id + \"' in pattern '\" + pattern + \"'\");\n    params[id] = new $$UMFP.Param(id, type, config, location);\n    return params[id];\n  }\n\n  function quoteRegExp(string, pattern, squash, optional) {\n    var surroundPattern = ['',''], result = string.replace(/[\\\\\\[\\]\\^$*+?.()|{}]/g, \"\\\\$&\");\n    if (!pattern) return result;\n    switch(squash) {\n      case false: surroundPattern = ['(', ')' + (optional ? \"?\" : \"\")]; break;\n      case true:  surroundPattern = ['?(', ')?']; break;\n      default:    surroundPattern = ['(' + squash + \"|\", ')?']; break;\n    }\n    return result + surroundPattern[0] + pattern + surroundPattern[1];\n  }\n\n  this.source = pattern;\n\n  // Split into static segments separated by path parameter placeholders.\n  // The number of segments is always 1 more than the number of parameters.\n  function matchDetails(m, isSearch) {\n    var id, regexp, segment, type, cfg, arrayMode;\n    id          = m[2] || m[3]; // IE[78] returns '' for unmatched groups instead of null\n    cfg         = config.params[id];\n    segment     = pattern.substring(last, m.index);\n    regexp      = isSearch ? m[4] : m[4] || (m[1] == '*' ? '.*' : null);\n    type        = $$UMFP.type(regexp || \"string\") || inherit($$UMFP.type(\"string\"), { pattern: new RegExp(regexp, config.caseInsensitive ? 'i' : undefined) });\n    return {\n      id: id, regexp: regexp, segment: segment, type: type, cfg: cfg\n    };\n  }\n\n  var p, param, segment;\n  while ((m = placeholder.exec(pattern))) {\n    p = matchDetails(m, false);\n    if (p.segment.indexOf('?') >= 0) break; // we're into the search part\n\n    param = addParameter(p.id, p.type, p.cfg, \"path\");\n    compiled += quoteRegExp(p.segment, param.type.pattern.source, param.squash, param.isOptional);\n    segments.push(p.segment);\n    last = placeholder.lastIndex;\n  }\n  segment = pattern.substring(last);\n\n  // Find any search parameter names and remove them from the last segment\n  var i = segment.indexOf('?');\n\n  if (i >= 0) {\n    var search = this.sourceSearch = segment.substring(i);\n    segment = segment.substring(0, i);\n    this.sourcePath = pattern.substring(0, last + i);\n\n    if (search.length > 0) {\n      last = 0;\n      while ((m = searchPlaceholder.exec(search))) {\n        p = matchDetails(m, true);\n        param = addParameter(p.id, p.type, p.cfg, \"search\");\n        last = placeholder.lastIndex;\n        // check if ?&\n      }\n    }\n  } else {\n    this.sourcePath = pattern;\n    this.sourceSearch = '';\n  }\n\n  compiled += quoteRegExp(segment) + (config.strict === false ? '\\/?' : '') + '$';\n  segments.push(segment);\n\n  this.regexp = new RegExp(compiled, config.caseInsensitive ? 'i' : undefined);\n  this.prefix = segments[0];\n  this.$$paramNames = paramNames;\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#concat\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns a new matcher for a pattern constructed by appending the path part and adding the\n * search parameters of the specified pattern to this pattern. The current pattern is not\n * modified. This can be understood as creating a pattern for URLs that are relative to (or\n * suffixes of) the current pattern.\n *\n * @example\n * The following two matchers are equivalent:\n * <pre>\n * new UrlMatcher('/user/{id}?q').concat('/details?date');\n * new UrlMatcher('/user/{id}/details?q&date');\n * </pre>\n *\n * @param {string} pattern  The pattern to append.\n * @param {Object} config  An object hash of the configuration for the matcher.\n * @returns {UrlMatcher}  A matcher for the concatenated pattern.\n */\nUrlMatcher.prototype.concat = function (pattern, config) {\n  // Because order of search parameters is irrelevant, we can add our own search\n  // parameters to the end of the new pattern. Parse the new pattern by itself\n  // and then join the bits together, but it's much easier to do this on a string level.\n  var defaultConfig = {\n    caseInsensitive: $$UMFP.caseInsensitive(),\n    strict: $$UMFP.strictMode(),\n    squash: $$UMFP.defaultSquashPolicy()\n  };\n  return new UrlMatcher(this.sourcePath + pattern + this.sourceSearch, extend(defaultConfig, config), this);\n};\n\nUrlMatcher.prototype.toString = function () {\n  return this.source;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#exec\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Tests the specified path against this matcher, and returns an object containing the captured\n * parameter values, or null if the path does not match. The returned object contains the values\n * of any search parameters that are mentioned in the pattern, but their value may be null if\n * they are not present in `searchParams`. This means that search parameters are always treated\n * as optional.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q&r').exec('/user/bob', {\n *   x: '1', q: 'hello'\n * });\n * // returns { id: 'bob', q: 'hello', r: null }\n * </pre>\n *\n * @param {string} path  The URL path to match, e.g. `$location.path()`.\n * @param {Object} searchParams  URL search parameters, e.g. `$location.search()`.\n * @returns {Object}  The captured parameter values.\n */\nUrlMatcher.prototype.exec = function (path, searchParams) {\n  var m = this.regexp.exec(path);\n  if (!m) return null;\n  searchParams = searchParams || {};\n\n  var paramNames = this.parameters(), nTotal = paramNames.length,\n    nPath = this.segments.length - 1,\n    values = {}, i, j, cfg, paramName;\n\n  if (nPath !== m.length - 1) throw new Error(\"Unbalanced capture group in route '\" + this.source + \"'\");\n\n  function decodePathArray(string) {\n    function reverseString(str) { return str.split(\"\").reverse().join(\"\"); }\n    function unquoteDashes(str) { return str.replace(/\\\\-/g, \"-\"); }\n\n    var split = reverseString(string).split(/-(?!\\\\)/);\n    var allReversed = map(split, reverseString);\n    return map(allReversed, unquoteDashes).reverse();\n  }\n\n  for (i = 0; i < nPath; i++) {\n    paramName = paramNames[i];\n    var param = this.params[paramName];\n    var paramVal = m[i+1];\n    // if the param value matches a pre-replace pair, replace the value before decoding.\n    for (j = 0; j < param.replace; j++) {\n      if (param.replace[j].from === paramVal) paramVal = param.replace[j].to;\n    }\n    if (paramVal && param.array === true) paramVal = decodePathArray(paramVal);\n    values[paramName] = param.value(paramVal);\n  }\n  for (/**/; i < nTotal; i++) {\n    paramName = paramNames[i];\n    values[paramName] = this.params[paramName].value(searchParams[paramName]);\n  }\n\n  return values;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#parameters\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Returns the names of all path and search parameters of this pattern in an unspecified order.\n *\n * @returns {Array.<string>}  An array of parameter names. Must be treated as read-only. If the\n *    pattern has no parameters, an empty array is returned.\n */\nUrlMatcher.prototype.parameters = function (param) {\n  if (!isDefined(param)) return this.$$paramNames;\n  return this.params[param] || null;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#validate\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Checks an object hash of parameters to validate their correctness according to the parameter\n * types of this `UrlMatcher`.\n *\n * @param {Object} params The object hash of parameters to validate.\n * @returns {boolean} Returns `true` if `params` validates, otherwise `false`.\n */\nUrlMatcher.prototype.validates = function (params) {\n  return this.params.$$validates(params);\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:UrlMatcher#format\n * @methodOf ui.router.util.type:UrlMatcher\n *\n * @description\n * Creates a URL that matches this pattern by substituting the specified values\n * for the path and search parameters. Null values for path parameters are\n * treated as empty strings.\n *\n * @example\n * <pre>\n * new UrlMatcher('/user/{id}?q').format({ id:'bob', q:'yes' });\n * // returns '/user/bob?q=yes'\n * </pre>\n *\n * @param {Object} values  the values to substitute for the parameters in this pattern.\n * @returns {string}  the formatted URL (path and optionally search part).\n */\nUrlMatcher.prototype.format = function (values) {\n  values = values || {};\n  var segments = this.segments, params = this.parameters(), paramset = this.params;\n  if (!this.validates(values)) return null;\n\n  var i, search = false, nPath = segments.length - 1, nTotal = params.length, result = segments[0];\n\n  function encodeDashes(str) { // Replace dashes with encoded \"\\-\"\n    return encodeURIComponent(str).replace(/-/g, function(c) { return '%5C%' + c.charCodeAt(0).toString(16).toUpperCase(); });\n  }\n\n  for (i = 0; i < nTotal; i++) {\n    var isPathParam = i < nPath;\n    var name = params[i], param = paramset[name], value = param.value(values[name]);\n    var isDefaultValue = param.isOptional && param.type.equals(param.value(), value);\n    var squash = isDefaultValue ? param.squash : false;\n    var encoded = param.type.encode(value);\n\n    if (isPathParam) {\n      var nextSegment = segments[i + 1];\n      if (squash === false) {\n        if (encoded != null) {\n          if (isArray(encoded)) {\n            result += map(encoded, encodeDashes).join(\"-\");\n          } else {\n            result += encodeURIComponent(encoded);\n          }\n        }\n        result += nextSegment;\n      } else if (squash === true) {\n        var capture = result.match(/\\/$/) ? /\\/?(.*)/ : /(.*)/;\n        result += nextSegment.match(capture)[1];\n      } else if (isString(squash)) {\n        result += squash + nextSegment;\n      }\n    } else {\n      if (encoded == null || (isDefaultValue && squash !== false)) continue;\n      if (!isArray(encoded)) encoded = [ encoded ];\n      encoded = map(encoded, encodeURIComponent).join('&' + name + '=');\n      result += (search ? '&' : '?') + (name + '=' + encoded);\n      search = true;\n    }\n  }\n\n  return result;\n};\n\n/**\n * @ngdoc object\n * @name ui.router.util.type:Type\n *\n * @description\n * Implements an interface to define custom parameter types that can be decoded from and encoded to\n * string parameters matched in a URL. Used by {@link ui.router.util.type:UrlMatcher `UrlMatcher`}\n * objects when matching or formatting URLs, or comparing or validating parameter values.\n *\n * See {@link ui.router.util.$urlMatcherFactory#methods_type `$urlMatcherFactory#type()`} for more\n * information on registering custom types.\n *\n * @param {Object} config  A configuration object which contains the custom type definition.  The object's\n *        properties will override the default methods and/or pattern in `Type`'s public interface.\n * @example\n * <pre>\n * {\n *   decode: function(val) { return parseInt(val, 10); },\n *   encode: function(val) { return val && val.toString(); },\n *   equals: function(a, b) { return this.is(a) && a === b; },\n *   is: function(val) { return angular.isNumber(val) isFinite(val) && val % 1 === 0; },\n *   pattern: /\\d+/\n * }\n * </pre>\n *\n * @property {RegExp} pattern The regular expression pattern used to match values of this type when\n *           coming from a substring of a URL.\n *\n * @returns {Object}  Returns a new `Type` object.\n */\nfunction Type(config) {\n  extend(this, config);\n}\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#is\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Detects whether a value is of a particular type. Accepts a native (decoded) value\n * and determines whether it matches the current `Type` object.\n *\n * @param {*} val  The value to check.\n * @param {string} key  Optional. If the type check is happening in the context of a specific\n *        {@link ui.router.util.type:UrlMatcher `UrlMatcher`} object, this is the name of the\n *        parameter in which `val` is stored. Can be used for meta-programming of `Type` objects.\n * @returns {Boolean}  Returns `true` if the value matches the type, otherwise `false`.\n */\nType.prototype.is = function(val, key) {\n  return true;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#encode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Encodes a custom/native type value to a string that can be embedded in a URL. Note that the\n * return value does *not* need to be URL-safe (i.e. passed through `encodeURIComponent()`), it\n * only needs to be a representation of `val` that has been coerced to a string.\n *\n * @param {*} val  The value to encode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {string}  Returns a string representation of `val` that can be encoded in a URL.\n */\nType.prototype.encode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#decode\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Converts a parameter value (from URL string or transition param) to a custom/native value.\n *\n * @param {string} val  The URL parameter value to decode.\n * @param {string} key  The name of the parameter in which `val` is stored. Can be used for\n *        meta-programming of `Type` objects.\n * @returns {*}  Returns a custom representation of the URL parameter value.\n */\nType.prototype.decode = function(val, key) {\n  return val;\n};\n\n/**\n * @ngdoc function\n * @name ui.router.util.type:Type#equals\n * @methodOf ui.router.util.type:Type\n *\n * @description\n * Determines whether two decoded values are equivalent.\n *\n * @param {*} a  A value to compare against.\n * @param {*} b  A value to compare against.\n * @returns {Boolean}  Returns `true` if the values are equivalent/equal, otherwise `false`.\n */\nType.prototype.equals = function(a, b) {\n  return a == b;\n};\n\nType.prototype.$subPattern = function() {\n  var sub = this.pattern.toString();\n  return sub.substr(1, sub.length - 2);\n};\n\nType.prototype.pattern = /.*/;\n\nType.prototype.toString = function() { return \"{Type:\" + this.name + \"}\"; };\n\n/** Given an encoded string, or a decoded object, returns a decoded object */\nType.prototype.$normalize = function(val) {\n  return this.is(val) ? val : this.decode(val);\n};\n\n/*\n * Wraps an existing custom Type as an array of Type, depending on 'mode'.\n * e.g.:\n * - urlmatcher pattern \"/path?{queryParam[]:int}\"\n * - url: \"/path?queryParam=1&queryParam=2\n * - $stateParams.queryParam will be [1, 2]\n * if `mode` is \"auto\", then\n * - url: \"/path?queryParam=1 will create $stateParams.queryParam: 1\n * - url: \"/path?queryParam=1&queryParam=2 will create $stateParams.queryParam: [1, 2]\n */\nType.prototype.$asArray = function(mode, isSearch) {\n  if (!mode) return this;\n  if (mode === \"auto\" && !isSearch) throw new Error(\"'auto' array mode is for query parameters only\");\n\n  function ArrayType(type, mode) {\n    function bindTo(type, callbackName) {\n      return function() {\n        return type[callbackName].apply(type, arguments);\n      };\n    }\n\n    // Wrap non-array value as array\n    function arrayWrap(val) { return isArray(val) ? val : (isDefined(val) ? [ val ] : []); }\n    // Unwrap array value for \"auto\" mode. Return undefined for empty array.\n    function arrayUnwrap(val) {\n      switch(val.length) {\n        case 0: return undefined;\n        case 1: return mode === \"auto\" ? val[0] : val;\n        default: return val;\n      }\n    }\n    function falsey(val) { return !val; }\n\n    // Wraps type (.is/.encode/.decode) functions to operate on each value of an array\n    function arrayHandler(callback, allTruthyMode) {\n      return function handleArray(val) {\n        val = arrayWrap(val);\n        var result = map(val, callback);\n        if (allTruthyMode === true)\n          return filter(result, falsey).length === 0;\n        return arrayUnwrap(result);\n      };\n    }\n\n    // Wraps type (.equals) functions to operate on each value of an array\n    function arrayEqualsHandler(callback) {\n      return function handleArray(val1, val2) {\n        var left = arrayWrap(val1), right = arrayWrap(val2);\n        if (left.length !== right.length) return false;\n        for (var i = 0; i < left.length; i++) {\n          if (!callback(left[i], right[i])) return false;\n        }\n        return true;\n      };\n    }\n\n    this.encode = arrayHandler(bindTo(type, 'encode'));\n    this.decode = arrayHandler(bindTo(type, 'decode'));\n    this.is     = arrayHandler(bindTo(type, 'is'), true);\n    this.equals = arrayEqualsHandler(bindTo(type, 'equals'));\n    this.pattern = type.pattern;\n    this.$normalize = arrayHandler(bindTo(type, '$normalize'));\n    this.name = type.name;\n    this.$arrayMode = mode;\n  }\n\n  return new ArrayType(this, mode);\n};\n\n\n\n/**\n * @ngdoc object\n * @name ui.router.util.$urlMatcherFactory\n *\n * @description\n * Factory for {@link ui.router.util.type:UrlMatcher `UrlMatcher`} instances. The factory\n * is also available to providers under the name `$urlMatcherFactoryProvider`.\n */\nfunction $UrlMatcherFactory() {\n  $$UMFP = this;\n\n  var isCaseInsensitive = false, isStrictMode = true, defaultSquashPolicy = false;\n\n  function valToString(val) { return val != null ? val.toString().replace(/\\//g, \"%2F\") : val; }\n  function valFromString(val) { return val != null ? val.toString().replace(/%2F/g, \"/\") : val; }\n\n  var $types = {}, enqueue = true, typeQueue = [], injector, defaultTypes = {\n    string: {\n      encode: valToString,\n      decode: valFromString,\n      // TODO: in 1.0, make string .is() return false if value is undefined/null by default.\n      // In 0.2.x, string params are optional by default for backwards compat\n      is: function(val) { return val == null || !isDefined(val) || typeof val === \"string\"; },\n      pattern: /[^/]*/\n    },\n    int: {\n      encode: valToString,\n      decode: function(val) { return parseInt(val, 10); },\n      is: function(val) { return isDefined(val) && this.decode(val.toString()) === val; },\n      pattern: /\\d+/\n    },\n    bool: {\n      encode: function(val) { return val ? 1 : 0; },\n      decode: function(val) { return parseInt(val, 10) !== 0; },\n      is: function(val) { return val === true || val === false; },\n      pattern: /0|1/\n    },\n    date: {\n      encode: function (val) {\n        if (!this.is(val))\n          return undefined;\n        return [ val.getFullYear(),\n          ('0' + (val.getMonth() + 1)).slice(-2),\n          ('0' + val.getDate()).slice(-2)\n        ].join(\"-\");\n      },\n      decode: function (val) {\n        if (this.is(val)) return val;\n        var match = this.capture.exec(val);\n        return match ? new Date(match[1], match[2] - 1, match[3]) : undefined;\n      },\n      is: function(val) { return val instanceof Date && !isNaN(val.valueOf()); },\n      equals: function (a, b) { return this.is(a) && this.is(b) && a.toISOString() === b.toISOString(); },\n      pattern: /[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1])/,\n      capture: /([0-9]{4})-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/\n    },\n    json: {\n      encode: angular.toJson,\n      decode: angular.fromJson,\n      is: angular.isObject,\n      equals: angular.equals,\n      pattern: /[^/]*/\n    },\n    any: { // does not encode/decode\n      encode: angular.identity,\n      decode: angular.identity,\n      equals: angular.equals,\n      pattern: /.*/\n    }\n  };\n\n  function getDefaultConfig() {\n    return {\n      strict: isStrictMode,\n      caseInsensitive: isCaseInsensitive\n    };\n  }\n\n  function isInjectable(value) {\n    return (isFunction(value) || (isArray(value) && isFunction(value[value.length - 1])));\n  }\n\n  /**\n   * [Internal] Get the default value of a parameter, which may be an injectable function.\n   */\n  $UrlMatcherFactory.$$getDefaultValue = function(config) {\n    if (!isInjectable(config.value)) return config.value;\n    if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n    return injector.invoke(config.value);\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#caseInsensitive\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URL matching should be case sensitive (the default behavior), or not.\n   *\n   * @param {boolean} value `false` to match URL in a case sensitive manner; otherwise `true`;\n   * @returns {boolean} the current value of caseInsensitive\n   */\n  this.caseInsensitive = function(value) {\n    if (isDefined(value))\n      isCaseInsensitive = value;\n    return isCaseInsensitive;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#strictMode\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Defines whether URLs should match trailing slashes, or not (the default behavior).\n   *\n   * @param {boolean=} value `false` to match trailing slashes in URLs, otherwise `true`.\n   * @returns {boolean} the current value of strictMode\n   */\n  this.strictMode = function(value) {\n    if (isDefined(value))\n      isStrictMode = value;\n    return isStrictMode;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#defaultSquashPolicy\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Sets the default behavior when generating or matching URLs with default parameter values.\n   *\n   * @param {string} value A string that defines the default parameter URL squashing behavior.\n   *    `nosquash`: When generating an href with a default parameter value, do not squash the parameter value from the URL\n   *    `slash`: When generating an href with a default parameter value, squash (remove) the parameter value, and, if the\n   *             parameter is surrounded by slashes, squash (remove) one slash from the URL\n   *    any other string, e.g. \"~\": When generating an href with a default parameter value, squash (remove)\n   *             the parameter value from the URL and replace it with this string.\n   */\n  this.defaultSquashPolicy = function(value) {\n    if (!isDefined(value)) return defaultSquashPolicy;\n    if (value !== true && value !== false && !isString(value))\n      throw new Error(\"Invalid squash policy: \" + value + \". Valid policies: false, true, arbitrary-string\");\n    defaultSquashPolicy = value;\n    return value;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#compile\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Creates a {@link ui.router.util.type:UrlMatcher `UrlMatcher`} for the specified pattern.\n   *\n   * @param {string} pattern  The URL pattern.\n   * @param {Object} config  The config object hash.\n   * @returns {UrlMatcher}  The UrlMatcher.\n   */\n  this.compile = function (pattern, config) {\n    return new UrlMatcher(pattern, extend(getDefaultConfig(), config));\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#isMatcher\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Returns true if the specified object is a `UrlMatcher`, or false otherwise.\n   *\n   * @param {Object} object  The object to perform the type check against.\n   * @returns {Boolean}  Returns `true` if the object matches the `UrlMatcher` interface, by\n   *          implementing all the same methods.\n   */\n  this.isMatcher = function (o) {\n    if (!isObject(o)) return false;\n    var result = true;\n\n    forEach(UrlMatcher.prototype, function(val, name) {\n      if (isFunction(val)) {\n        result = result && (isDefined(o[name]) && isFunction(o[name]));\n      }\n    });\n    return result;\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.util.$urlMatcherFactory#type\n   * @methodOf ui.router.util.$urlMatcherFactory\n   *\n   * @description\n   * Registers a custom {@link ui.router.util.type:Type `Type`} object that can be used to\n   * generate URLs with typed parameters.\n   *\n   * @param {string} name  The type name.\n   * @param {Object|Function} definition   The type definition. See\n   *        {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   * @param {Object|Function} definitionFn (optional) A function that is injected before the app\n   *        runtime starts.  The result of this function is merged into the existing `definition`.\n   *        See {@link ui.router.util.type:Type `Type`} for information on the values accepted.\n   *\n   * @returns {Object}  Returns `$urlMatcherFactoryProvider`.\n   *\n   * @example\n   * This is a simple example of a custom type that encodes and decodes items from an\n   * array, using the array index as the URL-encoded value:\n   *\n   * <pre>\n   * var list = ['John', 'Paul', 'George', 'Ringo'];\n   *\n   * $urlMatcherFactoryProvider.type('listItem', {\n   *   encode: function(item) {\n   *     // Represent the list item in the URL using its corresponding index\n   *     return list.indexOf(item);\n   *   },\n   *   decode: function(item) {\n   *     // Look up the list item by index\n   *     return list[parseInt(item, 10)];\n   *   },\n   *   is: function(item) {\n   *     // Ensure the item is valid by checking to see that it appears\n   *     // in the list\n   *     return list.indexOf(item) > -1;\n   *   }\n   * });\n   *\n   * $stateProvider.state('list', {\n   *   url: \"/list/{item:listItem}\",\n   *   controller: function($scope, $stateParams) {\n   *     console.log($stateParams.item);\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * // Changes URL to '/list/3', logs \"Ringo\" to the console\n   * $state.go('list', { item: \"Ringo\" });\n   * </pre>\n   *\n   * This is a more complex example of a type that relies on dependency injection to\n   * interact with services, and uses the parameter name from the URL to infer how to\n   * handle encoding and decoding parameter values:\n   *\n   * <pre>\n   * // Defines a custom type that gets a value from a service,\n   * // where each service gets different types of values from\n   * // a backend API:\n   * $urlMatcherFactoryProvider.type('dbObject', {}, function(Users, Posts) {\n   *\n   *   // Matches up services to URL parameter names\n   *   var services = {\n   *     user: Users,\n   *     post: Posts\n   *   };\n   *\n   *   return {\n   *     encode: function(object) {\n   *       // Represent the object in the URL using its unique ID\n   *       return object.id;\n   *     },\n   *     decode: function(value, key) {\n   *       // Look up the object by ID, using the parameter\n   *       // name (key) to call the correct service\n   *       return services[key].findById(value);\n   *     },\n   *     is: function(object, key) {\n   *       // Check that object is a valid dbObject\n   *       return angular.isObject(object) && object.id && services[key];\n   *     }\n   *     equals: function(a, b) {\n   *       // Check the equality of decoded objects by comparing\n   *       // their unique IDs\n   *       return a.id === b.id;\n   *     }\n   *   };\n   * });\n   *\n   * // In a config() block, you can then attach URLs with\n   * // type-annotated parameters:\n   * $stateProvider.state('users', {\n   *   url: \"/users\",\n   *   // ...\n   * }).state('users.item', {\n   *   url: \"/{user:dbObject}\",\n   *   controller: function($scope, $stateParams) {\n   *     // $stateParams.user will now be an object returned from\n   *     // the Users service\n   *   },\n   *   // ...\n   * });\n   * </pre>\n   */\n  this.type = function (name, definition, definitionFn) {\n    if (!isDefined(definition)) return $types[name];\n    if ($types.hasOwnProperty(name)) throw new Error(\"A type named '\" + name + \"' has already been defined.\");\n\n    $types[name] = new Type(extend({ name: name }, definition));\n    if (definitionFn) {\n      typeQueue.push({ name: name, def: definitionFn });\n      if (!enqueue) flushTypeQueue();\n    }\n    return this;\n  };\n\n  // `flushTypeQueue()` waits until `$urlMatcherFactory` is injected before invoking the queued `definitionFn`s\n  function flushTypeQueue() {\n    while(typeQueue.length) {\n      var type = typeQueue.shift();\n      if (type.pattern) throw new Error(\"You cannot override a type's .pattern at runtime.\");\n      angular.extend($types[type.name], injector.invoke(type.def));\n    }\n  }\n\n  // Register default types. Store them in the prototype of $types.\n  forEach(defaultTypes, function(type, name) { $types[name] = new Type(extend({name: name}, type)); });\n  $types = inherit($types, {});\n\n  /* No need to document $get, since it returns this */\n  this.$get = ['$injector', function ($injector) {\n    injector = $injector;\n    enqueue = false;\n    flushTypeQueue();\n\n    forEach(defaultTypes, function(type, name) {\n      if (!$types[name]) $types[name] = new Type(type);\n    });\n    return this;\n  }];\n\n  this.Param = function Param(id, type, config, location) {\n    var self = this;\n    config = unwrapShorthand(config);\n    type = getType(config, type, location);\n    var arrayMode = getArrayMode();\n    type = arrayMode ? type.$asArray(arrayMode, location === \"search\") : type;\n    if (type.name === \"string\" && !arrayMode && location === \"path\" && config.value === undefined)\n      config.value = \"\"; // for 0.2.x; in 0.3.0+ do not automatically default to \"\"\n    var isOptional = config.value !== undefined;\n    var squash = getSquashPolicy(config, isOptional);\n    var replace = getReplace(config, arrayMode, isOptional, squash);\n\n    function unwrapShorthand(config) {\n      var keys = isObject(config) ? objectKeys(config) : [];\n      var isShorthand = indexOf(keys, \"value\") === -1 && indexOf(keys, \"type\") === -1 &&\n                        indexOf(keys, \"squash\") === -1 && indexOf(keys, \"array\") === -1;\n      if (isShorthand) config = { value: config };\n      config.$$fn = isInjectable(config.value) ? config.value : function () { return config.value; };\n      return config;\n    }\n\n    function getType(config, urlType, location) {\n      if (config.type && urlType) throw new Error(\"Param '\"+id+\"' has two type configurations.\");\n      if (urlType) return urlType;\n      if (!config.type) return (location === \"config\" ? $types.any : $types.string);\n      return config.type instanceof Type ? config.type : new Type(config.type);\n    }\n\n    // array config: param name (param[]) overrides default settings.  explicit config overrides param name.\n    function getArrayMode() {\n      var arrayDefaults = { array: (location === \"search\" ? \"auto\" : false) };\n      var arrayParamNomenclature = id.match(/\\[\\]$/) ? { array: true } : {};\n      return extend(arrayDefaults, arrayParamNomenclature, config).array;\n    }\n\n    /**\n     * returns false, true, or the squash value to indicate the \"default parameter url squash policy\".\n     */\n    function getSquashPolicy(config, isOptional) {\n      var squash = config.squash;\n      if (!isOptional || squash === false) return false;\n      if (!isDefined(squash) || squash == null) return defaultSquashPolicy;\n      if (squash === true || isString(squash)) return squash;\n      throw new Error(\"Invalid squash policy: '\" + squash + \"'. Valid policies: false, true, or arbitrary string\");\n    }\n\n    function getReplace(config, arrayMode, isOptional, squash) {\n      var replace, configuredKeys, defaultPolicy = [\n        { from: \"\",   to: (isOptional || arrayMode ? undefined : \"\") },\n        { from: null, to: (isOptional || arrayMode ? undefined : \"\") }\n      ];\n      replace = isArray(config.replace) ? config.replace : [];\n      if (isString(squash))\n        replace.push({ from: squash, to: undefined });\n      configuredKeys = map(replace, function(item) { return item.from; } );\n      return filter(defaultPolicy, function(item) { return indexOf(configuredKeys, item.from) === -1; }).concat(replace);\n    }\n\n    /**\n     * [Internal] Get the default value of a parameter, which may be an injectable function.\n     */\n    function $$getDefaultValue() {\n      if (!injector) throw new Error(\"Injectable functions cannot be called at configuration time\");\n      var defaultValue = injector.invoke(config.$$fn);\n      if (defaultValue !== null && defaultValue !== undefined && !self.type.is(defaultValue))\n        throw new Error(\"Default value (\" + defaultValue + \") for parameter '\" + self.id + \"' is not an instance of Type (\" + self.type.name + \")\");\n      return defaultValue;\n    }\n\n    /**\n     * [Internal] Gets the decoded representation of a value if the value is defined, otherwise, returns the\n     * default value, which may be the result of an injectable function.\n     */\n    function $value(value) {\n      function hasReplaceVal(val) { return function(obj) { return obj.from === val; }; }\n      function $replace(value) {\n        var replacement = map(filter(self.replace, hasReplaceVal(value)), function(obj) { return obj.to; });\n        return replacement.length ? replacement[0] : value;\n      }\n      value = $replace(value);\n      return !isDefined(value) ? $$getDefaultValue() : self.type.$normalize(value);\n    }\n\n    function toString() { return \"{Param:\" + id + \" \" + type + \" squash: '\" + squash + \"' optional: \" + isOptional + \"}\"; }\n\n    extend(this, {\n      id: id,\n      type: type,\n      location: location,\n      array: arrayMode,\n      squash: squash,\n      replace: replace,\n      isOptional: isOptional,\n      value: $value,\n      dynamic: undefined,\n      config: config,\n      toString: toString\n    });\n  };\n\n  function ParamSet(params) {\n    extend(this, params || {});\n  }\n\n  ParamSet.prototype = {\n    $$new: function() {\n      return inherit(this, extend(new ParamSet(), { $$parent: this}));\n    },\n    $$keys: function () {\n      var keys = [], chain = [], parent = this,\n        ignore = objectKeys(ParamSet.prototype);\n      while (parent) { chain.push(parent); parent = parent.$$parent; }\n      chain.reverse();\n      forEach(chain, function(paramset) {\n        forEach(objectKeys(paramset), function(key) {\n            if (indexOf(keys, key) === -1 && indexOf(ignore, key) === -1) keys.push(key);\n        });\n      });\n      return keys;\n    },\n    $$values: function(paramValues) {\n      var values = {}, self = this;\n      forEach(self.$$keys(), function(key) {\n        values[key] = self[key].value(paramValues && paramValues[key]);\n      });\n      return values;\n    },\n    $$equals: function(paramValues1, paramValues2) {\n      var equal = true, self = this;\n      forEach(self.$$keys(), function(key) {\n        var left = paramValues1 && paramValues1[key], right = paramValues2 && paramValues2[key];\n        if (!self[key].type.equals(left, right)) equal = false;\n      });\n      return equal;\n    },\n    $$validates: function $$validate(paramValues) {\n      var keys = this.$$keys(), i, param, rawVal, normalized, encoded;\n      for (i = 0; i < keys.length; i++) {\n        param = this[keys[i]];\n        rawVal = paramValues[keys[i]];\n        if ((rawVal === undefined || rawVal === null) && param.isOptional)\n          break; // There was no parameter value, but the param is optional\n        normalized = param.type.$normalize(rawVal);\n        if (!param.type.is(normalized))\n          return false; // The value was not of the correct Type, and could not be decoded to the correct Type\n        encoded = param.type.encode(normalized);\n        if (angular.isString(encoded) && !param.type.pattern.exec(encoded))\n          return false; // The value was of the correct type, but when encoded, did not match the Type's regexp\n      }\n      return true;\n    },\n    $$parent: undefined\n  };\n\n  this.ParamSet = ParamSet;\n}\n\n// Register as a provider so it's available to other providers\nangular.module('ui.router.util').provider('$urlMatcherFactory', $UrlMatcherFactory);\nangular.module('ui.router.util').run(['$urlMatcherFactory', function($urlMatcherFactory) { }]);\n\n/**\n * @ngdoc object\n * @name ui.router.router.$urlRouterProvider\n *\n * @requires ui.router.util.$urlMatcherFactoryProvider\n * @requires $locationProvider\n *\n * @description\n * `$urlRouterProvider` has the responsibility of watching `$location`. \n * When `$location` changes it runs through a list of rules one by one until a \n * match is found. `$urlRouterProvider` is used behind the scenes anytime you specify \n * a url in a state configuration. All urls are compiled into a UrlMatcher object.\n *\n * There are several methods on `$urlRouterProvider` that make it useful to use directly\n * in your module config.\n */\n$UrlRouterProvider.$inject = ['$locationProvider', '$urlMatcherFactoryProvider'];\nfunction $UrlRouterProvider(   $locationProvider,   $urlMatcherFactory) {\n  var rules = [], otherwise = null, interceptDeferred = false, listener;\n\n  // Returns a string that is a prefix of all strings matching the RegExp\n  function regExpPrefix(re) {\n    var prefix = /^\\^((?:\\\\[^a-zA-Z0-9]|[^\\\\\\[\\]\\^$*+?.()|{}]+)*)/.exec(re.source);\n    return (prefix != null) ? prefix[1].replace(/\\\\(.)/g, \"$1\") : '';\n  }\n\n  // Interpolates matched values into a String.replace()-style pattern\n  function interpolate(pattern, match) {\n    return pattern.replace(/\\$(\\$|\\d{1,2})/, function (m, what) {\n      return match[what === '$' ? 0 : Number(what)];\n    });\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#rule\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines rules that are used by `$urlRouterProvider` to find matches for\n   * specific URLs.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // Here's an example of how you might allow case insensitive urls\n   *   $urlRouterProvider.rule(function ($injector, $location) {\n   *     var path = $location.path(),\n   *         normalized = path.toLowerCase();\n   *\n   *     if (path !== normalized) {\n   *       return normalized;\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {object} rule Handler function that takes `$injector` and `$location`\n   * services as arguments. You can use them to return a valid path as a string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.rule = function (rule) {\n    if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    rules.push(rule);\n    return this;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouterProvider#otherwise\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Defines a path that is used when an invalid route is requested.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   // if the path doesn't match any of the urls you configured\n   *   // otherwise will take care of routing the user to the\n   *   // specified url\n   *   $urlRouterProvider.otherwise('/index');\n   *\n   *   // Example of using function rule as param\n   *   $urlRouterProvider.otherwise(function ($injector, $location) {\n   *     return '/a/valid/url';\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} rule The url path you want to redirect to or a function \n   * rule that returns the url path. The function version is passed two params: \n   * `$injector` and `$location` services, and must return a url string.\n   *\n   * @return {object} `$urlRouterProvider` - `$urlRouterProvider` instance\n   */\n  this.otherwise = function (rule) {\n    if (isString(rule)) {\n      var redirect = rule;\n      rule = function () { return redirect; };\n    }\n    else if (!isFunction(rule)) throw new Error(\"'rule' must be a function\");\n    otherwise = rule;\n    return this;\n  };\n\n\n  function handleIfMatch($injector, handler, match) {\n    if (!match) return false;\n    var result = $injector.invoke(handler, handler, { $match: match });\n    return isDefined(result) ? result : true;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#when\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Registers a handler for a given url matching. if handle is a string, it is\n   * treated as a redirect, and is interpolated according to the syntax of match\n   * (i.e. like `String.replace()` for `RegExp`, or like a `UrlMatcher` pattern otherwise).\n   *\n   * If the handler is a function, it is injectable. It gets invoked if `$location`\n   * matches. You have the option of inject the match object as `$match`.\n   *\n   * The handler can return\n   *\n   * - **falsy** to indicate that the rule didn't match after all, then `$urlRouter`\n   *   will continue trying to find another one that matches.\n   * - **string** which is treated as a redirect and passed to `$location.url()`\n   * - **void** or any **truthy** value tells `$urlRouter` that the url was handled.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *   $urlRouterProvider.when($state.url, function ($match, $stateParams) {\n   *     if ($state.$current.navigable !== state ||\n   *         !equalForKeys($match, $stateParams) {\n   *      $state.transitionTo(state, $match, false);\n   *     }\n   *   });\n   * });\n   * </pre>\n   *\n   * @param {string|object} what The incoming path that you want to redirect.\n   * @param {string|object} handler The path you want to redirect your user to.\n   */\n  this.when = function (what, handler) {\n    var redirect, handlerIsString = isString(handler);\n    if (isString(what)) what = $urlMatcherFactory.compile(what);\n\n    if (!handlerIsString && !isFunction(handler) && !isArray(handler))\n      throw new Error(\"invalid 'handler' in when()\");\n\n    var strategies = {\n      matcher: function (what, handler) {\n        if (handlerIsString) {\n          redirect = $urlMatcherFactory.compile(handler);\n          handler = ['$match', function ($match) { return redirect.format($match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path(), $location.search()));\n        }, {\n          prefix: isString(what.prefix) ? what.prefix : ''\n        });\n      },\n      regex: function (what, handler) {\n        if (what.global || what.sticky) throw new Error(\"when() RegExp must not be global or sticky\");\n\n        if (handlerIsString) {\n          redirect = handler;\n          handler = ['$match', function ($match) { return interpolate(redirect, $match); }];\n        }\n        return extend(function ($injector, $location) {\n          return handleIfMatch($injector, handler, what.exec($location.path()));\n        }, {\n          prefix: regExpPrefix(what)\n        });\n      }\n    };\n\n    var check = { matcher: $urlMatcherFactory.isMatcher(what), regex: what instanceof RegExp };\n\n    for (var n in check) {\n      if (check[n]) return this.rule(strategies[n](what, handler));\n    }\n\n    throw new Error(\"invalid 'what' in when()\");\n  };\n\n  /**\n   * @ngdoc function\n   * @name ui.router.router.$urlRouterProvider#deferIntercept\n   * @methodOf ui.router.router.$urlRouterProvider\n   *\n   * @description\n   * Disables (or enables) deferring location change interception.\n   *\n   * If you wish to customize the behavior of syncing the URL (for example, if you wish to\n   * defer a transition but maintain the current URL), call this method at configuration time.\n   * Then, at run time, call `$urlRouter.listen()` after you have configured your own\n   * `$locationChangeSuccess` event handler.\n   *\n   * @example\n   * <pre>\n   * var app = angular.module('app', ['ui.router.router']);\n   *\n   * app.config(function ($urlRouterProvider) {\n   *\n   *   // Prevent $urlRouter from automatically intercepting URL changes;\n   *   // this allows you to configure custom behavior in between\n   *   // location changes and route synchronization:\n   *   $urlRouterProvider.deferIntercept();\n   *\n   * }).run(function ($rootScope, $urlRouter, UserService) {\n   *\n   *   $rootScope.$on('$locationChangeSuccess', function(e) {\n   *     // UserService is an example service for managing user state\n   *     if (UserService.isLoggedIn()) return;\n   *\n   *     // Prevent $urlRouter's default handler from firing\n   *     e.preventDefault();\n   *\n   *     UserService.handleLogin().then(function() {\n   *       // Once the user has logged in, sync the current URL\n   *       // to the router:\n   *       $urlRouter.sync();\n   *     });\n   *   });\n   *\n   *   // Configures $urlRouter's listener *after* your custom listener\n   *   $urlRouter.listen();\n   * });\n   * </pre>\n   *\n   * @param {boolean} defer Indicates whether to defer location change interception. Passing\n            no parameter is equivalent to `true`.\n   */\n  this.deferIntercept = function (defer) {\n    if (defer === undefined) defer = true;\n    interceptDeferred = defer;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.router.$urlRouter\n   *\n   * @requires $location\n   * @requires $rootScope\n   * @requires $injector\n   * @requires $browser\n   *\n   * @description\n   *\n   */\n  this.$get = $get;\n  $get.$inject = ['$location', '$rootScope', '$injector', '$browser'];\n  function $get(   $location,   $rootScope,   $injector,   $browser) {\n\n    var baseHref = $browser.baseHref(), location = $location.url(), lastPushedUrl;\n\n    function appendBasePath(url, isHtml5, absolute) {\n      if (baseHref === '/') return url;\n      if (isHtml5) return baseHref.slice(0, -1) + url;\n      if (absolute) return baseHref.slice(1) + url;\n      return url;\n    }\n\n    // TODO: Optimize groups of rules with non-empty prefix into some sort of decision tree\n    function update(evt) {\n      if (evt && evt.defaultPrevented) return;\n      var ignoreUpdate = lastPushedUrl && $location.url() === lastPushedUrl;\n      lastPushedUrl = undefined;\n      // TODO: Re-implement this in 1.0 for https://github.com/angular-ui/ui-router/issues/1573\n      //if (ignoreUpdate) return true;\n\n      function check(rule) {\n        var handled = rule($injector, $location);\n\n        if (!handled) return false;\n        if (isString(handled)) $location.replace().url(handled);\n        return true;\n      }\n      var n = rules.length, i;\n\n      for (i = 0; i < n; i++) {\n        if (check(rules[i])) return;\n      }\n      // always check otherwise last to allow dynamic updates to the set of rules\n      if (otherwise) check(otherwise);\n    }\n\n    function listen() {\n      listener = listener || $rootScope.$on('$locationChangeSuccess', update);\n      return listener;\n    }\n\n    if (!interceptDeferred) listen();\n\n    return {\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#sync\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * Triggers an update; the same update that happens when the address bar url changes, aka `$locationChangeSuccess`.\n       * This method is useful when you need to use `preventDefault()` on the `$locationChangeSuccess` event,\n       * perform some custom logic (route protection, auth, config, redirection, etc) and then finally proceed\n       * with the transition by calling `$urlRouter.sync()`.\n       *\n       * @example\n       * <pre>\n       * angular.module('app', ['ui.router'])\n       *   .run(function($rootScope, $urlRouter) {\n       *     $rootScope.$on('$locationChangeSuccess', function(evt) {\n       *       // Halt state change from even starting\n       *       evt.preventDefault();\n       *       // Perform custom logic\n       *       var meetsRequirement = ...\n       *       // Continue with the update and state transition if logic allows\n       *       if (meetsRequirement) $urlRouter.sync();\n       *     });\n       * });\n       * </pre>\n       */\n      sync: function() {\n        update();\n      },\n\n      listen: function() {\n        return listen();\n      },\n\n      update: function(read) {\n        if (read) {\n          location = $location.url();\n          return;\n        }\n        if ($location.url() === location) return;\n\n        $location.url(location);\n        $location.replace();\n      },\n\n      push: function(urlMatcher, params, options) {\n         var url = urlMatcher.format(params || {});\n\n        // Handle the special hash param, if needed\n        if (url !== null && params && params['#']) {\n            url += '#' + params['#'];\n        }\n\n        $location.url(url);\n        lastPushedUrl = options && options.$$avoidResync ? $location.url() : undefined;\n        if (options && options.replace) $location.replace();\n      },\n\n      /**\n       * @ngdoc function\n       * @name ui.router.router.$urlRouter#href\n       * @methodOf ui.router.router.$urlRouter\n       *\n       * @description\n       * A URL generation method that returns the compiled URL for a given\n       * {@link ui.router.util.type:UrlMatcher `UrlMatcher`}, populated with the provided parameters.\n       *\n       * @example\n       * <pre>\n       * $bob = $urlRouter.href(new UrlMatcher(\"/about/:person\"), {\n       *   person: \"bob\"\n       * });\n       * // $bob == \"/about/bob\";\n       * </pre>\n       *\n       * @param {UrlMatcher} urlMatcher The `UrlMatcher` object which is used as the template of the URL to generate.\n       * @param {object=} params An object of parameter values to fill the matcher's required parameters.\n       * @param {object=} options Options object. The options are:\n       *\n       * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n       *\n       * @returns {string} Returns the fully compiled URL, or `null` if `params` fail validation against `urlMatcher`\n       */\n      href: function(urlMatcher, params, options) {\n        if (!urlMatcher.validates(params)) return null;\n\n        var isHtml5 = $locationProvider.html5Mode();\n        if (angular.isObject(isHtml5)) {\n          isHtml5 = isHtml5.enabled;\n        }\n        \n        var url = urlMatcher.format(params);\n        options = options || {};\n\n        if (!isHtml5 && url !== null) {\n          url = \"#\" + $locationProvider.hashPrefix() + url;\n        }\n\n        // Handle special hash param, if needed\n        if (url !== null && params && params['#']) {\n          url += '#' + params['#'];\n        }\n\n        url = appendBasePath(url, isHtml5, options.absolute);\n\n        if (!options.absolute || !url) {\n          return url;\n        }\n\n        var slash = (!isHtml5 && url ? '/' : ''), port = $location.port();\n        port = (port === 80 || port === 443 ? '' : ':' + port);\n\n        return [$location.protocol(), '://', $location.host(), port, slash, url].join('');\n      }\n    };\n  }\n}\n\nangular.module('ui.router.router').provider('$urlRouter', $UrlRouterProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$stateProvider\n *\n * @requires ui.router.router.$urlRouterProvider\n * @requires ui.router.util.$urlMatcherFactoryProvider\n *\n * @description\n * The new `$stateProvider` works similar to Angular's v1 router, but it focuses purely\n * on state.\n *\n * A state corresponds to a \"place\" in the application in terms of the overall UI and\n * navigation. A state describes (via the controller / template / view properties) what\n * the UI looks like and does at that place.\n *\n * States often have things in common, and the primary way of factoring out these\n * commonalities in this model is via the state hierarchy, i.e. parent/child states aka\n * nested states.\n *\n * The `$stateProvider` provides interfaces to declare these states for your app.\n */\n$StateProvider.$inject = ['$urlRouterProvider', '$urlMatcherFactoryProvider'];\nfunction $StateProvider(   $urlRouterProvider,   $urlMatcherFactory) {\n\n  var root, states = {}, $state, queue = {}, abstractKey = 'abstract';\n\n  // Builds state properties from definition passed to registerState()\n  var stateBuilder = {\n\n    // Derive parent state from a hierarchical name only if 'parent' is not explicitly defined.\n    // state.children = [];\n    // if (parent) parent.children.push(state);\n    parent: function(state) {\n      if (isDefined(state.parent) && state.parent) return findState(state.parent);\n      // regex matches any valid composite state name\n      // would match \"contact.list\" but not \"contacts\"\n      var compositeName = /^(.+)\\.[^.]+$/.exec(state.name);\n      return compositeName ? findState(compositeName[1]) : root;\n    },\n\n    // inherit 'data' from parent and override by own values (if any)\n    data: function(state) {\n      if (state.parent && state.parent.data) {\n        state.data = state.self.data = extend({}, state.parent.data, state.data);\n      }\n      return state.data;\n    },\n\n    // Build a URLMatcher if necessary, either via a relative or absolute URL\n    url: function(state) {\n      var url = state.url, config = { params: state.params || {} };\n\n      if (isString(url)) {\n        if (url.charAt(0) == '^') return $urlMatcherFactory.compile(url.substring(1), config);\n        return (state.parent.navigable || root).url.concat(url, config);\n      }\n\n      if (!url || $urlMatcherFactory.isMatcher(url)) return url;\n      throw new Error(\"Invalid url '\" + url + \"' in state '\" + state + \"'\");\n    },\n\n    // Keep track of the closest ancestor state that has a URL (i.e. is navigable)\n    navigable: function(state) {\n      return state.url ? state : (state.parent ? state.parent.navigable : null);\n    },\n\n    // Own parameters for this state. state.url.params is already built at this point. Create and add non-url params\n    ownParams: function(state) {\n      var params = state.url && state.url.params || new $$UMFP.ParamSet();\n      forEach(state.params || {}, function(config, id) {\n        if (!params[id]) params[id] = new $$UMFP.Param(id, null, config, \"config\");\n      });\n      return params;\n    },\n\n    // Derive parameters for this state and ensure they're a super-set of parent's parameters\n    params: function(state) {\n      return state.parent && state.parent.params ? extend(state.parent.params.$$new(), state.ownParams) : new $$UMFP.ParamSet();\n    },\n\n    // If there is no explicit multi-view configuration, make one up so we don't have\n    // to handle both cases in the view directive later. Note that having an explicit\n    // 'views' property will mean the default unnamed view properties are ignored. This\n    // is also a good time to resolve view names to absolute names, so everything is a\n    // straight lookup at link time.\n    views: function(state) {\n      var views = {};\n\n      forEach(isDefined(state.views) ? state.views : { '': state }, function (view, name) {\n        if (name.indexOf('@') < 0) name += '@' + state.parent.name;\n        views[name] = view;\n      });\n      return views;\n    },\n\n    // Keep a full path from the root down to this state as this is needed for state activation.\n    path: function(state) {\n      return state.parent ? state.parent.path.concat(state) : []; // exclude root from path\n    },\n\n    // Speed up $state.contains() as it's used a lot\n    includes: function(state) {\n      var includes = state.parent ? extend({}, state.parent.includes) : {};\n      includes[state.name] = true;\n      return includes;\n    },\n\n    $delegates: {}\n  };\n\n  function isRelative(stateName) {\n    return stateName.indexOf(\".\") === 0 || stateName.indexOf(\"^\") === 0;\n  }\n\n  function findState(stateOrName, base) {\n    if (!stateOrName) return undefined;\n\n    var isStr = isString(stateOrName),\n        name  = isStr ? stateOrName : stateOrName.name,\n        path  = isRelative(name);\n\n    if (path) {\n      if (!base) throw new Error(\"No reference point given for path '\"  + name + \"'\");\n      base = findState(base);\n      \n      var rel = name.split(\".\"), i = 0, pathLength = rel.length, current = base;\n\n      for (; i < pathLength; i++) {\n        if (rel[i] === \"\" && i === 0) {\n          current = base;\n          continue;\n        }\n        if (rel[i] === \"^\") {\n          if (!current.parent) throw new Error(\"Path '\" + name + \"' not valid for state '\" + base.name + \"'\");\n          current = current.parent;\n          continue;\n        }\n        break;\n      }\n      rel = rel.slice(i).join(\".\");\n      name = current.name + (current.name && rel ? \".\" : \"\") + rel;\n    }\n    var state = states[name];\n\n    if (state && (isStr || (!isStr && (state === stateOrName || state.self === stateOrName)))) {\n      return state;\n    }\n    return undefined;\n  }\n\n  function queueState(parentName, state) {\n    if (!queue[parentName]) {\n      queue[parentName] = [];\n    }\n    queue[parentName].push(state);\n  }\n\n  function flushQueuedChildren(parentName) {\n    var queued = queue[parentName] || [];\n    while(queued.length) {\n      registerState(queued.shift());\n    }\n  }\n\n  function registerState(state) {\n    // Wrap a new object around the state so we can store our private details easily.\n    state = inherit(state, {\n      self: state,\n      resolve: state.resolve || {},\n      toString: function() { return this.name; }\n    });\n\n    var name = state.name;\n    if (!isString(name) || name.indexOf('@') >= 0) throw new Error(\"State must have a valid name\");\n    if (states.hasOwnProperty(name)) throw new Error(\"State '\" + name + \"'' is already defined\");\n\n    // Get parent name\n    var parentName = (name.indexOf('.') !== -1) ? name.substring(0, name.lastIndexOf('.'))\n        : (isString(state.parent)) ? state.parent\n        : (isObject(state.parent) && isString(state.parent.name)) ? state.parent.name\n        : '';\n\n    // If parent is not registered yet, add state to queue and register later\n    if (parentName && !states[parentName]) {\n      return queueState(parentName, state.self);\n    }\n\n    for (var key in stateBuilder) {\n      if (isFunction(stateBuilder[key])) state[key] = stateBuilder[key](state, stateBuilder.$delegates[key]);\n    }\n    states[name] = state;\n\n    // Register the state in the global state list and with $urlRouter if necessary.\n    if (!state[abstractKey] && state.url) {\n      $urlRouterProvider.when(state.url, ['$match', '$stateParams', function ($match, $stateParams) {\n        if ($state.$current.navigable != state || !equalForKeys($match, $stateParams)) {\n          $state.transitionTo(state, $match, { inherit: true, location: false });\n        }\n      }]);\n    }\n\n    // Register any queued children\n    flushQueuedChildren(name);\n\n    return state;\n  }\n\n  // Checks text to see if it looks like a glob.\n  function isGlob (text) {\n    return text.indexOf('*') > -1;\n  }\n\n  // Returns true if glob matches current $state name.\n  function doesStateMatchGlob (glob) {\n    var globSegments = glob.split('.'),\n        segments = $state.$current.name.split('.');\n\n    //match single stars\n    for (var i = 0, l = globSegments.length; i < l; i++) {\n      if (globSegments[i] === '*') {\n        segments[i] = '*';\n      }\n    }\n\n    //match greedy starts\n    if (globSegments[0] === '**') {\n       segments = segments.slice(indexOf(segments, globSegments[1]));\n       segments.unshift('**');\n    }\n    //match greedy ends\n    if (globSegments[globSegments.length - 1] === '**') {\n       segments.splice(indexOf(segments, globSegments[globSegments.length - 2]) + 1, Number.MAX_VALUE);\n       segments.push('**');\n    }\n\n    if (globSegments.length != segments.length) {\n      return false;\n    }\n\n    return segments.join('') === globSegments.join('');\n  }\n\n\n  // Implicit root state that is always active\n  root = registerState({\n    name: '',\n    url: '^',\n    views: null,\n    'abstract': true\n  });\n  root.navigable = null;\n\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#decorator\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Allows you to extend (carefully) or override (at your own peril) the \n   * `stateBuilder` object used internally by `$stateProvider`. This can be used \n   * to add custom functionality to ui-router, for example inferring templateUrl \n   * based on the state name.\n   *\n   * When passing only a name, it returns the current (original or decorated) builder\n   * function that matches `name`.\n   *\n   * The builder functions that can be decorated are listed below. Though not all\n   * necessarily have a good use case for decoration, that is up to you to decide.\n   *\n   * In addition, users can attach custom decorators, which will generate new \n   * properties within the state's internal definition. There is currently no clear \n   * use-case for this beyond accessing internal states (i.e. $state.$current), \n   * however, expect this to become increasingly relevant as we introduce additional \n   * meta-programming features.\n   *\n   * **Warning**: Decorators should not be interdependent because the order of \n   * execution of the builder functions in non-deterministic. Builder functions \n   * should only be dependent on the state definition object and super function.\n   *\n   *\n   * Existing builder functions and current return values:\n   *\n   * - **parent** `{object}` - returns the parent state object.\n   * - **data** `{object}` - returns state data, including any inherited data that is not\n   *   overridden by own values (if any).\n   * - **url** `{object}` - returns a {@link ui.router.util.type:UrlMatcher UrlMatcher}\n   *   or `null`.\n   * - **navigable** `{object}` - returns closest ancestor state that has a URL (aka is \n   *   navigable).\n   * - **params** `{object}` - returns an array of state params that are ensured to \n   *   be a super-set of parent's params.\n   * - **views** `{object}` - returns a views object where each key is an absolute view \n   *   name (i.e. \"viewName@stateName\") and each value is the config object \n   *   (template, controller) for the view. Even when you don't use the views object \n   *   explicitly on a state config, one is still created for you internally.\n   *   So by decorating this builder function you have access to decorating template \n   *   and controller properties.\n   * - **ownParams** `{object}` - returns an array of params that belong to the state, \n   *   not including any params defined by ancestor states.\n   * - **path** `{string}` - returns the full path from the root down to this state. \n   *   Needed for state activation.\n   * - **includes** `{object}` - returns an object that includes every state that \n   *   would pass a `$state.includes()` test.\n   *\n   * @example\n   * <pre>\n   * // Override the internal 'views' builder with a function that takes the state\n   * // definition, and a reference to the internal function being overridden:\n   * $stateProvider.decorator('views', function (state, parent) {\n   *   var result = {},\n   *       views = parent(state);\n   *\n   *   angular.forEach(views, function (config, name) {\n   *     var autoName = (state.name + '.' + name).replace('.', '/');\n   *     config.templateUrl = config.templateUrl || '/partials/' + autoName + '.html';\n   *     result[name] = config;\n   *   });\n   *   return result;\n   * });\n   *\n   * $stateProvider.state('home', {\n   *   views: {\n   *     'contact.list': { controller: 'ListController' },\n   *     'contact.item': { controller: 'ItemController' }\n   *   }\n   * });\n   *\n   * // ...\n   *\n   * $state.go('home');\n   * // Auto-populates list and item views with /partials/home/contact/list.html,\n   * // and /partials/home/contact/item.html, respectively.\n   * </pre>\n   *\n   * @param {string} name The name of the builder function to decorate. \n   * @param {object} func A function that is responsible for decorating the original \n   * builder function. The function receives two parameters:\n   *\n   *   - `{object}` - state - The state config object.\n   *   - `{object}` - super - The original builder function.\n   *\n   * @return {object} $stateProvider - $stateProvider instance\n   */\n  this.decorator = decorator;\n  function decorator(name, func) {\n    /*jshint validthis: true */\n    if (isString(name) && !isDefined(func)) {\n      return stateBuilder[name];\n    }\n    if (!isFunction(func) || !isString(name)) {\n      return this;\n    }\n    if (stateBuilder[name] && !stateBuilder.$delegates[name]) {\n      stateBuilder.$delegates[name] = stateBuilder[name];\n    }\n    stateBuilder[name] = func;\n    return this;\n  }\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$stateProvider#state\n   * @methodOf ui.router.state.$stateProvider\n   *\n   * @description\n   * Registers a state configuration under a given state name. The stateConfig object\n   * has the following acceptable properties.\n   *\n   * @param {string} name A unique state name, e.g. \"home\", \"about\", \"contacts\".\n   * To create a parent/child state use a dot, e.g. \"about.sales\", \"home.newest\".\n   * @param {object} stateConfig State configuration object.\n   * @param {string|function=} stateConfig.template\n   * <a id='template'></a>\n   *   html template as a string or a function that returns\n   *   an html template as a string which should be used by the uiView directives. This property \n   *   takes precedence over templateUrl.\n   *   \n   *   If `template` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by\n   *     applying the current state\n   *\n   * <pre>template:\n   *   \"<h1>inline template definition</h1>\" +\n   *   \"<div ui-view></div>\"</pre>\n   * <pre>template: function(params) {\n   *       return \"<h1>generated template</h1>\"; }</pre>\n   * </div>\n   *\n   * @param {string|function=} stateConfig.templateUrl\n   * <a id='templateUrl'></a>\n   *\n   *   path or function that returns a path to an html\n   *   template that should be used by uiView.\n   *   \n   *   If `templateUrl` is a function, it will be called with the following parameters:\n   *\n   *   - {array.&lt;object&gt;} - state parameters extracted from the current $location.path() by \n   *     applying the current state\n   *\n   * <pre>templateUrl: \"home.html\"</pre>\n   * <pre>templateUrl: function(params) {\n   *     return myTemplates[params.pageId]; }</pre>\n   *\n   * @param {function=} stateConfig.templateProvider\n   * <a id='templateProvider'></a>\n   *    Provider function that returns HTML content string.\n   * <pre> templateProvider:\n   *       function(MyTemplateService, params) {\n   *         return MyTemplateService.getTemplate(params.pageId);\n   *       }</pre>\n   *\n   * @param {string|function=} stateConfig.controller\n   * <a id='controller'></a>\n   *\n   *  Controller fn that should be associated with newly\n   *   related scope or the name of a registered controller if passed as a string.\n   *   Optionally, the ControllerAs may be declared here.\n   * <pre>controller: \"MyRegisteredController\"</pre>\n   * <pre>controller:\n   *     \"MyRegisteredController as fooCtrl\"}</pre>\n   * <pre>controller: function($scope, MyService) {\n   *     $scope.data = MyService.getData(); }</pre>\n   *\n   * @param {function=} stateConfig.controllerProvider\n   * <a id='controllerProvider'></a>\n   *\n   * Injectable provider function that returns the actual controller or string.\n   * <pre>controllerProvider:\n   *   function(MyResolveData) {\n   *     if (MyResolveData.foo)\n   *       return \"FooCtrl\"\n   *     else if (MyResolveData.bar)\n   *       return \"BarCtrl\";\n   *     else return function($scope) {\n   *       $scope.baz = \"Qux\";\n   *     }\n   *   }</pre>\n   *\n   * @param {string=} stateConfig.controllerAs\n   * <a id='controllerAs'></a>\n   * \n   * A controller alias name. If present the controller will be\n   *   published to scope under the controllerAs name.\n   * <pre>controllerAs: \"myCtrl\"</pre>\n   *\n   * @param {string|object=} stateConfig.parent\n   * <a id='parent'></a>\n   * Optionally specifies the parent state of this state.\n   *\n   * <pre>parent: 'parentState'</pre>\n   * <pre>parent: parentState // JS variable</pre>\n   *\n   * @param {object=} stateConfig.resolve\n   * <a id='resolve'></a>\n   *\n   * An optional map&lt;string, function&gt; of dependencies which\n   *   should be injected into the controller. If any of these dependencies are promises, \n   *   the router will wait for them all to be resolved before the controller is instantiated.\n   *   If all the promises are resolved successfully, the $stateChangeSuccess event is fired\n   *   and the values of the resolved promises are injected into any controllers that reference them.\n   *   If any  of the promises are rejected the $stateChangeError event is fired.\n   *\n   *   The map object is:\n   *   \n   *   - key - {string}: name of dependency to be injected into controller\n   *   - factory - {string|function}: If string then it is alias for service. Otherwise if function, \n   *     it is injected and return value it treated as dependency. If result is a promise, it is \n   *     resolved before its value is injected into controller.\n   *\n   * <pre>resolve: {\n   *     myResolve1:\n   *       function($http, $stateParams) {\n   *         return $http.get(\"/api/foos/\"+stateParams.fooID);\n   *       }\n   *     }</pre>\n   *\n   * @param {string=} stateConfig.url\n   * <a id='url'></a>\n   *\n   *   A url fragment with optional parameters. When a state is navigated or\n   *   transitioned to, the `$stateParams` service will be populated with any \n   *   parameters that were passed.\n   *\n   *   (See {@link ui.router.util.type:UrlMatcher UrlMatcher} `UrlMatcher`} for\n   *   more details on acceptable patterns )\n   *\n   * examples:\n   * <pre>url: \"/home\"\n   * url: \"/users/:userid\"\n   * url: \"/books/{bookid:[a-zA-Z_-]}\"\n   * url: \"/books/{categoryid:int}\"\n   * url: \"/books/{publishername:string}/{categoryid:int}\"\n   * url: \"/messages?before&after\"\n   * url: \"/messages?{before:date}&{after:date}\"\n   * url: \"/messages/:mailboxid?{before:date}&{after:date}\"\n   * </pre>\n   *\n   * @param {object=} stateConfig.views\n   * <a id='views'></a>\n   * an optional map&lt;string, object&gt; which defined multiple views, or targets views\n   * manually/explicitly.\n   *\n   * Examples:\n   *\n   * Targets three named `ui-view`s in the parent state's template\n   * <pre>views: {\n   *     header: {\n   *       controller: \"headerCtrl\",\n   *       templateUrl: \"header.html\"\n   *     }, body: {\n   *       controller: \"bodyCtrl\",\n   *       templateUrl: \"body.html\"\n   *     }, footer: {\n   *       controller: \"footCtrl\",\n   *       templateUrl: \"footer.html\"\n   *     }\n   *   }</pre>\n   *\n   * Targets named `ui-view=\"header\"` from grandparent state 'top''s template, and named `ui-view=\"body\" from parent state's template.\n   * <pre>views: {\n   *     'header@top': {\n   *       controller: \"msgHeaderCtrl\",\n   *       templateUrl: \"msgHeader.html\"\n   *     }, 'body': {\n   *       controller: \"messagesCtrl\",\n   *       templateUrl: \"messages.html\"\n   *     }\n   *   }</pre>\n   *\n   * @param {boolean=} [stateConfig.abstract=false]\n   * <a id='abstract'></a>\n   * An abstract state will never be directly activated,\n   *   but can provide inherited properties to its common children states.\n   * <pre>abstract: true</pre>\n   *\n   * @param {function=} stateConfig.onEnter\n   * <a id='onEnter'></a>\n   *\n   * Callback function for when a state is entered. Good way\n   *   to trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onEnter: function(MyService, $stateParams) {\n   *     MyService.foo($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {function=} stateConfig.onExit\n   * <a id='onExit'></a>\n   *\n   * Callback function for when a state is exited. Good way to\n   *   trigger an action or dispatch an event, such as opening a dialog.\n   * If minifying your scripts, make sure to explictly annotate this function,\n   * because it won't be automatically annotated by your build tools.\n   *\n   * <pre>onExit: function(MyService, $stateParams) {\n   *     MyService.cleanup($stateParams.myParam);\n   * }</pre>\n   *\n   * @param {boolean=} [stateConfig.reloadOnSearch=true]\n   * <a id='reloadOnSearch'></a>\n   *\n   * If `false`, will not retrigger the same state\n   *   just because a search/query parameter has changed (via $location.search() or $location.hash()). \n   *   Useful for when you'd like to modify $location.search() without triggering a reload.\n   * <pre>reloadOnSearch: false</pre>\n   *\n   * @param {object=} stateConfig.data\n   * <a id='data'></a>\n   *\n   * Arbitrary data object, useful for custom configuration.  The parent state's `data` is\n   *   prototypally inherited.  In other words, adding a data property to a state adds it to\n   *   the entire subtree via prototypal inheritance.\n   *\n   * <pre>data: {\n   *     requiredRole: 'foo'\n   * } </pre>\n   *\n   * @param {object=} stateConfig.params\n   * <a id='params'></a>\n   *\n   * A map which optionally configures parameters declared in the `url`, or\n   *   defines additional non-url parameters.  For each parameter being\n   *   configured, add a configuration object keyed to the name of the parameter.\n   *\n   *   Each parameter configuration object may contain the following properties:\n   *\n   *   - ** value ** - {object|function=}: specifies the default value for this\n   *     parameter.  This implicitly sets this parameter as optional.\n   *\n   *     When UI-Router routes to a state and no value is\n   *     specified for this parameter in the URL or transition, the\n   *     default value will be used instead.  If `value` is a function,\n   *     it will be injected and invoked, and the return value used.\n   *\n   *     *Note*: `undefined` is treated as \"no default value\" while `null`\n   *     is treated as \"the default value is `null`\".\n   *\n   *     *Shorthand*: If you only need to configure the default value of the\n   *     parameter, you may use a shorthand syntax.   In the **`params`**\n   *     map, instead mapping the param name to a full parameter configuration\n   *     object, simply set map it to the default parameter value, e.g.:\n   *\n   * <pre>// define a parameter's default value\n   * params: {\n   *     param1: { value: \"defaultValue\" }\n   * }\n   * // shorthand default values\n   * params: {\n   *     param1: \"defaultValue\",\n   *     param2: \"param2Default\"\n   * }</pre>\n   *\n   *   - ** array ** - {boolean=}: *(default: false)* If true, the param value will be\n   *     treated as an array of values.  If you specified a Type, the value will be\n   *     treated as an array of the specified Type.  Note: query parameter values\n   *     default to a special `\"auto\"` mode.\n   *\n   *     For query parameters in `\"auto\"` mode, if multiple  values for a single parameter\n   *     are present in the URL (e.g.: `/foo?bar=1&bar=2&bar=3`) then the values\n   *     are mapped to an array (e.g.: `{ foo: [ '1', '2', '3' ] }`).  However, if\n   *     only one value is present (e.g.: `/foo?bar=1`) then the value is treated as single\n   *     value (e.g.: `{ foo: '1' }`).\n   *\n   * <pre>params: {\n   *     param1: { array: true }\n   * }</pre>\n   *\n   *   - ** squash ** - {bool|string=}: `squash` configures how a default parameter value is represented in the URL when\n   *     the current parameter value is the same as the default value. If `squash` is not set, it uses the\n   *     configured default squash policy.\n   *     (See {@link ui.router.util.$urlMatcherFactory#methods_defaultSquashPolicy `defaultSquashPolicy()`})\n   *\n   *   There are three squash settings:\n   *\n   *     - false: The parameter's default value is not squashed.  It is encoded and included in the URL\n   *     - true: The parameter's default value is omitted from the URL.  If the parameter is preceeded and followed\n   *       by slashes in the state's `url` declaration, then one of those slashes are omitted.\n   *       This can allow for cleaner looking URLs.\n   *     - `\"<arbitrary string>\"`: The parameter's default value is replaced with an arbitrary placeholder of  your choice.\n   *\n   * <pre>params: {\n   *     param1: {\n   *       value: \"defaultId\",\n   *       squash: true\n   * } }\n   * // squash \"defaultValue\" to \"~\"\n   * params: {\n   *     param1: {\n   *       value: \"defaultValue\",\n   *       squash: \"~\"\n   * } }\n   * </pre>\n   *\n   *\n   * @example\n   * <pre>\n   * // Some state name examples\n   *\n   * // stateName can be a single top-level name (must be unique).\n   * $stateProvider.state(\"home\", {});\n   *\n   * // Or it can be a nested state name. This state is a child of the\n   * // above \"home\" state.\n   * $stateProvider.state(\"home.newest\", {});\n   *\n   * // Nest states as deeply as needed.\n   * $stateProvider.state(\"home.newest.abc.xyz.inception\", {});\n   *\n   * // state() returns $stateProvider, so you can chain state declarations.\n   * $stateProvider\n   *   .state(\"home\", {})\n   *   .state(\"about\", {})\n   *   .state(\"contacts\", {});\n   * </pre>\n   *\n   */\n  this.state = state;\n  function state(name, definition) {\n    /*jshint validthis: true */\n    if (isObject(name)) definition = name;\n    else definition.name = name;\n    registerState(definition);\n    return this;\n  }\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$state\n   *\n   * @requires $rootScope\n   * @requires $q\n   * @requires ui.router.state.$view\n   * @requires $injector\n   * @requires ui.router.util.$resolve\n   * @requires ui.router.state.$stateParams\n   * @requires ui.router.router.$urlRouter\n   *\n   * @property {object} params A param object, e.g. {sectionId: section.id)}, that \n   * you'd like to test against the current active state.\n   * @property {object} current A reference to the state's config object. However \n   * you passed it in. Useful for accessing custom data.\n   * @property {object} transition Currently pending transition. A promise that'll \n   * resolve or reject.\n   *\n   * @description\n   * `$state` service is responsible for representing states as well as transitioning\n   * between them. It also provides interfaces to ask for current state or even states\n   * you're coming from.\n   */\n  this.$get = $get;\n  $get.$inject = ['$rootScope', '$q', '$view', '$injector', '$resolve', '$stateParams', '$urlRouter', '$location', '$urlMatcherFactory'];\n  function $get(   $rootScope,   $q,   $view,   $injector,   $resolve,   $stateParams,   $urlRouter,   $location,   $urlMatcherFactory) {\n\n    var TransitionSuperseded = $q.reject(new Error('transition superseded'));\n    var TransitionPrevented = $q.reject(new Error('transition prevented'));\n    var TransitionAborted = $q.reject(new Error('transition aborted'));\n    var TransitionFailed = $q.reject(new Error('transition failed'));\n\n    // Handles the case where a state which is the target of a transition is not found, and the user\n    // can optionally retry or defer the transition\n    function handleRedirect(redirect, state, params, options) {\n      /**\n       * @ngdoc event\n       * @name ui.router.state.$state#$stateNotFound\n       * @eventOf ui.router.state.$state\n       * @eventType broadcast on root scope\n       * @description\n       * Fired when a requested state **cannot be found** using the provided state name during transition.\n       * The event is broadcast allowing any handlers a single chance to deal with the error (usually by\n       * lazy-loading the unfound state). A special `unfoundState` object is passed to the listener handler,\n       * you can see its three properties in the example. You can use `event.preventDefault()` to abort the\n       * transition and the promise returned from `go` will be rejected with a `'transition aborted'` value.\n       *\n       * @param {Object} event Event object.\n       * @param {Object} unfoundState Unfound State information. Contains: `to, toParams, options` properties.\n       * @param {State} fromState Current state object.\n       * @param {Object} fromParams Current state params.\n       *\n       * @example\n       *\n       * <pre>\n       * // somewhere, assume lazy.state has not been defined\n       * $state.go(\"lazy.state\", {a:1, b:2}, {inherit:false});\n       *\n       * // somewhere else\n       * $scope.$on('$stateNotFound',\n       * function(event, unfoundState, fromState, fromParams){\n       *     console.log(unfoundState.to); // \"lazy.state\"\n       *     console.log(unfoundState.toParams); // {a:1, b:2}\n       *     console.log(unfoundState.options); // {inherit:false} + default options\n       * })\n       * </pre>\n       */\n      var evt = $rootScope.$broadcast('$stateNotFound', redirect, state, params);\n\n      if (evt.defaultPrevented) {\n        $urlRouter.update();\n        return TransitionAborted;\n      }\n\n      if (!evt.retry) {\n        return null;\n      }\n\n      // Allow the handler to return a promise to defer state lookup retry\n      if (options.$retry) {\n        $urlRouter.update();\n        return TransitionFailed;\n      }\n      var retryTransition = $state.transition = $q.when(evt.retry);\n\n      retryTransition.then(function() {\n        if (retryTransition !== $state.transition) return TransitionSuperseded;\n        redirect.options.$retry = true;\n        return $state.transitionTo(redirect.to, redirect.toParams, redirect.options);\n      }, function() {\n        return TransitionAborted;\n      });\n      $urlRouter.update();\n\n      return retryTransition;\n    }\n\n    root.locals = { resolve: null, globals: { $stateParams: {} } };\n\n    $state = {\n      params: {},\n      current: root.self,\n      $current: root,\n      transition: null\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#reload\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method that force reloads the current state. All resolves are re-resolved,\n     * controllers reinstantiated, and events re-fired.\n     *\n     * @example\n     * <pre>\n     * var app angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.reload = function(){\n     *     $state.reload();\n     *   }\n     * });\n     * </pre>\n     *\n     * `reload()` is just an alias for:\n     * <pre>\n     * $state.transitionTo($state.current, $stateParams, { \n     *   reload: true, inherit: false, notify: true\n     * });\n     * </pre>\n     *\n     * @param {string=|object=} state - A state name or a state object, which is the root of the resolves to be re-resolved.\n     * @example\n     * <pre>\n     * //assuming app application consists of 3 states: 'contacts', 'contacts.detail', 'contacts.detail.item' \n     * //and current state is 'contacts.detail.item'\n     * var app angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.reload = function(){\n     *     //will reload 'contact.detail' and 'contact.detail.item' states\n     *     $state.reload('contact.detail');\n     *   }\n     * });\n     * </pre>\n     *\n     * `reload()` is just an alias for:\n     * <pre>\n     * $state.transitionTo($state.current, $stateParams, { \n     *   reload: true, inherit: false, notify: true\n     * });\n     * </pre>\n\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.reload = function reload(state) {\n      return $state.transitionTo($state.current, $stateParams, { reload: state || true, inherit: false, notify: true});\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#go\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Convenience method for transitioning to a new state. `$state.go` calls \n     * `$state.transitionTo` internally but automatically sets options to \n     * `{ location: true, inherit: true, relative: $state.$current, notify: true }`. \n     * This allows you to easily use an absolute or relative to path and specify \n     * only the parameters you'd like to update (while letting unspecified parameters \n     * inherit from the currently active ancestor states).\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.go('contact.detail');\n     *   };\n     * });\n     * </pre>\n     * <img src='../ngdoc_assets/StateGoExamples.png'/>\n     *\n     * @param {string} to Absolute state name or relative state path. Some examples:\n     *\n     * - `$state.go('contact.detail')` - will go to the `contact.detail` state\n     * - `$state.go('^')` - will go to a parent state\n     * - `$state.go('^.sibling')` - will go to a sibling state\n     * - `$state.go('.child.grandchild')` - will go to grandchild state\n     *\n     * @param {object=} params A map of the parameters that will be sent to the state, \n     * will populate $stateParams. Any parameters that are not specified will be inherited from currently \n     * defined parameters. This allows, for example, going to a sibling state that shares parameters\n     * specified in a parent state. Parameter inheritance only works between common ancestor states, I.e.\n     * transitioning to a sibling will get you the parameters for all parents, transitioning to a child\n     * will get you all current parameters, etc.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *\n     * @returns {promise} A promise representing the state of the new transition.\n     *\n     * Possible success values:\n     *\n     * - $state.current\n     *\n     * <br/>Possible rejection values:\n     *\n     * - 'transition superseded' - when a newer transition has been started after this one\n     * - 'transition prevented' - when `event.preventDefault()` has been called in a `$stateChangeStart` listener\n     * - 'transition aborted' - when `event.preventDefault()` has been called in a `$stateNotFound` listener or\n     *   when a `$stateNotFound` `event.retry` promise errors.\n     * - 'transition failed' - when a state has been unsuccessfully found after 2 tries.\n     * - *resolve error* - when an error has occurred with a `resolve`\n     *\n     */\n    $state.go = function go(to, params, options) {\n      return $state.transitionTo(to, params, extend({ inherit: true, relative: $state.$current }, options));\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#transitionTo\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Low-level method for transitioning to a new state. {@link ui.router.state.$state#methods_go $state.go}\n     * uses `transitionTo` internally. `$state.go` is recommended in most situations.\n     *\n     * @example\n     * <pre>\n     * var app = angular.module('app', ['ui.router']);\n     *\n     * app.controller('ctrl', function ($scope, $state) {\n     *   $scope.changeState = function () {\n     *     $state.transitionTo('contact.detail');\n     *   };\n     * });\n     * </pre>\n     *\n     * @param {string} to State name.\n     * @param {object=} toParams A map of the parameters that will be sent to the state,\n     * will populate $stateParams.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`location`** - {boolean=true|string=} - If `true` will update the url in the location bar, if `false`\n     *    will not. If string, must be `\"replace\"`, which will update url and also replace last history record.\n     * - **`inherit`** - {boolean=false}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`notify`** - {boolean=true}, If `true` will broadcast $stateChangeStart and $stateChangeSuccess events.\n     * - **`reload`** (v0.2.5) - {boolean=false|string=|object=}, If `true` will force transition even if the state or params \n     *    have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd\n     *    use this when you want to force a reload when *everything* is the same, including search params.\n     *    if String, then will reload the state with the name given in reload, and any children.\n     *    if Object, then a stateObj is expected, will reload the state found in stateObj, and any children.\n     *\n     * @returns {promise} A promise representing the state of the new transition. See\n     * {@link ui.router.state.$state#methods_go $state.go}.\n     */\n    $state.transitionTo = function transitionTo(to, toParams, options) {\n      toParams = toParams || {};\n      options = extend({\n        location: true, inherit: false, relative: null, notify: true, reload: false, $retry: false\n      }, options || {});\n\n      var from = $state.$current, fromParams = $state.params, fromPath = from.path;\n      var evt, toState = findState(to, options.relative);\n\n      // Store the hash param for later (since it will be stripped out by various methods)\n      var hash = toParams['#'];\n\n      if (!isDefined(toState)) {\n        var redirect = { to: to, toParams: toParams, options: options };\n        var redirectResult = handleRedirect(redirect, from.self, fromParams, options);\n\n        if (redirectResult) {\n          return redirectResult;\n        }\n\n        // Always retry once if the $stateNotFound was not prevented\n        // (handles either redirect changed or state lazy-definition)\n        to = redirect.to;\n        toParams = redirect.toParams;\n        options = redirect.options;\n        toState = findState(to, options.relative);\n\n        if (!isDefined(toState)) {\n          if (!options.relative) throw new Error(\"No such state '\" + to + \"'\");\n          throw new Error(\"Could not resolve '\" + to + \"' from state '\" + options.relative + \"'\");\n        }\n      }\n      if (toState[abstractKey]) throw new Error(\"Cannot transition to abstract state '\" + to + \"'\");\n      if (options.inherit) toParams = inheritParams($stateParams, toParams || {}, $state.$current, toState);\n      if (!toState.params.$$validates(toParams)) return TransitionFailed;\n\n      toParams = toState.params.$$values(toParams);\n      to = toState;\n\n      var toPath = to.path;\n\n      // Starting from the root of the path, keep all levels that haven't changed\n      var keep = 0, state = toPath[keep], locals = root.locals, toLocals = [];\n\n      if (!options.reload) {\n        while (state && state === fromPath[keep] && state.ownParams.$$equals(toParams, fromParams)) {\n          locals = toLocals[keep] = state.locals;\n          keep++;\n          state = toPath[keep];\n        }\n      } else if (isString(options.reload) || isObject(options.reload)) {\n        if (isObject(options.reload) && !options.reload.name) {\n          throw new Error('Invalid reload state object');\n        }\n        \n        var reloadState = options.reload === true ? fromPath[0] : findState(options.reload);\n        if (options.reload && !reloadState) {\n          throw new Error(\"No such reload state '\" + (isString(options.reload) ? options.reload : options.reload.name) + \"'\");\n        }\n\n        while (state && state === fromPath[keep] && state !== reloadState) {\n          locals = toLocals[keep] = state.locals;\n          keep++;\n          state = toPath[keep];\n        }\n      }\n\n      // If we're going to the same state and all locals are kept, we've got nothing to do.\n      // But clear 'transition', as we still want to cancel any other pending transitions.\n      // TODO: We may not want to bump 'transition' if we're called from a location change\n      // that we've initiated ourselves, because we might accidentally abort a legitimate\n      // transition initiated from code?\n      if (shouldSkipReload(to, toParams, from, fromParams, locals, options)) {\n        if (hash) toParams['#'] = hash;\n        $state.params = toParams;\n        copy($state.params, $stateParams);\n        if (options.location && to.navigable && to.navigable.url) {\n          $urlRouter.push(to.navigable.url, toParams, {\n            $$avoidResync: true, replace: options.location === 'replace'\n          });\n          $urlRouter.update(true);\n        }\n        $state.transition = null;\n        return $q.when($state.current);\n      }\n\n      // Filter parameters before we pass them to event handlers etc.\n      toParams = filterByKeys(to.params.$$keys(), toParams || {});\n\n      // Broadcast start event and cancel the transition if requested\n      if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeStart\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when the state transition **begins**. You can use `event.preventDefault()`\n         * to prevent the transition from happening and then the transition promise will be\n         * rejected with a `'transition prevented'` value.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         *\n         * @example\n         *\n         * <pre>\n         * $rootScope.$on('$stateChangeStart',\n         * function(event, toState, toParams, fromState, fromParams){\n         *     event.preventDefault();\n         *     // transitionTo() promise will be rejected with\n         *     // a 'transition prevented' error\n         * })\n         * </pre>\n         */\n        if ($rootScope.$broadcast('$stateChangeStart', to.self, toParams, from.self, fromParams).defaultPrevented) {\n          $rootScope.$broadcast('$stateChangeCancel', to.self, toParams, from.self, fromParams);\n          $urlRouter.update();\n          return TransitionPrevented;\n        }\n      }\n\n      // Resolve locals for the remaining states, but don't update any global state just\n      // yet -- if anything fails to resolve the current state needs to remain untouched.\n      // We also set up an inheritance chain for the locals here. This allows the view directive\n      // to quickly look up the correct definition for each view in the current state. Even\n      // though we create the locals object itself outside resolveState(), it is initially\n      // empty and gets filled asynchronously. We need to keep track of the promise for the\n      // (fully resolved) current locals, and pass this down the chain.\n      var resolved = $q.when(locals);\n\n      for (var l = keep; l < toPath.length; l++, state = toPath[l]) {\n        locals = toLocals[l] = inherit(locals);\n        resolved = resolveState(state, toParams, state === to, resolved, locals, options);\n      }\n\n      // Once everything is resolved, we are ready to perform the actual transition\n      // and return a promise for the new state. We also keep track of what the\n      // current promise is, so that we can detect overlapping transitions and\n      // keep only the outcome of the last transition.\n      var transition = $state.transition = resolved.then(function () {\n        var l, entering, exiting;\n\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Exit 'from' states not kept\n        for (l = fromPath.length - 1; l >= keep; l--) {\n          exiting = fromPath[l];\n          if (exiting.self.onExit) {\n            $injector.invoke(exiting.self.onExit, exiting.self, exiting.locals.globals);\n          }\n          exiting.locals = null;\n        }\n\n        // Enter 'to' states not kept\n        for (l = keep; l < toPath.length; l++) {\n          entering = toPath[l];\n          entering.locals = toLocals[l];\n          if (entering.self.onEnter) {\n            $injector.invoke(entering.self.onEnter, entering.self, entering.locals.globals);\n          }\n        }\n\n        // Re-add the saved hash before we start returning things\n        if (hash) toParams['#'] = hash;\n\n        // Run it again, to catch any transitions in callbacks\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        // Update globals in $state\n        $state.$current = to;\n        $state.current = to.self;\n        $state.params = toParams;\n        copy($state.params, $stateParams);\n        $state.transition = null;\n\n        if (options.location && to.navigable) {\n          $urlRouter.push(to.navigable.url, to.navigable.locals.globals.$stateParams, {\n            $$avoidResync: true, replace: options.location === 'replace'\n          });\n        }\n\n        if (options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeSuccess\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired once the state transition is **complete**.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         */\n          $rootScope.$broadcast('$stateChangeSuccess', to.self, toParams, from.self, fromParams);\n        }\n        $urlRouter.update(true);\n\n        return $state.current;\n      }, function (error) {\n        if ($state.transition !== transition) return TransitionSuperseded;\n\n        $state.transition = null;\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$stateChangeError\n         * @eventOf ui.router.state.$state\n         * @eventType broadcast on root scope\n         * @description\n         * Fired when an **error occurs** during transition. It's important to note that if you\n         * have any errors in your resolve functions (javascript errors, non-existent services, etc)\n         * they will not throw traditionally. You must listen for this $stateChangeError event to\n         * catch **ALL** errors.\n         *\n         * @param {Object} event Event object.\n         * @param {State} toState The state being transitioned to.\n         * @param {Object} toParams The params supplied to the `toState`.\n         * @param {State} fromState The current state, pre-transition.\n         * @param {Object} fromParams The params supplied to the `fromState`.\n         * @param {Error} error The resolve error object.\n         */\n        evt = $rootScope.$broadcast('$stateChangeError', to.self, toParams, from.self, fromParams, error);\n\n        if (!evt.defaultPrevented) {\n            $urlRouter.update();\n        }\n\n        return $q.reject(error);\n      });\n\n      return transition;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#is\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Similar to {@link ui.router.state.$state#methods_includes $state.includes},\n     * but only checks for the full state name. If params is supplied then it will be\n     * tested for strict equality against the current active params object, so all params\n     * must match with none missing and no extras.\n     *\n     * @example\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // absolute name\n     * $state.is('contact.details.item'); // returns true\n     * $state.is(contactDetailItemStateObject); // returns true\n     *\n     * // relative name (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.is('.item')}\">Item</div>\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name (absolute or relative) or state object you'd like to check.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`, that you'd like\n     * to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object} -  If `stateOrName` is a relative state name and `options.relative` is set, .is will\n     * test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it is the state.\n     */\n    $state.is = function is(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) { return undefined; }\n      if ($state.$current !== state) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams) : true;\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#includes\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A method to determine if the current active state is equal to or is the child of the\n     * state stateName. If any params are passed then they will be tested for a match as well.\n     * Not all the parameters need to be passed, just the ones you'd like to test for equality.\n     *\n     * @example\n     * Partial and relative names\n     * <pre>\n     * $state.$current.name = 'contacts.details.item';\n     *\n     * // Using partial names\n     * $state.includes(\"contacts\"); // returns true\n     * $state.includes(\"contacts.details\"); // returns true\n     * $state.includes(\"contacts.details.item\"); // returns true\n     * $state.includes(\"contacts.list\"); // returns false\n     * $state.includes(\"about\"); // returns false\n     *\n     * // Using relative names (. and ^), typically from a template\n     * // E.g. from the 'contacts.details' template\n     * <div ng-class=\"{highlighted: $state.includes('.item')}\">Item</div>\n     * </pre>\n     *\n     * Basic globbing patterns\n     * <pre>\n     * $state.$current.name = 'contacts.details.item.url';\n     *\n     * $state.includes(\"*.details.*.*\"); // returns true\n     * $state.includes(\"*.details.**\"); // returns true\n     * $state.includes(\"**.item.**\"); // returns true\n     * $state.includes(\"*.details.item.url\"); // returns true\n     * $state.includes(\"*.details.*.url\"); // returns true\n     * $state.includes(\"*.details.*\"); // returns false\n     * $state.includes(\"item.**\"); // returns false\n     * </pre>\n     *\n     * @param {string} stateOrName A partial name, relative name, or glob pattern\n     * to be searched for within the current state name.\n     * @param {object=} params A param object, e.g. `{sectionId: section.id}`,\n     * that you'd like to test against the current active state.\n     * @param {object=} options An options object.  The options are:\n     *\n     * - **`relative`** - {string|object=} -  If `stateOrName` is a relative state reference and `options.relative` is set,\n     * .includes will test relative to `options.relative` state (or name).\n     *\n     * @returns {boolean} Returns true if it does include the state\n     */\n    $state.includes = function includes(stateOrName, params, options) {\n      options = extend({ relative: $state.$current }, options || {});\n      if (isString(stateOrName) && isGlob(stateOrName)) {\n        if (!doesStateMatchGlob(stateOrName)) {\n          return false;\n        }\n        stateOrName = $state.$current.name;\n      }\n\n      var state = findState(stateOrName, options.relative);\n      if (!isDefined(state)) { return undefined; }\n      if (!isDefined($state.$current.includes[state.name])) { return false; }\n      return params ? equalForKeys(state.params.$$values(params), $stateParams, objectKeys(params)) : true;\n    };\n\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#href\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * A url generation method that returns the compiled url for the given state populated with the given params.\n     *\n     * @example\n     * <pre>\n     * expect($state.href(\"about.person\", { person: \"bob\" })).toEqual(\"/about/bob\");\n     * </pre>\n     *\n     * @param {string|object} stateOrName The state name or state object you'd like to generate a url from.\n     * @param {object=} params An object of parameter values to fill the state's required parameters.\n     * @param {object=} options Options object. The options are:\n     *\n     * - **`lossy`** - {boolean=true} -  If true, and if there is no url associated with the state provided in the\n     *    first parameter, then the constructed href url will be built from the first navigable ancestor (aka\n     *    ancestor with a valid url).\n     * - **`inherit`** - {boolean=true}, If `true` will inherit url parameters from current url.\n     * - **`relative`** - {object=$state.$current}, When transitioning with relative path (e.g '^'), \n     *    defines which state to be relative from.\n     * - **`absolute`** - {boolean=false},  If true will generate an absolute url, e.g. \"http://www.example.com/fullurl\".\n     * \n     * @returns {string} compiled state url\n     */\n    $state.href = function href(stateOrName, params, options) {\n      options = extend({\n        lossy:    true,\n        inherit:  true,\n        absolute: false,\n        relative: $state.$current\n      }, options || {});\n\n      var state = findState(stateOrName, options.relative);\n\n      if (!isDefined(state)) return null;\n      if (options.inherit) params = inheritParams($stateParams, params || {}, $state.$current, state);\n      \n      var nav = (state && options.lossy) ? state.navigable : state;\n\n      if (!nav || nav.url === undefined || nav.url === null) {\n        return null;\n      }\n      return $urlRouter.href(nav.url, filterByKeys(state.params.$$keys().concat('#'), params || {}), {\n        absolute: options.absolute\n      });\n    };\n\n    /**\n     * @ngdoc function\n     * @name ui.router.state.$state#get\n     * @methodOf ui.router.state.$state\n     *\n     * @description\n     * Returns the state configuration object for any specific state or all states.\n     *\n     * @param {string|object=} stateOrName (absolute or relative) If provided, will only get the config for\n     * the requested state. If not provided, returns an array of ALL state configs.\n     * @param {string|object=} context When stateOrName is a relative state reference, the state will be retrieved relative to context.\n     * @returns {Object|Array} State configuration object or array of all objects.\n     */\n    $state.get = function (stateOrName, context) {\n      if (arguments.length === 0) return map(objectKeys(states), function(name) { return states[name].self; });\n      var state = findState(stateOrName, context || $state.$current);\n      return (state && state.self) ? state.self : null;\n    };\n\n    function resolveState(state, params, paramsAreFiltered, inherited, dst, options) {\n      // Make a restricted $stateParams with only the parameters that apply to this state if\n      // necessary. In addition to being available to the controller and onEnter/onExit callbacks,\n      // we also need $stateParams to be available for any $injector calls we make during the\n      // dependency resolution process.\n      var $stateParams = (paramsAreFiltered) ? params : filterByKeys(state.params.$$keys(), params);\n      var locals = { $stateParams: $stateParams };\n\n      // Resolve 'global' dependencies for the state, i.e. those not specific to a view.\n      // We're also including $stateParams in this; that way the parameters are restricted\n      // to the set that should be visible to the state, and are independent of when we update\n      // the global $state and $stateParams values.\n      dst.resolve = $resolve.resolve(state.resolve, locals, dst.resolve, state);\n      var promises = [dst.resolve.then(function (globals) {\n        dst.globals = globals;\n      })];\n      if (inherited) promises.push(inherited);\n\n      function resolveViews() {\n        var viewsPromises = [];\n\n        // Resolve template and dependencies for all views.\n        forEach(state.views, function (view, name) {\n          var injectables = (view.resolve && view.resolve !== state.resolve ? view.resolve : {});\n          injectables.$template = [ function () {\n            return $view.load(name, { view: view, locals: dst.globals, params: $stateParams, notify: options.notify }) || '';\n          }];\n\n          viewsPromises.push($resolve.resolve(injectables, dst.globals, dst.resolve, state).then(function (result) {\n            // References to the controller (only instantiated at link time)\n            if (isFunction(view.controllerProvider) || isArray(view.controllerProvider)) {\n              var injectLocals = angular.extend({}, injectables, dst.globals);\n              result.$$controller = $injector.invoke(view.controllerProvider, null, injectLocals);\n            } else {\n              result.$$controller = view.controller;\n            }\n            // Provide access to the state itself for internal use\n            result.$$state = state;\n            result.$$controllerAs = view.controllerAs;\n            dst[name] = result;\n          }));\n        });\n\n        return $q.all(viewsPromises).then(function(){\n          return dst.globals;\n        });\n      }\n\n      // Wait for all the promises and then return the activation object\n      return $q.all(promises).then(resolveViews).then(function (values) {\n        return dst;\n      });\n    }\n\n    return $state;\n  }\n\n  function shouldSkipReload(to, toParams, from, fromParams, locals, options) {\n    // Return true if there are no differences in non-search (path/object) params, false if there are differences\n    function nonSearchParamsEqual(fromAndToState, fromParams, toParams) {\n      // Identify whether all the parameters that differ between `fromParams` and `toParams` were search params.\n      function notSearchParam(key) {\n        return fromAndToState.params[key].location != \"search\";\n      }\n      var nonQueryParamKeys = fromAndToState.params.$$keys().filter(notSearchParam);\n      var nonQueryParams = pick.apply({}, [fromAndToState.params].concat(nonQueryParamKeys));\n      var nonQueryParamSet = new $$UMFP.ParamSet(nonQueryParams);\n      return nonQueryParamSet.$$equals(fromParams, toParams);\n    }\n\n    // If reload was not explicitly requested\n    // and we're transitioning to the same state we're already in\n    // and    the locals didn't change\n    //     or they changed in a way that doesn't merit reloading\n    //        (reloadOnParams:false, or reloadOnSearch.false and only search params changed)\n    // Then return true.\n    if (!options.reload && to === from &&\n      (locals === from.locals || (to.self.reloadOnSearch === false && nonSearchParamsEqual(from, fromParams, toParams)))) {\n      return true;\n    }\n  }\n}\n\nangular.module('ui.router.state')\n  .value('$stateParams', {})\n  .provider('$state', $StateProvider);\n\n\n$ViewProvider.$inject = [];\nfunction $ViewProvider() {\n\n  this.$get = $get;\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$view\n   *\n   * @requires ui.router.util.$templateFactory\n   * @requires $rootScope\n   *\n   * @description\n   *\n   */\n  $get.$inject = ['$rootScope', '$templateFactory'];\n  function $get(   $rootScope,   $templateFactory) {\n    return {\n      // $view.load('full.viewName', { template: ..., controller: ..., resolve: ..., async: false, params: ... })\n      /**\n       * @ngdoc function\n       * @name ui.router.state.$view#load\n       * @methodOf ui.router.state.$view\n       *\n       * @description\n       *\n       * @param {string} name name\n       * @param {object} options option object.\n       */\n      load: function load(name, options) {\n        var result, defaults = {\n          template: null, controller: null, view: null, locals: null, notify: true, async: true, params: {}\n        };\n        options = extend(defaults, options);\n\n        if (options.view) {\n          result = $templateFactory.fromConfig(options.view, options.params, options.locals);\n        }\n        if (result && options.notify) {\n        /**\n         * @ngdoc event\n         * @name ui.router.state.$state#$viewContentLoading\n         * @eventOf ui.router.state.$view\n         * @eventType broadcast on root scope\n         * @description\n         *\n         * Fired once the view **begins loading**, *before* the DOM is rendered.\n         *\n         * @param {Object} event Event object.\n         * @param {Object} viewConfig The view config properties (template, controller, etc).\n         *\n         * @example\n         *\n         * <pre>\n         * $scope.$on('$viewContentLoading',\n         * function(event, viewConfig){\n         *     // Access to all the view config properties.\n         *     // and one special property 'targetView'\n         *     // viewConfig.targetView\n         * });\n         * </pre>\n         */\n          $rootScope.$broadcast('$viewContentLoading', options);\n        }\n        return result;\n      }\n    };\n  }\n}\n\nangular.module('ui.router.state').provider('$view', $ViewProvider);\n\n/**\n * @ngdoc object\n * @name ui.router.state.$uiViewScrollProvider\n *\n * @description\n * Provider that returns the {@link ui.router.state.$uiViewScroll} service function.\n */\nfunction $ViewScrollProvider() {\n\n  var useAnchorScroll = false;\n\n  /**\n   * @ngdoc function\n   * @name ui.router.state.$uiViewScrollProvider#useAnchorScroll\n   * @methodOf ui.router.state.$uiViewScrollProvider\n   *\n   * @description\n   * Reverts back to using the core [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll) service for\n   * scrolling based on the url anchor.\n   */\n  this.useAnchorScroll = function () {\n    useAnchorScroll = true;\n  };\n\n  /**\n   * @ngdoc object\n   * @name ui.router.state.$uiViewScroll\n   *\n   * @requires $anchorScroll\n   * @requires $timeout\n   *\n   * @description\n   * When called with a jqLite element, it scrolls the element into view (after a\n   * `$timeout` so the DOM has time to refresh).\n   *\n   * If you prefer to rely on `$anchorScroll` to scroll the view to the anchor,\n   * this can be enabled by calling {@link ui.router.state.$uiViewScrollProvider#methods_useAnchorScroll `$uiViewScrollProvider.useAnchorScroll()`}.\n   */\n  this.$get = ['$anchorScroll', '$timeout', function ($anchorScroll, $timeout) {\n    if (useAnchorScroll) {\n      return $anchorScroll;\n    }\n\n    return function ($element) {\n      return $timeout(function () {\n        $element[0].scrollIntoView();\n      }, 0, false);\n    };\n  }];\n}\n\nangular.module('ui.router.state').provider('$uiViewScroll', $ViewScrollProvider);\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-view\n *\n * @requires ui.router.state.$state\n * @requires $compile\n * @requires $controller\n * @requires $injector\n * @requires ui.router.state.$uiViewScroll\n * @requires $document\n *\n * @restrict ECA\n *\n * @description\n * The ui-view directive tells $state where to place your templates.\n *\n * @param {string=} name A view name. The name should be unique amongst the other views in the\n * same state. You can have views of the same name that live in different states.\n *\n * @param {string=} autoscroll It allows you to set the scroll behavior of the browser window\n * when a view is populated. By default, $anchorScroll is overridden by ui-router's custom scroll\n * service, {@link ui.router.state.$uiViewScroll}. This custom service let's you\n * scroll ui-view elements into view when they are populated during a state activation.\n *\n * *Note: To revert back to old [`$anchorScroll`](http://docs.angularjs.org/api/ng.$anchorScroll)\n * functionality, call `$uiViewScrollProvider.useAnchorScroll()`.*\n *\n * @param {string=} onload Expression to evaluate whenever the view updates.\n * \n * @example\n * A view can be unnamed or named. \n * <pre>\n * <!-- Unnamed -->\n * <div ui-view></div> \n * \n * <!-- Named -->\n * <div ui-view=\"viewName\"></div>\n * </pre>\n *\n * You can only have one unnamed view within any template (or root html). If you are only using a \n * single view and it is unnamed then you can populate it like so:\n * <pre>\n * <div ui-view></div> \n * $stateProvider.state(\"home\", {\n *   template: \"<h1>HELLO!</h1>\"\n * })\n * </pre>\n * \n * The above is a convenient shortcut equivalent to specifying your view explicitly with the {@link ui.router.state.$stateProvider#views `views`}\n * config property, by name, in this case an empty name:\n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * But typically you'll only use the views property if you name your view or have more than one view \n * in the same template. There's not really a compelling reason to name a view if its the only one, \n * but you could if you wanted, like so:\n * <pre>\n * <div ui-view=\"main\"></div>\n * </pre> \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"main\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     }\n *   }    \n * })\n * </pre>\n * \n * Really though, you'll use views to set up multiple views:\n * <pre>\n * <div ui-view></div>\n * <div ui-view=\"chart\"></div> \n * <div ui-view=\"data\"></div> \n * </pre>\n * \n * <pre>\n * $stateProvider.state(\"home\", {\n *   views: {\n *     \"\": {\n *       template: \"<h1>HELLO!</h1>\"\n *     },\n *     \"chart\": {\n *       template: \"<chart_thing/>\"\n *     },\n *     \"data\": {\n *       template: \"<data_thing/>\"\n *     }\n *   }    \n * })\n * </pre>\n *\n * Examples for `autoscroll`:\n *\n * <pre>\n * <!-- If autoscroll present with no expression,\n *      then scroll ui-view into view -->\n * <ui-view autoscroll/>\n *\n * <!-- If autoscroll present with valid expression,\n *      then scroll ui-view into view if expression evaluates to true -->\n * <ui-view autoscroll='true'/>\n * <ui-view autoscroll='false'/>\n * <ui-view autoscroll='scopeVariable'/>\n * </pre>\n */\n$ViewDirective.$inject = ['$state', '$injector', '$uiViewScroll', '$interpolate'];\nfunction $ViewDirective(   $state,   $injector,   $uiViewScroll,   $interpolate) {\n\n  function getService() {\n    return ($injector.has) ? function(service) {\n      return $injector.has(service) ? $injector.get(service) : null;\n    } : function(service) {\n      try {\n        return $injector.get(service);\n      } catch (e) {\n        return null;\n      }\n    };\n  }\n\n  var service = getService(),\n      $animator = service('$animator'),\n      $animate = service('$animate');\n\n  // Returns a set of DOM manipulation functions based on which Angular version\n  // it should use\n  function getRenderer(attrs, scope) {\n    var statics = function() {\n      return {\n        enter: function (element, target, cb) { target.after(element); cb(); },\n        leave: function (element, cb) { element.remove(); cb(); }\n      };\n    };\n\n    if ($animate) {\n      return {\n        enter: function(element, target, cb) {\n          var promise = $animate.enter(element, null, target, cb);\n          if (promise && promise.then) promise.then(cb);\n        },\n        leave: function(element, cb) {\n          var promise = $animate.leave(element, cb);\n          if (promise && promise.then) promise.then(cb);\n        }\n      };\n    }\n\n    if ($animator) {\n      var animate = $animator && $animator(scope, attrs);\n\n      return {\n        enter: function(element, target, cb) {animate.enter(element, null, target); cb(); },\n        leave: function(element, cb) { animate.leave(element); cb(); }\n      };\n    }\n\n    return statics();\n  }\n\n  var directive = {\n    restrict: 'ECA',\n    terminal: true,\n    priority: 400,\n    transclude: 'element',\n    compile: function (tElement, tAttrs, $transclude) {\n      return function (scope, $element, attrs) {\n        var previousEl, currentEl, currentScope, latestLocals,\n            onloadExp     = attrs.onload || '',\n            autoScrollExp = attrs.autoscroll,\n            renderer      = getRenderer(attrs, scope);\n\n        scope.$on('$stateChangeSuccess', function() {\n          updateView(false);\n        });\n        scope.$on('$viewContentLoading', function() {\n          updateView(false);\n        });\n\n        updateView(true);\n\n        function cleanupLastView() {\n          if (previousEl) {\n            previousEl.remove();\n            previousEl = null;\n          }\n\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n\n          if (currentEl) {\n            renderer.leave(currentEl, function() {\n              previousEl = null;\n            });\n\n            previousEl = currentEl;\n            currentEl = null;\n          }\n        }\n\n        function updateView(firstTime) {\n          var newScope,\n              name            = getUiViewName(scope, attrs, $element, $interpolate),\n              previousLocals  = name && $state.$current && $state.$current.locals[name];\n\n          if (!firstTime && previousLocals === latestLocals) return; // nothing to do\n          newScope = scope.$new();\n          latestLocals = $state.$current.locals[name];\n\n          var clone = $transclude(newScope, function(clone) {\n            renderer.enter(clone, $element, function onUiViewEnter() {\n              if(currentScope) {\n                currentScope.$emit('$viewContentAnimationEnded');\n              }\n\n              if (angular.isDefined(autoScrollExp) && !autoScrollExp || scope.$eval(autoScrollExp)) {\n                $uiViewScroll(clone);\n              }\n            });\n            cleanupLastView();\n          });\n\n          currentEl = clone;\n          currentScope = newScope;\n          /**\n           * @ngdoc event\n           * @name ui.router.state.directive:ui-view#$viewContentLoaded\n           * @eventOf ui.router.state.directive:ui-view\n           * @eventType emits on ui-view directive scope\n           * @description           *\n           * Fired once the view is **loaded**, *after* the DOM is rendered.\n           *\n           * @param {Object} event Event object.\n           */\n          currentScope.$emit('$viewContentLoaded');\n          currentScope.$eval(onloadExp);\n        }\n      };\n    }\n  };\n\n  return directive;\n}\n\n$ViewDirectiveFill.$inject = ['$compile', '$controller', '$state', '$interpolate'];\nfunction $ViewDirectiveFill (  $compile,   $controller,   $state,   $interpolate) {\n  return {\n    restrict: 'ECA',\n    priority: -400,\n    compile: function (tElement) {\n      var initial = tElement.html();\n      return function (scope, $element, attrs) {\n        var current = $state.$current,\n            name = getUiViewName(scope, attrs, $element, $interpolate),\n            locals  = current && current.locals[name];\n\n        if (! locals) {\n          return;\n        }\n\n        $element.data('$uiView', { name: name, state: locals.$$state });\n        $element.html(locals.$template ? locals.$template : initial);\n\n        var link = $compile($element.contents());\n\n        if (locals.$$controller) {\n          locals.$scope = scope;\n          locals.$element = $element;\n          var controller = $controller(locals.$$controller, locals);\n          if (locals.$$controllerAs) {\n            scope[locals.$$controllerAs] = controller;\n          }\n          $element.data('$ngControllerController', controller);\n          $element.children().data('$ngControllerController', controller);\n        }\n\n        link(scope);\n      };\n    }\n  };\n}\n\n/**\n * Shared ui-view code for both directives:\n * Given scope, element, and its attributes, return the view's name\n */\nfunction getUiViewName(scope, attrs, element, $interpolate) {\n  var name = $interpolate(attrs.uiView || attrs.name || '')(scope);\n  var inherited = element.inheritedData('$uiView');\n  return name.indexOf('@') >= 0 ?  name :  (name + '@' + (inherited ? inherited.state.name : ''));\n}\n\nangular.module('ui.router.state').directive('uiView', $ViewDirective);\nangular.module('ui.router.state').directive('uiView', $ViewDirectiveFill);\n\nfunction parseStateRef(ref, current) {\n  var preparsed = ref.match(/^\\s*({[^}]*})\\s*$/), parsed;\n  if (preparsed) ref = current + '(' + preparsed[1] + ')';\n  parsed = ref.replace(/\\n/g, \" \").match(/^([^(]+?)\\s*(\\((.*)\\))?$/);\n  if (!parsed || parsed.length !== 4) throw new Error(\"Invalid state ref '\" + ref + \"'\");\n  return { state: parsed[1], paramExpr: parsed[3] || null };\n}\n\nfunction stateContext(el) {\n  var stateData = el.parent().inheritedData('$uiView');\n\n  if (stateData && stateData.state && stateData.state.name) {\n    return stateData.state;\n  }\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref\n *\n * @requires ui.router.state.$state\n * @requires $timeout\n *\n * @restrict A\n *\n * @description\n * A directive that binds a link (`<a>` tag) to a state. If the state has an associated \n * URL, the directive will automatically generate & update the `href` attribute via \n * the {@link ui.router.state.$state#methods_href $state.href()} method. Clicking \n * the link will trigger a state transition with optional parameters. \n *\n * Also middle-clicking, right-clicking, and ctrl-clicking on the link will be \n * handled natively by the browser.\n *\n * You can also use relative state paths within ui-sref, just like the relative \n * paths passed to `$state.go()`. You just need to be aware that the path is relative\n * to the state that the link lives in, in other words the state that loaded the \n * template containing the link.\n *\n * You can specify options to pass to {@link ui.router.state.$state#go $state.go()}\n * using the `ui-sref-opts` attribute. Options are restricted to `location`, `inherit`,\n * and `reload`.\n *\n * @example\n * Here's an example of how you'd use ui-sref and how it would compile. If you have the \n * following template:\n * <pre>\n * <a ui-sref=\"home\">Home</a> | <a ui-sref=\"about\">About</a> | <a ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a ui-sref=\"contacts.detail({ id: contact.id })\">{{ contact.name }}</a>\n *     </li>\n * </ul>\n * </pre>\n * \n * Then the compiled html would be (assuming Html5Mode is off and current state is contacts):\n * <pre>\n * <a href=\"#/home\" ui-sref=\"home\">Home</a> | <a href=\"#/about\" ui-sref=\"about\">About</a> | <a href=\"#/contacts?page=2\" ui-sref=\"{page: 2}\">Next page</a>\n * \n * <ul>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/1\" ui-sref=\"contacts.detail({ id: contact.id })\">Joe</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/2\" ui-sref=\"contacts.detail({ id: contact.id })\">Alice</a>\n *     </li>\n *     <li ng-repeat=\"contact in contacts\">\n *         <a href=\"#/contacts/3\" ui-sref=\"contacts.detail({ id: contact.id })\">Bob</a>\n *     </li>\n * </ul>\n *\n * <a ui-sref=\"home\" ui-sref-opts=\"{reload: true}\">Home</a>\n * </pre>\n *\n * @param {string} ui-sref 'stateName' can be any valid absolute or relative state\n * @param {Object} ui-sref-opts options to pass to {@link ui.router.state.$state#go $state.go()}\n */\n$StateRefDirective.$inject = ['$state', '$timeout'];\nfunction $StateRefDirective($state, $timeout) {\n  var allowedOptions = ['location', 'inherit', 'reload', 'absolute'];\n\n  return {\n    restrict: 'A',\n    require: ['?^uiSrefActive', '?^uiSrefActiveEq'],\n    link: function(scope, element, attrs, uiSrefActive) {\n      var ref = parseStateRef(attrs.uiSref, $state.current.name);\n      var params = null, url = null, base = stateContext(element) || $state.$current;\n      // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n      var hrefKind = Object.prototype.toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n                 'xlink:href' : 'href';\n      var newHref = null, isAnchor = element.prop(\"tagName\").toUpperCase() === \"A\";\n      var isForm = element[0].nodeName === \"FORM\";\n      var attr = isForm ? \"action\" : hrefKind, nav = true;\n\n      var options = { relative: base, inherit: true };\n      var optionsOverride = scope.$eval(attrs.uiSrefOpts) || {};\n\n      angular.forEach(allowedOptions, function(option) {\n        if (option in optionsOverride) {\n          options[option] = optionsOverride[option];\n        }\n      });\n\n      var update = function(newVal) {\n        if (newVal) params = angular.copy(newVal);\n        if (!nav) return;\n\n        newHref = $state.href(ref.state, params, options);\n\n        var activeDirective = uiSrefActive[1] || uiSrefActive[0];\n        if (activeDirective) {\n          activeDirective.$$addStateInfo(ref.state, params);\n        }\n        if (newHref === null) {\n          nav = false;\n          return false;\n        }\n        attrs.$set(attr, newHref);\n      };\n\n      if (ref.paramExpr) {\n        scope.$watch(ref.paramExpr, function(newVal, oldVal) {\n          if (newVal !== params) update(newVal);\n        }, true);\n        params = angular.copy(scope.$eval(ref.paramExpr));\n      }\n      update();\n\n      if (isForm) return;\n\n      element.bind(\"click\", function(e) {\n        var button = e.which || e.button;\n        if ( !(button > 1 || e.ctrlKey || e.metaKey || e.shiftKey || element.attr('target')) ) {\n          // HACK: This is to allow ng-clicks to be processed before the transition is initiated:\n          var transition = $timeout(function() {\n            $state.go(ref.state, params, options);\n          });\n          e.preventDefault();\n\n          // if the state has no URL, ignore one preventDefault from the <a> directive.\n          var ignorePreventDefaultCount = isAnchor && !newHref ? 1: 0;\n          e.preventDefault = function() {\n            if (ignorePreventDefaultCount-- <= 0)\n              $timeout.cancel(transition);\n          };\n        }\n      });\n    }\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * A directive working alongside ui-sref to add classes to an element when the\n * related ui-sref directive's state is active, and removing them when it is inactive.\n * The primary use-case is to simplify the special appearance of navigation menus\n * relying on `ui-sref`, by having the \"active\" state's menu button appear different,\n * distinguishing it from the inactive menu items.\n *\n * ui-sref-active can live on the same element as ui-sref or on a parent element. The first\n * ui-sref-active found at the same level or above the ui-sref will be used.\n *\n * Will activate when the ui-sref's target state or any child state is active. If you\n * need to activate only when the ui-sref target state is active and *not* any of\n * it's children, then you will use\n * {@link ui.router.state.directive:ui-sref-active-eq ui-sref-active-eq}\n *\n * @example\n * Given the following template:\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item\">\n *     <a href ui-sref=\"app.user({user: 'bilbobaggins'})\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n *\n * When the app state is \"app.user\" (or any children states), and contains the state parameter \"user\" with value \"bilbobaggins\",\n * the resulting HTML will appear as (note the 'active' class):\n * <pre>\n * <ul>\n *   <li ui-sref-active=\"active\" class=\"item active\">\n *     <a ui-sref=\"app.user({user: 'bilbobaggins'})\" href=\"/users/bilbobaggins\">@bilbobaggins</a>\n *   </li>\n * </ul>\n * </pre>\n *\n * The class name is interpolated **once** during the directives link time (any further changes to the\n * interpolated value are ignored).\n *\n * Multiple classes may be specified in a space-separated format:\n * <pre>\n * <ul>\n *   <li ui-sref-active='class1 class2 class3'>\n *     <a ui-sref=\"app.user\">link</a>\n *   </li>\n * </ul>\n * </pre>\n */\n\n/**\n * @ngdoc directive\n * @name ui.router.state.directive:ui-sref-active-eq\n *\n * @requires ui.router.state.$state\n * @requires ui.router.state.$stateParams\n * @requires $interpolate\n *\n * @restrict A\n *\n * @description\n * The same as {@link ui.router.state.directive:ui-sref-active ui-sref-active} but will only activate\n * when the exact target state used in the `ui-sref` is active; no child states.\n *\n */\n$StateRefActiveDirective.$inject = ['$state', '$stateParams', '$interpolate'];\nfunction $StateRefActiveDirective($state, $stateParams, $interpolate) {\n  return  {\n    restrict: \"A\",\n    controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {\n      var states = [], activeClass;\n\n      // There probably isn't much point in $observing this\n      // uiSrefActive and uiSrefActiveEq share the same directive object with some\n      // slight difference in logic routing\n      activeClass = $interpolate($attrs.uiSrefActiveEq || $attrs.uiSrefActive || '', false)($scope);\n\n      // Allow uiSref to communicate with uiSrefActive[Equals]\n      this.$$addStateInfo = function (newState, newParams) {\n        var state = $state.get(newState, stateContext($element));\n\n        states.push({\n          state: state || { name: newState },\n          params: newParams\n        });\n\n        update();\n      };\n\n      $scope.$on('$stateChangeSuccess', update);\n\n      // Update route state\n      function update() {\n        if (anyMatch()) {\n          $element.addClass(activeClass);\n        } else {\n          $element.removeClass(activeClass);\n        }\n      }\n\n      function anyMatch() {\n        for (var i = 0; i < states.length; i++) {\n          if (isMatch(states[i].state, states[i].params)) {\n            return true;\n          }\n        }\n        return false;\n      }\n\n      function isMatch(state, params) {\n        if (typeof $attrs.uiSrefActiveEq !== 'undefined') {\n          return $state.is(state.name, params);\n        } else {\n          return $state.includes(state.name, params);\n        }\n      }\n    }]\n  };\n}\n\nangular.module('ui.router.state')\n  .directive('uiSref', $StateRefDirective)\n  .directive('uiSrefActive', $StateRefActiveDirective)\n  .directive('uiSrefActiveEq', $StateRefActiveDirective);\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:isState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_is $state.is(\"stateName\")}.\n */\n$IsStateFilter.$inject = ['$state'];\nfunction $IsStateFilter($state) {\n  var isFilter = function (state) {\n    return $state.is(state);\n  };\n  isFilter.$stateful = true;\n  return isFilter;\n}\n\n/**\n * @ngdoc filter\n * @name ui.router.state.filter:includedByState\n *\n * @requires ui.router.state.$state\n *\n * @description\n * Translates to {@link ui.router.state.$state#methods_includes $state.includes('fullOrPartialStateName')}.\n */\n$IncludedByStateFilter.$inject = ['$state'];\nfunction $IncludedByStateFilter($state) {\n  var includesFilter = function (state) {\n    return $state.includes(state);\n  };\n  includesFilter.$stateful = true;\n  return  includesFilter;\n}\n\nangular.module('ui.router.state')\n  .filter('isState', $IsStateFilter)\n  .filter('includedByState', $IncludedByStateFilter);\n})(window, window.angular);"
  },
  {
    "path": "examples/server/php/public/vendor/angular.js",
    "content": "/**\n * @license AngularJS v1.4.4\n * (c) 2010-2015 Google, Inc. http://angularjs.org\n * License: MIT\n */\n(function(window, document, undefined) {'use strict';\n\n/**\n * @description\n *\n * This object provides a utility for producing rich Error messages within\n * Angular. It can be called as follows:\n *\n * var exampleMinErr = minErr('example');\n * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);\n *\n * The above creates an instance of minErr in the example namespace. The\n * resulting error will have a namespaced error code of example.one.  The\n * resulting error will replace {0} with the value of foo, and {1} with the\n * value of bar. The object is not restricted in the number of arguments it can\n * take.\n *\n * If fewer arguments are specified than necessary for interpolation, the extra\n * interpolation markers will be preserved in the final string.\n *\n * Since data will be parsed statically during a build step, some restrictions\n * are applied with respect to how minErr instances are created and called.\n * Instances should have names of the form namespaceMinErr for a minErr created\n * using minErr('namespace') . Error codes, namespaces and template strings\n * should all be static strings, not variables or general expressions.\n *\n * @param {string} module The namespace to use for the new minErr instance.\n * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning\n *   error from returned function, for cases when a particular type of error is useful.\n * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance\n */\n\nfunction minErr(module, ErrorConstructor) {\n  ErrorConstructor = ErrorConstructor || Error;\n  return function() {\n    var SKIP_INDEXES = 2;\n\n    var templateArgs = arguments,\n      code = templateArgs[0],\n      message = '[' + (module ? module + ':' : '') + code + '] ',\n      template = templateArgs[1],\n      paramPrefix, i;\n\n    message += template.replace(/\\{\\d+\\}/g, function(match) {\n      var index = +match.slice(1, -1),\n        shiftedIndex = index + SKIP_INDEXES;\n\n      if (shiftedIndex < templateArgs.length) {\n        return toDebugString(templateArgs[shiftedIndex]);\n      }\n\n      return match;\n    });\n\n    message += '\\nhttp://errors.angularjs.org/1.4.4/' +\n      (module ? module + '/' : '') + code;\n\n    for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {\n      message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +\n        encodeURIComponent(toDebugString(templateArgs[i]));\n    }\n\n    return new ErrorConstructor(message);\n  };\n}\n\n/* We need to tell jshint what variables are being exported */\n/* global angular: true,\n  msie: true,\n  jqLite: true,\n  jQuery: true,\n  slice: true,\n  splice: true,\n  push: true,\n  toString: true,\n  ngMinErr: true,\n  angularModule: true,\n  uid: true,\n  REGEX_STRING_REGEXP: true,\n  VALIDITY_STATE_PROPERTY: true,\n\n  lowercase: true,\n  uppercase: true,\n  manualLowercase: true,\n  manualUppercase: true,\n  nodeName_: true,\n  isArrayLike: true,\n  forEach: true,\n  forEachSorted: true,\n  reverseParams: true,\n  nextUid: true,\n  setHashKey: true,\n  extend: true,\n  toInt: true,\n  inherit: true,\n  merge: true,\n  noop: true,\n  identity: true,\n  valueFn: true,\n  isUndefined: true,\n  isDefined: true,\n  isObject: true,\n  isBlankObject: true,\n  isString: true,\n  isNumber: true,\n  isDate: true,\n  isArray: true,\n  isFunction: true,\n  isRegExp: true,\n  isWindow: true,\n  isScope: true,\n  isFile: true,\n  isFormData: true,\n  isBlob: true,\n  isBoolean: true,\n  isPromiseLike: true,\n  trim: true,\n  escapeForRegexp: true,\n  isElement: true,\n  makeMap: true,\n  includes: true,\n  arrayRemove: true,\n  copy: true,\n  shallowCopy: true,\n  equals: true,\n  csp: true,\n  jq: true,\n  concat: true,\n  sliceArgs: true,\n  bind: true,\n  toJsonReplacer: true,\n  toJson: true,\n  fromJson: true,\n  convertTimezoneToLocal: true,\n  timezoneToOffset: true,\n  startingTag: true,\n  tryDecodeURIComponent: true,\n  parseKeyValue: true,\n  toKeyValue: true,\n  encodeUriSegment: true,\n  encodeUriQuery: true,\n  angularInit: true,\n  bootstrap: true,\n  getTestability: true,\n  snake_case: true,\n  bindJQuery: true,\n  assertArg: true,\n  assertArgFn: true,\n  assertNotHasOwnProperty: true,\n  getter: true,\n  getBlockNodes: true,\n  hasOwnProperty: true,\n  createMap: true,\n\n  NODE_TYPE_ELEMENT: true,\n  NODE_TYPE_ATTRIBUTE: true,\n  NODE_TYPE_TEXT: true,\n  NODE_TYPE_COMMENT: true,\n  NODE_TYPE_DOCUMENT: true,\n  NODE_TYPE_DOCUMENT_FRAGMENT: true,\n*/\n\n////////////////////////////////////\n\n/**\n * @ngdoc module\n * @name ng\n * @module ng\n * @description\n *\n * # ng (core module)\n * The ng module is loaded by default when an AngularJS application is started. The module itself\n * contains the essential components for an AngularJS application to function. The table below\n * lists a high level breakdown of each of the services/factories, filters, directives and testing\n * components available within this core module.\n *\n * <div doc-module-components=\"ng\"></div>\n */\n\nvar REGEX_STRING_REGEXP = /^\\/(.+)\\/([a-z]*)$/;\n\n// The name of a form control's ValidityState property.\n// This is used so that it's possible for internal tests to create mock ValidityStates.\nvar VALIDITY_STATE_PROPERTY = 'validity';\n\n/**\n * @ngdoc function\n * @name angular.lowercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to lowercase.\n * @param {string} string String to be converted to lowercase.\n * @returns {string} Lowercased string.\n */\nvar lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\n/**\n * @ngdoc function\n * @name angular.uppercase\n * @module ng\n * @kind function\n *\n * @description Converts the specified string to uppercase.\n * @param {string} string String to be converted to uppercase.\n * @returns {string} Uppercased string.\n */\nvar uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};\n\n\nvar manualLowercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})\n      : s;\n};\nvar manualUppercase = function(s) {\n  /* jshint bitwise: false */\n  return isString(s)\n      ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})\n      : s;\n};\n\n\n// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish\n// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods\n// with correct but slower alternatives.\nif ('i' !== 'I'.toLowerCase()) {\n  lowercase = manualLowercase;\n  uppercase = manualUppercase;\n}\n\n\nvar\n    msie,             // holds major version number for IE, or NaN if UA is not IE.\n    jqLite,           // delay binding since jQuery could be loaded after us.\n    jQuery,           // delay binding\n    slice             = [].slice,\n    splice            = [].splice,\n    push              = [].push,\n    toString          = Object.prototype.toString,\n    getPrototypeOf    = Object.getPrototypeOf,\n    ngMinErr          = minErr('ng'),\n\n    /** @name angular */\n    angular           = window.angular || (window.angular = {}),\n    angularModule,\n    uid               = 0;\n\n/**\n * documentMode is an IE-only property\n * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx\n */\nmsie = document.documentMode;\n\n\n/**\n * @private\n * @param {*} obj\n * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,\n *                   String ...)\n */\nfunction isArrayLike(obj) {\n  if (obj == null || isWindow(obj)) {\n    return false;\n  }\n\n  // Support: iOS 8.2 (not reproducible in simulator)\n  // \"length\" in obj used to prevent JIT error (gh-11508)\n  var length = \"length\" in Object(obj) && obj.length;\n\n  if (obj.nodeType === NODE_TYPE_ELEMENT && length) {\n    return true;\n  }\n\n  return isString(obj) || isArray(obj) || length === 0 ||\n         typeof length === 'number' && length > 0 && (length - 1) in obj;\n}\n\n/**\n * @ngdoc function\n * @name angular.forEach\n * @module ng\n * @kind function\n *\n * @description\n * Invokes the `iterator` function once for each item in `obj` collection, which can be either an\n * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`\n * is the value of an object property or an array element, `key` is the object property key or\n * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.\n *\n * It is worth noting that `.forEach` does not iterate over inherited properties because it filters\n * using the `hasOwnProperty` method.\n *\n * Unlike ES262's\n * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),\n * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just\n * return the value provided.\n *\n   ```js\n     var values = {name: 'misko', gender: 'male'};\n     var log = [];\n     angular.forEach(values, function(value, key) {\n       this.push(key + ': ' + value);\n     }, log);\n     expect(log).toEqual(['name: misko', 'gender: male']);\n   ```\n *\n * @param {Object|Array} obj Object to iterate over.\n * @param {Function} iterator Iterator function.\n * @param {Object=} context Object to become context (`this`) for the iterator function.\n * @returns {Object|Array} Reference to `obj`.\n */\n\nfunction forEach(obj, iterator, context) {\n  var key, length;\n  if (obj) {\n    if (isFunction(obj)) {\n      for (key in obj) {\n        // Need to check if hasOwnProperty exists,\n        // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function\n        if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (isArray(obj) || isArrayLike(obj)) {\n      var isPrimitive = typeof obj !== 'object';\n      for (key = 0, length = obj.length; key < length; key++) {\n        if (isPrimitive || key in obj) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else if (obj.forEach && obj.forEach !== forEach) {\n        obj.forEach(iterator, context, obj);\n    } else if (isBlankObject(obj)) {\n      // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty\n      for (key in obj) {\n        iterator.call(context, obj[key], key, obj);\n      }\n    } else if (typeof obj.hasOwnProperty === 'function') {\n      // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed\n      for (key in obj) {\n        if (obj.hasOwnProperty(key)) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    } else {\n      // Slow path for objects which do not have a method `hasOwnProperty`\n      for (key in obj) {\n        if (hasOwnProperty.call(obj, key)) {\n          iterator.call(context, obj[key], key, obj);\n        }\n      }\n    }\n  }\n  return obj;\n}\n\nfunction forEachSorted(obj, iterator, context) {\n  var keys = Object.keys(obj).sort();\n  for (var i = 0; i < keys.length; i++) {\n    iterator.call(context, obj[keys[i]], keys[i]);\n  }\n  return keys;\n}\n\n\n/**\n * when using forEach the params are value, key, but it is often useful to have key, value.\n * @param {function(string, *)} iteratorFn\n * @returns {function(*, string)}\n */\nfunction reverseParams(iteratorFn) {\n  return function(value, key) { iteratorFn(key, value); };\n}\n\n/**\n * A consistent way of creating unique IDs in angular.\n *\n * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before\n * we hit number precision issues in JavaScript.\n *\n * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M\n *\n * @returns {number} an unique alpha-numeric string\n */\nfunction nextUid() {\n  return ++uid;\n}\n\n\n/**\n * Set or clear the hashkey for an object.\n * @param obj object\n * @param h the hashkey (!truthy to delete the hashkey)\n */\nfunction setHashKey(obj, h) {\n  if (h) {\n    obj.$$hashKey = h;\n  } else {\n    delete obj.$$hashKey;\n  }\n}\n\n\nfunction baseExtend(dst, objs, deep) {\n  var h = dst.$$hashKey;\n\n  for (var i = 0, ii = objs.length; i < ii; ++i) {\n    var obj = objs[i];\n    if (!isObject(obj) && !isFunction(obj)) continue;\n    var keys = Object.keys(obj);\n    for (var j = 0, jj = keys.length; j < jj; j++) {\n      var key = keys[j];\n      var src = obj[key];\n\n      if (deep && isObject(src)) {\n        if (isDate(src)) {\n          dst[key] = new Date(src.valueOf());\n        } else if (isRegExp(src)) {\n          dst[key] = new RegExp(src);\n        } else {\n          if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};\n          baseExtend(dst[key], [src], true);\n        }\n      } else {\n        dst[key] = src;\n      }\n    }\n  }\n\n  setHashKey(dst, h);\n  return dst;\n}\n\n/**\n * @ngdoc function\n * @name angular.extend\n * @module ng\n * @kind function\n *\n * @description\n * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.\n *\n * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use\n * {@link angular.merge} for this.\n *\n * @param {Object} dst Destination object.\n * @param {...Object} src Source object(s).\n * @returns {Object} Reference to `dst`.\n */\nfunction extend(dst) {\n  return baseExtend(dst, slice.call(arguments, 1), false);\n}\n\n\n/**\n* @ngdoc function\n* @name angular.merge\n* @module ng\n* @kind function\n*\n* @description\n* Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)\n* to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so\n* by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.\n*\n* Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source\n* objects, performing a deep copy.\n*\n* @param {Object} dst Destination object.\n* @param {...Object} src Source object(s).\n* @returns {Object} Reference to `dst`.\n*/\nfunction merge(dst) {\n  return baseExtend(dst, slice.call(arguments, 1), true);\n}\n\n\n\nfunction toInt(str) {\n  return parseInt(str, 10);\n}\n\n\nfunction inherit(parent, extra) {\n  return extend(Object.create(parent), extra);\n}\n\n/**\n * @ngdoc function\n * @name angular.noop\n * @module ng\n * @kind function\n *\n * @description\n * A function that performs no operations. This function can be useful when writing code in the\n * functional style.\n   ```js\n     function foo(callback) {\n       var result = calculateResult();\n       (callback || angular.noop)(result);\n     }\n   ```\n */\nfunction noop() {}\nnoop.$inject = [];\n\n\n/**\n * @ngdoc function\n * @name angular.identity\n * @module ng\n * @kind function\n *\n * @description\n * A function that returns its first argument. This function is useful when writing code in the\n * functional style.\n *\n   ```js\n     function transformer(transformationFn, value) {\n       return (transformationFn || angular.identity)(value);\n     };\n   ```\n  * @param {*} value to be returned.\n  * @returns {*} the value passed in.\n */\nfunction identity($) {return $;}\nidentity.$inject = [];\n\n\nfunction valueFn(value) {return function() {return value;};}\n\nfunction hasCustomToString(obj) {\n  return isFunction(obj.toString) && obj.toString !== Object.prototype.toString;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isUndefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is undefined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is undefined.\n */\nfunction isUndefined(value) {return typeof value === 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDefined\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is defined.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is defined.\n */\nfunction isDefined(value) {return typeof value !== 'undefined';}\n\n\n/**\n * @ngdoc function\n * @name angular.isObject\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not\n * considered to be objects. Note that JavaScript arrays are objects.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Object` but not `null`.\n */\nfunction isObject(value) {\n  // http://jsperf.com/isobject4\n  return value !== null && typeof value === 'object';\n}\n\n\n/**\n * Determine if a value is an object with a null prototype\n *\n * @returns {boolean} True if `value` is an `Object` with a null prototype\n */\nfunction isBlankObject(value) {\n  return value !== null && typeof value === 'object' && !getPrototypeOf(value);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isString\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `String`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `String`.\n */\nfunction isString(value) {return typeof value === 'string';}\n\n\n/**\n * @ngdoc function\n * @name angular.isNumber\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Number`.\n *\n * This includes the \"special\" numbers `NaN`, `+Infinity` and `-Infinity`.\n *\n * If you wish to exclude these then you can use the native\n * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)\n * method.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Number`.\n */\nfunction isNumber(value) {return typeof value === 'number';}\n\n\n/**\n * @ngdoc function\n * @name angular.isDate\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a value is a date.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Date`.\n */\nfunction isDate(value) {\n  return toString.call(value) === '[object Date]';\n}\n\n\n/**\n * @ngdoc function\n * @name angular.isArray\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is an `Array`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is an `Array`.\n */\nvar isArray = Array.isArray;\n\n/**\n * @ngdoc function\n * @name angular.isFunction\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a `Function`.\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `Function`.\n */\nfunction isFunction(value) {return typeof value === 'function';}\n\n\n/**\n * Determines if a value is a regular expression object.\n *\n * @private\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a `RegExp`.\n */\nfunction isRegExp(value) {\n  return toString.call(value) === '[object RegExp]';\n}\n\n\n/**\n * Checks if `obj` is a window object.\n *\n * @private\n * @param {*} obj Object to check\n * @returns {boolean} True if `obj` is a window obj.\n */\nfunction isWindow(obj) {\n  return obj && obj.window === obj;\n}\n\n\nfunction isScope(obj) {\n  return obj && obj.$evalAsync && obj.$watch;\n}\n\n\nfunction isFile(obj) {\n  return toString.call(obj) === '[object File]';\n}\n\n\nfunction isFormData(obj) {\n  return toString.call(obj) === '[object FormData]';\n}\n\n\nfunction isBlob(obj) {\n  return toString.call(obj) === '[object Blob]';\n}\n\n\nfunction isBoolean(value) {\n  return typeof value === 'boolean';\n}\n\n\nfunction isPromiseLike(obj) {\n  return obj && isFunction(obj.then);\n}\n\n\nvar TYPED_ARRAY_REGEXP = /^\\[object (Uint8(Clamped)?)|(Uint16)|(Uint32)|(Int8)|(Int16)|(Int32)|(Float(32)|(64))Array\\]$/;\nfunction isTypedArray(value) {\n  return TYPED_ARRAY_REGEXP.test(toString.call(value));\n}\n\n\nvar trim = function(value) {\n  return isString(value) ? value.trim() : value;\n};\n\n// Copied from:\n// http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021\n// Prereq: s is a string.\nvar escapeForRegexp = function(s) {\n  return s.replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1').\n           replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * @ngdoc function\n * @name angular.isElement\n * @module ng\n * @kind function\n *\n * @description\n * Determines if a reference is a DOM element (or wrapped jQuery element).\n *\n * @param {*} value Reference to check.\n * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).\n */\nfunction isElement(node) {\n  return !!(node &&\n    (node.nodeName  // we are a direct element\n    || (node.prop && node.attr && node.find)));  // we have an on and find method part of jQuery API\n}\n\n/**\n * @param str 'key1,key2,...'\n * @returns {object} in the form of {key1:true, key2:true, ...}\n */\nfunction makeMap(str) {\n  var obj = {}, items = str.split(\",\"), i;\n  for (i = 0; i < items.length; i++) {\n    obj[items[i]] = true;\n  }\n  return obj;\n}\n\n\nfunction nodeName_(element) {\n  return lowercase(element.nodeName || (element[0] && element[0].nodeName));\n}\n\nfunction includes(array, obj) {\n  return Array.prototype.indexOf.call(array, obj) != -1;\n}\n\nfunction arrayRemove(array, value) {\n  var index = array.indexOf(value);\n  if (index >= 0) {\n    array.splice(index, 1);\n  }\n  return index;\n}\n\n/**\n * @ngdoc function\n * @name angular.copy\n * @module ng\n * @kind function\n *\n * @description\n * Creates a deep copy of `source`, which should be an object or an array.\n *\n * * If no destination is supplied, a copy of the object or array is created.\n * * If a destination is provided, all of its elements (for arrays) or properties (for objects)\n *   are deleted and then all elements/properties from the source are copied to it.\n * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.\n * * If `source` is identical to 'destination' an exception will be thrown.\n *\n * @param {*} source The source that will be used to make a copy.\n *                   Can be any type, including primitives, `null`, and `undefined`.\n * @param {(Object|Array)=} destination Destination into which the source is copied. If\n *     provided, must be of the same type as `source`.\n * @returns {*} The copy or updated `destination`, if `destination` was specified.\n *\n * @example\n <example module=\"copyExample\">\n <file name=\"index.html\">\n <div ng-controller=\"ExampleController\">\n <form novalidate class=\"simple-form\">\n Name: <input type=\"text\" ng-model=\"user.name\" /><br />\n E-mail: <input type=\"email\" ng-model=\"user.email\" /><br />\n Gender: <input type=\"radio\" ng-model=\"user.gender\" value=\"male\" />male\n <input type=\"radio\" ng-model=\"user.gender\" value=\"female\" />female<br />\n <button ng-click=\"reset()\">RESET</button>\n <button ng-click=\"update(user)\">SAVE</button>\n </form>\n <pre>form = {{user | json}}</pre>\n <pre>master = {{master | json}}</pre>\n </div>\n\n <script>\n  angular.module('copyExample', [])\n    .controller('ExampleController', ['$scope', function($scope) {\n      $scope.master= {};\n\n      $scope.update = function(user) {\n        // Example with 1 argument\n        $scope.master= angular.copy(user);\n      };\n\n      $scope.reset = function() {\n        // Example with 2 arguments\n        angular.copy($scope.master, $scope.user);\n      };\n\n      $scope.reset();\n    }]);\n </script>\n </file>\n </example>\n */\nfunction copy(source, destination, stackSource, stackDest) {\n  if (isWindow(source) || isScope(source)) {\n    throw ngMinErr('cpws',\n      \"Can't copy! Making copies of Window or Scope instances is not supported.\");\n  }\n  if (isTypedArray(destination)) {\n    throw ngMinErr('cpta',\n      \"Can't copy! TypedArray destination cannot be mutated.\");\n  }\n\n  if (!destination) {\n    destination = source;\n    if (isObject(source)) {\n      var index;\n      if (stackSource && (index = stackSource.indexOf(source)) !== -1) {\n        return stackDest[index];\n      }\n\n      // TypedArray, Date and RegExp have specific copy functionality and must be\n      // pushed onto the stack before returning.\n      // Array and other objects create the base object and recurse to copy child\n      // objects. The array/object will be pushed onto the stack when recursed.\n      if (isArray(source)) {\n        return copy(source, [], stackSource, stackDest);\n      } else if (isTypedArray(source)) {\n        destination = new source.constructor(source);\n      } else if (isDate(source)) {\n        destination = new Date(source.getTime());\n      } else if (isRegExp(source)) {\n        destination = new RegExp(source.source, source.toString().match(/[^\\/]*$/)[0]);\n        destination.lastIndex = source.lastIndex;\n      } else {\n        var emptyObject = Object.create(getPrototypeOf(source));\n        return copy(source, emptyObject, stackSource, stackDest);\n      }\n\n      if (stackDest) {\n        stackSource.push(source);\n        stackDest.push(destination);\n      }\n    }\n  } else {\n    if (source === destination) throw ngMinErr('cpi',\n      \"Can't copy! Source and destination are identical.\");\n\n    stackSource = stackSource || [];\n    stackDest = stackDest || [];\n\n    if (isObject(source)) {\n      stackSource.push(source);\n      stackDest.push(destination);\n    }\n\n    var result, key;\n    if (isArray(source)) {\n      destination.length = 0;\n      for (var i = 0; i < source.length; i++) {\n        destination.push(copy(source[i], null, stackSource, stackDest));\n      }\n    } else {\n      var h = destination.$$hashKey;\n      if (isArray(destination)) {\n        destination.length = 0;\n      } else {\n        forEach(destination, function(value, key) {\n          delete destination[key];\n        });\n      }\n      if (isBlankObject(source)) {\n        // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty\n        for (key in source) {\n          destination[key] = copy(source[key], null, stackSource, stackDest);\n        }\n      } else if (source && typeof source.hasOwnProperty === 'function') {\n        // Slow path, which must rely on hasOwnProperty\n        for (key in source) {\n          if (source.hasOwnProperty(key)) {\n            destination[key] = copy(source[key], null, stackSource, stackDest);\n          }\n        }\n      } else {\n        // Slowest path --- hasOwnProperty can't be called as a method\n        for (key in source) {\n          if (hasOwnProperty.call(source, key)) {\n            destination[key] = copy(source[key], null, stackSource, stackDest);\n          }\n        }\n      }\n      setHashKey(destination,h);\n    }\n  }\n  return destination;\n}\n\n/**\n * Creates a shallow copy of an object, an array or a primitive.\n *\n * Assumes that there are no proto properties for objects.\n */\nfunction shallowCopy(src, dst) {\n  if (isArray(src)) {\n    dst = dst || [];\n\n    for (var i = 0, ii = src.length; i < ii; i++) {\n      dst[i] = src[i];\n    }\n  } else if (isObject(src)) {\n    dst = dst || {};\n\n    for (var key in src) {\n      if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {\n        dst[key] = src[key];\n      }\n    }\n  }\n\n  return dst || src;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.equals\n * @module ng\n * @kind function\n *\n * @description\n * Determines if two objects or two values are equivalent. Supports value types, regular\n * expressions, arrays and objects.\n *\n * Two objects or values are considered equivalent if at least one of the following is true:\n *\n * * Both objects or values pass `===` comparison.\n * * Both objects or values are of the same type and all of their properties are equal by\n *   comparing them with `angular.equals`.\n * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)\n * * Both values represent the same regular expression (In JavaScript,\n *   /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual\n *   representation matches).\n *\n * During a property comparison, properties of `function` type and properties with names\n * that begin with `$` are ignored.\n *\n * Scope and DOMWindow objects are being compared only by identify (`===`).\n *\n * @param {*} o1 Object or value to compare.\n * @param {*} o2 Object or value to compare.\n * @returns {boolean} True if arguments are equal.\n */\nfunction equals(o1, o2) {\n  if (o1 === o2) return true;\n  if (o1 === null || o2 === null) return false;\n  if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN\n  var t1 = typeof o1, t2 = typeof o2, length, key, keySet;\n  if (t1 == t2) {\n    if (t1 == 'object') {\n      if (isArray(o1)) {\n        if (!isArray(o2)) return false;\n        if ((length = o1.length) == o2.length) {\n          for (key = 0; key < length; key++) {\n            if (!equals(o1[key], o2[key])) return false;\n          }\n          return true;\n        }\n      } else if (isDate(o1)) {\n        if (!isDate(o2)) return false;\n        return equals(o1.getTime(), o2.getTime());\n      } else if (isRegExp(o1)) {\n        return isRegExp(o2) ? o1.toString() == o2.toString() : false;\n      } else {\n        if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||\n          isArray(o2) || isDate(o2) || isRegExp(o2)) return false;\n        keySet = createMap();\n        for (key in o1) {\n          if (key.charAt(0) === '$' || isFunction(o1[key])) continue;\n          if (!equals(o1[key], o2[key])) return false;\n          keySet[key] = true;\n        }\n        for (key in o2) {\n          if (!(key in keySet) &&\n              key.charAt(0) !== '$' &&\n              o2[key] !== undefined &&\n              !isFunction(o2[key])) return false;\n        }\n        return true;\n      }\n    }\n  }\n  return false;\n}\n\nvar csp = function() {\n  if (!isDefined(csp.rules)) {\n\n\n    var ngCspElement = (document.querySelector('[ng-csp]') ||\n                    document.querySelector('[data-ng-csp]'));\n\n    if (ngCspElement) {\n      var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||\n                    ngCspElement.getAttribute('data-ng-csp');\n      csp.rules = {\n        noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),\n        noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)\n      };\n    } else {\n      csp.rules = {\n        noUnsafeEval: noUnsafeEval(),\n        noInlineStyle: false\n      };\n    }\n  }\n\n  return csp.rules;\n\n  function noUnsafeEval() {\n    try {\n      /* jshint -W031, -W054 */\n      new Function('');\n      /* jshint +W031, +W054 */\n      return false;\n    } catch (e) {\n      return true;\n    }\n  }\n};\n\n/**\n * @ngdoc directive\n * @module ng\n * @name ngJq\n *\n * @element ANY\n * @param {string=} ngJq the name of the library available under `window`\n * to be used for angular.element\n * @description\n * Use this directive to force the angular.element library.  This should be\n * used to force either jqLite by leaving ng-jq blank or setting the name of\n * the jquery variable under window (eg. jQuery).\n *\n * Since angular looks for this directive when it is loaded (doesn't wait for the\n * DOMContentLoaded event), it must be placed on an element that comes before the script\n * which loads angular. Also, only the first instance of `ng-jq` will be used and all\n * others ignored.\n *\n * @example\n * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.\n ```html\n <!doctype html>\n <html ng-app ng-jq>\n ...\n ...\n </html>\n ```\n * @example\n * This example shows how to use a jQuery based library of a different name.\n * The library name must be available at the top most 'window'.\n ```html\n <!doctype html>\n <html ng-app ng-jq=\"jQueryLib\">\n ...\n ...\n </html>\n ```\n */\nvar jq = function() {\n  if (isDefined(jq.name_)) return jq.name_;\n  var el;\n  var i, ii = ngAttrPrefixes.length, prefix, name;\n  for (i = 0; i < ii; ++i) {\n    prefix = ngAttrPrefixes[i];\n    if (el = document.querySelector('[' + prefix.replace(':', '\\\\:') + 'jq]')) {\n      name = el.getAttribute(prefix + 'jq');\n      break;\n    }\n  }\n\n  return (jq.name_ = name);\n};\n\nfunction concat(array1, array2, index) {\n  return array1.concat(slice.call(array2, index));\n}\n\nfunction sliceArgs(args, startIndex) {\n  return slice.call(args, startIndex || 0);\n}\n\n\n/* jshint -W101 */\n/**\n * @ngdoc function\n * @name angular.bind\n * @module ng\n * @kind function\n *\n * @description\n * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for\n * `fn`). You can supply optional `args` that are prebound to the function. This feature is also\n * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as\n * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).\n *\n * @param {Object} self Context which `fn` should be evaluated in.\n * @param {function()} fn Function to be bound.\n * @param {...*} args Optional arguments to be prebound to the `fn` function call.\n * @returns {function()} Function that wraps the `fn` with all the specified bindings.\n */\n/* jshint +W101 */\nfunction bind(self, fn) {\n  var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];\n  if (isFunction(fn) && !(fn instanceof RegExp)) {\n    return curryArgs.length\n      ? function() {\n          return arguments.length\n            ? fn.apply(self, concat(curryArgs, arguments, 0))\n            : fn.apply(self, curryArgs);\n        }\n      : function() {\n          return arguments.length\n            ? fn.apply(self, arguments)\n            : fn.call(self);\n        };\n  } else {\n    // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)\n    return fn;\n  }\n}\n\n\nfunction toJsonReplacer(key, value) {\n  var val = value;\n\n  if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {\n    val = undefined;\n  } else if (isWindow(value)) {\n    val = '$WINDOW';\n  } else if (value &&  document === value) {\n    val = '$DOCUMENT';\n  } else if (isScope(value)) {\n    val = '$SCOPE';\n  }\n\n  return val;\n}\n\n\n/**\n * @ngdoc function\n * @name angular.toJson\n * @module ng\n * @kind function\n *\n * @description\n * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be\n * stripped since angular uses this notation internally.\n *\n * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.\n * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.\n *    If set to an integer, the JSON output will contain that many spaces per indentation.\n * @returns {string|undefined} JSON-ified string representing `obj`.\n */\nfunction toJson(obj, pretty) {\n  if (typeof obj === 'undefined') return undefined;\n  if (!isNumber(pretty)) {\n    pretty = pretty ? 2 : null;\n  }\n  return JSON.stringify(obj, toJsonReplacer, pretty);\n}\n\n\n/**\n * @ngdoc function\n * @name angular.fromJson\n * @module ng\n * @kind function\n *\n * @description\n * Deserializes a JSON string.\n *\n * @param {string} json JSON string to deserialize.\n * @returns {Object|Array|string|number} Deserialized JSON string.\n */\nfunction fromJson(json) {\n  return isString(json)\n      ? JSON.parse(json)\n      : json;\n}\n\n\nfunction timezoneToOffset(timezone, fallback) {\n  var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;\n  return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;\n}\n\n\nfunction addDateMinutes(date, minutes) {\n  date = new Date(date.getTime());\n  date.setMinutes(date.getMinutes() + minutes);\n  return date;\n}\n\n\nfunction convertTimezoneToLocal(date, timezone, reverse) {\n  reverse = reverse ? -1 : 1;\n  var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());\n  return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));\n}\n\n\n/**\n * @returns {string} Returns the string representation of the element.\n */\nfunction startingTag(element) {\n  element = jqLite(element).clone();\n  try {\n    // turns out IE does not let you set .html() on elements which\n    // are not allowed to have children. So we just ignore it.\n    element.empty();\n  } catch (e) {}\n  var elemHtml = jqLite('<div>').append(element).html();\n  try {\n    return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :\n        elemHtml.\n          match(/^(<[^>]+>)/)[1].\n          replace(/^<([\\w\\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });\n  } catch (e) {\n    return lowercase(elemHtml);\n  }\n\n}\n\n\n/////////////////////////////////////////////////\n\n/**\n * Tries to decode the URI component without throwing an exception.\n *\n * @private\n * @param str value potential URI component to check.\n * @returns {boolean} True if `value` can be decoded\n * with the decodeURIComponent function.\n */\nfunction tryDecodeURIComponent(value) {\n  try {\n    return decodeURIComponent(value);\n  } catch (e) {\n    // Ignore any invalid uri component\n  }\n}\n\n\n/**\n * Parses an escaped url query string into key-value pairs.\n * @returns {Object.<string,boolean|Array>}\n */\nfunction parseKeyValue(/**string*/keyValue) {\n  var obj = {};\n  forEach((keyValue || \"\").split('&'), function(keyValue) {\n    var splitPoint, key, val;\n    if (keyValue) {\n      key = keyValue = keyValue.replace(/\\+/g,'%20');\n      splitPoint = keyValue.indexOf('=');\n      if (splitPoint !== -1) {\n        key = keyValue.substring(0, splitPoint);\n        val = keyValue.substring(splitPoint + 1);\n      }\n      key = tryDecodeURIComponent(key);\n      if (isDefined(key)) {\n        val = isDefined(val) ? tryDecodeURIComponent(val) : true;\n        if (!hasOwnProperty.call(obj, key)) {\n          obj[key] = val;\n        } else if (isArray(obj[key])) {\n          obj[key].push(val);\n        } else {\n          obj[key] = [obj[key],val];\n        }\n      }\n    }\n  });\n  return obj;\n}\n\nfunction toKeyValue(obj) {\n  var parts = [];\n  forEach(obj, function(value, key) {\n    if (isArray(value)) {\n      forEach(value, function(arrayValue) {\n        parts.push(encodeUriQuery(key, true) +\n                   (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));\n      });\n    } else {\n    parts.push(encodeUriQuery(key, true) +\n               (value === true ? '' : '=' + encodeUriQuery(value, true)));\n    }\n  });\n  return parts.length ? parts.join('&') : '';\n}\n\n\n/**\n * We need our custom method because encodeURIComponent is too aggressive and doesn't follow\n * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path\n * segments:\n *    segment       = *pchar\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriSegment(val) {\n  return encodeUriQuery(val, true).\n             replace(/%26/gi, '&').\n             replace(/%3D/gi, '=').\n             replace(/%2B/gi, '+');\n}\n\n\n/**\n * This method is intended for encoding *key* or *value* parts of query component. We need a custom\n * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be\n * encoded per http://tools.ietf.org/html/rfc3986:\n *    query       = *( pchar / \"/\" / \"?\" )\n *    pchar         = unreserved / pct-encoded / sub-delims / \":\" / \"@\"\n *    unreserved    = ALPHA / DIGIT / \"-\" / \".\" / \"_\" / \"~\"\n *    pct-encoded   = \"%\" HEXDIG HEXDIG\n *    sub-delims    = \"!\" / \"$\" / \"&\" / \"'\" / \"(\" / \")\"\n *                     / \"*\" / \"+\" / \",\" / \";\" / \"=\"\n */\nfunction encodeUriQuery(val, pctEncodeSpaces) {\n  return encodeURIComponent(val).\n             replace(/%40/gi, '@').\n             replace(/%3A/gi, ':').\n             replace(/%24/g, '$').\n             replace(/%2C/gi, ',').\n             replace(/%3B/gi, ';').\n             replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n}\n\nvar ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];\n\nfunction getNgAttribute(element, ngAttr) {\n  var attr, i, ii = ngAttrPrefixes.length;\n  for (i = 0; i < ii; ++i) {\n    attr = ngAttrPrefixes[i] + ngAttr;\n    if (isString(attr = element.getAttribute(attr))) {\n      return attr;\n    }\n  }\n  return null;\n}\n\n/**\n * @ngdoc directive\n * @name ngApp\n * @module ng\n *\n * @element ANY\n * @param {angular.Module} ngApp an optional application\n *   {@link angular.module module} name to load.\n * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be\n *   created in \"strict-di\" mode. This means that the application will fail to invoke functions which\n *   do not use explicit function annotation (and are thus unsuitable for minification), as described\n *   in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in\n *   tracking down the root of these bugs.\n *\n * @description\n *\n * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive\n * designates the **root element** of the application and is typically placed near the root element\n * of the page - e.g. on the `<body>` or `<html>` tags.\n *\n * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`\n * found in the document will be used to define the root element to auto-bootstrap as an\n * application. To run multiple applications in an HTML document you must manually bootstrap them using\n * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.\n *\n * You can specify an **AngularJS module** to be used as the root module for the application.  This\n * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It\n * should contain the application code needed or have dependencies on other modules that will\n * contain the code. See {@link angular.module} for more information.\n *\n * In the example below if the `ngApp` directive were not placed on the `html` element then the\n * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`\n * would not be resolved to `3`.\n *\n * `ngApp` is the easiest, and most common way to bootstrap an application.\n *\n <example module=\"ngAppDemo\">\n   <file name=\"index.html\">\n   <div ng-controller=\"ngAppDemoController\">\n     I can add: {{a}} + {{b}} =  {{ a+b }}\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {\n     $scope.a = 1;\n     $scope.b = 2;\n   });\n   </file>\n </example>\n *\n * Using `ngStrictDi`, you would see something like this:\n *\n <example ng-app-included=\"true\">\n   <file name=\"index.html\">\n   <div ng-app=\"ngAppStrictDemo\" ng-strict-di>\n       <div ng-controller=\"GoodController1\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style (see\n              script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"GoodController2\">\n           Name: <input ng-model=\"name\"><br />\n           Hello, {{name}}!\n\n           <p>This renders because the controller does not fail to\n              instantiate, by using explicit annotation style\n              (see script.js for details)\n           </p>\n       </div>\n\n       <div ng-controller=\"BadController\">\n           I can add: {{a}} + {{b}} =  {{ a+b }}\n\n           <p>The controller could not be instantiated, due to relying\n              on automatic function annotations (which are disabled in\n              strict mode). As such, the content of this section is not\n              interpolated, and there should be an error in your web console.\n           </p>\n       </div>\n   </div>\n   </file>\n   <file name=\"script.js\">\n   angular.module('ngAppStrictDemo', [])\n     // BadController will fail to instantiate, due to relying on automatic function annotation,\n     // rather than an explicit annotation\n     .controller('BadController', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     })\n     // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,\n     // due to using explicit annotations using the array style and $inject property, respectively.\n     .controller('GoodController1', ['$scope', function($scope) {\n       $scope.a = 1;\n       $scope.b = 2;\n     }])\n     .controller('GoodController2', GoodController2);\n     function GoodController2($scope) {\n       $scope.name = \"World\";\n     }\n     GoodController2.$inject = ['$scope'];\n   </file>\n   <file name=\"style.css\">\n   div[ng-controller] {\n       margin-bottom: 1em;\n       -webkit-border-radius: 4px;\n       border-radius: 4px;\n       border: 1px solid;\n       padding: .5em;\n   }\n   div[ng-controller^=Good] {\n       border-color: #d6e9c6;\n       background-color: #dff0d8;\n       color: #3c763d;\n   }\n   div[ng-controller^=Bad] {\n       border-color: #ebccd1;\n       background-color: #f2dede;\n       color: #a94442;\n       margin-bottom: 0;\n   }\n   </file>\n </example>\n */\nfunction angularInit(element, bootstrap) {\n  var appElement,\n      module,\n      config = {};\n\n  // The element `element` has priority over any other element\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n\n    if (!appElement && element.hasAttribute && element.hasAttribute(name)) {\n      appElement = element;\n      module = element.getAttribute(name);\n    }\n  });\n  forEach(ngAttrPrefixes, function(prefix) {\n    var name = prefix + 'app';\n    var candidate;\n\n    if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\\\:') + ']'))) {\n      appElement = candidate;\n      module = candidate.getAttribute(name);\n    }\n  });\n  if (appElement) {\n    config.strictDi = getNgAttribute(appElement, \"strict-di\") !== null;\n    bootstrap(appElement, module ? [module] : [], config);\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.bootstrap\n * @module ng\n * @description\n * Use this function to manually start up angular application.\n *\n * See: {@link guide/bootstrap Bootstrap}\n *\n * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.\n * They must use {@link ng.directive:ngApp ngApp}.\n *\n * Angular will detect if it has been loaded into the browser more than once and only allow the\n * first loaded script to be bootstrapped and will report a warning to the browser console for\n * each of the subsequent scripts. This prevents strange results in applications, where otherwise\n * multiple instances of Angular try to work on the DOM.\n *\n * ```html\n * <!doctype html>\n * <html>\n * <body>\n * <div ng-controller=\"WelcomeController\">\n *   {{greeting}}\n * </div>\n *\n * <script src=\"angular.js\"></script>\n * <script>\n *   var app = angular.module('demo', [])\n *   .controller('WelcomeController', function($scope) {\n *       $scope.greeting = 'Welcome!';\n *   });\n *   angular.bootstrap(document, ['demo']);\n * </script>\n * </body>\n * </html>\n * ```\n *\n * @param {DOMElement} element DOM element which is the root of angular application.\n * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.\n *     Each item in the array should be the name of a predefined module or a (DI annotated)\n *     function that will be invoked by the injector as a `config` block.\n *     See: {@link angular.module modules}\n * @param {Object=} config an object for defining configuration options for the application. The\n *     following keys are supported:\n *\n * * `strictDi` - disable automatic function annotation for the application. This is meant to\n *   assist in finding bugs which break minified code. Defaults to `false`.\n *\n * @returns {auto.$injector} Returns the newly created injector for this app.\n */\nfunction bootstrap(element, modules, config) {\n  if (!isObject(config)) config = {};\n  var defaultConfig = {\n    strictDi: false\n  };\n  config = extend(defaultConfig, config);\n  var doBootstrap = function() {\n    element = jqLite(element);\n\n    if (element.injector()) {\n      var tag = (element[0] === document) ? 'document' : startingTag(element);\n      //Encode angle brackets to prevent input from being sanitized to empty string #8683\n      throw ngMinErr(\n          'btstrpd',\n          \"App Already Bootstrapped with this Element '{0}'\",\n          tag.replace(/</,'&lt;').replace(/>/,'&gt;'));\n    }\n\n    modules = modules || [];\n    modules.unshift(['$provide', function($provide) {\n      $provide.value('$rootElement', element);\n    }]);\n\n    if (config.debugInfoEnabled) {\n      // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.\n      modules.push(['$compileProvider', function($compileProvider) {\n        $compileProvider.debugInfoEnabled(true);\n      }]);\n    }\n\n    modules.unshift('ng');\n    var injector = createInjector(modules, config.strictDi);\n    injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',\n       function bootstrapApply(scope, element, compile, injector) {\n        scope.$apply(function() {\n          element.data('$injector', injector);\n          compile(element)(scope);\n        });\n      }]\n    );\n    return injector;\n  };\n\n  var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;\n  var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;\n\n  if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {\n    config.debugInfoEnabled = true;\n    window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');\n  }\n\n  if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {\n    return doBootstrap();\n  }\n\n  window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');\n  angular.resumeBootstrap = function(extraModules) {\n    forEach(extraModules, function(module) {\n      modules.push(module);\n    });\n    return doBootstrap();\n  };\n\n  if (isFunction(angular.resumeDeferredBootstrap)) {\n    angular.resumeDeferredBootstrap();\n  }\n}\n\n/**\n * @ngdoc function\n * @name angular.reloadWithDebugInfo\n * @module ng\n * @description\n * Use this function to reload the current application with debug information turned on.\n * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.\n *\n * See {@link ng.$compileProvider#debugInfoEnabled} for more.\n */\nfunction reloadWithDebugInfo() {\n  window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;\n  window.location.reload();\n}\n\n/**\n * @name angular.getTestability\n * @module ng\n * @description\n * Get the testability service for the instance of Angular on the given\n * element.\n * @param {DOMElement} element DOM element which is the root of angular application.\n */\nfunction getTestability(rootElement) {\n  var injector = angular.element(rootElement).injector();\n  if (!injector) {\n    throw ngMinErr('test',\n      'no injector found for element argument to getTestability');\n  }\n  return injector.get('$$testability');\n}\n\nvar SNAKE_CASE_REGEXP = /[A-Z]/g;\nfunction snake_case(name, separator) {\n  separator = separator || '_';\n  return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {\n    return (pos ? separator : '') + letter.toLowerCase();\n  });\n}\n\nvar bindJQueryFired = false;\nvar skipDestroyOnNextJQueryCleanData;\nfunction bindJQuery() {\n  var originalCleanData;\n\n  if (bindJQueryFired) {\n    return;\n  }\n\n  // bind to jQuery if present;\n  var jqName = jq();\n  jQuery = window.jQuery; // use default jQuery.\n  if (isDefined(jqName)) { // `ngJq` present\n    jQuery = jqName === null ? undefined : window[jqName]; // if empty; use jqLite. if not empty, use jQuery specified by `ngJq`.\n  }\n\n  // Use jQuery if it exists with proper functionality, otherwise default to us.\n  // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.\n  // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older\n  // versions. It will not work for sure with jQuery <1.7, though.\n  if (jQuery && jQuery.fn.on) {\n    jqLite = jQuery;\n    extend(jQuery.fn, {\n      scope: JQLitePrototype.scope,\n      isolateScope: JQLitePrototype.isolateScope,\n      controller: JQLitePrototype.controller,\n      injector: JQLitePrototype.injector,\n      inheritedData: JQLitePrototype.inheritedData\n    });\n\n    // All nodes removed from the DOM via various jQuery APIs like .remove()\n    // are passed through jQuery.cleanData. Monkey-patch this method to fire\n    // the $destroy event on all removed nodes.\n    originalCleanData = jQuery.cleanData;\n    jQuery.cleanData = function(elems) {\n      var events;\n      if (!skipDestroyOnNextJQueryCleanData) {\n        for (var i = 0, elem; (elem = elems[i]) != null; i++) {\n          events = jQuery._data(elem, \"events\");\n          if (events && events.$destroy) {\n            jQuery(elem).triggerHandler('$destroy');\n          }\n        }\n      } else {\n        skipDestroyOnNextJQueryCleanData = false;\n      }\n      originalCleanData(elems);\n    };\n  } else {\n    jqLite = JQLite;\n  }\n\n  angular.element = jqLite;\n\n  // Prevent double-proxying.\n  bindJQueryFired = true;\n}\n\n/**\n * throw error if the argument is falsy.\n */\nfunction assertArg(arg, name, reason) {\n  if (!arg) {\n    throw ngMinErr('areq', \"Argument '{0}' is {1}\", (name || '?'), (reason || \"required\"));\n  }\n  return arg;\n}\n\nfunction assertArgFn(arg, name, acceptArrayAnnotation) {\n  if (acceptArrayAnnotation && isArray(arg)) {\n      arg = arg[arg.length - 1];\n  }\n\n  assertArg(isFunction(arg), name, 'not a function, got ' +\n      (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));\n  return arg;\n}\n\n/**\n * throw error if the name given is hasOwnProperty\n * @param  {String} name    the name to test\n * @param  {String} context the context in which the name is used, such as module or directive\n */\nfunction assertNotHasOwnProperty(name, context) {\n  if (name === 'hasOwnProperty') {\n    throw ngMinErr('badname', \"hasOwnProperty is not a valid {0} name\", context);\n  }\n}\n\n/**\n * Return the value accessible from the object by path. Any undefined traversals are ignored\n * @param {Object} obj starting object\n * @param {String} path path to traverse\n * @param {boolean} [bindFnToScope=true]\n * @returns {Object} value as accessible by path\n */\n//TODO(misko): this function needs to be removed\nfunction getter(obj, path, bindFnToScope) {\n  if (!path) return obj;\n  var keys = path.split('.');\n  var key;\n  var lastInstance = obj;\n  var len = keys.length;\n\n  for (var i = 0; i < len; i++) {\n    key = keys[i];\n    if (obj) {\n      obj = (lastInstance = obj)[key];\n    }\n  }\n  if (!bindFnToScope && isFunction(obj)) {\n    return bind(lastInstance, obj);\n  }\n  return obj;\n}\n\n/**\n * Return the DOM siblings between the first and last node in the given array.\n * @param {Array} array like object\n * @returns {jqLite} jqLite collection containing the nodes\n */\nfunction getBlockNodes(nodes) {\n  // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original\n  //             collection, otherwise update the original collection.\n  var node = nodes[0];\n  var endNode = nodes[nodes.length - 1];\n  var blockNodes = [node];\n\n  do {\n    node = node.nextSibling;\n    if (!node) break;\n    blockNodes.push(node);\n  } while (node !== endNode);\n\n  return jqLite(blockNodes);\n}\n\n\n/**\n * Creates a new object without a prototype. This object is useful for lookup without having to\n * guard against prototypically inherited properties via hasOwnProperty.\n *\n * Related micro-benchmarks:\n * - http://jsperf.com/object-create2\n * - http://jsperf.com/proto-map-lookup/2\n * - http://jsperf.com/for-in-vs-object-keys2\n *\n * @returns {Object}\n */\nfunction createMap() {\n  return Object.create(null);\n}\n\nvar NODE_TYPE_ELEMENT = 1;\nvar NODE_TYPE_ATTRIBUTE = 2;\nvar NODE_TYPE_TEXT = 3;\nvar NODE_TYPE_COMMENT = 8;\nvar NODE_TYPE_DOCUMENT = 9;\nvar NODE_TYPE_DOCUMENT_FRAGMENT = 11;\n\n/**\n * @ngdoc type\n * @name angular.Module\n * @module ng\n * @description\n *\n * Interface for configuring angular {@link angular.module modules}.\n */\n\nfunction setupModuleLoader(window) {\n\n  var $injectorMinErr = minErr('$injector');\n  var ngMinErr = minErr('ng');\n\n  function ensure(obj, name, factory) {\n    return obj[name] || (obj[name] = factory());\n  }\n\n  var angular = ensure(window, 'angular', Object);\n\n  // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap\n  angular.$$minErr = angular.$$minErr || minErr;\n\n  return ensure(angular, 'module', function() {\n    /** @type {Object.<string, angular.Module>} */\n    var modules = {};\n\n    /**\n     * @ngdoc function\n     * @name angular.module\n     * @module ng\n     * @description\n     *\n     * The `angular.module` is a global place for creating, registering and retrieving Angular\n     * modules.\n     * All modules (angular core or 3rd party) that should be available to an application must be\n     * registered using this mechanism.\n     *\n     * Passing one argument retrieves an existing {@link angular.Module},\n     * whereas passing more than one argument creates a new {@link angular.Module}\n     *\n     *\n     * # Module\n     *\n     * A module is a collection of services, directives, controllers, filters, and configuration information.\n     * `angular.module` is used to configure the {@link auto.$injector $injector}.\n     *\n     * ```js\n     * // Create a new module\n     * var myModule = angular.module('myModule', []);\n     *\n     * // register a new service\n     * myModule.value('appName', 'MyCoolApp');\n     *\n     * // configure existing services inside initialization blocks.\n     * myModule.config(['$locationProvider', function($locationProvider) {\n     *   // Configure existing providers\n     *   $locationProvider.hashPrefix('!');\n     * }]);\n     * ```\n     *\n     * Then you can create an injector and load your modules like this:\n     *\n     * ```js\n     * var injector = angular.injector(['ng', 'myModule'])\n     * ```\n     *\n     * However it's more likely that you'll just use\n     * {@link ng.directive:ngApp ngApp} or\n     * {@link angular.bootstrap} to simplify this process for you.\n     *\n     * @param {!string} name The name of the module to create or retrieve.\n     * @param {!Array.<string>=} requires If specified then new module is being created. If\n     *        unspecified then the module is being retrieved for further configuration.\n     * @param {Function=} configFn Optional configuration function for the module. Same as\n     *        {@link angular.Module#config Module#config()}.\n     * @returns {module} new module with the {@link angular.Module} api.\n     */\n    return function module(name, requires, configFn) {\n      var assertNotHasOwnProperty = function(name, context) {\n        if (name === 'hasOwnProperty') {\n          throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);\n        }\n      };\n\n      assertNotHasOwnProperty(name, 'module');\n      if (requires && modules.hasOwnProperty(name)) {\n        modules[name] = null;\n      }\n      return ensure(modules, name, function() {\n        if (!requires) {\n          throw $injectorMinErr('nomod', \"Module '{0}' is not available! You either misspelled \" +\n             \"the module name or forgot to load it. If registering a module ensure that you \" +\n             \"specify the dependencies as the second argument.\", name);\n        }\n\n        /** @type {!Array.<Array.<*>>} */\n        var invokeQueue = [];\n\n        /** @type {!Array.<Function>} */\n        var configBlocks = [];\n\n        /** @type {!Array.<Function>} */\n        var runBlocks = [];\n\n        var config = invokeLater('$injector', 'invoke', 'push', configBlocks);\n\n        /** @type {angular.Module} */\n        var moduleInstance = {\n          // Private state\n          _invokeQueue: invokeQueue,\n          _configBlocks: configBlocks,\n          _runBlocks: runBlocks,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#requires\n           * @module ng\n           *\n           * @description\n           * Holds the list of modules which the injector will load before the current module is\n           * loaded.\n           */\n          requires: requires,\n\n          /**\n           * @ngdoc property\n           * @name angular.Module#name\n           * @module ng\n           *\n           * @description\n           * Name of the module.\n           */\n          name: name,\n\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#provider\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerType Construction function for creating new instance of the\n           *                                service.\n           * @description\n           * See {@link auto.$provide#provider $provide.provider()}.\n           */\n          provider: invokeLaterAndSetModuleName('$provide', 'provider'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#factory\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} providerFunction Function for creating new instance of the service.\n           * @description\n           * See {@link auto.$provide#factory $provide.factory()}.\n           */\n          factory: invokeLaterAndSetModuleName('$provide', 'factory'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#service\n           * @module ng\n           * @param {string} name service name\n           * @param {Function} constructor A constructor function that will be instantiated.\n           * @description\n           * See {@link auto.$provide#service $provide.service()}.\n           */\n          service: invokeLaterAndSetModuleName('$provide', 'service'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#value\n           * @module ng\n           * @param {string} name service name\n           * @param {*} object Service instance object.\n           * @description\n           * See {@link auto.$provide#value $provide.value()}.\n           */\n          value: invokeLater('$provide', 'value'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#constant\n           * @module ng\n           * @param {string} name constant name\n           * @param {*} object Constant value.\n           * @description\n           * Because the constant are fixed, they get applied before other provide methods.\n           * See {@link auto.$provide#constant $provide.constant()}.\n           */\n          constant: invokeLater('$provide', 'constant', 'unshift'),\n\n           /**\n           * @ngdoc method\n           * @name angular.Module#decorator\n           * @module ng\n           * @param {string} The name of the service to decorate.\n           * @param {Function} This function will be invoked when the service needs to be\n           *                                    instantiated and should return the decorated service instance.\n           * @description\n           * See {@link auto.$provide#decorator $provide.decorator()}.\n           */\n          decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#animation\n           * @module ng\n           * @param {string} name animation name\n           * @param {Function} animationFactory Factory function for creating new instance of an\n           *                                    animation.\n           * @description\n           *\n           * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.\n           *\n           *\n           * Defines an animation hook that can be later used with\n           * {@link $animate $animate} service and directives that use this service.\n           *\n           * ```js\n           * module.animation('.animation-name', function($inject1, $inject2) {\n           *   return {\n           *     eventName : function(element, done) {\n           *       //code to run the animation\n           *       //once complete, then run done()\n           *       return function cancellationFunction(element) {\n           *         //code to cancel the animation\n           *       }\n           *     }\n           *   }\n           * })\n           * ```\n           *\n           * See {@link ng.$animateProvider#register $animateProvider.register()} and\n           * {@link ngAnimate ngAnimate module} for more information.\n           */\n          animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#filter\n           * @module ng\n           * @param {string} name Filter name - this must be a valid angular expression identifier\n           * @param {Function} filterFactory Factory function for creating new instance of filter.\n           * @description\n           * See {@link ng.$filterProvider#register $filterProvider.register()}.\n           *\n           * <div class=\"alert alert-warning\">\n           * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n           * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n           * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n           * (`myapp_subsection_filterx`).\n           * </div>\n           */\n          filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#controller\n           * @module ng\n           * @param {string|Object} name Controller name, or an object map of controllers where the\n           *    keys are the names and the values are the constructors.\n           * @param {Function} constructor Controller constructor function.\n           * @description\n           * See {@link ng.$controllerProvider#register $controllerProvider.register()}.\n           */\n          controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#directive\n           * @module ng\n           * @param {string|Object} name Directive name, or an object map of directives where the\n           *    keys are the names and the values are the factories.\n           * @param {Function} directiveFactory Factory function for creating new instance of\n           * directives.\n           * @description\n           * See {@link ng.$compileProvider#directive $compileProvider.directive()}.\n           */\n          directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#config\n           * @module ng\n           * @param {Function} configFn Execute this function on module load. Useful for service\n           *    configuration.\n           * @description\n           * Use this method to register work which needs to be performed on module loading.\n           * For more about how to configure services, see\n           * {@link providers#provider-recipe Provider Recipe}.\n           */\n          config: config,\n\n          /**\n           * @ngdoc method\n           * @name angular.Module#run\n           * @module ng\n           * @param {Function} initializationFn Execute this function after injector creation.\n           *    Useful for application initialization.\n           * @description\n           * Use this method to register work which should be performed when the injector is done\n           * loading all modules.\n           */\n          run: function(block) {\n            runBlocks.push(block);\n            return this;\n          }\n        };\n\n        if (configFn) {\n          config(configFn);\n        }\n\n        return moduleInstance;\n\n        /**\n         * @param {string} provider\n         * @param {string} method\n         * @param {String=} insertMethod\n         * @returns {angular.Module}\n         */\n        function invokeLater(provider, method, insertMethod, queue) {\n          if (!queue) queue = invokeQueue;\n          return function() {\n            queue[insertMethod || 'push']([provider, method, arguments]);\n            return moduleInstance;\n          };\n        }\n\n        /**\n         * @param {string} provider\n         * @param {string} method\n         * @returns {angular.Module}\n         */\n        function invokeLaterAndSetModuleName(provider, method) {\n          return function(recipeName, factoryFunction) {\n            if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;\n            invokeQueue.push([provider, method, arguments]);\n            return moduleInstance;\n          };\n        }\n      });\n    };\n  });\n\n}\n\n/* global: toDebugString: true */\n\nfunction serializeObject(obj) {\n  var seen = [];\n\n  return JSON.stringify(obj, function(key, val) {\n    val = toJsonReplacer(key, val);\n    if (isObject(val)) {\n\n      if (seen.indexOf(val) >= 0) return '<<already seen>>';\n\n      seen.push(val);\n    }\n    return val;\n  });\n}\n\nfunction toDebugString(obj) {\n  if (typeof obj === 'function') {\n    return obj.toString().replace(/ \\{[\\s\\S]*$/, '');\n  } else if (typeof obj === 'undefined') {\n    return 'undefined';\n  } else if (typeof obj !== 'string') {\n    return serializeObject(obj);\n  }\n  return obj;\n}\n\n/* global angularModule: true,\n  version: true,\n\n  $CompileProvider,\n\n  htmlAnchorDirective,\n  inputDirective,\n  inputDirective,\n  formDirective,\n  scriptDirective,\n  selectDirective,\n  styleDirective,\n  optionDirective,\n  ngBindDirective,\n  ngBindHtmlDirective,\n  ngBindTemplateDirective,\n  ngClassDirective,\n  ngClassEvenDirective,\n  ngClassOddDirective,\n  ngCloakDirective,\n  ngControllerDirective,\n  ngFormDirective,\n  ngHideDirective,\n  ngIfDirective,\n  ngIncludeDirective,\n  ngIncludeFillContentDirective,\n  ngInitDirective,\n  ngNonBindableDirective,\n  ngPluralizeDirective,\n  ngRepeatDirective,\n  ngShowDirective,\n  ngStyleDirective,\n  ngSwitchDirective,\n  ngSwitchWhenDirective,\n  ngSwitchDefaultDirective,\n  ngOptionsDirective,\n  ngTranscludeDirective,\n  ngModelDirective,\n  ngListDirective,\n  ngChangeDirective,\n  patternDirective,\n  patternDirective,\n  requiredDirective,\n  requiredDirective,\n  minlengthDirective,\n  minlengthDirective,\n  maxlengthDirective,\n  maxlengthDirective,\n  ngValueDirective,\n  ngModelOptionsDirective,\n  ngAttributeAliasDirectives,\n  ngEventDirectives,\n\n  $AnchorScrollProvider,\n  $AnimateProvider,\n  $CoreAnimateCssProvider,\n  $$CoreAnimateQueueProvider,\n  $$CoreAnimateRunnerProvider,\n  $BrowserProvider,\n  $CacheFactoryProvider,\n  $ControllerProvider,\n  $DocumentProvider,\n  $ExceptionHandlerProvider,\n  $FilterProvider,\n  $$ForceReflowProvider,\n  $InterpolateProvider,\n  $IntervalProvider,\n  $$HashMapProvider,\n  $HttpProvider,\n  $HttpParamSerializerProvider,\n  $HttpParamSerializerJQLikeProvider,\n  $HttpBackendProvider,\n  $LocationProvider,\n  $LogProvider,\n  $ParseProvider,\n  $RootScopeProvider,\n  $QProvider,\n  $$QProvider,\n  $$SanitizeUriProvider,\n  $SceProvider,\n  $SceDelegateProvider,\n  $SnifferProvider,\n  $TemplateCacheProvider,\n  $TemplateRequestProvider,\n  $$TestabilityProvider,\n  $TimeoutProvider,\n  $$RAFProvider,\n  $WindowProvider,\n  $$jqLiteProvider,\n  $$CookieReaderProvider\n*/\n\n\n/**\n * @ngdoc object\n * @name angular.version\n * @module ng\n * @description\n * An object that contains information about the current AngularJS version. This object has the\n * following properties:\n *\n * - `full` – `{string}` – Full version string, such as \"0.9.18\".\n * - `major` – `{number}` – Major version number, such as \"0\".\n * - `minor` – `{number}` – Minor version number, such as \"9\".\n * - `dot` – `{number}` – Dot version number, such as \"18\".\n * - `codeName` – `{string}` – Code name of the release, such as \"jiggling-armfat\".\n */\nvar version = {\n  full: '1.4.4',    // all of these placeholder strings will be replaced by grunt's\n  major: 1,    // package task\n  minor: 4,\n  dot: 4,\n  codeName: 'pylon-requirement'\n};\n\n\nfunction publishExternalAPI(angular) {\n  extend(angular, {\n    'bootstrap': bootstrap,\n    'copy': copy,\n    'extend': extend,\n    'merge': merge,\n    'equals': equals,\n    'element': jqLite,\n    'forEach': forEach,\n    'injector': createInjector,\n    'noop': noop,\n    'bind': bind,\n    'toJson': toJson,\n    'fromJson': fromJson,\n    'identity': identity,\n    'isUndefined': isUndefined,\n    'isDefined': isDefined,\n    'isString': isString,\n    'isFunction': isFunction,\n    'isObject': isObject,\n    'isNumber': isNumber,\n    'isElement': isElement,\n    'isArray': isArray,\n    'version': version,\n    'isDate': isDate,\n    'lowercase': lowercase,\n    'uppercase': uppercase,\n    'callbacks': {counter: 0},\n    'getTestability': getTestability,\n    '$$minErr': minErr,\n    '$$csp': csp,\n    'reloadWithDebugInfo': reloadWithDebugInfo\n  });\n\n  angularModule = setupModuleLoader(window);\n\n  angularModule('ng', ['ngLocale'], ['$provide',\n    function ngModule($provide) {\n      // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.\n      $provide.provider({\n        $$sanitizeUri: $$SanitizeUriProvider\n      });\n      $provide.provider('$compile', $CompileProvider).\n        directive({\n            a: htmlAnchorDirective,\n            input: inputDirective,\n            textarea: inputDirective,\n            form: formDirective,\n            script: scriptDirective,\n            select: selectDirective,\n            style: styleDirective,\n            option: optionDirective,\n            ngBind: ngBindDirective,\n            ngBindHtml: ngBindHtmlDirective,\n            ngBindTemplate: ngBindTemplateDirective,\n            ngClass: ngClassDirective,\n            ngClassEven: ngClassEvenDirective,\n            ngClassOdd: ngClassOddDirective,\n            ngCloak: ngCloakDirective,\n            ngController: ngControllerDirective,\n            ngForm: ngFormDirective,\n            ngHide: ngHideDirective,\n            ngIf: ngIfDirective,\n            ngInclude: ngIncludeDirective,\n            ngInit: ngInitDirective,\n            ngNonBindable: ngNonBindableDirective,\n            ngPluralize: ngPluralizeDirective,\n            ngRepeat: ngRepeatDirective,\n            ngShow: ngShowDirective,\n            ngStyle: ngStyleDirective,\n            ngSwitch: ngSwitchDirective,\n            ngSwitchWhen: ngSwitchWhenDirective,\n            ngSwitchDefault: ngSwitchDefaultDirective,\n            ngOptions: ngOptionsDirective,\n            ngTransclude: ngTranscludeDirective,\n            ngModel: ngModelDirective,\n            ngList: ngListDirective,\n            ngChange: ngChangeDirective,\n            pattern: patternDirective,\n            ngPattern: patternDirective,\n            required: requiredDirective,\n            ngRequired: requiredDirective,\n            minlength: minlengthDirective,\n            ngMinlength: minlengthDirective,\n            maxlength: maxlengthDirective,\n            ngMaxlength: maxlengthDirective,\n            ngValue: ngValueDirective,\n            ngModelOptions: ngModelOptionsDirective\n        }).\n        directive({\n          ngInclude: ngIncludeFillContentDirective\n        }).\n        directive(ngAttributeAliasDirectives).\n        directive(ngEventDirectives);\n      $provide.provider({\n        $anchorScroll: $AnchorScrollProvider,\n        $animate: $AnimateProvider,\n        $animateCss: $CoreAnimateCssProvider,\n        $$animateQueue: $$CoreAnimateQueueProvider,\n        $$AnimateRunner: $$CoreAnimateRunnerProvider,\n        $browser: $BrowserProvider,\n        $cacheFactory: $CacheFactoryProvider,\n        $controller: $ControllerProvider,\n        $document: $DocumentProvider,\n        $exceptionHandler: $ExceptionHandlerProvider,\n        $filter: $FilterProvider,\n        $$forceReflow: $$ForceReflowProvider,\n        $interpolate: $InterpolateProvider,\n        $interval: $IntervalProvider,\n        $http: $HttpProvider,\n        $httpParamSerializer: $HttpParamSerializerProvider,\n        $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,\n        $httpBackend: $HttpBackendProvider,\n        $location: $LocationProvider,\n        $log: $LogProvider,\n        $parse: $ParseProvider,\n        $rootScope: $RootScopeProvider,\n        $q: $QProvider,\n        $$q: $$QProvider,\n        $sce: $SceProvider,\n        $sceDelegate: $SceDelegateProvider,\n        $sniffer: $SnifferProvider,\n        $templateCache: $TemplateCacheProvider,\n        $templateRequest: $TemplateRequestProvider,\n        $$testability: $$TestabilityProvider,\n        $timeout: $TimeoutProvider,\n        $window: $WindowProvider,\n        $$rAF: $$RAFProvider,\n        $$jqLite: $$jqLiteProvider,\n        $$HashMap: $$HashMapProvider,\n        $$cookieReader: $$CookieReaderProvider\n      });\n    }\n  ]);\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* global JQLitePrototype: true,\n  addEventListenerFn: true,\n  removeEventListenerFn: true,\n  BOOLEAN_ATTR: true,\n  ALIASED_ATTR: true,\n*/\n\n//////////////////////////////////\n//JQLite\n//////////////////////////////////\n\n/**\n * @ngdoc function\n * @name angular.element\n * @module ng\n * @kind function\n *\n * @description\n * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.\n *\n * If jQuery is available, `angular.element` is an alias for the\n * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`\n * delegates to Angular's built-in subset of jQuery, called \"jQuery lite\" or \"jqLite.\"\n *\n * <div class=\"alert alert-success\">jqLite is a tiny, API-compatible subset of jQuery that allows\n * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most\n * commonly needed functionality with the goal of having a very small footprint.</div>\n *\n * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.\n *\n * <div class=\"alert\">**Note:** all element references in Angular are always wrapped with jQuery or\n * jqLite; they are never raw DOM references.</div>\n *\n * ## Angular's jqLite\n * jqLite provides only the following jQuery methods:\n *\n * - [`addClass()`](http://api.jquery.com/addClass/)\n * - [`after()`](http://api.jquery.com/after/)\n * - [`append()`](http://api.jquery.com/append/)\n * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters\n * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData\n * - [`children()`](http://api.jquery.com/children/) - Does not support selectors\n * - [`clone()`](http://api.jquery.com/clone/)\n * - [`contents()`](http://api.jquery.com/contents/)\n * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.\n * - [`data()`](http://api.jquery.com/data/)\n * - [`detach()`](http://api.jquery.com/detach/)\n * - [`empty()`](http://api.jquery.com/empty/)\n * - [`eq()`](http://api.jquery.com/eq/)\n * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name\n * - [`hasClass()`](http://api.jquery.com/hasClass/)\n * - [`html()`](http://api.jquery.com/html/)\n * - [`next()`](http://api.jquery.com/next/) - Does not support selectors\n * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData\n * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors\n * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors\n * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors\n * - [`prepend()`](http://api.jquery.com/prepend/)\n * - [`prop()`](http://api.jquery.com/prop/)\n * - [`ready()`](http://api.jquery.com/ready/)\n * - [`remove()`](http://api.jquery.com/remove/)\n * - [`removeAttr()`](http://api.jquery.com/removeAttr/)\n * - [`removeClass()`](http://api.jquery.com/removeClass/)\n * - [`removeData()`](http://api.jquery.com/removeData/)\n * - [`replaceWith()`](http://api.jquery.com/replaceWith/)\n * - [`text()`](http://api.jquery.com/text/)\n * - [`toggleClass()`](http://api.jquery.com/toggleClass/)\n * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.\n * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces\n * - [`val()`](http://api.jquery.com/val/)\n * - [`wrap()`](http://api.jquery.com/wrap/)\n *\n * ## jQuery/jqLite Extras\n * Angular also provides the following additional methods and events to both jQuery and jqLite:\n *\n * ### Events\n * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event\n *    on all DOM nodes being removed.  This can be used to clean up any 3rd party bindings to the DOM\n *    element before it is removed.\n *\n * ### Methods\n * - `controller(name)` - retrieves the controller of the current element or its parent. By default\n *   retrieves controller associated with the `ngController` directive. If `name` is provided as\n *   camelCase directive name, then the controller for this directive will be retrieved (e.g.\n *   `'ngModel'`).\n * - `injector()` - retrieves the injector of the current element or its parent.\n * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current\n *   element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to\n *   be enabled.\n * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the\n *   current element. This getter should be used only on elements that contain a directive which starts a new isolate\n *   scope. Calling `scope()` on this element always returns the original non-isolate scope.\n *   Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.\n * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top\n *   parent element is reached.\n *\n * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.\n * @returns {Object} jQuery object.\n */\n\nJQLite.expando = 'ng339';\n\nvar jqCache = JQLite.cache = {},\n    jqId = 1,\n    addEventListenerFn = function(element, type, fn) {\n      element.addEventListener(type, fn, false);\n    },\n    removeEventListenerFn = function(element, type, fn) {\n      element.removeEventListener(type, fn, false);\n    };\n\n/*\n * !!! This is an undocumented \"private\" function !!!\n */\nJQLite._data = function(node) {\n  //jQuery always returns an object on cache miss\n  return this.cache[node[this.expando]] || {};\n};\n\nfunction jqNextId() { return ++jqId; }\n\n\nvar SPECIAL_CHARS_REGEXP = /([\\:\\-\\_]+(.))/g;\nvar MOZ_HACK_REGEXP = /^moz([A-Z])/;\nvar MOUSE_EVENT_MAP= { mouseleave: \"mouseout\", mouseenter: \"mouseover\"};\nvar jqLiteMinErr = minErr('jqLite');\n\n/**\n * Converts snake_case to camelCase.\n * Also there is special case for Moz prefix starting with upper case letter.\n * @param name Name to normalize\n */\nfunction camelCase(name) {\n  return name.\n    replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {\n      return offset ? letter.toUpperCase() : letter;\n    }).\n    replace(MOZ_HACK_REGEXP, 'Moz$1');\n}\n\nvar SINGLE_TAG_REGEXP = /^<(\\w+)\\s*\\/?>(?:<\\/\\1>|)$/;\nvar HTML_REGEXP = /<|&#?\\w+;/;\nvar TAG_NAME_REGEXP = /<([\\w:]+)/;\nvar XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\\w:]+)[^>]*)\\/>/gi;\n\nvar wrapMap = {\n  'option': [1, '<select multiple=\"multiple\">', '</select>'],\n\n  'thead': [1, '<table>', '</table>'],\n  'col': [2, '<table><colgroup>', '</colgroup></table>'],\n  'tr': [2, '<table><tbody>', '</tbody></table>'],\n  'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],\n  '_default': [0, \"\", \"\"]\n};\n\nwrapMap.optgroup = wrapMap.option;\nwrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;\nwrapMap.th = wrapMap.td;\n\n\nfunction jqLiteIsTextNode(html) {\n  return !HTML_REGEXP.test(html);\n}\n\nfunction jqLiteAcceptsData(node) {\n  // The window object can accept data but has no nodeType\n  // Otherwise we are only interested in elements (1) and documents (9)\n  var nodeType = node.nodeType;\n  return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;\n}\n\nfunction jqLiteHasData(node) {\n  for (var key in jqCache[node.ng339]) {\n    return true;\n  }\n  return false;\n}\n\nfunction jqLiteBuildFragment(html, context) {\n  var tmp, tag, wrap,\n      fragment = context.createDocumentFragment(),\n      nodes = [], i;\n\n  if (jqLiteIsTextNode(html)) {\n    // Convert non-html into a text node\n    nodes.push(context.createTextNode(html));\n  } else {\n    // Convert html into DOM nodes\n    tmp = tmp || fragment.appendChild(context.createElement(\"div\"));\n    tag = (TAG_NAME_REGEXP.exec(html) || [\"\", \"\"])[1].toLowerCase();\n    wrap = wrapMap[tag] || wrapMap._default;\n    tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, \"<$1></$2>\") + wrap[2];\n\n    // Descend through wrappers to the right content\n    i = wrap[0];\n    while (i--) {\n      tmp = tmp.lastChild;\n    }\n\n    nodes = concat(nodes, tmp.childNodes);\n\n    tmp = fragment.firstChild;\n    tmp.textContent = \"\";\n  }\n\n  // Remove wrapper from fragment\n  fragment.textContent = \"\";\n  fragment.innerHTML = \"\"; // Clear inner HTML\n  forEach(nodes, function(node) {\n    fragment.appendChild(node);\n  });\n\n  return fragment;\n}\n\nfunction jqLiteParseHTML(html, context) {\n  context = context || document;\n  var parsed;\n\n  if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {\n    return [context.createElement(parsed[1])];\n  }\n\n  if ((parsed = jqLiteBuildFragment(html, context))) {\n    return parsed.childNodes;\n  }\n\n  return [];\n}\n\n/////////////////////////////////////////////\nfunction JQLite(element) {\n  if (element instanceof JQLite) {\n    return element;\n  }\n\n  var argIsString;\n\n  if (isString(element)) {\n    element = trim(element);\n    argIsString = true;\n  }\n  if (!(this instanceof JQLite)) {\n    if (argIsString && element.charAt(0) != '<') {\n      throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');\n    }\n    return new JQLite(element);\n  }\n\n  if (argIsString) {\n    jqLiteAddNodes(this, jqLiteParseHTML(element));\n  } else {\n    jqLiteAddNodes(this, element);\n  }\n}\n\nfunction jqLiteClone(element) {\n  return element.cloneNode(true);\n}\n\nfunction jqLiteDealoc(element, onlyDescendants) {\n  if (!onlyDescendants) jqLiteRemoveData(element);\n\n  if (element.querySelectorAll) {\n    var descendants = element.querySelectorAll('*');\n    for (var i = 0, l = descendants.length; i < l; i++) {\n      jqLiteRemoveData(descendants[i]);\n    }\n  }\n}\n\nfunction jqLiteOff(element, type, fn, unsupported) {\n  if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');\n\n  var expandoStore = jqLiteExpandoStore(element);\n  var events = expandoStore && expandoStore.events;\n  var handle = expandoStore && expandoStore.handle;\n\n  if (!handle) return; //no listeners registered\n\n  if (!type) {\n    for (type in events) {\n      if (type !== '$destroy') {\n        removeEventListenerFn(element, type, handle);\n      }\n      delete events[type];\n    }\n  } else {\n    forEach(type.split(' '), function(type) {\n      if (isDefined(fn)) {\n        var listenerFns = events[type];\n        arrayRemove(listenerFns || [], fn);\n        if (listenerFns && listenerFns.length > 0) {\n          return;\n        }\n      }\n\n      removeEventListenerFn(element, type, handle);\n      delete events[type];\n    });\n  }\n}\n\nfunction jqLiteRemoveData(element, name) {\n  var expandoId = element.ng339;\n  var expandoStore = expandoId && jqCache[expandoId];\n\n  if (expandoStore) {\n    if (name) {\n      delete expandoStore.data[name];\n      return;\n    }\n\n    if (expandoStore.handle) {\n      if (expandoStore.events.$destroy) {\n        expandoStore.handle({}, '$destroy');\n      }\n      jqLiteOff(element);\n    }\n    delete jqCache[expandoId];\n    element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it\n  }\n}\n\n\nfunction jqLiteExpandoStore(element, createIfNecessary) {\n  var expandoId = element.ng339,\n      expandoStore = expandoId && jqCache[expandoId];\n\n  if (createIfNecessary && !expandoStore) {\n    element.ng339 = expandoId = jqNextId();\n    expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};\n  }\n\n  return expandoStore;\n}\n\n\nfunction jqLiteData(element, key, value) {\n  if (jqLiteAcceptsData(element)) {\n\n    var isSimpleSetter = isDefined(value);\n    var isSimpleGetter = !isSimpleSetter && key && !isObject(key);\n    var massGetter = !key;\n    var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);\n    var data = expandoStore && expandoStore.data;\n\n    if (isSimpleSetter) { // data('key', value)\n      data[key] = value;\n    } else {\n      if (massGetter) {  // data()\n        return data;\n      } else {\n        if (isSimpleGetter) { // data('key')\n          // don't force creation of expandoStore if it doesn't exist yet\n          return data && data[key];\n        } else { // mass-setter: data({key1: val1, key2: val2})\n          extend(data, key);\n        }\n      }\n    }\n  }\n}\n\nfunction jqLiteHasClass(element, selector) {\n  if (!element.getAttribute) return false;\n  return ((\" \" + (element.getAttribute('class') || '') + \" \").replace(/[\\n\\t]/g, \" \").\n      indexOf(\" \" + selector + \" \") > -1);\n}\n\nfunction jqLiteRemoveClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    forEach(cssClasses.split(' '), function(cssClass) {\n      element.setAttribute('class', trim(\n          (\" \" + (element.getAttribute('class') || '') + \" \")\n          .replace(/[\\n\\t]/g, \" \")\n          .replace(\" \" + trim(cssClass) + \" \", \" \"))\n      );\n    });\n  }\n}\n\nfunction jqLiteAddClass(element, cssClasses) {\n  if (cssClasses && element.setAttribute) {\n    var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')\n                            .replace(/[\\n\\t]/g, \" \");\n\n    forEach(cssClasses.split(' '), function(cssClass) {\n      cssClass = trim(cssClass);\n      if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {\n        existingClasses += cssClass + ' ';\n      }\n    });\n\n    element.setAttribute('class', trim(existingClasses));\n  }\n}\n\n\nfunction jqLiteAddNodes(root, elements) {\n  // THIS CODE IS VERY HOT. Don't make changes without benchmarking.\n\n  if (elements) {\n\n    // if a Node (the most common case)\n    if (elements.nodeType) {\n      root[root.length++] = elements;\n    } else {\n      var length = elements.length;\n\n      // if an Array or NodeList and not a Window\n      if (typeof length === 'number' && elements.window !== elements) {\n        if (length) {\n          for (var i = 0; i < length; i++) {\n            root[root.length++] = elements[i];\n          }\n        }\n      } else {\n        root[root.length++] = elements;\n      }\n    }\n  }\n}\n\n\nfunction jqLiteController(element, name) {\n  return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');\n}\n\nfunction jqLiteInheritedData(element, name, value) {\n  // if element is the document object work with the html element instead\n  // this makes $(document).scope() possible\n  if (element.nodeType == NODE_TYPE_DOCUMENT) {\n    element = element.documentElement;\n  }\n  var names = isArray(name) ? name : [name];\n\n  while (element) {\n    for (var i = 0, ii = names.length; i < ii; i++) {\n      if ((value = jqLite.data(element, names[i])) !== undefined) return value;\n    }\n\n    // If dealing with a document fragment node with a host element, and no parent, use the host\n    // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM\n    // to lookup parent controllers.\n    element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);\n  }\n}\n\nfunction jqLiteEmpty(element) {\n  jqLiteDealoc(element, true);\n  while (element.firstChild) {\n    element.removeChild(element.firstChild);\n  }\n}\n\nfunction jqLiteRemove(element, keepData) {\n  if (!keepData) jqLiteDealoc(element);\n  var parent = element.parentNode;\n  if (parent) parent.removeChild(element);\n}\n\n\nfunction jqLiteDocumentLoaded(action, win) {\n  win = win || window;\n  if (win.document.readyState === 'complete') {\n    // Force the action to be run async for consistent behaviour\n    // from the action's point of view\n    // i.e. it will definitely not be in a $apply\n    win.setTimeout(action);\n  } else {\n    // No need to unbind this handler as load is only ever called once\n    jqLite(win).on('load', action);\n  }\n}\n\n//////////////////////////////////////////\n// Functions which are declared directly.\n//////////////////////////////////////////\nvar JQLitePrototype = JQLite.prototype = {\n  ready: function(fn) {\n    var fired = false;\n\n    function trigger() {\n      if (fired) return;\n      fired = true;\n      fn();\n    }\n\n    // check if document is already loaded\n    if (document.readyState === 'complete') {\n      setTimeout(trigger);\n    } else {\n      this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9\n      // we can not use jqLite since we are not done loading and jQuery could be loaded later.\n      // jshint -W064\n      JQLite(window).on('load', trigger); // fallback to window.onload for others\n      // jshint +W064\n    }\n  },\n  toString: function() {\n    var value = [];\n    forEach(this, function(e) { value.push('' + e);});\n    return '[' + value.join(', ') + ']';\n  },\n\n  eq: function(index) {\n      return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);\n  },\n\n  length: 0,\n  push: push,\n  sort: [].sort,\n  splice: [].splice\n};\n\n//////////////////////////////////////////\n// Functions iterating getter/setters.\n// these functions return self on setter and\n// value on get.\n//////////////////////////////////////////\nvar BOOLEAN_ATTR = {};\nforEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {\n  BOOLEAN_ATTR[lowercase(value)] = value;\n});\nvar BOOLEAN_ELEMENTS = {};\nforEach('input,select,option,textarea,button,form,details'.split(','), function(value) {\n  BOOLEAN_ELEMENTS[value] = true;\n});\nvar ALIASED_ATTR = {\n  'ngMinlength': 'minlength',\n  'ngMaxlength': 'maxlength',\n  'ngMin': 'min',\n  'ngMax': 'max',\n  'ngPattern': 'pattern'\n};\n\nfunction getBooleanAttrName(element, name) {\n  // check dom last since we will most likely fail on name\n  var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];\n\n  // booleanAttr is here twice to minimize DOM access\n  return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;\n}\n\nfunction getAliasedAttrName(element, name) {\n  var nodeName = element.nodeName;\n  return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];\n}\n\nforEach({\n  data: jqLiteData,\n  removeData: jqLiteRemoveData,\n  hasData: jqLiteHasData\n}, function(fn, name) {\n  JQLite[name] = fn;\n});\n\nforEach({\n  data: jqLiteData,\n  inheritedData: jqLiteInheritedData,\n\n  scope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);\n  },\n\n  isolateScope: function(element) {\n    // Can't use jqLiteData here directly so we stay compatible with jQuery!\n    return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');\n  },\n\n  controller: jqLiteController,\n\n  injector: function(element) {\n    return jqLiteInheritedData(element, '$injector');\n  },\n\n  removeAttr: function(element, name) {\n    element.removeAttribute(name);\n  },\n\n  hasClass: jqLiteHasClass,\n\n  css: function(element, name, value) {\n    name = camelCase(name);\n\n    if (isDefined(value)) {\n      element.style[name] = value;\n    } else {\n      return element.style[name];\n    }\n  },\n\n  attr: function(element, name, value) {\n    var nodeType = element.nodeType;\n    if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {\n      return;\n    }\n    var lowercasedName = lowercase(name);\n    if (BOOLEAN_ATTR[lowercasedName]) {\n      if (isDefined(value)) {\n        if (!!value) {\n          element[name] = true;\n          element.setAttribute(name, lowercasedName);\n        } else {\n          element[name] = false;\n          element.removeAttribute(lowercasedName);\n        }\n      } else {\n        return (element[name] ||\n                 (element.attributes.getNamedItem(name) || noop).specified)\n               ? lowercasedName\n               : undefined;\n      }\n    } else if (isDefined(value)) {\n      element.setAttribute(name, value);\n    } else if (element.getAttribute) {\n      // the extra argument \"2\" is to get the right thing for a.href in IE, see jQuery code\n      // some elements (e.g. Document) don't have get attribute, so return undefined\n      var ret = element.getAttribute(name, 2);\n      // normalize non-existing attributes to undefined (as jQuery)\n      return ret === null ? undefined : ret;\n    }\n  },\n\n  prop: function(element, name, value) {\n    if (isDefined(value)) {\n      element[name] = value;\n    } else {\n      return element[name];\n    }\n  },\n\n  text: (function() {\n    getText.$dv = '';\n    return getText;\n\n    function getText(element, value) {\n      if (isUndefined(value)) {\n        var nodeType = element.nodeType;\n        return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';\n      }\n      element.textContent = value;\n    }\n  })(),\n\n  val: function(element, value) {\n    if (isUndefined(value)) {\n      if (element.multiple && nodeName_(element) === 'select') {\n        var result = [];\n        forEach(element.options, function(option) {\n          if (option.selected) {\n            result.push(option.value || option.text);\n          }\n        });\n        return result.length === 0 ? null : result;\n      }\n      return element.value;\n    }\n    element.value = value;\n  },\n\n  html: function(element, value) {\n    if (isUndefined(value)) {\n      return element.innerHTML;\n    }\n    jqLiteDealoc(element, true);\n    element.innerHTML = value;\n  },\n\n  empty: jqLiteEmpty\n}, function(fn, name) {\n  /**\n   * Properties: writes return selection, reads return first value\n   */\n  JQLite.prototype[name] = function(arg1, arg2) {\n    var i, key;\n    var nodeCount = this.length;\n\n    // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it\n    // in a way that survives minification.\n    // jqLiteEmpty takes no arguments but is a setter.\n    if (fn !== jqLiteEmpty &&\n        (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {\n      if (isObject(arg1)) {\n\n        // we are a write, but the object properties are the key/values\n        for (i = 0; i < nodeCount; i++) {\n          if (fn === jqLiteData) {\n            // data() takes the whole object in jQuery\n            fn(this[i], arg1);\n          } else {\n            for (key in arg1) {\n              fn(this[i], key, arg1[key]);\n            }\n          }\n        }\n        // return self for chaining\n        return this;\n      } else {\n        // we are a read, so read the first child.\n        // TODO: do we still need this?\n        var value = fn.$dv;\n        // Only if we have $dv do we iterate over all, otherwise it is just the first element.\n        var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;\n        for (var j = 0; j < jj; j++) {\n          var nodeValue = fn(this[j], arg1, arg2);\n          value = value ? value + nodeValue : nodeValue;\n        }\n        return value;\n      }\n    } else {\n      // we are a write, so apply to all children\n      for (i = 0; i < nodeCount; i++) {\n        fn(this[i], arg1, arg2);\n      }\n      // return self for chaining\n      return this;\n    }\n  };\n});\n\nfunction createEventHandler(element, events) {\n  var eventHandler = function(event, type) {\n    // jQuery specific api\n    event.isDefaultPrevented = function() {\n      return event.defaultPrevented;\n    };\n\n    var eventFns = events[type || event.type];\n    var eventFnsLength = eventFns ? eventFns.length : 0;\n\n    if (!eventFnsLength) return;\n\n    if (isUndefined(event.immediatePropagationStopped)) {\n      var originalStopImmediatePropagation = event.stopImmediatePropagation;\n      event.stopImmediatePropagation = function() {\n        event.immediatePropagationStopped = true;\n\n        if (event.stopPropagation) {\n          event.stopPropagation();\n        }\n\n        if (originalStopImmediatePropagation) {\n          originalStopImmediatePropagation.call(event);\n        }\n      };\n    }\n\n    event.isImmediatePropagationStopped = function() {\n      return event.immediatePropagationStopped === true;\n    };\n\n    // Copy event handlers in case event handlers array is modified during execution.\n    if ((eventFnsLength > 1)) {\n      eventFns = shallowCopy(eventFns);\n    }\n\n    for (var i = 0; i < eventFnsLength; i++) {\n      if (!event.isImmediatePropagationStopped()) {\n        eventFns[i].call(element, event);\n      }\n    }\n  };\n\n  // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all\n  //       events on `element`\n  eventHandler.elem = element;\n  return eventHandler;\n}\n\n//////////////////////////////////////////\n// Functions iterating traversal.\n// These functions chain results into a single\n// selector.\n//////////////////////////////////////////\nforEach({\n  removeData: jqLiteRemoveData,\n\n  on: function jqLiteOn(element, type, fn, unsupported) {\n    if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');\n\n    // Do not add event handlers to non-elements because they will not be cleaned up.\n    if (!jqLiteAcceptsData(element)) {\n      return;\n    }\n\n    var expandoStore = jqLiteExpandoStore(element, true);\n    var events = expandoStore.events;\n    var handle = expandoStore.handle;\n\n    if (!handle) {\n      handle = expandoStore.handle = createEventHandler(element, events);\n    }\n\n    // http://jsperf.com/string-indexof-vs-split\n    var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];\n    var i = types.length;\n\n    while (i--) {\n      type = types[i];\n      var eventFns = events[type];\n\n      if (!eventFns) {\n        events[type] = [];\n\n        if (type === 'mouseenter' || type === 'mouseleave') {\n          // Refer to jQuery's implementation of mouseenter & mouseleave\n          // Read about mouseenter and mouseleave:\n          // http://www.quirksmode.org/js/events_mouse.html#link8\n\n          jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {\n            var target = this, related = event.relatedTarget;\n            // For mousenter/leave call the handler if related is outside the target.\n            // NB: No relatedTarget if the mouse left/entered the browser window\n            if (!related || (related !== target && !target.contains(related))) {\n              handle(event, type);\n            }\n          });\n\n        } else {\n          if (type !== '$destroy') {\n            addEventListenerFn(element, type, handle);\n          }\n        }\n        eventFns = events[type];\n      }\n      eventFns.push(fn);\n    }\n  },\n\n  off: jqLiteOff,\n\n  one: function(element, type, fn) {\n    element = jqLite(element);\n\n    //add the listener twice so that when it is called\n    //you can remove the original function and still be\n    //able to call element.off(ev, fn) normally\n    element.on(type, function onFn() {\n      element.off(type, fn);\n      element.off(type, onFn);\n    });\n    element.on(type, fn);\n  },\n\n  replaceWith: function(element, replaceNode) {\n    var index, parent = element.parentNode;\n    jqLiteDealoc(element);\n    forEach(new JQLite(replaceNode), function(node) {\n      if (index) {\n        parent.insertBefore(node, index.nextSibling);\n      } else {\n        parent.replaceChild(node, element);\n      }\n      index = node;\n    });\n  },\n\n  children: function(element) {\n    var children = [];\n    forEach(element.childNodes, function(element) {\n      if (element.nodeType === NODE_TYPE_ELEMENT) {\n        children.push(element);\n      }\n    });\n    return children;\n  },\n\n  contents: function(element) {\n    return element.contentDocument || element.childNodes || [];\n  },\n\n  append: function(element, node) {\n    var nodeType = element.nodeType;\n    if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;\n\n    node = new JQLite(node);\n\n    for (var i = 0, ii = node.length; i < ii; i++) {\n      var child = node[i];\n      element.appendChild(child);\n    }\n  },\n\n  prepend: function(element, node) {\n    if (element.nodeType === NODE_TYPE_ELEMENT) {\n      var index = element.firstChild;\n      forEach(new JQLite(node), function(child) {\n        element.insertBefore(child, index);\n      });\n    }\n  },\n\n  wrap: function(element, wrapNode) {\n    wrapNode = jqLite(wrapNode).eq(0).clone()[0];\n    var parent = element.parentNode;\n    if (parent) {\n      parent.replaceChild(wrapNode, element);\n    }\n    wrapNode.appendChild(element);\n  },\n\n  remove: jqLiteRemove,\n\n  detach: function(element) {\n    jqLiteRemove(element, true);\n  },\n\n  after: function(element, newElement) {\n    var index = element, parent = element.parentNode;\n    newElement = new JQLite(newElement);\n\n    for (var i = 0, ii = newElement.length; i < ii; i++) {\n      var node = newElement[i];\n      parent.insertBefore(node, index.nextSibling);\n      index = node;\n    }\n  },\n\n  addClass: jqLiteAddClass,\n  removeClass: jqLiteRemoveClass,\n\n  toggleClass: function(element, selector, condition) {\n    if (selector) {\n      forEach(selector.split(' '), function(className) {\n        var classCondition = condition;\n        if (isUndefined(classCondition)) {\n          classCondition = !jqLiteHasClass(element, className);\n        }\n        (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);\n      });\n    }\n  },\n\n  parent: function(element) {\n    var parent = element.parentNode;\n    return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;\n  },\n\n  next: function(element) {\n    return element.nextElementSibling;\n  },\n\n  find: function(element, selector) {\n    if (element.getElementsByTagName) {\n      return element.getElementsByTagName(selector);\n    } else {\n      return [];\n    }\n  },\n\n  clone: jqLiteClone,\n\n  triggerHandler: function(element, event, extraParameters) {\n\n    var dummyEvent, eventFnsCopy, handlerArgs;\n    var eventName = event.type || event;\n    var expandoStore = jqLiteExpandoStore(element);\n    var events = expandoStore && expandoStore.events;\n    var eventFns = events && events[eventName];\n\n    if (eventFns) {\n      // Create a dummy event to pass to the handlers\n      dummyEvent = {\n        preventDefault: function() { this.defaultPrevented = true; },\n        isDefaultPrevented: function() { return this.defaultPrevented === true; },\n        stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },\n        isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },\n        stopPropagation: noop,\n        type: eventName,\n        target: element\n      };\n\n      // If a custom event was provided then extend our dummy event with it\n      if (event.type) {\n        dummyEvent = extend(dummyEvent, event);\n      }\n\n      // Copy event handlers in case event handlers array is modified during execution.\n      eventFnsCopy = shallowCopy(eventFns);\n      handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];\n\n      forEach(eventFnsCopy, function(fn) {\n        if (!dummyEvent.isImmediatePropagationStopped()) {\n          fn.apply(element, handlerArgs);\n        }\n      });\n    }\n  }\n}, function(fn, name) {\n  /**\n   * chaining functions\n   */\n  JQLite.prototype[name] = function(arg1, arg2, arg3) {\n    var value;\n\n    for (var i = 0, ii = this.length; i < ii; i++) {\n      if (isUndefined(value)) {\n        value = fn(this[i], arg1, arg2, arg3);\n        if (isDefined(value)) {\n          // any function which returns a value needs to be wrapped\n          value = jqLite(value);\n        }\n      } else {\n        jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));\n      }\n    }\n    return isDefined(value) ? value : this;\n  };\n\n  // bind legacy bind/unbind to on/off\n  JQLite.prototype.bind = JQLite.prototype.on;\n  JQLite.prototype.unbind = JQLite.prototype.off;\n});\n\n\n// Provider for private $$jqLite service\nfunction $$jqLiteProvider() {\n  this.$get = function $$jqLite() {\n    return extend(JQLite, {\n      hasClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteHasClass(node, classes);\n      },\n      addClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteAddClass(node, classes);\n      },\n      removeClass: function(node, classes) {\n        if (node.attr) node = node[0];\n        return jqLiteRemoveClass(node, classes);\n      }\n    });\n  };\n}\n\n/**\n * Computes a hash of an 'obj'.\n * Hash of a:\n *  string is string\n *  number is number as string\n *  object is either result of calling $$hashKey function on the object or uniquely generated id,\n *         that is also assigned to the $$hashKey property of the object.\n *\n * @param obj\n * @returns {string} hash string such that the same input will have the same hash string.\n *         The resulting string key is in 'type:hashKey' format.\n */\nfunction hashKey(obj, nextUidFn) {\n  var key = obj && obj.$$hashKey;\n\n  if (key) {\n    if (typeof key === 'function') {\n      key = obj.$$hashKey();\n    }\n    return key;\n  }\n\n  var objType = typeof obj;\n  if (objType == 'function' || (objType == 'object' && obj !== null)) {\n    key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();\n  } else {\n    key = objType + ':' + obj;\n  }\n\n  return key;\n}\n\n/**\n * HashMap which can use objects as keys\n */\nfunction HashMap(array, isolatedUid) {\n  if (isolatedUid) {\n    var uid = 0;\n    this.nextUid = function() {\n      return ++uid;\n    };\n  }\n  forEach(array, this.put, this);\n}\nHashMap.prototype = {\n  /**\n   * Store key value pair\n   * @param key key to store can be any type\n   * @param value value to store can be any type\n   */\n  put: function(key, value) {\n    this[hashKey(key, this.nextUid)] = value;\n  },\n\n  /**\n   * @param key\n   * @returns {Object} the value for the key\n   */\n  get: function(key) {\n    return this[hashKey(key, this.nextUid)];\n  },\n\n  /**\n   * Remove the key/value pair\n   * @param key\n   */\n  remove: function(key) {\n    var value = this[key = hashKey(key, this.nextUid)];\n    delete this[key];\n    return value;\n  }\n};\n\nvar $$HashMapProvider = [function() {\n  this.$get = [function() {\n    return HashMap;\n  }];\n}];\n\n/**\n * @ngdoc function\n * @module ng\n * @name angular.injector\n * @kind function\n *\n * @description\n * Creates an injector object that can be used for retrieving services as well as for\n * dependency injection (see {@link guide/di dependency injection}).\n *\n * @param {Array.<string|Function>} modules A list of module functions or their aliases. See\n *     {@link angular.module}. The `ng` module must be explicitly added.\n * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which\n *     disallows argument name annotation inference.\n * @returns {injector} Injector object. See {@link auto.$injector $injector}.\n *\n * @example\n * Typical usage\n * ```js\n *   // create an injector\n *   var $injector = angular.injector(['ng']);\n *\n *   // use the injector to kick off your application\n *   // use the type inference to auto inject arguments, or use implicit injection\n *   $injector.invoke(function($rootScope, $compile, $document) {\n *     $compile($document)($rootScope);\n *     $rootScope.$digest();\n *   });\n * ```\n *\n * Sometimes you want to get access to the injector of a currently running Angular app\n * from outside Angular. Perhaps, you want to inject and compile some markup after the\n * application has been bootstrapped. You can do this using the extra `injector()` added\n * to JQuery/jqLite elements. See {@link angular.element}.\n *\n * *This is fairly rare but could be the case if a third party library is injecting the\n * markup.*\n *\n * In the following example a new block of HTML containing a `ng-controller`\n * directive is added to the end of the document body by JQuery. We then compile and link\n * it into the current AngularJS scope.\n *\n * ```js\n * var $div = $('<div ng-controller=\"MyCtrl\">{{content.label}}</div>');\n * $(document.body).append($div);\n *\n * angular.element(document).injector().invoke(function($compile) {\n *   var scope = angular.element($div).scope();\n *   $compile($div)(scope);\n * });\n * ```\n */\n\n\n/**\n * @ngdoc module\n * @name auto\n * @description\n *\n * Implicit module which gets automatically added to each {@link auto.$injector $injector}.\n */\n\nvar FN_ARGS = /^[^\\(]*\\(\\s*([^\\)]*)\\)/m;\nvar FN_ARG_SPLIT = /,/;\nvar FN_ARG = /^\\s*(_?)(\\S+?)\\1\\s*$/;\nvar STRIP_COMMENTS = /((\\/\\/.*$)|(\\/\\*[\\s\\S]*?\\*\\/))/mg;\nvar $injectorMinErr = minErr('$injector');\n\nfunction anonFn(fn) {\n  // For anonymous functions, showing at the very least the function signature can help in\n  // debugging.\n  var fnText = fn.toString().replace(STRIP_COMMENTS, ''),\n      args = fnText.match(FN_ARGS);\n  if (args) {\n    return 'function(' + (args[1] || '').replace(/[\\s\\r\\n]+/, ' ') + ')';\n  }\n  return 'fn';\n}\n\nfunction annotate(fn, strictDi, name) {\n  var $inject,\n      fnText,\n      argDecl,\n      last;\n\n  if (typeof fn === 'function') {\n    if (!($inject = fn.$inject)) {\n      $inject = [];\n      if (fn.length) {\n        if (strictDi) {\n          if (!isString(name) || !name) {\n            name = fn.name || anonFn(fn);\n          }\n          throw $injectorMinErr('strictdi',\n            '{0} is not using explicit annotation and cannot be invoked in strict mode', name);\n        }\n        fnText = fn.toString().replace(STRIP_COMMENTS, '');\n        argDecl = fnText.match(FN_ARGS);\n        forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {\n          arg.replace(FN_ARG, function(all, underscore, name) {\n            $inject.push(name);\n          });\n        });\n      }\n      fn.$inject = $inject;\n    }\n  } else if (isArray(fn)) {\n    last = fn.length - 1;\n    assertArgFn(fn[last], 'fn');\n    $inject = fn.slice(0, last);\n  } else {\n    assertArgFn(fn, 'fn', true);\n  }\n  return $inject;\n}\n\n///////////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $injector\n *\n * @description\n *\n * `$injector` is used to retrieve object instances as defined by\n * {@link auto.$provide provider}, instantiate types, invoke methods,\n * and load modules.\n *\n * The following always holds true:\n *\n * ```js\n *   var $injector = angular.injector();\n *   expect($injector.get('$injector')).toBe($injector);\n *   expect($injector.invoke(function($injector) {\n *     return $injector;\n *   })).toBe($injector);\n * ```\n *\n * # Injection Function Annotation\n *\n * JavaScript does not have annotations, and annotations are needed for dependency injection. The\n * following are all valid ways of annotating function with injection arguments and are equivalent.\n *\n * ```js\n *   // inferred (only works if code not minified/obfuscated)\n *   $injector.invoke(function(serviceA){});\n *\n *   // annotated\n *   function explicit(serviceA) {};\n *   explicit.$inject = ['serviceA'];\n *   $injector.invoke(explicit);\n *\n *   // inline\n *   $injector.invoke(['serviceA', function(serviceA){}]);\n * ```\n *\n * ## Inference\n *\n * In JavaScript calling `toString()` on a function returns the function definition. The definition\n * can then be parsed and the function arguments can be extracted. This method of discovering\n * annotations is disallowed when the injector is in strict mode.\n * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the\n * argument names.\n *\n * ## `$inject` Annotation\n * By adding an `$inject` property onto a function the injection parameters can be specified.\n *\n * ## Inline\n * As an array of injection names, where the last item in the array is the function to call.\n */\n\n/**\n * @ngdoc method\n * @name $injector#get\n *\n * @description\n * Return an instance of the service.\n *\n * @param {string} name The name of the instance to retrieve.\n * @param {string=} caller An optional string to provide the origin of the function call for error messages.\n * @return {*} The instance.\n */\n\n/**\n * @ngdoc method\n * @name $injector#invoke\n *\n * @description\n * Invoke the method and supply the method arguments from the `$injector`.\n *\n * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are\n *   injected according to the {@link guide/di $inject Annotation} rules.\n * @param {Object=} self The `this` for the invoked method.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n *                         object first, before the `$injector` is consulted.\n * @returns {*} the value returned by the invoked `fn` function.\n */\n\n/**\n * @ngdoc method\n * @name $injector#has\n *\n * @description\n * Allows the user to query if the particular service exists.\n *\n * @param {string} name Name of the service to query.\n * @returns {boolean} `true` if injector has given service.\n */\n\n/**\n * @ngdoc method\n * @name $injector#instantiate\n * @description\n * Create a new instance of JS type. The method takes a constructor function, invokes the new\n * operator, and supplies all of the arguments to the constructor function as specified by the\n * constructor annotation.\n *\n * @param {Function} Type Annotated constructor function.\n * @param {Object=} locals Optional object. If preset then any argument names are read from this\n * object first, before the `$injector` is consulted.\n * @returns {Object} new instance of `Type`.\n */\n\n/**\n * @ngdoc method\n * @name $injector#annotate\n *\n * @description\n * Returns an array of service names which the function is requesting for injection. This API is\n * used by the injector to determine which services need to be injected into the function when the\n * function is invoked. There are three ways in which the function can be annotated with the needed\n * dependencies.\n *\n * # Argument names\n *\n * The simplest form is to extract the dependencies from the arguments of the function. This is done\n * by converting the function into a string using `toString()` method and extracting the argument\n * names.\n * ```js\n *   // Given\n *   function MyController($scope, $route) {\n *     // ...\n *   }\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * You can disallow this method by using strict injection mode.\n *\n * This method does not work with code minification / obfuscation. For this reason the following\n * annotation strategies are supported.\n *\n * # The `$inject` property\n *\n * If a function has an `$inject` property and its value is an array of strings, then the strings\n * represent names of services to be injected into the function.\n * ```js\n *   // Given\n *   var MyController = function(obfuscatedScope, obfuscatedRoute) {\n *     // ...\n *   }\n *   // Define function dependencies\n *   MyController['$inject'] = ['$scope', '$route'];\n *\n *   // Then\n *   expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);\n * ```\n *\n * # The array notation\n *\n * It is often desirable to inline Injected functions and that's when setting the `$inject` property\n * is very inconvenient. In these situations using the array notation to specify the dependencies in\n * a way that survives minification is a better choice:\n *\n * ```js\n *   // We wish to write this (not minification / obfuscation safe)\n *   injector.invoke(function($compile, $rootScope) {\n *     // ...\n *   });\n *\n *   // We are forced to write break inlining\n *   var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {\n *     // ...\n *   };\n *   tmpFn.$inject = ['$compile', '$rootScope'];\n *   injector.invoke(tmpFn);\n *\n *   // To better support inline function the inline annotation is supported\n *   injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {\n *     // ...\n *   }]);\n *\n *   // Therefore\n *   expect(injector.annotate(\n *      ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])\n *    ).toEqual(['$compile', '$rootScope']);\n * ```\n *\n * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to\n * be retrieved as described above.\n *\n * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.\n *\n * @returns {Array.<string>} The names of the services which the function requires.\n */\n\n\n\n\n/**\n * @ngdoc service\n * @name $provide\n *\n * @description\n *\n * The {@link auto.$provide $provide} service has a number of methods for registering components\n * with the {@link auto.$injector $injector}. Many of these functions are also exposed on\n * {@link angular.Module}.\n *\n * An Angular **service** is a singleton object created by a **service factory**.  These **service\n * factories** are functions which, in turn, are created by a **service provider**.\n * The **service providers** are constructor functions. When instantiated they must contain a\n * property called `$get`, which holds the **service factory** function.\n *\n * When you request a service, the {@link auto.$injector $injector} is responsible for finding the\n * correct **service provider**, instantiating it and then calling its `$get` **service factory**\n * function to get the instance of the **service**.\n *\n * Often services have no configuration options and there is no need to add methods to the service\n * provider.  The provider will be no more than a constructor function with a `$get` property. For\n * these cases the {@link auto.$provide $provide} service has additional helper methods to register\n * services without specifying a provider.\n *\n * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the\n *     {@link auto.$injector $injector}\n * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by\n *     providers and services.\n * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by\n *     services, not providers.\n * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,\n *     that will be wrapped in a **service provider** object, whose `$get` property will contain the\n *     given factory function.\n * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`\n *     that will be wrapped in a **service provider** object, whose `$get` property will instantiate\n *      a new object using the given constructor function.\n *\n * See the individual methods for more information and examples.\n */\n\n/**\n * @ngdoc method\n * @name $provide#provider\n * @description\n *\n * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions\n * are constructor functions, whose instances are responsible for \"providing\" a factory for a\n * service.\n *\n * Service provider names start with the name of the service they provide followed by `Provider`.\n * For example, the {@link ng.$log $log} service has a provider called\n * {@link ng.$logProvider $logProvider}.\n *\n * Service provider objects can have additional methods which allow configuration of the provider\n * and its service. Importantly, you can configure what kind of service is created by the `$get`\n * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a\n * method {@link ng.$logProvider#debugEnabled debugEnabled}\n * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the\n * console or not.\n *\n * @param {string} name The name of the instance. NOTE: the provider will be available under `name +\n                        'Provider'` key.\n * @param {(Object|function())} provider If the provider is:\n *\n *   - `Object`: then it should have a `$get` method. The `$get` method will be invoked using\n *     {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.\n *   - `Constructor`: a new instance of the provider will be created using\n *     {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.\n *\n * @returns {Object} registered provider instance\n\n * @example\n *\n * The following example shows how to create a simple event tracking service and register it using\n * {@link auto.$provide#provider $provide.provider()}.\n *\n * ```js\n *  // Define the eventTracker provider\n *  function EventTrackerProvider() {\n *    var trackingUrl = '/track';\n *\n *    // A provider method for configuring where the tracked events should been saved\n *    this.setTrackingUrl = function(url) {\n *      trackingUrl = url;\n *    };\n *\n *    // The service factory function\n *    this.$get = ['$http', function($http) {\n *      var trackedEvents = {};\n *      return {\n *        // Call this to track an event\n *        event: function(event) {\n *          var count = trackedEvents[event] || 0;\n *          count += 1;\n *          trackedEvents[event] = count;\n *          return count;\n *        },\n *        // Call this to save the tracked events to the trackingUrl\n *        save: function() {\n *          $http.post(trackingUrl, trackedEvents);\n *        }\n *      };\n *    }];\n *  }\n *\n *  describe('eventTracker', function() {\n *    var postSpy;\n *\n *    beforeEach(module(function($provide) {\n *      // Register the eventTracker provider\n *      $provide.provider('eventTracker', EventTrackerProvider);\n *    }));\n *\n *    beforeEach(module(function(eventTrackerProvider) {\n *      // Configure eventTracker provider\n *      eventTrackerProvider.setTrackingUrl('/custom-track');\n *    }));\n *\n *    it('tracks events', inject(function(eventTracker) {\n *      expect(eventTracker.event('login')).toEqual(1);\n *      expect(eventTracker.event('login')).toEqual(2);\n *    }));\n *\n *    it('saves to the tracking url', inject(function(eventTracker, $http) {\n *      postSpy = spyOn($http, 'post');\n *      eventTracker.event('login');\n *      eventTracker.save();\n *      expect(postSpy).toHaveBeenCalled();\n *      expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');\n *      expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');\n *      expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });\n *    }));\n *  });\n * ```\n */\n\n/**\n * @ngdoc method\n * @name $provide#factory\n * @description\n *\n * Register a **service factory**, which will be called to return the service instance.\n * This is short for registering a service where its provider consists of only a `$get` property,\n * which is the given service factory function.\n * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to\n * configure your service in a provider.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.\n *                      Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service\n * ```js\n *   $provide.factory('ping', ['$http', function($http) {\n *     return function ping() {\n *       return $http.send('/ping');\n *     };\n *   }]);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#service\n * @description\n *\n * Register a **service constructor**, which will be invoked with `new` to create the service\n * instance.\n * This is short for registering a service where its provider's `$get` property is the service\n * constructor function that will be used to instantiate the service instance.\n *\n * You should use {@link auto.$provide#service $provide.service(class)} if you define your service\n * as a type/class.\n *\n * @param {string} name The name of the instance.\n * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)\n *     that will be instantiated.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here is an example of registering a service using\n * {@link auto.$provide#service $provide.service(class)}.\n * ```js\n *   var Ping = function($http) {\n *     this.$http = $http;\n *   };\n *\n *   Ping.$inject = ['$http'];\n *\n *   Ping.prototype.send = function() {\n *     return this.$http.get('/ping');\n *   };\n *   $provide.service('ping', Ping);\n * ```\n * You would then inject and use this service like this:\n * ```js\n *   someModule.controller('Ctrl', ['ping', function(ping) {\n *     ping.send();\n *   }]);\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#value\n * @description\n *\n * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a\n * number, an array, an object or a function.  This is short for registering a service where its\n * provider's `$get` property is a factory function that takes no arguments and returns the **value\n * service**.\n *\n * Value services are similar to constant services, except that they cannot be injected into a\n * module configuration function (see {@link angular.Module#config}) but they can be overridden by\n * an Angular\n * {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the instance.\n * @param {*} value The value.\n * @returns {Object} registered provider instance\n *\n * @example\n * Here are some examples of creating value services.\n * ```js\n *   $provide.value('ADMIN_USER', 'admin');\n *\n *   $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });\n *\n *   $provide.value('halfOf', function(value) {\n *     return value / 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#constant\n * @description\n *\n * Register a **constant service**, such as a string, a number, an array, an object or a function,\n * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be\n * injected into a module configuration function (see {@link angular.Module#config}) and it cannot\n * be overridden by an Angular {@link auto.$provide#decorator decorator}.\n *\n * @param {string} name The name of the constant.\n * @param {*} value The constant value.\n * @returns {Object} registered instance\n *\n * @example\n * Here a some examples of creating constants:\n * ```js\n *   $provide.constant('SHARD_HEIGHT', 306);\n *\n *   $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);\n *\n *   $provide.constant('double', function(value) {\n *     return value * 2;\n *   });\n * ```\n */\n\n\n/**\n * @ngdoc method\n * @name $provide#decorator\n * @description\n *\n * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator\n * intercepts the creation of a service, allowing it to override or modify the behaviour of the\n * service. The object returned by the decorator may be the original service, or a new service\n * object which replaces or wraps and delegates to the original service.\n *\n * @param {string} name The name of the service to decorate.\n * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be\n *    instantiated and should return the decorated service instance. The function is called using\n *    the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.\n *    Local injection arguments:\n *\n *    * `$delegate` - The original service instance, which can be monkey patched, configured,\n *      decorated or delegated to.\n *\n * @example\n * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting\n * calls to {@link ng.$log#error $log.warn()}.\n * ```js\n *   $provide.decorator('$log', ['$delegate', function($delegate) {\n *     $delegate.warn = $delegate.error;\n *     return $delegate;\n *   }]);\n * ```\n */\n\n\nfunction createInjector(modulesToLoad, strictDi) {\n  strictDi = (strictDi === true);\n  var INSTANTIATING = {},\n      providerSuffix = 'Provider',\n      path = [],\n      loadedModules = new HashMap([], true),\n      providerCache = {\n        $provide: {\n            provider: supportObject(provider),\n            factory: supportObject(factory),\n            service: supportObject(service),\n            value: supportObject(value),\n            constant: supportObject(constant),\n            decorator: decorator\n          }\n      },\n      providerInjector = (providerCache.$injector =\n          createInternalInjector(providerCache, function(serviceName, caller) {\n            if (angular.isString(caller)) {\n              path.push(caller);\n            }\n            throw $injectorMinErr('unpr', \"Unknown provider: {0}\", path.join(' <- '));\n          })),\n      instanceCache = {},\n      instanceInjector = (instanceCache.$injector =\n          createInternalInjector(instanceCache, function(serviceName, caller) {\n            var provider = providerInjector.get(serviceName + providerSuffix, caller);\n            return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);\n          }));\n\n\n  forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });\n\n  return instanceInjector;\n\n  ////////////////////////////////////\n  // $provider\n  ////////////////////////////////////\n\n  function supportObject(delegate) {\n    return function(key, value) {\n      if (isObject(key)) {\n        forEach(key, reverseParams(delegate));\n      } else {\n        return delegate(key, value);\n      }\n    };\n  }\n\n  function provider(name, provider_) {\n    assertNotHasOwnProperty(name, 'service');\n    if (isFunction(provider_) || isArray(provider_)) {\n      provider_ = providerInjector.instantiate(provider_);\n    }\n    if (!provider_.$get) {\n      throw $injectorMinErr('pget', \"Provider '{0}' must define $get factory method.\", name);\n    }\n    return providerCache[name + providerSuffix] = provider_;\n  }\n\n  function enforceReturnValue(name, factory) {\n    return function enforcedReturnValue() {\n      var result = instanceInjector.invoke(factory, this);\n      if (isUndefined(result)) {\n        throw $injectorMinErr('undef', \"Provider '{0}' must return a value from $get factory method.\", name);\n      }\n      return result;\n    };\n  }\n\n  function factory(name, factoryFn, enforce) {\n    return provider(name, {\n      $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn\n    });\n  }\n\n  function service(name, constructor) {\n    return factory(name, ['$injector', function($injector) {\n      return $injector.instantiate(constructor);\n    }]);\n  }\n\n  function value(name, val) { return factory(name, valueFn(val), false); }\n\n  function constant(name, value) {\n    assertNotHasOwnProperty(name, 'constant');\n    providerCache[name] = value;\n    instanceCache[name] = value;\n  }\n\n  function decorator(serviceName, decorFn) {\n    var origProvider = providerInjector.get(serviceName + providerSuffix),\n        orig$get = origProvider.$get;\n\n    origProvider.$get = function() {\n      var origInstance = instanceInjector.invoke(orig$get, origProvider);\n      return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});\n    };\n  }\n\n  ////////////////////////////////////\n  // Module Loading\n  ////////////////////////////////////\n  function loadModules(modulesToLoad) {\n    assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');\n    var runBlocks = [], moduleFn;\n    forEach(modulesToLoad, function(module) {\n      if (loadedModules.get(module)) return;\n      loadedModules.put(module, true);\n\n      function runInvokeQueue(queue) {\n        var i, ii;\n        for (i = 0, ii = queue.length; i < ii; i++) {\n          var invokeArgs = queue[i],\n              provider = providerInjector.get(invokeArgs[0]);\n\n          provider[invokeArgs[1]].apply(provider, invokeArgs[2]);\n        }\n      }\n\n      try {\n        if (isString(module)) {\n          moduleFn = angularModule(module);\n          runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);\n          runInvokeQueue(moduleFn._invokeQueue);\n          runInvokeQueue(moduleFn._configBlocks);\n        } else if (isFunction(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else if (isArray(module)) {\n            runBlocks.push(providerInjector.invoke(module));\n        } else {\n          assertArgFn(module, 'module');\n        }\n      } catch (e) {\n        if (isArray(module)) {\n          module = module[module.length - 1];\n        }\n        if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {\n          // Safari & FF's stack traces don't contain error.message content\n          // unlike those of Chrome and IE\n          // So if stack doesn't contain message, we create a new string that contains both.\n          // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.\n          /* jshint -W022 */\n          e = e.message + '\\n' + e.stack;\n        }\n        throw $injectorMinErr('modulerr', \"Failed to instantiate module {0} due to:\\n{1}\",\n                  module, e.stack || e.message || e);\n      }\n    });\n    return runBlocks;\n  }\n\n  ////////////////////////////////////\n  // internal Injector\n  ////////////////////////////////////\n\n  function createInternalInjector(cache, factory) {\n\n    function getService(serviceName, caller) {\n      if (cache.hasOwnProperty(serviceName)) {\n        if (cache[serviceName] === INSTANTIATING) {\n          throw $injectorMinErr('cdep', 'Circular dependency found: {0}',\n                    serviceName + ' <- ' + path.join(' <- '));\n        }\n        return cache[serviceName];\n      } else {\n        try {\n          path.unshift(serviceName);\n          cache[serviceName] = INSTANTIATING;\n          return cache[serviceName] = factory(serviceName, caller);\n        } catch (err) {\n          if (cache[serviceName] === INSTANTIATING) {\n            delete cache[serviceName];\n          }\n          throw err;\n        } finally {\n          path.shift();\n        }\n      }\n    }\n\n    function invoke(fn, self, locals, serviceName) {\n      if (typeof locals === 'string') {\n        serviceName = locals;\n        locals = null;\n      }\n\n      var args = [],\n          $inject = createInjector.$$annotate(fn, strictDi, serviceName),\n          length, i,\n          key;\n\n      for (i = 0, length = $inject.length; i < length; i++) {\n        key = $inject[i];\n        if (typeof key !== 'string') {\n          throw $injectorMinErr('itkn',\n                  'Incorrect injection token! Expected service name as string, got {0}', key);\n        }\n        args.push(\n          locals && locals.hasOwnProperty(key)\n          ? locals[key]\n          : getService(key, serviceName)\n        );\n      }\n      if (isArray(fn)) {\n        fn = fn[length];\n      }\n\n      // http://jsperf.com/angularjs-invoke-apply-vs-switch\n      // #5388\n      return fn.apply(self, args);\n    }\n\n    function instantiate(Type, locals, serviceName) {\n      // Check if Type is annotated and use just the given function at n-1 as parameter\n      // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);\n      // Object creation: http://jsperf.com/create-constructor/2\n      var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);\n      var returnedValue = invoke(Type, instance, locals, serviceName);\n\n      return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;\n    }\n\n    return {\n      invoke: invoke,\n      instantiate: instantiate,\n      get: getService,\n      annotate: createInjector.$$annotate,\n      has: function(name) {\n        return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);\n      }\n    };\n  }\n}\n\ncreateInjector.$$annotate = annotate;\n\n/**\n * @ngdoc provider\n * @name $anchorScrollProvider\n *\n * @description\n * Use `$anchorScrollProvider` to disable automatic scrolling whenever\n * {@link ng.$location#hash $location.hash()} changes.\n */\nfunction $AnchorScrollProvider() {\n\n  var autoScrollingEnabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $anchorScrollProvider#disableAutoScrolling\n   *\n   * @description\n   * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to\n   * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />\n   * Use this method to disable automatic scrolling.\n   *\n   * If automatic scrolling is disabled, one must explicitly call\n   * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the\n   * current hash.\n   */\n  this.disableAutoScrolling = function() {\n    autoScrollingEnabled = false;\n  };\n\n  /**\n   * @ngdoc service\n   * @name $anchorScroll\n   * @kind function\n   * @requires $window\n   * @requires $location\n   * @requires $rootScope\n   *\n   * @description\n   * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the\n   * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified\n   * in the\n   * [HTML5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).\n   *\n   * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to\n   * match any anchor whenever it changes. This can be disabled by calling\n   * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.\n   *\n   * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a\n   * vertical scroll-offset (either fixed or dynamic).\n   *\n   * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of\n   *                       {@link ng.$location#hash $location.hash()} will be used.\n   *\n   * @property {(number|function|jqLite)} yOffset\n   * If set, specifies a vertical scroll-offset. This is often useful when there are fixed\n   * positioned elements at the top of the page, such as navbars, headers etc.\n   *\n   * `yOffset` can be specified in various ways:\n   * - **number**: A fixed number of pixels to be used as offset.<br /><br />\n   * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return\n   *   a number representing the offset (in pixels).<br /><br />\n   * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from\n   *   the top of the page to the element's bottom will be used as offset.<br />\n   *   **Note**: The element will be taken into account only as long as its `position` is set to\n   *   `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust\n   *   their height and/or positioning according to the viewport's size.\n   *\n   * <br />\n   * <div class=\"alert alert-warning\">\n   * In order for `yOffset` to work properly, scrolling should take place on the document's root and\n   * not some child element.\n   * </div>\n   *\n   * @example\n     <example module=\"anchorScrollExample\">\n       <file name=\"index.html\">\n         <div id=\"scrollArea\" ng-controller=\"ScrollController\">\n           <a ng-click=\"gotoBottom()\">Go to bottom</a>\n           <a id=\"bottom\"></a> You're at the bottom!\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollExample', [])\n           .controller('ScrollController', ['$scope', '$location', '$anchorScroll',\n             function ($scope, $location, $anchorScroll) {\n               $scope.gotoBottom = function() {\n                 // set the location.hash to the id of\n                 // the element you wish to scroll to.\n                 $location.hash('bottom');\n\n                 // call $anchorScroll()\n                 $anchorScroll();\n               };\n             }]);\n       </file>\n       <file name=\"style.css\">\n         #scrollArea {\n           height: 280px;\n           overflow: auto;\n         }\n\n         #bottom {\n           display: block;\n           margin-top: 2000px;\n         }\n       </file>\n     </example>\n   *\n   * <hr />\n   * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).\n   * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.\n   *\n   * @example\n     <example module=\"anchorScrollOffsetExample\">\n       <file name=\"index.html\">\n         <div class=\"fixed-header\" ng-controller=\"headerCtrl\">\n           <a href=\"\" ng-click=\"gotoAnchor(x)\" ng-repeat=\"x in [1,2,3,4,5]\">\n             Go to anchor {{x}}\n           </a>\n         </div>\n         <div id=\"anchor{{x}}\" class=\"anchor\" ng-repeat=\"x in [1,2,3,4,5]\">\n           Anchor {{x}} of 5\n         </div>\n       </file>\n       <file name=\"script.js\">\n         angular.module('anchorScrollOffsetExample', [])\n           .run(['$anchorScroll', function($anchorScroll) {\n             $anchorScroll.yOffset = 50;   // always scroll by 50 extra pixels\n           }])\n           .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',\n             function ($anchorScroll, $location, $scope) {\n               $scope.gotoAnchor = function(x) {\n                 var newHash = 'anchor' + x;\n                 if ($location.hash() !== newHash) {\n                   // set the $location.hash to `newHash` and\n                   // $anchorScroll will automatically scroll to it\n                   $location.hash('anchor' + x);\n                 } else {\n                   // call $anchorScroll() explicitly,\n                   // since $location.hash hasn't changed\n                   $anchorScroll();\n                 }\n               };\n             }\n           ]);\n       </file>\n       <file name=\"style.css\">\n         body {\n           padding-top: 50px;\n         }\n\n         .anchor {\n           border: 2px dashed DarkOrchid;\n           padding: 10px 10px 200px 10px;\n         }\n\n         .fixed-header {\n           background-color: rgba(0, 0, 0, 0.2);\n           height: 50px;\n           position: fixed;\n           top: 0; left: 0; right: 0;\n         }\n\n         .fixed-header > a {\n           display: inline-block;\n           margin: 5px 15px;\n         }\n       </file>\n     </example>\n   */\n  this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {\n    var document = $window.document;\n\n    // Helper function to get first anchor from a NodeList\n    // (using `Array#some()` instead of `angular#forEach()` since it's more performant\n    //  and working in all supported browsers.)\n    function getFirstAnchor(list) {\n      var result = null;\n      Array.prototype.some.call(list, function(element) {\n        if (nodeName_(element) === 'a') {\n          result = element;\n          return true;\n        }\n      });\n      return result;\n    }\n\n    function getYOffset() {\n\n      var offset = scroll.yOffset;\n\n      if (isFunction(offset)) {\n        offset = offset();\n      } else if (isElement(offset)) {\n        var elem = offset[0];\n        var style = $window.getComputedStyle(elem);\n        if (style.position !== 'fixed') {\n          offset = 0;\n        } else {\n          offset = elem.getBoundingClientRect().bottom;\n        }\n      } else if (!isNumber(offset)) {\n        offset = 0;\n      }\n\n      return offset;\n    }\n\n    function scrollTo(elem) {\n      if (elem) {\n        elem.scrollIntoView();\n\n        var offset = getYOffset();\n\n        if (offset) {\n          // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.\n          // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the\n          // top of the viewport.\n          //\n          // IF the number of pixels from the top of `elem` to the end of the page's content is less\n          // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some\n          // way down the page.\n          //\n          // This is often the case for elements near the bottom of the page.\n          //\n          // In such cases we do not need to scroll the whole `offset` up, just the difference between\n          // the top of the element and the offset, which is enough to align the top of `elem` at the\n          // desired position.\n          var elemTop = elem.getBoundingClientRect().top;\n          $window.scrollBy(0, elemTop - offset);\n        }\n      } else {\n        $window.scrollTo(0, 0);\n      }\n    }\n\n    function scroll(hash) {\n      hash = isString(hash) ? hash : $location.hash();\n      var elm;\n\n      // empty hash, scroll to the top of the page\n      if (!hash) scrollTo(null);\n\n      // element with given id\n      else if ((elm = document.getElementById(hash))) scrollTo(elm);\n\n      // first anchor with given name :-D\n      else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);\n\n      // no element and hash == 'top', scroll to the top of the page\n      else if (hash === 'top') scrollTo(null);\n    }\n\n    // does not scroll when user clicks on anchor link that is currently on\n    // (no url change, no $location.hash() change), browser native does scroll\n    if (autoScrollingEnabled) {\n      $rootScope.$watch(function autoScrollWatch() {return $location.hash();},\n        function autoScrollWatchAction(newVal, oldVal) {\n          // skip the initial scroll if $location.hash is empty\n          if (newVal === oldVal && newVal === '') return;\n\n          jqLiteDocumentLoaded(function() {\n            $rootScope.$evalAsync(scroll);\n          });\n        });\n    }\n\n    return scroll;\n  }];\n}\n\nvar $animateMinErr = minErr('$animate');\nvar ELEMENT_NODE = 1;\nvar NG_ANIMATE_CLASSNAME = 'ng-animate';\n\nfunction mergeClasses(a,b) {\n  if (!a && !b) return '';\n  if (!a) return b;\n  if (!b) return a;\n  if (isArray(a)) a = a.join(' ');\n  if (isArray(b)) b = b.join(' ');\n  return a + ' ' + b;\n}\n\nfunction extractElementNode(element) {\n  for (var i = 0; i < element.length; i++) {\n    var elm = element[i];\n    if (elm.nodeType === ELEMENT_NODE) {\n      return elm;\n    }\n  }\n}\n\nfunction splitClasses(classes) {\n  if (isString(classes)) {\n    classes = classes.split(' ');\n  }\n\n  // Use createMap() to prevent class assumptions involving property names in\n  // Object.prototype\n  var obj = createMap();\n  forEach(classes, function(klass) {\n    // sometimes the split leaves empty string values\n    // incase extra spaces were applied to the options\n    if (klass.length) {\n      obj[klass] = true;\n    }\n  });\n  return obj;\n}\n\n// if any other type of options value besides an Object value is\n// passed into the $animate.method() animation then this helper code\n// will be run which will ignore it. While this patch is not the\n// greatest solution to this, a lot of existing plugins depend on\n// $animate to either call the callback (< 1.2) or return a promise\n// that can be changed. This helper function ensures that the options\n// are wiped clean incase a callback function is provided.\nfunction prepareAnimateOptions(options) {\n  return isObject(options)\n      ? options\n      : {};\n}\n\nvar $$CoreAnimateRunnerProvider = function() {\n  this.$get = ['$q', '$$rAF', function($q, $$rAF) {\n    function AnimateRunner() {}\n    AnimateRunner.all = noop;\n    AnimateRunner.chain = noop;\n    AnimateRunner.prototype = {\n      end: noop,\n      cancel: noop,\n      resume: noop,\n      pause: noop,\n      complete: noop,\n      then: function(pass, fail) {\n        return $q(function(resolve) {\n          $$rAF(function() {\n            resolve();\n          });\n        }).then(pass, fail);\n      }\n    };\n    return AnimateRunner;\n  }];\n};\n\n// this is prefixed with Core since it conflicts with\n// the animateQueueProvider defined in ngAnimate/animateQueue.js\nvar $$CoreAnimateQueueProvider = function() {\n  var postDigestQueue = new HashMap();\n  var postDigestElements = [];\n\n  this.$get = ['$$AnimateRunner', '$rootScope',\n       function($$AnimateRunner,   $rootScope) {\n    return {\n      enabled: noop,\n      on: noop,\n      off: noop,\n      pin: noop,\n\n      push: function(element, event, options, domOperation) {\n        domOperation        && domOperation();\n\n        options = options || {};\n        options.from        && element.css(options.from);\n        options.to          && element.css(options.to);\n\n        if (options.addClass || options.removeClass) {\n          addRemoveClassesPostDigest(element, options.addClass, options.removeClass);\n        }\n\n        return new $$AnimateRunner(); // jshint ignore:line\n      }\n    };\n\n    function addRemoveClassesPostDigest(element, add, remove) {\n      var classVal, data = postDigestQueue.get(element);\n\n      if (!data) {\n        postDigestQueue.put(element, data = {});\n        postDigestElements.push(element);\n      }\n\n      var updateData = function(classes, value) {\n        var changed = false;\n        if (classes) {\n          classes = isString(classes) ? classes.split(' ') :\n                    isArray(classes) ? classes : [];\n          forEach(classes, function(className) {\n            if (className) {\n              changed = true;\n              data[className] = value;\n            }\n          });\n        }\n        return changed;\n      };\n\n      var classesAdded = updateData(add, true);\n      var classesRemoved = updateData(remove, false);\n      if ((!classesAdded && !classesRemoved) || postDigestElements.length > 1) return;\n\n      $rootScope.$$postDigest(function() {\n        forEach(postDigestElements, function(element) {\n          var data = postDigestQueue.get(element);\n          if (data) {\n            var existing = splitClasses(element.attr('class'));\n            var toAdd = '';\n            var toRemove = '';\n            forEach(data, function(status, className) {\n              var hasClass = !!existing[className];\n              if (status !== hasClass) {\n                if (status) {\n                  toAdd += (toAdd.length ? ' ' : '') + className;\n                } else {\n                  toRemove += (toRemove.length ? ' ' : '') + className;\n                }\n              }\n            });\n\n            forEach(element, function(elm) {\n              toAdd    && jqLiteAddClass(elm, toAdd);\n              toRemove && jqLiteRemoveClass(elm, toRemove);\n            });\n            postDigestQueue.remove(element);\n          }\n        });\n\n        postDigestElements.length = 0;\n      });\n    }\n  }];\n};\n\n/**\n * @ngdoc provider\n * @name $animateProvider\n *\n * @description\n * Default implementation of $animate that doesn't perform any animations, instead just\n * synchronously performs DOM updates and resolves the returned runner promise.\n *\n * In order to enable animations the `ngAnimate` module has to be loaded.\n *\n * To see the functional implementation check out `src/ngAnimate/animate.js`.\n */\nvar $AnimateProvider = ['$provide', function($provide) {\n  var provider = this;\n\n  this.$$registeredAnimations = Object.create(null);\n\n   /**\n   * @ngdoc method\n   * @name $animateProvider#register\n   *\n   * @description\n   * Registers a new injectable animation factory function. The factory function produces the\n   * animation object which contains callback functions for each event that is expected to be\n   * animated.\n   *\n   *   * `eventFn`: `function(element, ... , doneFunction, options)`\n   *   The element to animate, the `doneFunction` and the options fed into the animation. Depending\n   *   on the type of animation additional arguments will be injected into the animation function. The\n   *   list below explains the function signatures for the different animation methods:\n   *\n   *   - setClass: function(element, addedClasses, removedClasses, doneFunction, options)\n   *   - addClass: function(element, addedClasses, doneFunction, options)\n   *   - removeClass: function(element, removedClasses, doneFunction, options)\n   *   - enter, leave, move: function(element, doneFunction, options)\n   *   - animate: function(element, fromStyles, toStyles, doneFunction, options)\n   *\n   *   Make sure to trigger the `doneFunction` once the animation is fully complete.\n   *\n   * ```js\n   *   return {\n   *     //enter, leave, move signature\n   *     eventFn : function(element, done, options) {\n   *       //code to run the animation\n   *       //once complete, then run done()\n   *       return function endFunction(wasCancelled) {\n   *         //code to cancel the animation\n   *       }\n   *     }\n   *   }\n   * ```\n   *\n   * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).\n   * @param {Function} factory The factory function that will be executed to return the animation\n   *                           object.\n   */\n  this.register = function(name, factory) {\n    if (name && name.charAt(0) !== '.') {\n      throw $animateMinErr('notcsel', \"Expecting class selector starting with '.' got '{0}'.\", name);\n    }\n\n    var key = name + '-animation';\n    provider.$$registeredAnimations[name.substr(1)] = key;\n    $provide.factory(key, factory);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $animateProvider#classNameFilter\n   *\n   * @description\n   * Sets and/or returns the CSS class regular expression that is checked when performing\n   * an animation. Upon bootstrap the classNameFilter value is not set at all and will\n   * therefore enable $animate to attempt to perform an animation on any element that is triggered.\n   * When setting the `classNameFilter` value, animations will only be performed on elements\n   * that successfully match the filter expression. This in turn can boost performance\n   * for low-powered devices as well as applications containing a lot of structural operations.\n   * @param {RegExp=} expression The className expression which will be checked against all animations\n   * @return {RegExp} The current CSS className expression value. If null then there is no expression value\n   */\n  this.classNameFilter = function(expression) {\n    if (arguments.length === 1) {\n      this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;\n      if (this.$$classNameFilter) {\n        var reservedRegex = new RegExp(\"(\\\\s+|\\\\/)\" + NG_ANIMATE_CLASSNAME + \"(\\\\s+|\\\\/)\");\n        if (reservedRegex.test(this.$$classNameFilter.toString())) {\n          throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the \"{0}\" CSS class.', NG_ANIMATE_CLASSNAME);\n\n        }\n      }\n    }\n    return this.$$classNameFilter;\n  };\n\n  this.$get = ['$$animateQueue', function($$animateQueue) {\n    function domInsert(element, parentElement, afterElement) {\n      // if for some reason the previous element was removed\n      // from the dom sometime before this code runs then let's\n      // just stick to using the parent element as the anchor\n      if (afterElement) {\n        var afterNode = extractElementNode(afterElement);\n        if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {\n          afterElement = null;\n        }\n      }\n      afterElement ? afterElement.after(element) : parentElement.prepend(element);\n    }\n\n    /**\n     * @ngdoc service\n     * @name $animate\n     * @description The $animate service exposes a series of DOM utility methods that provide support\n     * for animation hooks. The default behavior is the application of DOM operations, however,\n     * when an animation is detected (and animations are enabled), $animate will do the heavy lifting\n     * to ensure that animation runs with the triggered DOM operation.\n     *\n     * By default $animate doesn't trigger an animations. This is because the `ngAnimate` module isn't\n     * included and only when it is active then the animation hooks that `$animate` triggers will be\n     * functional. Once active then all structural `ng-` directives will trigger animations as they perform\n     * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,\n     * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.\n     *\n     * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.\n     *\n     * To learn more about enabling animation support, click here to visit the\n     * {@link ngAnimate ngAnimate module page}.\n     */\n    return {\n      // we don't call it directly since non-existant arguments may\n      // be interpreted as null within the sub enabled function\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#on\n       * @kind function\n       * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)\n       *    has fired on the given element or among any of its children. Once the listener is fired, the provided callback\n       *    is fired with the following params:\n       *\n       * ```js\n       * $animate.on('enter', container,\n       *    function callback(element, phase) {\n       *      // cool we detected an enter animation within the container\n       *    }\n       * );\n       * ```\n       *\n       * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)\n       * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself\n       *     as well as among its children\n       * @param {Function} callback the callback function that will be fired when the listener is triggered\n       *\n       * The arguments present in the callback function are:\n       * * `element` - The captured DOM element that the animation was fired on.\n       * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).\n       */\n      on: $$animateQueue.on,\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#off\n       * @kind function\n       * @description Deregisters an event listener based on the event which has been associated with the provided element. This method\n       * can be used in three different ways depending on the arguments:\n       *\n       * ```js\n       * // remove all the animation event listeners listening for `enter`\n       * $animate.off('enter');\n       *\n       * // remove all the animation event listeners listening for `enter` on the given element and its children\n       * $animate.off('enter', container);\n       *\n       * // remove the event listener function provided by `listenerFn` that is set\n       * // to listen for `enter` on the given `element` as well as its children\n       * $animate.off('enter', container, callback);\n       * ```\n       *\n       * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)\n       * @param {DOMElement=} container the container element the event listener was placed on\n       * @param {Function=} callback the callback function that was registered as the listener\n       */\n      off: $$animateQueue.off,\n\n      /**\n       * @ngdoc method\n       * @name $animate#pin\n       * @kind function\n       * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists\n       *    outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the\n       *    element despite being outside the realm of the application or within another application. Say for example if the application\n       *    was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated\n       *    as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind\n       *    that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.\n       *\n       *    Note that this feature is only active when the `ngAnimate` module is used.\n       *\n       * @param {DOMElement} element the external element that will be pinned\n       * @param {DOMElement} parentElement the host parent element that will be associated with the external element\n       */\n      pin: $$animateQueue.pin,\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#enabled\n       * @kind function\n       * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This\n       * function can be called in four ways:\n       *\n       * ```js\n       * // returns true or false\n       * $animate.enabled();\n       *\n       * // changes the enabled state for all animations\n       * $animate.enabled(false);\n       * $animate.enabled(true);\n       *\n       * // returns true or false if animations are enabled for an element\n       * $animate.enabled(element);\n       *\n       * // changes the enabled state for an element and its children\n       * $animate.enabled(element, true);\n       * $animate.enabled(element, false);\n       * ```\n       *\n       * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state\n       * @param {boolean=} enabled whether or not the animations will be enabled for the element\n       *\n       * @return {boolean} whether or not animations are enabled\n       */\n      enabled: $$animateQueue.enabled,\n\n      /**\n       * @ngdoc method\n       * @name $animate#cancel\n       * @kind function\n       * @description Cancels the provided animation.\n       *\n       * @param {Promise} animationPromise The animation promise that is returned when an animation is started.\n       */\n      cancel: function(runner) {\n        runner.end && runner.end();\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#enter\n       * @kind function\n       * @description Inserts the element into the DOM either after the `after` element (if provided) or\n       *   as the first child within the `parent` element and then triggers an animation.\n       *   A promise is returned that will be resolved during the next digest once the animation\n       *   has completed.\n       *\n       * @param {DOMElement} element the element which will be inserted into the DOM\n       * @param {DOMElement} parent the parent element which will append the element as\n       *   a child (so long as the after element is not present)\n       * @param {DOMElement=} after the sibling element after which the element will be appended\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      enter: function(element, parent, after, options) {\n        parent = parent && jqLite(parent);\n        after = after && jqLite(after);\n        parent = parent || after.parent();\n        domInsert(element, parent, after);\n        return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));\n      },\n\n      /**\n       *\n       * @ngdoc method\n       * @name $animate#move\n       * @kind function\n       * @description Inserts (moves) the element into its new position in the DOM either after\n       *   the `after` element (if provided) or as the first child within the `parent` element\n       *   and then triggers an animation. A promise is returned that will be resolved\n       *   during the next digest once the animation has completed.\n       *\n       * @param {DOMElement} element the element which will be moved into the new DOM position\n       * @param {DOMElement} parent the parent element which will append the element as\n       *   a child (so long as the after element is not present)\n       * @param {DOMElement=} after the sibling element after which the element will be appended\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      move: function(element, parent, after, options) {\n        parent = parent && jqLite(parent);\n        after = after && jqLite(after);\n        parent = parent || after.parent();\n        domInsert(element, parent, after);\n        return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#leave\n       * @kind function\n       * @description Triggers an animation and then removes the element from the DOM.\n       * When the function is called a promise is returned that will be resolved during the next\n       * digest once the animation has completed.\n       *\n       * @param {DOMElement} element the element which will be removed from the DOM\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      leave: function(element, options) {\n        return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {\n          element.remove();\n        });\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#addClass\n       * @kind function\n       *\n       * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon\n       *   execution, the addClass operation will only be handled after the next digest and it will not trigger an\n       *   animation if element already contains the CSS class or if the class is removed at a later step.\n       *   Note that class-based animations are treated differently compared to structural animations\n       *   (like enter, move and leave) since the CSS classes may be added/removed at different points\n       *   depending if CSS or JavaScript animations are used.\n       *\n       * @param {DOMElement} element the element which the CSS classes will be applied to\n       * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      addClass: function(element, className, options) {\n        options = prepareAnimateOptions(options);\n        options.addClass = mergeClasses(options.addclass, className);\n        return $$animateQueue.push(element, 'addClass', options);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#removeClass\n       * @kind function\n       *\n       * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon\n       *   execution, the removeClass operation will only be handled after the next digest and it will not trigger an\n       *   animation if element does not contain the CSS class or if the class is added at a later step.\n       *   Note that class-based animations are treated differently compared to structural animations\n       *   (like enter, move and leave) since the CSS classes may be added/removed at different points\n       *   depending if CSS or JavaScript animations are used.\n       *\n       * @param {DOMElement} element the element which the CSS classes will be applied to\n       * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      removeClass: function(element, className, options) {\n        options = prepareAnimateOptions(options);\n        options.removeClass = mergeClasses(options.removeClass, className);\n        return $$animateQueue.push(element, 'removeClass', options);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#setClass\n       * @kind function\n       *\n       * @description Performs both the addition and removal of a CSS classes on an element and (during the process)\n       *    triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and\n       *    `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has\n       *    passed. Note that class-based animations are treated differently compared to structural animations\n       *    (like enter, move and leave) since the CSS classes may be added/removed at different points\n       *    depending if CSS or JavaScript animations are used.\n       *\n       * @param {DOMElement} element the element which the CSS classes will be applied to\n       * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)\n       * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      setClass: function(element, add, remove, options) {\n        options = prepareAnimateOptions(options);\n        options.addClass = mergeClasses(options.addClass, add);\n        options.removeClass = mergeClasses(options.removeClass, remove);\n        return $$animateQueue.push(element, 'setClass', options);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $animate#animate\n       * @kind function\n       *\n       * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.\n       * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take\n       * on the provided styles. For example, if a transition animation is set for the given className then the provided from and\n       * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles\n       * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).\n       *\n       * @param {DOMElement} element the element which the CSS styles will be applied to\n       * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.\n       * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.\n       * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If\n       *    this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.\n       *    (Note that if no animation is detected then this value will not be appplied to the element.)\n       * @param {object=} options an optional collection of options/styles that will be applied to the element\n       *\n       * @return {Promise} the animation callback promise\n       */\n      animate: function(element, from, to, className, options) {\n        options = prepareAnimateOptions(options);\n        options.from = options.from ? extend(options.from, from) : from;\n        options.to   = options.to   ? extend(options.to, to)     : to;\n\n        className = className || 'ng-inline-animate';\n        options.tempClasses = mergeClasses(options.tempClasses, className);\n        return $$animateQueue.push(element, 'animate', options);\n      }\n    };\n  }];\n}];\n\n/**\n * @ngdoc service\n * @name $animateCss\n * @kind object\n *\n * @description\n * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,\n * then the `$animateCss` service will actually perform animations.\n *\n * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.\n */\nvar $CoreAnimateCssProvider = function() {\n  this.$get = ['$$rAF', '$q', function($$rAF, $q) {\n\n    var RAFPromise = function() {};\n    RAFPromise.prototype = {\n      done: function(cancel) {\n        this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();\n      },\n      end: function() {\n        this.done();\n      },\n      cancel: function() {\n        this.done(true);\n      },\n      getPromise: function() {\n        if (!this.defer) {\n          this.defer = $q.defer();\n        }\n        return this.defer.promise;\n      },\n      then: function(f1,f2) {\n        return this.getPromise().then(f1,f2);\n      },\n      'catch': function(f1) {\n        return this.getPromise().catch(f1);\n      },\n      'finally': function(f1) {\n        return this.getPromise().finally(f1);\n      }\n    };\n\n    return function(element, options) {\n      if (options.from) {\n        element.css(options.from);\n        options.from = null;\n      }\n\n      var closed, runner = new RAFPromise();\n      return {\n        start: run,\n        end: run\n      };\n\n      function run() {\n        $$rAF(function() {\n          close();\n          if (!closed) {\n            runner.done();\n          }\n          closed = true;\n        });\n        return runner;\n      }\n\n      function close() {\n        if (options.addClass) {\n          element.addClass(options.addClass);\n          options.addClass = null;\n        }\n        if (options.removeClass) {\n          element.removeClass(options.removeClass);\n          options.removeClass = null;\n        }\n        if (options.to) {\n          element.css(options.to);\n          options.to = null;\n        }\n      }\n    };\n  }];\n};\n\n/* global stripHash: true */\n\n/**\n * ! This is a private undocumented service !\n *\n * @name $browser\n * @requires $log\n * @description\n * This object has two goals:\n *\n * - hide all the global state in the browser caused by the window object\n * - abstract away all the browser specific features and inconsistencies\n *\n * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`\n * service, which can be used for convenient testing of the application without the interaction with\n * the real browser apis.\n */\n/**\n * @param {object} window The global window object.\n * @param {object} document jQuery wrapped document.\n * @param {object} $log window.console or an object with the same interface.\n * @param {object} $sniffer $sniffer service\n */\nfunction Browser(window, document, $log, $sniffer) {\n  var self = this,\n      rawDocument = document[0],\n      location = window.location,\n      history = window.history,\n      setTimeout = window.setTimeout,\n      clearTimeout = window.clearTimeout,\n      pendingDeferIds = {};\n\n  self.isMock = false;\n\n  var outstandingRequestCount = 0;\n  var outstandingRequestCallbacks = [];\n\n  // TODO(vojta): remove this temporary api\n  self.$$completeOutstandingRequest = completeOutstandingRequest;\n  self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };\n\n  /**\n   * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`\n   * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.\n   */\n  function completeOutstandingRequest(fn) {\n    try {\n      fn.apply(null, sliceArgs(arguments, 1));\n    } finally {\n      outstandingRequestCount--;\n      if (outstandingRequestCount === 0) {\n        while (outstandingRequestCallbacks.length) {\n          try {\n            outstandingRequestCallbacks.pop()();\n          } catch (e) {\n            $log.error(e);\n          }\n        }\n      }\n    }\n  }\n\n  function getHash(url) {\n    var index = url.indexOf('#');\n    return index === -1 ? '' : url.substr(index);\n  }\n\n  /**\n   * @private\n   * Note: this method is used only by scenario runner\n   * TODO(vojta): prefix this method with $$ ?\n   * @param {function()} callback Function that will be called when no outstanding request\n   */\n  self.notifyWhenNoOutstandingRequests = function(callback) {\n    if (outstandingRequestCount === 0) {\n      callback();\n    } else {\n      outstandingRequestCallbacks.push(callback);\n    }\n  };\n\n  //////////////////////////////////////////////////////////////\n  // URL API\n  //////////////////////////////////////////////////////////////\n\n  var cachedState, lastHistoryState,\n      lastBrowserUrl = location.href,\n      baseElement = document.find('base'),\n      reloadLocation = null;\n\n  cacheState();\n  lastHistoryState = cachedState;\n\n  /**\n   * @name $browser#url\n   *\n   * @description\n   * GETTER:\n   * Without any argument, this method just returns current value of location.href.\n   *\n   * SETTER:\n   * With at least one argument, this method sets url to new value.\n   * If html5 history api supported, pushState/replaceState is used, otherwise\n   * location.href/location.replace is used.\n   * Returns its own instance to allow chaining\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to change url.\n   *\n   * @param {string} url New url (when used as setter)\n   * @param {boolean=} replace Should new url replace current history record?\n   * @param {object=} state object to use with pushState/replaceState\n   */\n  self.url = function(url, replace, state) {\n    // In modern browsers `history.state` is `null` by default; treating it separately\n    // from `undefined` would cause `$browser.url('/foo')` to change `history.state`\n    // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.\n    if (isUndefined(state)) {\n      state = null;\n    }\n\n    // Android Browser BFCache causes location, history reference to become stale.\n    if (location !== window.location) location = window.location;\n    if (history !== window.history) history = window.history;\n\n    // setter\n    if (url) {\n      var sameState = lastHistoryState === state;\n\n      // Don't change anything if previous and current URLs and states match. This also prevents\n      // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.\n      // See https://github.com/angular/angular.js/commit/ffb2701\n      if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {\n        return self;\n      }\n      var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);\n      lastBrowserUrl = url;\n      lastHistoryState = state;\n      // Don't use history API if only the hash changed\n      // due to a bug in IE10/IE11 which leads\n      // to not firing a `hashchange` nor `popstate` event\n      // in some cases (see #9143).\n      if ($sniffer.history && (!sameBase || !sameState)) {\n        history[replace ? 'replaceState' : 'pushState'](state, '', url);\n        cacheState();\n        // Do the assignment again so that those two variables are referentially identical.\n        lastHistoryState = cachedState;\n      } else {\n        if (!sameBase || reloadLocation) {\n          reloadLocation = url;\n        }\n        if (replace) {\n          location.replace(url);\n        } else if (!sameBase) {\n          location.href = url;\n        } else {\n          location.hash = getHash(url);\n        }\n      }\n      return self;\n    // getter\n    } else {\n      // - reloadLocation is needed as browsers don't allow to read out\n      //   the new location.href if a reload happened.\n      // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172\n      return reloadLocation || location.href.replace(/%27/g,\"'\");\n    }\n  };\n\n  /**\n   * @name $browser#state\n   *\n   * @description\n   * This method is a getter.\n   *\n   * Return history.state or null if history.state is undefined.\n   *\n   * @returns {object} state\n   */\n  self.state = function() {\n    return cachedState;\n  };\n\n  var urlChangeListeners = [],\n      urlChangeInit = false;\n\n  function cacheStateAndFireUrlChange() {\n    cacheState();\n    fireUrlChange();\n  }\n\n  function getCurrentState() {\n    try {\n      return history.state;\n    } catch (e) {\n      // MSIE can reportedly throw when there is no state (UNCONFIRMED).\n    }\n  }\n\n  // This variable should be used *only* inside the cacheState function.\n  var lastCachedState = null;\n  function cacheState() {\n    // This should be the only place in $browser where `history.state` is read.\n    cachedState = getCurrentState();\n    cachedState = isUndefined(cachedState) ? null : cachedState;\n\n    // Prevent callbacks fo fire twice if both hashchange & popstate were fired.\n    if (equals(cachedState, lastCachedState)) {\n      cachedState = lastCachedState;\n    }\n    lastCachedState = cachedState;\n  }\n\n  function fireUrlChange() {\n    if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {\n      return;\n    }\n\n    lastBrowserUrl = self.url();\n    lastHistoryState = cachedState;\n    forEach(urlChangeListeners, function(listener) {\n      listener(self.url(), cachedState);\n    });\n  }\n\n  /**\n   * @name $browser#onUrlChange\n   *\n   * @description\n   * Register callback function that will be called, when url changes.\n   *\n   * It's only called when the url is changed from outside of angular:\n   * - user types different url into address bar\n   * - user clicks on history (forward/back) button\n   * - user clicks on a link\n   *\n   * It's not called when url is changed by $browser.url() method\n   *\n   * The listener gets called with new url as parameter.\n   *\n   * NOTE: this api is intended for use only by the $location service. Please use the\n   * {@link ng.$location $location service} to monitor url changes in angular apps.\n   *\n   * @param {function(string)} listener Listener function to be called when url changes.\n   * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.\n   */\n  self.onUrlChange = function(callback) {\n    // TODO(vojta): refactor to use node's syntax for events\n    if (!urlChangeInit) {\n      // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)\n      // don't fire popstate when user change the address bar and don't fire hashchange when url\n      // changed by push/replaceState\n\n      // html5 history api - popstate event\n      if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);\n      // hashchange event\n      jqLite(window).on('hashchange', cacheStateAndFireUrlChange);\n\n      urlChangeInit = true;\n    }\n\n    urlChangeListeners.push(callback);\n    return callback;\n  };\n\n  /**\n   * @private\n   * Remove popstate and hashchange handler from window.\n   *\n   * NOTE: this api is intended for use only by $rootScope.\n   */\n  self.$$applicationDestroyed = function() {\n    jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);\n  };\n\n  /**\n   * Checks whether the url has changed outside of Angular.\n   * Needs to be exported to be able to check for changes that have been done in sync,\n   * as hashchange/popstate events fire in async.\n   */\n  self.$$checkUrlChange = fireUrlChange;\n\n  //////////////////////////////////////////////////////////////\n  // Misc API\n  //////////////////////////////////////////////////////////////\n\n  /**\n   * @name $browser#baseHref\n   *\n   * @description\n   * Returns current <base href>\n   * (always relative - without domain)\n   *\n   * @returns {string} The current base href\n   */\n  self.baseHref = function() {\n    var href = baseElement.attr('href');\n    return href ? href.replace(/^(https?\\:)?\\/\\/[^\\/]*/, '') : '';\n  };\n\n  /**\n   * @name $browser#defer\n   * @param {function()} fn A function, who's execution should be deferred.\n   * @param {number=} [delay=0] of milliseconds to defer the function execution.\n   * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.\n   *\n   * @description\n   * Executes a fn asynchronously via `setTimeout(fn, delay)`.\n   *\n   * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using\n   * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed\n   * via `$browser.defer.flush()`.\n   *\n   */\n  self.defer = function(fn, delay) {\n    var timeoutId;\n    outstandingRequestCount++;\n    timeoutId = setTimeout(function() {\n      delete pendingDeferIds[timeoutId];\n      completeOutstandingRequest(fn);\n    }, delay || 0);\n    pendingDeferIds[timeoutId] = true;\n    return timeoutId;\n  };\n\n\n  /**\n   * @name $browser#defer.cancel\n   *\n   * @description\n   * Cancels a deferred task identified with `deferId`.\n   *\n   * @param {*} deferId Token returned by the `$browser.defer` function.\n   * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n   *                    canceled.\n   */\n  self.defer.cancel = function(deferId) {\n    if (pendingDeferIds[deferId]) {\n      delete pendingDeferIds[deferId];\n      clearTimeout(deferId);\n      completeOutstandingRequest(noop);\n      return true;\n    }\n    return false;\n  };\n\n}\n\nfunction $BrowserProvider() {\n  this.$get = ['$window', '$log', '$sniffer', '$document',\n      function($window, $log, $sniffer, $document) {\n        return new Browser($window, $document, $log, $sniffer);\n      }];\n}\n\n/**\n * @ngdoc service\n * @name $cacheFactory\n *\n * @description\n * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to\n * them.\n *\n * ```js\n *\n *  var cache = $cacheFactory('cacheId');\n *  expect($cacheFactory.get('cacheId')).toBe(cache);\n *  expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();\n *\n *  cache.put(\"key\", \"value\");\n *  cache.put(\"another key\", \"another value\");\n *\n *  // We've specified no options on creation\n *  expect(cache.info()).toEqual({id: 'cacheId', size: 2});\n *\n * ```\n *\n *\n * @param {string} cacheId Name or id of the newly created cache.\n * @param {object=} options Options object that specifies the cache behavior. Properties:\n *\n *   - `{number=}` `capacity` — turns the cache into LRU cache.\n *\n * @returns {object} Newly created cache object with the following set of methods:\n *\n * - `{object}` `info()` — Returns id, size, and options of cache.\n * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns\n *   it.\n * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.\n * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.\n * - `{void}` `removeAll()` — Removes all cached values.\n * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.\n *\n * @example\n   <example module=\"cacheExampleApp\">\n     <file name=\"index.html\">\n       <div ng-controller=\"CacheController\">\n         <input ng-model=\"newCacheKey\" placeholder=\"Key\">\n         <input ng-model=\"newCacheValue\" placeholder=\"Value\">\n         <button ng-click=\"put(newCacheKey, newCacheValue)\">Cache</button>\n\n         <p ng-if=\"keys.length\">Cached Values</p>\n         <div ng-repeat=\"key in keys\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"cache.get(key)\"></b>\n         </div>\n\n         <p>Cache Info</p>\n         <div ng-repeat=\"(key, value) in cache.info()\">\n           <span ng-bind=\"key\"></span>\n           <span>: </span>\n           <b ng-bind=\"value\"></b>\n         </div>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('cacheExampleApp', []).\n         controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {\n           $scope.keys = [];\n           $scope.cache = $cacheFactory('cacheId');\n           $scope.put = function(key, value) {\n             if ($scope.cache.get(key) === undefined) {\n               $scope.keys.push(key);\n             }\n             $scope.cache.put(key, value === undefined ? null : value);\n           };\n         }]);\n     </file>\n     <file name=\"style.css\">\n       p {\n         margin: 10px 0 3px;\n       }\n     </file>\n   </example>\n */\nfunction $CacheFactoryProvider() {\n\n  this.$get = function() {\n    var caches = {};\n\n    function cacheFactory(cacheId, options) {\n      if (cacheId in caches) {\n        throw minErr('$cacheFactory')('iid', \"CacheId '{0}' is already taken!\", cacheId);\n      }\n\n      var size = 0,\n          stats = extend({}, options, {id: cacheId}),\n          data = {},\n          capacity = (options && options.capacity) || Number.MAX_VALUE,\n          lruHash = {},\n          freshEnd = null,\n          staleEnd = null;\n\n      /**\n       * @ngdoc type\n       * @name $cacheFactory.Cache\n       *\n       * @description\n       * A cache object used to store and retrieve data, primarily used by\n       * {@link $http $http} and the {@link ng.directive:script script} directive to cache\n       * templates and other data.\n       *\n       * ```js\n       *  angular.module('superCache')\n       *    .factory('superCache', ['$cacheFactory', function($cacheFactory) {\n       *      return $cacheFactory('super-cache');\n       *    }]);\n       * ```\n       *\n       * Example test:\n       *\n       * ```js\n       *  it('should behave like a cache', inject(function(superCache) {\n       *    superCache.put('key', 'value');\n       *    superCache.put('another key', 'another value');\n       *\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 2\n       *    });\n       *\n       *    superCache.remove('another key');\n       *    expect(superCache.get('another key')).toBeUndefined();\n       *\n       *    superCache.removeAll();\n       *    expect(superCache.info()).toEqual({\n       *      id: 'super-cache',\n       *      size: 0\n       *    });\n       *  }));\n       * ```\n       */\n      return caches[cacheId] = {\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#put\n         * @kind function\n         *\n         * @description\n         * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be\n         * retrieved later, and incrementing the size of the cache if the key was not already\n         * present in the cache. If behaving like an LRU cache, it will also remove stale\n         * entries from the set.\n         *\n         * It will not insert undefined values into the cache.\n         *\n         * @param {string} key the key under which the cached data is stored.\n         * @param {*} value the value to store alongside the key. If it is undefined, the key\n         *    will not be stored.\n         * @returns {*} the value stored.\n         */\n        put: function(key, value) {\n          if (isUndefined(value)) return;\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key] || (lruHash[key] = {key: key});\n\n            refresh(lruEntry);\n          }\n\n          if (!(key in data)) size++;\n          data[key] = value;\n\n          if (size > capacity) {\n            this.remove(staleEnd.key);\n          }\n\n          return value;\n        },\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#get\n         * @kind function\n         *\n         * @description\n         * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the data to be retrieved\n         * @returns {*} the value stored.\n         */\n        get: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            refresh(lruEntry);\n          }\n\n          return data[key];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#remove\n         * @kind function\n         *\n         * @description\n         * Removes an entry from the {@link $cacheFactory.Cache Cache} object.\n         *\n         * @param {string} key the key of the entry to be removed\n         */\n        remove: function(key) {\n          if (capacity < Number.MAX_VALUE) {\n            var lruEntry = lruHash[key];\n\n            if (!lruEntry) return;\n\n            if (lruEntry == freshEnd) freshEnd = lruEntry.p;\n            if (lruEntry == staleEnd) staleEnd = lruEntry.n;\n            link(lruEntry.n,lruEntry.p);\n\n            delete lruHash[key];\n          }\n\n          delete data[key];\n          size--;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#removeAll\n         * @kind function\n         *\n         * @description\n         * Clears the cache object of any entries.\n         */\n        removeAll: function() {\n          data = {};\n          size = 0;\n          lruHash = {};\n          freshEnd = staleEnd = null;\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#destroy\n         * @kind function\n         *\n         * @description\n         * Destroys the {@link $cacheFactory.Cache Cache} object entirely,\n         * removing it from the {@link $cacheFactory $cacheFactory} set.\n         */\n        destroy: function() {\n          data = null;\n          stats = null;\n          lruHash = null;\n          delete caches[cacheId];\n        },\n\n\n        /**\n         * @ngdoc method\n         * @name $cacheFactory.Cache#info\n         * @kind function\n         *\n         * @description\n         * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.\n         *\n         * @returns {object} an object with the following properties:\n         *   <ul>\n         *     <li>**id**: the id of the cache instance</li>\n         *     <li>**size**: the number of entries kept in the cache instance</li>\n         *     <li>**...**: any additional properties from the options object when creating the\n         *       cache.</li>\n         *   </ul>\n         */\n        info: function() {\n          return extend({}, stats, {size: size});\n        }\n      };\n\n\n      /**\n       * makes the `entry` the freshEnd of the LRU linked list\n       */\n      function refresh(entry) {\n        if (entry != freshEnd) {\n          if (!staleEnd) {\n            staleEnd = entry;\n          } else if (staleEnd == entry) {\n            staleEnd = entry.n;\n          }\n\n          link(entry.n, entry.p);\n          link(entry, freshEnd);\n          freshEnd = entry;\n          freshEnd.n = null;\n        }\n      }\n\n\n      /**\n       * bidirectionally links two entries of the LRU linked list\n       */\n      function link(nextEntry, prevEntry) {\n        if (nextEntry != prevEntry) {\n          if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify\n          if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify\n        }\n      }\n    }\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#info\n   *\n   * @description\n   * Get information about all the caches that have been created\n   *\n   * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`\n   */\n    cacheFactory.info = function() {\n      var info = {};\n      forEach(caches, function(cache, cacheId) {\n        info[cacheId] = cache.info();\n      });\n      return info;\n    };\n\n\n  /**\n   * @ngdoc method\n   * @name $cacheFactory#get\n   *\n   * @description\n   * Get access to a cache object by the `cacheId` used when it was created.\n   *\n   * @param {string} cacheId Name or id of a cache to access.\n   * @returns {object} Cache object identified by the cacheId or undefined if no such cache.\n   */\n    cacheFactory.get = function(cacheId) {\n      return caches[cacheId];\n    };\n\n\n    return cacheFactory;\n  };\n}\n\n/**\n * @ngdoc service\n * @name $templateCache\n *\n * @description\n * The first time a template is used, it is loaded in the template cache for quick retrieval. You\n * can load templates directly into the cache in a `script` tag, or by consuming the\n * `$templateCache` service directly.\n *\n * Adding via the `script` tag:\n *\n * ```html\n *   <script type=\"text/ng-template\" id=\"templateId.html\">\n *     <p>This is the content of the template</p>\n *   </script>\n * ```\n *\n * **Note:** the `script` tag containing the template does not need to be included in the `head` of\n * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,\n * element with ng-app attribute), otherwise the template will be ignored.\n *\n * Adding via the `$templateCache` service:\n *\n * ```js\n * var myApp = angular.module('myApp', []);\n * myApp.run(function($templateCache) {\n *   $templateCache.put('templateId.html', 'This is the content of the template');\n * });\n * ```\n *\n * To retrieve the template later, simply use it in your HTML:\n * ```html\n * <div ng-include=\" 'templateId.html' \"></div>\n * ```\n *\n * or get it via Javascript:\n * ```js\n * $templateCache.get('templateId.html')\n * ```\n *\n * See {@link ng.$cacheFactory $cacheFactory}.\n *\n */\nfunction $TemplateCacheProvider() {\n  this.$get = ['$cacheFactory', function($cacheFactory) {\n    return $cacheFactory('templates');\n  }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\n/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!\n *\n * DOM-related variables:\n *\n * - \"node\" - DOM Node\n * - \"element\" - DOM Element or Node\n * - \"$node\" or \"$element\" - jqLite-wrapped node or element\n *\n *\n * Compiler related stuff:\n *\n * - \"linkFn\" - linking fn of a single directive\n * - \"nodeLinkFn\" - function that aggregates all linking fns for a particular node\n * - \"childLinkFn\" -  function that aggregates all linking fns for child nodes of a particular node\n * - \"compositeLinkFn\" - function that aggregates all linking fns for a compilation root (nodeList)\n */\n\n\n/**\n * @ngdoc service\n * @name $compile\n * @kind function\n *\n * @description\n * Compiles an HTML string or DOM into a template and produces a template function, which\n * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.\n *\n * The compilation is a process of walking the DOM tree and matching DOM elements to\n * {@link ng.$compileProvider#directive directives}.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** This document is an in-depth reference of all directive options.\n * For a gentle introduction to directives with examples of common use cases,\n * see the {@link guide/directive directive guide}.\n * </div>\n *\n * ## Comprehensive Directive API\n *\n * There are many different options for a directive.\n *\n * The difference resides in the return value of the factory function.\n * You can either return a \"Directive Definition Object\" (see below) that defines the directive properties,\n * or just the `postLink` function (all other properties will have the default values).\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's recommended to use the \"directive definition object\" form.\n * </div>\n *\n * Here's an example directive declared with a Directive Definition Object:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       priority: 0,\n *       template: '<div></div>', // or // function(tElement, tAttrs) { ... },\n *       // or\n *       // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },\n *       transclude: false,\n *       restrict: 'A',\n *       templateNamespace: 'html',\n *       scope: false,\n *       controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },\n *       controllerAs: 'stringIdentifier',\n *       bindToController: false,\n *       require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],\n *       compile: function compile(tElement, tAttrs, transclude) {\n *         return {\n *           pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *           post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *         }\n *         // or\n *         // return function postLink( ... ) { ... }\n *       },\n *       // or\n *       // link: {\n *       //  pre: function preLink(scope, iElement, iAttrs, controller) { ... },\n *       //  post: function postLink(scope, iElement, iAttrs, controller) { ... }\n *       // }\n *       // or\n *       // link: function postLink( ... ) { ... }\n *     };\n *     return directiveDefinitionObject;\n *   });\n * ```\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Any unspecified options will use the default value. You can see the default values below.\n * </div>\n *\n * Therefore the above can be simplified as:\n *\n * ```js\n *   var myModule = angular.module(...);\n *\n *   myModule.directive('directiveName', function factory(injectables) {\n *     var directiveDefinitionObject = {\n *       link: function postLink(scope, iElement, iAttrs) { ... }\n *     };\n *     return directiveDefinitionObject;\n *     // or\n *     // return function postLink(scope, iElement, iAttrs) { ... }\n *   });\n * ```\n *\n *\n *\n * ### Directive Definition Object\n *\n * The directive definition object provides instructions to the {@link ng.$compile\n * compiler}. The attributes are:\n *\n * #### `multiElement`\n * When this property is set to true, the HTML compiler will collect DOM nodes between\n * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them\n * together as the directive elements. It is recommended that this feature be used on directives\n * which are not strictly behavioural (such as {@link ngClick}), and which\n * do not manipulate or replace child nodes (such as {@link ngInclude}).\n *\n * #### `priority`\n * When there are multiple directives defined on a single DOM element, sometimes it\n * is necessary to specify the order in which the directives are applied. The `priority` is used\n * to sort the directives before their `compile` functions get called. Priority is defined as a\n * number. Directives with greater numerical `priority` are compiled first. Pre-link functions\n * are also run in priority order, but post-link functions are run in reverse order. The order\n * of directives with the same priority is undefined. The default priority is `0`.\n *\n * #### `terminal`\n * If set to true then the current `priority` will be the last set of directives\n * which will execute (any directives at the current priority will still execute\n * as the order of execution on same `priority` is undefined). Note that expressions\n * and other directives used in the directive's template will also be excluded from execution.\n *\n * #### `scope`\n * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the\n * same element request a new scope, only one new scope is created. The new scope rule does not\n * apply for the root of the template since the root of the template always gets a new scope.\n *\n * **If set to `{}` (object hash),** then a new \"isolate\" scope is created. The 'isolate' scope differs from\n * normal scope in that it does not prototypically inherit from the parent scope. This is useful\n * when creating reusable components, which should not accidentally read or modify data in the\n * parent scope.\n *\n * The 'isolate' scope takes an object hash which defines a set of local scope properties\n * derived from the parent scope. These local properties are useful for aliasing values for\n * templates. Locals definition is a hash of local scope property to its source:\n *\n * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is\n *   always a string since DOM attributes are strings. If no `attr` name is specified  then the\n *   attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"hello {{name}}\">` and widget definition\n *   of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect\n *   the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the\n *   `localName` property on the widget scope. The `name` is read from the parent scope (not\n *   component scope).\n *\n * * `=` or `=attr` - set up bi-directional binding between a local scope property and the\n *   parent scope property of name defined via the value of the `attr` attribute. If no `attr`\n *   name is specified then the attribute name is assumed to be the same as the local name.\n *   Given `<widget my-attr=\"parentModel\">` and widget definition of\n *   `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the\n *   value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected\n *   in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent\n *   scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You\n *   can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If\n *   you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use\n *   `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).\n *\n * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.\n *   If no `attr` name is specified then the attribute name is assumed to be the same as the\n *   local name. Given `<widget my-attr=\"count = count + value\">` and widget definition of\n *   `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to\n *   a function wrapper for the `count = count + value` expression. Often it's desirable to\n *   pass data from the isolated scope via an expression to the parent scope, this can be\n *   done by passing a map of local variable names and values into the expression wrapper fn.\n *   For example, if the expression is `increment(amount)` then we can specify the amount value\n *   by calling the `localFn` as `localFn({amount: 22})`.\n *\n *\n * #### `bindToController`\n * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will\n * allow a component to have its properties bound to the controller, rather than to scope. When the controller\n * is instantiated, the initial values of the isolate scope bindings are already available.\n *\n * #### `controller`\n * Controller constructor function. The controller is instantiated before the\n * pre-linking phase and it is shared with other directives (see\n * `require` attribute). This allows the directives to communicate with each other and augment\n * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:\n *\n * * `$scope` - Current scope associated with the element\n * * `$element` - Current element\n * * `$attrs` - Current attributes object for the element\n * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:\n *   `function([scope], cloneLinkingFn, futureParentElement)`.\n *    * `scope`: optional argument to override the scope.\n *    * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.\n *    * `futureParentElement`:\n *        * defines the parent to which the `cloneLinkingFn` will add the cloned elements.\n *        * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.\n *        * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)\n *          and when the `cloneLinkinFn` is passed,\n *          as those elements need to created and cloned in a special way when they are defined outside their\n *          usual containers (e.g. like `<svg>`).\n *        * See also the `directive.templateNamespace` property.\n *\n *\n * #### `require`\n * Require another directive and inject its controller as the fourth argument to the linking function. The\n * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the\n * injected argument will be an array in corresponding order. If no such directive can be\n * found, or if the directive does not have a controller, then an error is raised (unless no link function\n * is specified, in which case error checking is skipped). The name can be prefixed with:\n *\n * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.\n * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.\n * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.\n * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.\n * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass\n *   `null` to the `link` fn if not found.\n * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass\n *   `null` to the `link` fn if not found.\n *\n *\n * #### `controllerAs`\n * Identifier name for a reference to the controller in the directive's scope.\n * This allows the controller to be referenced from the directive template. The directive\n * needs to define a scope for this configuration to be used. Useful in the case when\n * directive is used as component.\n *\n *\n * #### `restrict`\n * String of subset of `EACM` which restricts the directive to a specific directive\n * declaration style. If omitted, the defaults (elements and attributes) are used.\n *\n * * `E` - Element name (default): `<my-directive></my-directive>`\n * * `A` - Attribute (default): `<div my-directive=\"exp\"></div>`\n * * `C` - Class: `<div class=\"my-directive: exp;\"></div>`\n * * `M` - Comment: `<!-- directive: my-directive exp -->`\n *\n *\n * #### `templateNamespace`\n * String representing the document type used by the markup in the template.\n * AngularJS needs this information as those elements need to be created and cloned\n * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.\n *\n * * `html` - All root nodes in the template are HTML. Root nodes may also be\n *   top-level elements such as `<svg>` or `<math>`.\n * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).\n * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).\n *\n * If no `templateNamespace` is specified, then the namespace is considered to be `html`.\n *\n * #### `template`\n * HTML markup that may:\n * * Replace the contents of the directive's element (default).\n * * Replace the directive's element itself (if `replace` is true - DEPRECATED).\n * * Wrap the contents of the directive's element (if `transclude` is true).\n *\n * Value may be:\n *\n * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.\n * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`\n *   function api below) and returns a string value.\n *\n *\n * #### `templateUrl`\n * This is similar to `template` but the template is loaded from the specified URL, asynchronously.\n *\n * Because template loading is asynchronous the compiler will suspend compilation of directives on that element\n * for later when the template has been resolved.  In the meantime it will continue to compile and link\n * sibling and parent elements as though this element had not contained any directives.\n *\n * The compiler does not suspend the entire compilation to wait for templates to be loaded because this\n * would result in the whole app \"stalling\" until all templates are loaded asynchronously - even in the\n * case when only one deeply nested directive has `templateUrl`.\n *\n * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}\n *\n * You can specify `templateUrl` as a string representing the URL or as a function which takes two\n * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns\n * a string value representing the url.  In either case, the template URL is passed through {@link\n * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.\n *\n *\n * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)\n * specify what the template should replace. Defaults to `false`.\n *\n * * `true` - the template will replace the directive's element.\n * * `false` - the template will replace the contents of the directive's element.\n *\n * The replacement process migrates all of the attributes / classes from the old element to the new\n * one. See the {@link guide/directive#template-expanding-directive\n * Directives Guide} for an example.\n *\n * There are very few scenarios where element replacement is required for the application function,\n * the main one being reusable custom components that are used within SVG contexts\n * (because SVG doesn't work with custom elements in the DOM tree).\n *\n * #### `transclude`\n * Extract the contents of the element where the directive appears and make it available to the directive.\n * The contents are compiled and provided to the directive as a **transclusion function**. See the\n * {@link $compile#transclusion Transclusion} section below.\n *\n * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the\n * directive's element or the entire element:\n *\n * * `true` - transclude the content (i.e. the child nodes) of the directive's element.\n * * `'element'` - transclude the whole of the directive's element including any directives on this\n *   element that defined at a lower priority than this directive. When used, the `template`\n *   property is ignored.\n *\n *\n * #### `compile`\n *\n * ```js\n *   function compile(tElement, tAttrs, transclude) { ... }\n * ```\n *\n * The compile function deals with transforming the template DOM. Since most directives do not do\n * template transformation, it is not used often. The compile function takes the following arguments:\n *\n *   * `tElement` - template element - The element where the directive has been declared. It is\n *     safe to do template transformation on the element and child elements only.\n *\n *   * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared\n *     between all directive compile functions.\n *\n *   * `transclude` -  [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`\n *\n * <div class=\"alert alert-warning\">\n * **Note:** The template instance and the link instance may be different objects if the template has\n * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that\n * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration\n * should be done in a linking function rather than in a compile function.\n * </div>\n\n * <div class=\"alert alert-warning\">\n * **Note:** The compile function cannot handle directives that recursively use themselves in their\n * own templates or compile functions. Compiling these directives results in an infinite loop and a\n * stack overflow errors.\n *\n * This can be avoided by manually using $compile in the postLink function to imperatively compile\n * a directive's template instead of relying on automatic template compilation via `template` or\n * `templateUrl` declaration or manual compilation inside the compile function.\n * </div>\n *\n * <div class=\"alert alert-danger\">\n * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it\n *   e.g. does not know about the right outer scope. Please use the transclude function that is passed\n *   to the link function instead.\n * </div>\n\n * A compile function can have a return value which can be either a function or an object.\n *\n * * returning a (post-link) function - is equivalent to registering the linking function via the\n *   `link` property of the config object when the compile function is empty.\n *\n * * returning an object with function(s) registered via `pre` and `post` properties - allows you to\n *   control when a linking function should be called during the linking phase. See info about\n *   pre-linking and post-linking functions below.\n *\n *\n * #### `link`\n * This property is used only if the `compile` property is not defined.\n *\n * ```js\n *   function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }\n * ```\n *\n * The link function is responsible for registering DOM listeners as well as updating the DOM. It is\n * executed after the template has been cloned. This is where most of the directive logic will be\n * put.\n *\n *   * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the\n *     directive for registering {@link ng.$rootScope.Scope#$watch watches}.\n *\n *   * `iElement` - instance element - The element where the directive is to be used. It is safe to\n *     manipulate the children of the element only in `postLink` function since the children have\n *     already been linked.\n *\n *   * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared\n *     between all directive linking functions.\n *\n *   * `controller` - the directive's required controller instance(s) - Instances are shared\n *     among all directives, which allows the directives to use the controllers as a communication\n *     channel. The exact value depends on the directive's `require` property:\n *       * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one\n *       * `string`: the controller instance\n *       * `array`: array of controller instances\n *\n *     If a required controller cannot be found, and it is optional, the instance is `null`,\n *     otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.\n *\n *     Note that you can also require the directive's own controller - it will be made available like\n *     any other controller.\n *\n *   * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.\n *     This is the same as the `$transclude`\n *     parameter of directive controllers, see there for details.\n *     `function([scope], cloneLinkingFn, futureParentElement)`.\n *\n * #### Pre-linking function\n *\n * Executed before the child elements are linked. Not safe to do DOM transformation since the\n * compiler linking function will fail to locate the correct elements for linking.\n *\n * #### Post-linking function\n *\n * Executed after the child elements are linked.\n *\n * Note that child elements that contain `templateUrl` directives will not have been compiled\n * and linked since they are waiting for their template to load asynchronously and their own\n * compilation and linking has been suspended until that occurs.\n *\n * It is safe to do DOM transformation in the post-linking function on elements that are not waiting\n * for their async templates to be resolved.\n *\n *\n * ### Transclusion\n *\n * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and\n * copying them to another part of the DOM, while maintaining their connection to the original AngularJS\n * scope from where they were taken.\n *\n * Transclusion is used (often with {@link ngTransclude}) to insert the\n * original contents of a directive's element into a specified place in the template of the directive.\n * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded\n * content has access to the properties on the scope from which it was taken, even if the directive\n * has isolated scope.\n * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.\n *\n * This makes it possible for the widget to have private state for its template, while the transcluded\n * content has access to its originating scope.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** When testing an element transclude directive you must not place the directive at the root of the\n * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives\n * Testing Transclusion Directives}.\n * </div>\n *\n * #### Transclusion Functions\n *\n * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion\n * function** to the directive's `link` function and `controller`. This transclusion function is a special\n * **linking function** that will return the compiled contents linked to a new transclusion scope.\n *\n * <div class=\"alert alert-info\">\n * If you are just using {@link ngTransclude} then you don't need to worry about this function, since\n * ngTransclude will deal with it for us.\n * </div>\n *\n * If you want to manually control the insertion and removal of the transcluded content in your directive\n * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery\n * object that contains the compiled DOM, which is linked to the correct transclusion scope.\n *\n * When you call a transclusion function you can pass in a **clone attach function**. This function accepts\n * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded\n * content and the `scope` is the newly created transclusion scope, to which the clone is bound.\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function\n * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.\n * </div>\n *\n * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone\n * attach function**:\n *\n * ```js\n * var transcludedContent, transclusionScope;\n *\n * $transclude(function(clone, scope) {\n *   element.append(clone);\n *   transcludedContent = clone;\n *   transclusionScope = scope;\n * });\n * ```\n *\n * Later, if you want to remove the transcluded content from your DOM then you should also destroy the\n * associated transclusion scope:\n *\n * ```js\n * transcludedContent.remove();\n * transclusionScope.$destroy();\n * ```\n *\n * <div class=\"alert alert-info\">\n * **Best Practice**: if you intend to add and remove transcluded content manually in your directive\n * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),\n * then you are also responsible for calling `$destroy` on the transclusion scope.\n * </div>\n *\n * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}\n * automatically destroy their transluded clones as necessary so you do not need to worry about this if\n * you are simply using {@link ngTransclude} to inject the transclusion into your directive.\n *\n *\n * #### Transclusion Scopes\n *\n * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion\n * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed\n * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it\n * was taken.\n *\n * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look\n * like this:\n *\n * ```html\n * <div ng-app>\n *   <div isolate>\n *     <div transclusion>\n *     </div>\n *   </div>\n * </div>\n * ```\n *\n * The `$parent` scope hierarchy will look like this:\n *\n * ```\n * - $rootScope\n *   - isolate\n *     - transclusion\n * ```\n *\n * but the scopes will inherit prototypically from different scopes to their `$parent`.\n *\n * ```\n * - $rootScope\n *   - transclusion\n * - isolate\n * ```\n *\n *\n * ### Attributes\n *\n * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the\n * `link()` or `compile()` functions. It has a variety of uses.\n *\n * accessing *Normalized attribute names:*\n * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.\n * the attributes object allows for normalized access to\n *   the attributes.\n *\n * * *Directive inter-communication:* All directives share the same instance of the attributes\n *   object which allows the directives to use the attributes object as inter directive\n *   communication.\n *\n * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object\n *   allowing other directives to read the interpolated value.\n *\n * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes\n *   that contain interpolation (e.g. `src=\"{{bar}}\"`). Not only is this very efficient but it's also\n *   the only way to easily get the actual value because during the linking phase the interpolation\n *   hasn't been evaluated yet and so the value is at this time set to `undefined`.\n *\n * ```js\n * function linkingFn(scope, elm, attrs, ctrl) {\n *   // get the attribute value\n *   console.log(attrs.ngModel);\n *\n *   // change the attribute\n *   attrs.$set('ngModel', 'new value');\n *\n *   // observe changes to interpolated attribute\n *   attrs.$observe('ngModel', function(value) {\n *     console.log('ngModel has changed value to ' + value);\n *   });\n * }\n * ```\n *\n * ## Example\n *\n * <div class=\"alert alert-warning\">\n * **Note**: Typically directives are registered with `module.directive`. The example below is\n * to illustrate how `$compile` works.\n * </div>\n *\n <example module=\"compileExample\">\n   <file name=\"index.html\">\n    <script>\n      angular.module('compileExample', [], function($compileProvider) {\n        // configure new 'compile' directive by passing a directive\n        // factory function. The factory function injects the '$compile'\n        $compileProvider.directive('compile', function($compile) {\n          // directive factory creates a link function\n          return function(scope, element, attrs) {\n            scope.$watch(\n              function(scope) {\n                 // watch the 'compile' expression for changes\n                return scope.$eval(attrs.compile);\n              },\n              function(value) {\n                // when the 'compile' expression changes\n                // assign it into the current DOM\n                element.html(value);\n\n                // compile the new DOM and link it to the current\n                // scope.\n                // NOTE: we only compile .childNodes so that\n                // we don't get into infinite loop compiling ourselves\n                $compile(element.contents())(scope);\n              }\n            );\n          };\n        });\n      })\n      .controller('GreeterController', ['$scope', function($scope) {\n        $scope.name = 'Angular';\n        $scope.html = 'Hello {{name}}';\n      }]);\n    </script>\n    <div ng-controller=\"GreeterController\">\n      <input ng-model=\"name\"> <br/>\n      <textarea ng-model=\"html\"></textarea> <br/>\n      <div compile=\"html\"></div>\n    </div>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n     it('should auto compile', function() {\n       var textarea = $('textarea');\n       var output = $('div[compile]');\n       // The initial state reads 'Hello Angular'.\n       expect(output.getText()).toBe('Hello Angular');\n       textarea.clear();\n       textarea.sendKeys('{{name}}!');\n       expect(output.getText()).toBe('Angular!');\n     });\n   </file>\n </example>\n\n *\n *\n * @param {string|DOMElement} element Element or HTML string to compile into a template function.\n * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.\n *\n * <div class=\"alert alert-danger\">\n * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it\n *   e.g. will not use the right outer scope. Please pass the transclude function as a\n *   `parentBoundTranscludeFn` to the link function instead.\n * </div>\n *\n * @param {number} maxPriority only apply directives lower than given priority (Only effects the\n *                 root element(s), not their children)\n * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template\n * (a DOM element/tree) to a scope. Where:\n *\n *  * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.\n *  * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the\n *  `template` and call the `cloneAttachFn` function allowing the caller to attach the\n *  cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is\n *  called as: <br/> `cloneAttachFn(clonedElement, scope)` where:\n *\n *      * `clonedElement` - is a clone of the original `element` passed into the compiler.\n *      * `scope` - is the current scope with which the linking function is working with.\n *\n *  * `options` - An optional object hash with linking options. If `options` is provided, then the following\n *  keys may be used to control linking behavior:\n *\n *      * `parentBoundTranscludeFn` - the transclude function made available to\n *        directives; if given, it will be passed through to the link functions of\n *        directives found in `element` during compilation.\n *      * `transcludeControllers` - an object hash with keys that map controller names\n *        to controller instances; if given, it will make the controllers\n *        available to directives.\n *      * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add\n *        the cloned elements; only needed for transcludes that are allowed to contain non html\n *        elements (e.g. SVG elements). See also the directive.controller property.\n *\n * Calling the linking function returns the element of the template. It is either the original\n * element passed in, or the clone of the element if the `cloneAttachFn` is provided.\n *\n * After linking the view is not updated until after a call to $digest which typically is done by\n * Angular automatically.\n *\n * If you need access to the bound view, there are two ways to do it:\n *\n * - If you are not asking the linking function to clone the template, create the DOM element(s)\n *   before you send them to the compiler and keep this reference around.\n *   ```js\n *     var element = $compile('<p>{{total}}</p>')(scope);\n *   ```\n *\n * - if on the other hand, you need the element to be cloned, the view reference from the original\n *   example would not point to the clone, but rather to the original template that was cloned. In\n *   this case, you can access the clone via the cloneAttachFn:\n *   ```js\n *     var templateElement = angular.element('<p>{{total}}</p>'),\n *         scope = ....;\n *\n *     var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {\n *       //attach the clone to DOM document at the right place\n *     });\n *\n *     //now we have reference to the cloned DOM via `clonedElement`\n *   ```\n *\n *\n * For information on how the compiler works, see the\n * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.\n */\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc provider\n * @name $compileProvider\n *\n * @description\n */\n$CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];\nfunction $CompileProvider($provide, $$sanitizeUriProvider) {\n  var hasDirectives = {},\n      Suffix = 'Directive',\n      COMMENT_DIRECTIVE_REGEXP = /^\\s*directive\\:\\s*([\\w\\-]+)\\s+(.*)$/,\n      CLASS_DIRECTIVE_REGEXP = /(([\\w\\-]+)(?:\\:([^;]+))?;?)/,\n      ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),\n      REQUIRE_PREFIX_REGEXP = /^(?:(\\^\\^?)?(\\?)?(\\^\\^?)?)?/;\n\n  // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes\n  // The assumption is that future DOM event attribute names will begin with\n  // 'on' and be composed of only English letters.\n  var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;\n\n  function parseIsolateBindings(scope, directiveName, isController) {\n    var LOCAL_REGEXP = /^\\s*([@&]|=(\\*?))(\\??)\\s*(\\w*)\\s*$/;\n\n    var bindings = {};\n\n    forEach(scope, function(definition, scopeName) {\n      var match = definition.match(LOCAL_REGEXP);\n\n      if (!match) {\n        throw $compileMinErr('iscp',\n            \"Invalid {3} for directive '{0}'.\" +\n            \" Definition: {... {1}: '{2}' ...}\",\n            directiveName, scopeName, definition,\n            (isController ? \"controller bindings definition\" :\n            \"isolate scope definition\"));\n      }\n\n      bindings[scopeName] = {\n        mode: match[1][0],\n        collection: match[2] === '*',\n        optional: match[3] === '?',\n        attrName: match[4] || scopeName\n      };\n    });\n\n    return bindings;\n  }\n\n  function parseDirectiveBindings(directive, directiveName) {\n    var bindings = {\n      isolateScope: null,\n      bindToController: null\n    };\n    if (isObject(directive.scope)) {\n      if (directive.bindToController === true) {\n        bindings.bindToController = parseIsolateBindings(directive.scope,\n                                                         directiveName, true);\n        bindings.isolateScope = {};\n      } else {\n        bindings.isolateScope = parseIsolateBindings(directive.scope,\n                                                     directiveName, false);\n      }\n    }\n    if (isObject(directive.bindToController)) {\n      bindings.bindToController =\n          parseIsolateBindings(directive.bindToController, directiveName, true);\n    }\n    if (isObject(bindings.bindToController)) {\n      var controller = directive.controller;\n      var controllerAs = directive.controllerAs;\n      if (!controller) {\n        // There is no controller, there may or may not be a controllerAs property\n        throw $compileMinErr('noctrl',\n              \"Cannot bind to controller without directive '{0}'s controller.\",\n              directiveName);\n      } else if (!identifierForController(controller, controllerAs)) {\n        // There is a controller, but no identifier or controllerAs property\n        throw $compileMinErr('noident',\n              \"Cannot bind to controller without identifier for directive '{0}'.\",\n              directiveName);\n      }\n    }\n    return bindings;\n  }\n\n  function assertValidDirectiveName(name) {\n    var letter = name.charAt(0);\n    if (!letter || letter !== lowercase(letter)) {\n      throw $compileMinErr('baddir', \"Directive name '{0}' is invalid. The first character must be a lowercase letter\", name);\n    }\n    if (name !== name.trim()) {\n      throw $compileMinErr('baddir',\n            \"Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces\",\n            name);\n    }\n  }\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#directive\n   * @kind function\n   *\n   * @description\n   * Register a new directive with the compiler.\n   *\n   * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which\n   *    will match as <code>ng-bind</code>), or an object map of directives where the keys are the\n   *    names and the values are the factories.\n   * @param {Function|Array} directiveFactory An injectable directive factory function. See\n   *    {@link guide/directive} for more info.\n   * @returns {ng.$compileProvider} Self for chaining.\n   */\n   this.directive = function registerDirective(name, directiveFactory) {\n    assertNotHasOwnProperty(name, 'directive');\n    if (isString(name)) {\n      assertValidDirectiveName(name);\n      assertArg(directiveFactory, 'directiveFactory');\n      if (!hasDirectives.hasOwnProperty(name)) {\n        hasDirectives[name] = [];\n        $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',\n          function($injector, $exceptionHandler) {\n            var directives = [];\n            forEach(hasDirectives[name], function(directiveFactory, index) {\n              try {\n                var directive = $injector.invoke(directiveFactory);\n                if (isFunction(directive)) {\n                  directive = { compile: valueFn(directive) };\n                } else if (!directive.compile && directive.link) {\n                  directive.compile = valueFn(directive.link);\n                }\n                directive.priority = directive.priority || 0;\n                directive.index = index;\n                directive.name = directive.name || name;\n                directive.require = directive.require || (directive.controller && directive.name);\n                directive.restrict = directive.restrict || 'EA';\n                var bindings = directive.$$bindings =\n                    parseDirectiveBindings(directive, directive.name);\n                if (isObject(bindings.isolateScope)) {\n                  directive.$$isolateBindings = bindings.isolateScope;\n                }\n                directive.$$moduleName = directiveFactory.$$moduleName;\n                directives.push(directive);\n              } catch (e) {\n                $exceptionHandler(e);\n              }\n            });\n            return directives;\n          }]);\n      }\n      hasDirectives[name].push(directiveFactory);\n    } else {\n      forEach(name, reverseParams(registerDirective));\n    }\n    return this;\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#aHrefSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at preventing XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.aHrefSanitizationWhitelist();\n    }\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name $compileProvider#imgSrcSanitizationWhitelist\n   * @kind function\n   *\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);\n      return this;\n    } else {\n      return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name  $compileProvider#debugInfoEnabled\n   *\n   * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the\n   * current debugInfoEnabled state\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   *\n   * @kind function\n   *\n   * @description\n   * Call this method to enable/disable various debug runtime information in the compiler such as adding\n   * binding information and a reference to the current scope on to DOM elements.\n   * If enabled, the compiler will add the following to DOM elements that have been bound to the scope\n   * * `ng-binding` CSS class\n   * * `$binding` data property containing an array of the binding expressions\n   *\n   * You may want to disable this in production for a significant performance boost. See\n   * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.\n   *\n   * The default value is true.\n   */\n  var debugInfoEnabled = true;\n  this.debugInfoEnabled = function(enabled) {\n    if (isDefined(enabled)) {\n      debugInfoEnabled = enabled;\n      return this;\n    }\n    return debugInfoEnabled;\n  };\n\n  this.$get = [\n            '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',\n            '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',\n    function($injector,   $interpolate,   $exceptionHandler,   $templateRequest,   $parse,\n             $controller,   $rootScope,   $document,   $sce,   $animate,   $$sanitizeUri) {\n\n    var Attributes = function(element, attributesToCopy) {\n      if (attributesToCopy) {\n        var keys = Object.keys(attributesToCopy);\n        var i, l, key;\n\n        for (i = 0, l = keys.length; i < l; i++) {\n          key = keys[i];\n          this[key] = attributesToCopy[key];\n        }\n      } else {\n        this.$attr = {};\n      }\n\n      this.$$element = element;\n    };\n\n    Attributes.prototype = {\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$normalize\n       * @kind function\n       *\n       * @description\n       * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or\n       * `data-`) to its normalized, camelCase form.\n       *\n       * Also there is special case for Moz prefix starting with upper case letter.\n       *\n       * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}\n       *\n       * @param {string} name Name to normalize\n       */\n      $normalize: directiveNormalize,\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$addClass\n       * @kind function\n       *\n       * @description\n       * Adds the CSS class value specified by the classVal parameter to the element. If animations\n       * are enabled then an animation will be triggered for the class addition.\n       *\n       * @param {string} classVal The className value that will be added to the element\n       */\n      $addClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.addClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$removeClass\n       * @kind function\n       *\n       * @description\n       * Removes the CSS class value specified by the classVal parameter from the element. If\n       * animations are enabled then an animation will be triggered for the class removal.\n       *\n       * @param {string} classVal The className value that will be removed from the element\n       */\n      $removeClass: function(classVal) {\n        if (classVal && classVal.length > 0) {\n          $animate.removeClass(this.$$element, classVal);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$updateClass\n       * @kind function\n       *\n       * @description\n       * Adds and removes the appropriate CSS class values to the element based on the difference\n       * between the new and old CSS class values (specified as newClasses and oldClasses).\n       *\n       * @param {string} newClasses The current CSS className value\n       * @param {string} oldClasses The former CSS className value\n       */\n      $updateClass: function(newClasses, oldClasses) {\n        var toAdd = tokenDifference(newClasses, oldClasses);\n        if (toAdd && toAdd.length) {\n          $animate.addClass(this.$$element, toAdd);\n        }\n\n        var toRemove = tokenDifference(oldClasses, newClasses);\n        if (toRemove && toRemove.length) {\n          $animate.removeClass(this.$$element, toRemove);\n        }\n      },\n\n      /**\n       * Set a normalized attribute on the element in a way such that all directives\n       * can share the attribute. This function properly handles boolean attributes.\n       * @param {string} key Normalized key. (ie ngAttribute)\n       * @param {string|boolean} value The value to set. If `null` attribute will be deleted.\n       * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.\n       *     Defaults to true.\n       * @param {string=} attrName Optional none normalized name. Defaults to key.\n       */\n      $set: function(key, value, writeAttr, attrName) {\n        // TODO: decide whether or not to throw an error if \"class\"\n        //is set through this function since it may cause $updateClass to\n        //become unstable.\n\n        var node = this.$$element[0],\n            booleanKey = getBooleanAttrName(node, key),\n            aliasedKey = getAliasedAttrName(node, key),\n            observer = key,\n            nodeName;\n\n        if (booleanKey) {\n          this.$$element.prop(key, value);\n          attrName = booleanKey;\n        } else if (aliasedKey) {\n          this[aliasedKey] = value;\n          observer = aliasedKey;\n        }\n\n        this[key] = value;\n\n        // translate normalized key to actual key\n        if (attrName) {\n          this.$attr[key] = attrName;\n        } else {\n          attrName = this.$attr[key];\n          if (!attrName) {\n            this.$attr[key] = attrName = snake_case(key, '-');\n          }\n        }\n\n        nodeName = nodeName_(this.$$element);\n\n        if ((nodeName === 'a' && key === 'href') ||\n            (nodeName === 'img' && key === 'src')) {\n          // sanitize a[href] and img[src] values\n          this[key] = value = $$sanitizeUri(value, key === 'src');\n        } else if (nodeName === 'img' && key === 'srcset') {\n          // sanitize img[srcset] values\n          var result = \"\";\n\n          // first check if there are spaces because it's not the same pattern\n          var trimmedSrcset = trim(value);\n          //                (   999x   ,|   999w   ,|   ,|,   )\n          var srcPattern = /(\\s+\\d+x\\s*,|\\s+\\d+w\\s*,|\\s+,|,\\s+)/;\n          var pattern = /\\s/.test(trimmedSrcset) ? srcPattern : /(,)/;\n\n          // split srcset into tuple of uri and descriptor except for the last item\n          var rawUris = trimmedSrcset.split(pattern);\n\n          // for each tuples\n          var nbrUrisWith2parts = Math.floor(rawUris.length / 2);\n          for (var i = 0; i < nbrUrisWith2parts; i++) {\n            var innerIdx = i * 2;\n            // sanitize the uri\n            result += $$sanitizeUri(trim(rawUris[innerIdx]), true);\n            // add the descriptor\n            result += (\" \" + trim(rawUris[innerIdx + 1]));\n          }\n\n          // split the last item into uri and descriptor\n          var lastTuple = trim(rawUris[i * 2]).split(/\\s/);\n\n          // sanitize the last uri\n          result += $$sanitizeUri(trim(lastTuple[0]), true);\n\n          // and add the last descriptor if any\n          if (lastTuple.length === 2) {\n            result += (\" \" + trim(lastTuple[1]));\n          }\n          this[key] = value = result;\n        }\n\n        if (writeAttr !== false) {\n          if (value === null || value === undefined) {\n            this.$$element.removeAttr(attrName);\n          } else {\n            this.$$element.attr(attrName, value);\n          }\n        }\n\n        // fire observers\n        var $$observers = this.$$observers;\n        $$observers && forEach($$observers[observer], function(fn) {\n          try {\n            fn(value);\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        });\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $compile.directive.Attributes#$observe\n       * @kind function\n       *\n       * @description\n       * Observes an interpolated attribute.\n       *\n       * The observer function will be invoked once during the next `$digest` following\n       * compilation. The observer is then invoked whenever the interpolated value\n       * changes.\n       *\n       * @param {string} key Normalized key. (ie ngAttribute) .\n       * @param {function(interpolatedValue)} fn Function that will be called whenever\n                the interpolated value of the attribute changes.\n       *        See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.\n       * @returns {function()} Returns a deregistration function for this observer.\n       */\n      $observe: function(key, fn) {\n        var attrs = this,\n            $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),\n            listeners = ($$observers[key] || ($$observers[key] = []));\n\n        listeners.push(fn);\n        $rootScope.$evalAsync(function() {\n          if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {\n            // no one registered attribute interpolation function, so lets call it manually\n            fn(attrs[key]);\n          }\n        });\n\n        return function() {\n          arrayRemove(listeners, fn);\n        };\n      }\n    };\n\n\n    function safeAddClass($element, className) {\n      try {\n        $element.addClass(className);\n      } catch (e) {\n        // ignore, since it means that we are trying to set class on\n        // SVG element, where class name is read-only.\n      }\n    }\n\n\n    var startSymbol = $interpolate.startSymbol(),\n        endSymbol = $interpolate.endSymbol(),\n        denormalizeTemplate = (startSymbol == '{{' || endSymbol  == '}}')\n            ? identity\n            : function denormalizeTemplate(template) {\n              return template.replace(/\\{\\{/g, startSymbol).replace(/}}/g, endSymbol);\n        },\n        NG_ATTR_BINDING = /^ngAttr[A-Z]/;\n\n    compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {\n      var bindings = $element.data('$binding') || [];\n\n      if (isArray(binding)) {\n        bindings = bindings.concat(binding);\n      } else {\n        bindings.push(binding);\n      }\n\n      $element.data('$binding', bindings);\n    } : noop;\n\n    compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {\n      safeAddClass($element, 'ng-binding');\n    } : noop;\n\n    compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {\n      var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';\n      $element.data(dataName, scope);\n    } : noop;\n\n    compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {\n      safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');\n    } : noop;\n\n    return compile;\n\n    //================================\n\n    function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,\n                        previousCompileContext) {\n      if (!($compileNodes instanceof jqLite)) {\n        // jquery always rewraps, whereas we need to preserve the original selector so that we can\n        // modify it.\n        $compileNodes = jqLite($compileNodes);\n      }\n      // We can not compile top level text elements since text nodes can be merged and we will\n      // not be able to attach scope data to them, so we will wrap them in <span>\n      forEach($compileNodes, function(node, index) {\n        if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\\S+/) /* non-empty */ ) {\n          $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];\n        }\n      });\n      var compositeLinkFn =\n              compileNodes($compileNodes, transcludeFn, $compileNodes,\n                           maxPriority, ignoreDirective, previousCompileContext);\n      compile.$$addScopeClass($compileNodes);\n      var namespace = null;\n      return function publicLinkFn(scope, cloneConnectFn, options) {\n        assertArg(scope, 'scope');\n\n        options = options || {};\n        var parentBoundTranscludeFn = options.parentBoundTranscludeFn,\n          transcludeControllers = options.transcludeControllers,\n          futureParentElement = options.futureParentElement;\n\n        // When `parentBoundTranscludeFn` is passed, it is a\n        // `controllersBoundTransclude` function (it was previously passed\n        // as `transclude` to directive.link) so we must unwrap it to get\n        // its `boundTranscludeFn`\n        if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {\n          parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;\n        }\n\n        if (!namespace) {\n          namespace = detectNamespaceForChildElements(futureParentElement);\n        }\n        var $linkNode;\n        if (namespace !== 'html') {\n          // When using a directive with replace:true and templateUrl the $compileNodes\n          // (or a child element inside of them)\n          // might change, so we need to recreate the namespace adapted compileNodes\n          // for call to the link function.\n          // Note: This will already clone the nodes...\n          $linkNode = jqLite(\n            wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())\n          );\n        } else if (cloneConnectFn) {\n          // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart\n          // and sometimes changes the structure of the DOM.\n          $linkNode = JQLitePrototype.clone.call($compileNodes);\n        } else {\n          $linkNode = $compileNodes;\n        }\n\n        if (transcludeControllers) {\n          for (var controllerName in transcludeControllers) {\n            $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);\n          }\n        }\n\n        compile.$$addScopeInfo($linkNode, scope);\n\n        if (cloneConnectFn) cloneConnectFn($linkNode, scope);\n        if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);\n        return $linkNode;\n      };\n    }\n\n    function detectNamespaceForChildElements(parentElement) {\n      // TODO: Make this detect MathML as well...\n      var node = parentElement && parentElement[0];\n      if (!node) {\n        return 'html';\n      } else {\n        return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';\n      }\n    }\n\n    /**\n     * Compile function matches each node in nodeList against the directives. Once all directives\n     * for a particular node are collected their compile functions are executed. The compile\n     * functions return values - the linking functions - are combined into a composite linking\n     * function, which is the a linking function for the node.\n     *\n     * @param {NodeList} nodeList an array of nodes or NodeList to compile\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *        scope argument is auto-generated to the new child of the transcluded parent scope.\n     * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then\n     *        the rootElement must be set the jqLite collection of the compile root. This is\n     *        needed so that the jqLite collection items can be replaced with widgets.\n     * @param {number=} maxPriority Max directive priority.\n     * @returns {Function} A composite linking function of all of the matched directives or null.\n     */\n    function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,\n                            previousCompileContext) {\n      var linkFns = [],\n          attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;\n\n      for (var i = 0; i < nodeList.length; i++) {\n        attrs = new Attributes();\n\n        // we must always refer to nodeList[i] since the nodes can be replaced underneath us.\n        directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,\n                                        ignoreDirective);\n\n        nodeLinkFn = (directives.length)\n            ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,\n                                      null, [], [], previousCompileContext)\n            : null;\n\n        if (nodeLinkFn && nodeLinkFn.scope) {\n          compile.$$addScopeClass(attrs.$$element);\n        }\n\n        childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||\n                      !(childNodes = nodeList[i].childNodes) ||\n                      !childNodes.length)\n            ? null\n            : compileNodes(childNodes,\n                 nodeLinkFn ? (\n                  (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)\n                     && nodeLinkFn.transclude) : transcludeFn);\n\n        if (nodeLinkFn || childLinkFn) {\n          linkFns.push(i, nodeLinkFn, childLinkFn);\n          linkFnFound = true;\n          nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;\n        }\n\n        //use the previous context only for the first element in the virtual group\n        previousCompileContext = null;\n      }\n\n      // return a linking function if we have found anything, null otherwise\n      return linkFnFound ? compositeLinkFn : null;\n\n      function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {\n        var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;\n        var stableNodeList;\n\n\n        if (nodeLinkFnFound) {\n          // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our\n          // offsets don't get screwed up\n          var nodeListLength = nodeList.length;\n          stableNodeList = new Array(nodeListLength);\n\n          // create a sparse array by only copying the elements which have a linkFn\n          for (i = 0; i < linkFns.length; i+=3) {\n            idx = linkFns[i];\n            stableNodeList[idx] = nodeList[idx];\n          }\n        } else {\n          stableNodeList = nodeList;\n        }\n\n        for (i = 0, ii = linkFns.length; i < ii;) {\n          node = stableNodeList[linkFns[i++]];\n          nodeLinkFn = linkFns[i++];\n          childLinkFn = linkFns[i++];\n\n          if (nodeLinkFn) {\n            if (nodeLinkFn.scope) {\n              childScope = scope.$new();\n              compile.$$addScopeInfo(jqLite(node), childScope);\n              var destroyBindings = nodeLinkFn.$$destroyBindings;\n              if (destroyBindings) {\n                nodeLinkFn.$$destroyBindings = null;\n                childScope.$on('$destroyed', destroyBindings);\n              }\n            } else {\n              childScope = scope;\n            }\n\n            if (nodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(\n                  scope, nodeLinkFn.transclude, parentBoundTranscludeFn);\n\n            } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {\n              childBoundTranscludeFn = parentBoundTranscludeFn;\n\n            } else if (!parentBoundTranscludeFn && transcludeFn) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);\n\n            } else {\n              childBoundTranscludeFn = null;\n            }\n\n            nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn,\n                       nodeLinkFn);\n\n          } else if (childLinkFn) {\n            childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);\n          }\n        }\n      }\n    }\n\n    function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {\n\n      var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {\n\n        if (!transcludedScope) {\n          transcludedScope = scope.$new(false, containingScope);\n          transcludedScope.$$transcluded = true;\n        }\n\n        return transcludeFn(transcludedScope, cloneFn, {\n          parentBoundTranscludeFn: previousBoundTranscludeFn,\n          transcludeControllers: controllers,\n          futureParentElement: futureParentElement\n        });\n      };\n\n      return boundTranscludeFn;\n    }\n\n    /**\n     * Looks for directives on the given node and adds them to the directive collection which is\n     * sorted.\n     *\n     * @param node Node to search.\n     * @param directives An array to which the directives are added to. This array is sorted before\n     *        the function returns.\n     * @param attrs The shared attrs object which is used to populate the normalized attributes.\n     * @param {number=} maxPriority Max directive priority.\n     */\n    function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {\n      var nodeType = node.nodeType,\n          attrsMap = attrs.$attr,\n          match,\n          className;\n\n      switch (nodeType) {\n        case NODE_TYPE_ELEMENT: /* Element */\n          // use the node name: <directive>\n          addDirective(directives,\n              directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);\n\n          // iterate over the attributes\n          for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,\n                   j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {\n            var attrStartName = false;\n            var attrEndName = false;\n\n            attr = nAttrs[j];\n            name = attr.name;\n            value = trim(attr.value);\n\n            // support ngAttr attribute binding\n            ngAttrName = directiveNormalize(name);\n            if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {\n              name = name.replace(PREFIX_REGEXP, '')\n                .substr(8).replace(/_(.)/g, function(match, letter) {\n                  return letter.toUpperCase();\n                });\n            }\n\n            var directiveNName = ngAttrName.replace(/(Start|End)$/, '');\n            if (directiveIsMultiElement(directiveNName)) {\n              if (ngAttrName === directiveNName + 'Start') {\n                attrStartName = name;\n                attrEndName = name.substr(0, name.length - 5) + 'end';\n                name = name.substr(0, name.length - 6);\n              }\n            }\n\n            nName = directiveNormalize(name.toLowerCase());\n            attrsMap[nName] = name;\n            if (isNgAttr || !attrs.hasOwnProperty(nName)) {\n                attrs[nName] = value;\n                if (getBooleanAttrName(node, nName)) {\n                  attrs[nName] = true; // presence means true\n                }\n            }\n            addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);\n            addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,\n                          attrEndName);\n          }\n\n          // use class as directive\n          className = node.className;\n          if (isObject(className)) {\n              // Maybe SVGAnimatedString\n              className = className.animVal;\n          }\n          if (isString(className) && className !== '') {\n            while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {\n              nName = directiveNormalize(match[2]);\n              if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[3]);\n              }\n              className = className.substr(match.index + match[0].length);\n            }\n          }\n          break;\n        case NODE_TYPE_TEXT: /* Text Node */\n          if (msie === 11) {\n            // Workaround for #11781\n            while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {\n              node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;\n              node.parentNode.removeChild(node.nextSibling);\n            }\n          }\n          addTextInterpolateDirective(directives, node.nodeValue);\n          break;\n        case NODE_TYPE_COMMENT: /* Comment */\n          try {\n            match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);\n            if (match) {\n              nName = directiveNormalize(match[1]);\n              if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {\n                attrs[nName] = trim(match[2]);\n              }\n            }\n          } catch (e) {\n            // turns out that under some circumstances IE9 throws errors when one attempts to read\n            // comment's node value.\n            // Just ignore it and continue. (Can't seem to reproduce in test case.)\n          }\n          break;\n      }\n\n      directives.sort(byPriority);\n      return directives;\n    }\n\n    /**\n     * Given a node with an directive-start it collects all of the siblings until it finds\n     * directive-end.\n     * @param node\n     * @param attrStart\n     * @param attrEnd\n     * @returns {*}\n     */\n    function groupScan(node, attrStart, attrEnd) {\n      var nodes = [];\n      var depth = 0;\n      if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {\n        do {\n          if (!node) {\n            throw $compileMinErr('uterdir',\n                      \"Unterminated attribute, found '{0}' but no matching '{1}' found.\",\n                      attrStart, attrEnd);\n          }\n          if (node.nodeType == NODE_TYPE_ELEMENT) {\n            if (node.hasAttribute(attrStart)) depth++;\n            if (node.hasAttribute(attrEnd)) depth--;\n          }\n          nodes.push(node);\n          node = node.nextSibling;\n        } while (depth > 0);\n      } else {\n        nodes.push(node);\n      }\n\n      return jqLite(nodes);\n    }\n\n    /**\n     * Wrapper for linking function which converts normal linking function into a grouped\n     * linking function.\n     * @param linkFn\n     * @param attrStart\n     * @param attrEnd\n     * @returns {Function}\n     */\n    function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {\n      return function(scope, element, attrs, controllers, transcludeFn) {\n        element = groupScan(element[0], attrStart, attrEnd);\n        return linkFn(scope, element, attrs, controllers, transcludeFn);\n      };\n    }\n\n    /**\n     * Once the directives have been collected, their compile functions are executed. This method\n     * is responsible for inlining directive templates as well as terminating the application\n     * of the directives if the terminal directive has been reached.\n     *\n     * @param {Array} directives Array of collected directives to execute their compile function.\n     *        this needs to be pre-sorted by priority order.\n     * @param {Node} compileNode The raw DOM node to apply the compile functions to\n     * @param {Object} templateAttrs The shared attribute function\n     * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the\n     *                                                  scope argument is auto-generated to the new\n     *                                                  child of the transcluded parent scope.\n     * @param {JQLite} jqCollection If we are working on the root of the compile tree then this\n     *                              argument has the root jqLite array so that we can replace nodes\n     *                              on it.\n     * @param {Object=} originalReplaceDirective An optional directive that will be ignored when\n     *                                           compiling the transclusion.\n     * @param {Array.<Function>} preLinkFns\n     * @param {Array.<Function>} postLinkFns\n     * @param {Object} previousCompileContext Context used for previous compilation of the current\n     *                                        node\n     * @returns {Function} linkFn\n     */\n    function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,\n                                   jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,\n                                   previousCompileContext) {\n      previousCompileContext = previousCompileContext || {};\n\n      var terminalPriority = -Number.MAX_VALUE,\n          newScopeDirective = previousCompileContext.newScopeDirective,\n          controllerDirectives = previousCompileContext.controllerDirectives,\n          newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,\n          templateDirective = previousCompileContext.templateDirective,\n          nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,\n          hasTranscludeDirective = false,\n          hasTemplate = false,\n          hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,\n          $compileNode = templateAttrs.$$element = jqLite(compileNode),\n          directive,\n          directiveName,\n          $template,\n          replaceDirective = originalReplaceDirective,\n          childTranscludeFn = transcludeFn,\n          linkFn,\n          directiveValue;\n\n      // executes all directives on the current element\n      for (var i = 0, ii = directives.length; i < ii; i++) {\n        directive = directives[i];\n        var attrStart = directive.$$start;\n        var attrEnd = directive.$$end;\n\n        // collect multiblock sections\n        if (attrStart) {\n          $compileNode = groupScan(compileNode, attrStart, attrEnd);\n        }\n        $template = undefined;\n\n        if (terminalPriority > directive.priority) {\n          break; // prevent further processing of directives\n        }\n\n        if (directiveValue = directive.scope) {\n\n          // skip the check for directives with async templates, we'll check the derived sync\n          // directive when the template arrives\n          if (!directive.templateUrl) {\n            if (isObject(directiveValue)) {\n              // This directive is trying to add an isolated scope.\n              // Check that there is no scope of any kind already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,\n                                directive, $compileNode);\n              newIsolateScopeDirective = directive;\n            } else {\n              // This directive is trying to add a child scope.\n              // Check that there is no isolated scope already\n              assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,\n                                $compileNode);\n            }\n          }\n\n          newScopeDirective = newScopeDirective || directive;\n        }\n\n        directiveName = directive.name;\n\n        if (!directive.templateUrl && directive.controller) {\n          directiveValue = directive.controller;\n          controllerDirectives = controllerDirectives || createMap();\n          assertNoDuplicate(\"'\" + directiveName + \"' controller\",\n              controllerDirectives[directiveName], directive, $compileNode);\n          controllerDirectives[directiveName] = directive;\n        }\n\n        if (directiveValue = directive.transclude) {\n          hasTranscludeDirective = true;\n\n          // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.\n          // This option should only be used by directives that know how to safely handle element transclusion,\n          // where the transcluded nodes are added or replaced after linking.\n          if (!directive.$$tlb) {\n            assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);\n            nonTlbTranscludeDirective = directive;\n          }\n\n          if (directiveValue == 'element') {\n            hasElementTranscludeDirective = true;\n            terminalPriority = directive.priority;\n            $template = $compileNode;\n            $compileNode = templateAttrs.$$element =\n                jqLite(document.createComment(' ' + directiveName + ': ' +\n                                              templateAttrs[directiveName] + ' '));\n            compileNode = $compileNode[0];\n            replaceWith(jqCollection, sliceArgs($template), compileNode);\n\n            childTranscludeFn = compile($template, transcludeFn, terminalPriority,\n                                        replaceDirective && replaceDirective.name, {\n                                          // Don't pass in:\n                                          // - controllerDirectives - otherwise we'll create duplicates controllers\n                                          // - newIsolateScopeDirective or templateDirective - combining templates with\n                                          //   element transclusion doesn't make sense.\n                                          //\n                                          // We need only nonTlbTranscludeDirective so that we prevent putting transclusion\n                                          // on the same element more than once.\n                                          nonTlbTranscludeDirective: nonTlbTranscludeDirective\n                                        });\n          } else {\n            $template = jqLite(jqLiteClone(compileNode)).contents();\n            $compileNode.empty(); // clear contents\n            childTranscludeFn = compile($template, transcludeFn);\n          }\n        }\n\n        if (directive.template) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          directiveValue = (isFunction(directive.template))\n              ? directive.template($compileNode, templateAttrs)\n              : directive.template;\n\n          directiveValue = denormalizeTemplate(directiveValue);\n\n          if (directive.replace) {\n            replaceDirective = directive;\n            if (jqLiteIsTextNode(directiveValue)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  directiveName, '');\n            }\n\n            replaceWith(jqCollection, $compileNode, compileNode);\n\n            var newTemplateAttrs = {$attr: {}};\n\n            // combine directives from the original node and from the template:\n            // - take the array of directives for this element\n            // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)\n            // - collect directives from the template and sort them by priority\n            // - combine directives as: processed + template + unprocessed\n            var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);\n            var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));\n\n            if (newIsolateScopeDirective) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = directives.concat(templateDirectives).concat(unprocessedDirectives);\n            mergeTemplateAttributes(templateAttrs, newTemplateAttrs);\n\n            ii = directives.length;\n          } else {\n            $compileNode.html(directiveValue);\n          }\n        }\n\n        if (directive.templateUrl) {\n          hasTemplate = true;\n          assertNoDuplicate('template', templateDirective, directive, $compileNode);\n          templateDirective = directive;\n\n          if (directive.replace) {\n            replaceDirective = directive;\n          }\n\n          nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,\n              templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {\n                controllerDirectives: controllerDirectives,\n                newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,\n                newIsolateScopeDirective: newIsolateScopeDirective,\n                templateDirective: templateDirective,\n                nonTlbTranscludeDirective: nonTlbTranscludeDirective\n              });\n          ii = directives.length;\n        } else if (directive.compile) {\n          try {\n            linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);\n            if (isFunction(linkFn)) {\n              addLinkFns(null, linkFn, attrStart, attrEnd);\n            } else if (linkFn) {\n              addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);\n            }\n          } catch (e) {\n            $exceptionHandler(e, startingTag($compileNode));\n          }\n        }\n\n        if (directive.terminal) {\n          nodeLinkFn.terminal = true;\n          terminalPriority = Math.max(terminalPriority, directive.priority);\n        }\n\n      }\n\n      nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;\n      nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;\n      nodeLinkFn.templateOnThisElement = hasTemplate;\n      nodeLinkFn.transclude = childTranscludeFn;\n\n      previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;\n\n      // might be normal or delayed nodeLinkFn depending on if templateUrl is present\n      return nodeLinkFn;\n\n      ////////////////////\n\n      function addLinkFns(pre, post, attrStart, attrEnd) {\n        if (pre) {\n          if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);\n          pre.require = directive.require;\n          pre.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            pre = cloneAndAnnotateFn(pre, {isolateScope: true});\n          }\n          preLinkFns.push(pre);\n        }\n        if (post) {\n          if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);\n          post.require = directive.require;\n          post.directiveName = directiveName;\n          if (newIsolateScopeDirective === directive || directive.$$isolateScope) {\n            post = cloneAndAnnotateFn(post, {isolateScope: true});\n          }\n          postLinkFns.push(post);\n        }\n      }\n\n\n      function getControllers(directiveName, require, $element, elementControllers) {\n        var value;\n\n        if (isString(require)) {\n          var match = require.match(REQUIRE_PREFIX_REGEXP);\n          var name = require.substring(match[0].length);\n          var inheritType = match[1] || match[3];\n          var optional = match[2] === '?';\n\n          //If only parents then start at the parent element\n          if (inheritType === '^^') {\n            $element = $element.parent();\n          //Otherwise attempt getting the controller from elementControllers in case\n          //the element is transcluded (and has no data) and to avoid .data if possible\n          } else {\n            value = elementControllers && elementControllers[name];\n            value = value && value.instance;\n          }\n\n          if (!value) {\n            var dataName = '$' + name + 'Controller';\n            value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);\n          }\n\n          if (!value && !optional) {\n            throw $compileMinErr('ctreq',\n                \"Controller '{0}', required by directive '{1}', can't be found!\",\n                name, directiveName);\n          }\n        } else if (isArray(require)) {\n          value = [];\n          for (var i = 0, ii = require.length; i < ii; i++) {\n            value[i] = getControllers(directiveName, require[i], $element, elementControllers);\n          }\n        }\n\n        return value || null;\n      }\n\n      function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {\n        var elementControllers = createMap();\n        for (var controllerKey in controllerDirectives) {\n          var directive = controllerDirectives[controllerKey];\n          var locals = {\n            $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,\n            $element: $element,\n            $attrs: attrs,\n            $transclude: transcludeFn\n          };\n\n          var controller = directive.controller;\n          if (controller == '@') {\n            controller = attrs[directive.name];\n          }\n\n          var controllerInstance = $controller(controller, locals, true, directive.controllerAs);\n\n          // For directives with element transclusion the element is a comment,\n          // but jQuery .data doesn't support attaching data to comment nodes as it's hard to\n          // clean up (http://bugs.jquery.com/ticket/8335).\n          // Instead, we save the controllers for the element in a local hash and attach to .data\n          // later, once we have the actual element.\n          elementControllers[directive.name] = controllerInstance;\n          if (!hasElementTranscludeDirective) {\n            $element.data('$' + directive.name + 'Controller', controllerInstance.instance);\n          }\n        }\n        return elementControllers;\n      }\n\n      function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn,\n                          thisLinkFn) {\n        var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,\n            attrs;\n\n        if (compileNode === linkNode) {\n          attrs = templateAttrs;\n          $element = templateAttrs.$$element;\n        } else {\n          $element = jqLite(linkNode);\n          attrs = new Attributes($element, templateAttrs);\n        }\n\n        if (newIsolateScopeDirective) {\n          isolateScope = scope.$new(true);\n        }\n\n        if (boundTranscludeFn) {\n          // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`\n          // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`\n          transcludeFn = controllersBoundTransclude;\n          transcludeFn.$$boundTransclude = boundTranscludeFn;\n        }\n\n        if (controllerDirectives) {\n          elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);\n        }\n\n        if (newIsolateScopeDirective) {\n          // Initialize isolate scope bindings for new isolate scope directive.\n          compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||\n              templateDirective === newIsolateScopeDirective.$$originalDirective)));\n          compile.$$addScopeClass($element, true);\n          isolateScope.$$isolateBindings =\n              newIsolateScopeDirective.$$isolateBindings;\n          initializeDirectiveBindings(scope, attrs, isolateScope,\n                                      isolateScope.$$isolateBindings,\n                                      newIsolateScopeDirective, isolateScope);\n        }\n        if (elementControllers) {\n          // Initialize bindToController bindings for new/isolate scopes\n          var scopeDirective = newIsolateScopeDirective || newScopeDirective;\n          var bindings;\n          var controllerForBindings;\n          if (scopeDirective && elementControllers[scopeDirective.name]) {\n            bindings = scopeDirective.$$bindings.bindToController;\n            controller = elementControllers[scopeDirective.name];\n\n            if (controller && controller.identifier && bindings) {\n              controllerForBindings = controller;\n              thisLinkFn.$$destroyBindings =\n                  initializeDirectiveBindings(scope, attrs, controller.instance,\n                                              bindings, scopeDirective);\n            }\n          }\n          for (i in elementControllers) {\n            controller = elementControllers[i];\n            var controllerResult = controller();\n\n            if (controllerResult !== controller.instance) {\n              // If the controller constructor has a return value, overwrite the instance\n              // from setupControllers and update the element data\n              controller.instance = controllerResult;\n              $element.data('$' + i + 'Controller', controllerResult);\n              if (controller === controllerForBindings) {\n                // Remove and re-install bindToController bindings\n                thisLinkFn.$$destroyBindings();\n                thisLinkFn.$$destroyBindings =\n                  initializeDirectiveBindings(scope, attrs, controllerResult, bindings, scopeDirective);\n              }\n            }\n          }\n        }\n\n        // PRELINKING\n        for (i = 0, ii = preLinkFns.length; i < ii; i++) {\n          linkFn = preLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // RECURSION\n        // We only pass the isolate scope, if the isolate directive has a template,\n        // otherwise the child elements do not belong to the isolate directive.\n        var scopeToChild = scope;\n        if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {\n          scopeToChild = isolateScope;\n        }\n        childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);\n\n        // POSTLINKING\n        for (i = postLinkFns.length - 1; i >= 0; i--) {\n          linkFn = postLinkFns[i];\n          invokeLinkFn(linkFn,\n              linkFn.isolateScope ? isolateScope : scope,\n              $element,\n              attrs,\n              linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),\n              transcludeFn\n          );\n        }\n\n        // This is the function that is injected as `$transclude`.\n        // Note: all arguments are optional!\n        function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {\n          var transcludeControllers;\n\n          // No scope passed in:\n          if (!isScope(scope)) {\n            futureParentElement = cloneAttachFn;\n            cloneAttachFn = scope;\n            scope = undefined;\n          }\n\n          if (hasElementTranscludeDirective) {\n            transcludeControllers = elementControllers;\n          }\n          if (!futureParentElement) {\n            futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;\n          }\n          return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);\n        }\n      }\n    }\n\n    function markDirectivesAsIsolate(directives) {\n      // mark all directives as needing isolate scope.\n      for (var j = 0, jj = directives.length; j < jj; j++) {\n        directives[j] = inherit(directives[j], {$$isolateScope: true});\n      }\n    }\n\n    /**\n     * looks up the directive and decorates it with exception handling and proper parameters. We\n     * call this the boundDirective.\n     *\n     * @param {string} name name of the directive to look up.\n     * @param {string} location The directive must be found in specific format.\n     *   String containing any of theses characters:\n     *\n     *   * `E`: element name\n     *   * `A': attribute\n     *   * `C`: class\n     *   * `M`: comment\n     * @returns {boolean} true if directive was added.\n     */\n    function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,\n                          endAttrName) {\n      if (name === ignoreDirective) return null;\n      var match = null;\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          try {\n            directive = directives[i];\n            if ((maxPriority === undefined || maxPriority > directive.priority) &&\n                 directive.restrict.indexOf(location) != -1) {\n              if (startAttrName) {\n                directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});\n              }\n              tDirectives.push(directive);\n              match = directive;\n            }\n          } catch (e) { $exceptionHandler(e); }\n        }\n      }\n      return match;\n    }\n\n\n    /**\n     * looks up the directive and returns true if it is a multi-element directive,\n     * and therefore requires DOM nodes between -start and -end markers to be grouped\n     * together.\n     *\n     * @param {string} name name of the directive to look up.\n     * @returns true if directive was registered as multi-element.\n     */\n    function directiveIsMultiElement(name) {\n      if (hasDirectives.hasOwnProperty(name)) {\n        for (var directive, directives = $injector.get(name + Suffix),\n            i = 0, ii = directives.length; i < ii; i++) {\n          directive = directives[i];\n          if (directive.multiElement) {\n            return true;\n          }\n        }\n      }\n      return false;\n    }\n\n    /**\n     * When the element is replaced with HTML template then the new attributes\n     * on the template need to be merged with the existing attributes in the DOM.\n     * The desired effect is to have both of the attributes present.\n     *\n     * @param {object} dst destination attributes (original DOM)\n     * @param {object} src source attributes (from the directive template)\n     */\n    function mergeTemplateAttributes(dst, src) {\n      var srcAttr = src.$attr,\n          dstAttr = dst.$attr,\n          $element = dst.$$element;\n\n      // reapply the old attributes to the new element\n      forEach(dst, function(value, key) {\n        if (key.charAt(0) != '$') {\n          if (src[key] && src[key] !== value) {\n            value += (key === 'style' ? ';' : ' ') + src[key];\n          }\n          dst.$set(key, value, true, srcAttr[key]);\n        }\n      });\n\n      // copy the new attributes on the old attrs object\n      forEach(src, function(value, key) {\n        if (key == 'class') {\n          safeAddClass($element, value);\n          dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;\n        } else if (key == 'style') {\n          $element.attr('style', $element.attr('style') + ';' + value);\n          dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;\n          // `dst` will never contain hasOwnProperty as DOM parser won't let it.\n          // You will get an \"InvalidCharacterError: DOM Exception 5\" error if you\n          // have an attribute like \"has-own-property\" or \"data-has-own-property\", etc.\n        } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {\n          dst[key] = value;\n          dstAttr[key] = srcAttr[key];\n        }\n      });\n    }\n\n\n    function compileTemplateUrl(directives, $compileNode, tAttrs,\n        $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {\n      var linkQueue = [],\n          afterTemplateNodeLinkFn,\n          afterTemplateChildLinkFn,\n          beforeTemplateCompileNode = $compileNode[0],\n          origAsyncDirective = directives.shift(),\n          derivedSyncDirective = inherit(origAsyncDirective, {\n            templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective\n          }),\n          templateUrl = (isFunction(origAsyncDirective.templateUrl))\n              ? origAsyncDirective.templateUrl($compileNode, tAttrs)\n              : origAsyncDirective.templateUrl,\n          templateNamespace = origAsyncDirective.templateNamespace;\n\n      $compileNode.empty();\n\n      $templateRequest(templateUrl)\n        .then(function(content) {\n          var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;\n\n          content = denormalizeTemplate(content);\n\n          if (origAsyncDirective.replace) {\n            if (jqLiteIsTextNode(content)) {\n              $template = [];\n            } else {\n              $template = removeComments(wrapTemplate(templateNamespace, trim(content)));\n            }\n            compileNode = $template[0];\n\n            if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {\n              throw $compileMinErr('tplrt',\n                  \"Template for directive '{0}' must have exactly one root element. {1}\",\n                  origAsyncDirective.name, templateUrl);\n            }\n\n            tempTemplateAttrs = {$attr: {}};\n            replaceWith($rootElement, $compileNode, compileNode);\n            var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);\n\n            if (isObject(origAsyncDirective.scope)) {\n              markDirectivesAsIsolate(templateDirectives);\n            }\n            directives = templateDirectives.concat(directives);\n            mergeTemplateAttributes(tAttrs, tempTemplateAttrs);\n          } else {\n            compileNode = beforeTemplateCompileNode;\n            $compileNode.html(content);\n          }\n\n          directives.unshift(derivedSyncDirective);\n\n          afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,\n              childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,\n              previousCompileContext);\n          forEach($rootElement, function(node, i) {\n            if (node == compileNode) {\n              $rootElement[i] = $compileNode[0];\n            }\n          });\n          afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);\n\n          while (linkQueue.length) {\n            var scope = linkQueue.shift(),\n                beforeTemplateLinkNode = linkQueue.shift(),\n                linkRootElement = linkQueue.shift(),\n                boundTranscludeFn = linkQueue.shift(),\n                linkNode = $compileNode[0];\n\n            if (scope.$$destroyed) continue;\n\n            if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {\n              var oldClasses = beforeTemplateLinkNode.className;\n\n              if (!(previousCompileContext.hasElementTranscludeDirective &&\n                  origAsyncDirective.replace)) {\n                // it was cloned therefore we have to clone as well.\n                linkNode = jqLiteClone(compileNode);\n              }\n              replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);\n\n              // Copy in CSS classes from original node\n              safeAddClass(jqLite(linkNode), oldClasses);\n            }\n            if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n              childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n            } else {\n              childBoundTranscludeFn = boundTranscludeFn;\n            }\n            afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,\n              childBoundTranscludeFn, afterTemplateNodeLinkFn);\n          }\n          linkQueue = null;\n        });\n\n      return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {\n        var childBoundTranscludeFn = boundTranscludeFn;\n        if (scope.$$destroyed) return;\n        if (linkQueue) {\n          linkQueue.push(scope,\n                         node,\n                         rootElement,\n                         childBoundTranscludeFn);\n        } else {\n          if (afterTemplateNodeLinkFn.transcludeOnThisElement) {\n            childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);\n          }\n          afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn,\n                                  afterTemplateNodeLinkFn);\n        }\n      };\n    }\n\n\n    /**\n     * Sorting function for bound directives.\n     */\n    function byPriority(a, b) {\n      var diff = b.priority - a.priority;\n      if (diff !== 0) return diff;\n      if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;\n      return a.index - b.index;\n    }\n\n    function assertNoDuplicate(what, previousDirective, directive, element) {\n\n      function wrapModuleNameIfDefined(moduleName) {\n        return moduleName ?\n          (' (module: ' + moduleName + ')') :\n          '';\n      }\n\n      if (previousDirective) {\n        throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',\n            previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),\n            directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));\n      }\n    }\n\n\n    function addTextInterpolateDirective(directives, text) {\n      var interpolateFn = $interpolate(text, true);\n      if (interpolateFn) {\n        directives.push({\n          priority: 0,\n          compile: function textInterpolateCompileFn(templateNode) {\n            var templateNodeParent = templateNode.parent(),\n                hasCompileParent = !!templateNodeParent.length;\n\n            // When transcluding a template that has bindings in the root\n            // we don't have a parent and thus need to add the class during linking fn.\n            if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);\n\n            return function textInterpolateLinkFn(scope, node) {\n              var parent = node.parent();\n              if (!hasCompileParent) compile.$$addBindingClass(parent);\n              compile.$$addBindingInfo(parent, interpolateFn.expressions);\n              scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {\n                node[0].nodeValue = value;\n              });\n            };\n          }\n        });\n      }\n    }\n\n\n    function wrapTemplate(type, template) {\n      type = lowercase(type || 'html');\n      switch (type) {\n      case 'svg':\n      case 'math':\n        var wrapper = document.createElement('div');\n        wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';\n        return wrapper.childNodes[0].childNodes;\n      default:\n        return template;\n      }\n    }\n\n\n    function getTrustedContext(node, attrNormalizedName) {\n      if (attrNormalizedName == \"srcdoc\") {\n        return $sce.HTML;\n      }\n      var tag = nodeName_(node);\n      // maction[xlink:href] can source SVG.  It's not limited to <maction>.\n      if (attrNormalizedName == \"xlinkHref\" ||\n          (tag == \"form\" && attrNormalizedName == \"action\") ||\n          (tag != \"img\" && (attrNormalizedName == \"src\" ||\n                            attrNormalizedName == \"ngSrc\"))) {\n        return $sce.RESOURCE_URL;\n      }\n    }\n\n\n    function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {\n      var trustedContext = getTrustedContext(node, name);\n      allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;\n\n      var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);\n\n      // no interpolation found -> ignore\n      if (!interpolateFn) return;\n\n\n      if (name === \"multiple\" && nodeName_(node) === \"select\") {\n        throw $compileMinErr(\"selmulti\",\n            \"Binding to the 'multiple' attribute is not supported. Element: {0}\",\n            startingTag(node));\n      }\n\n      directives.push({\n        priority: 100,\n        compile: function() {\n            return {\n              pre: function attrInterpolatePreLinkFn(scope, element, attr) {\n                var $$observers = (attr.$$observers || (attr.$$observers = {}));\n\n                if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {\n                  throw $compileMinErr('nodomevents',\n                      \"Interpolations for HTML DOM event attributes are disallowed.  Please use the \" +\n                          \"ng- versions (such as ng-click instead of onclick) instead.\");\n                }\n\n                // If the attribute has changed since last $interpolate()ed\n                var newValue = attr[name];\n                if (newValue !== value) {\n                  // we need to interpolate again since the attribute value has been updated\n                  // (e.g. by another directive's compile function)\n                  // ensure unset/empty values make interpolateFn falsy\n                  interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);\n                  value = newValue;\n                }\n\n                // if attribute was updated so that there is no interpolation going on we don't want to\n                // register any observers\n                if (!interpolateFn) return;\n\n                // initialize attr object so that it's ready in case we need the value for isolate\n                // scope initialization, otherwise the value would not be available from isolate\n                // directive's linking fn during linking phase\n                attr[name] = interpolateFn(scope);\n\n                ($$observers[name] || ($$observers[name] = [])).$$inter = true;\n                (attr.$$observers && attr.$$observers[name].$$scope || scope).\n                  $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {\n                    //special case for class attribute addition + removal\n                    //so that class changes can tap into the animation\n                    //hooks provided by the $animate service. Be sure to\n                    //skip animations when the first digest occurs (when\n                    //both the new and the old values are the same) since\n                    //the CSS classes are the non-interpolated values\n                    if (name === 'class' && newValue != oldValue) {\n                      attr.$updateClass(newValue, oldValue);\n                    } else {\n                      attr.$set(name, newValue);\n                    }\n                  });\n              }\n            };\n          }\n      });\n    }\n\n\n    /**\n     * This is a special jqLite.replaceWith, which can replace items which\n     * have no parents, provided that the containing jqLite collection is provided.\n     *\n     * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes\n     *                               in the root of the tree.\n     * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep\n     *                                  the shell, but replace its DOM node reference.\n     * @param {Node} newNode The new DOM node.\n     */\n    function replaceWith($rootElement, elementsToRemove, newNode) {\n      var firstElementToRemove = elementsToRemove[0],\n          removeCount = elementsToRemove.length,\n          parent = firstElementToRemove.parentNode,\n          i, ii;\n\n      if ($rootElement) {\n        for (i = 0, ii = $rootElement.length; i < ii; i++) {\n          if ($rootElement[i] == firstElementToRemove) {\n            $rootElement[i++] = newNode;\n            for (var j = i, j2 = j + removeCount - 1,\n                     jj = $rootElement.length;\n                 j < jj; j++, j2++) {\n              if (j2 < jj) {\n                $rootElement[j] = $rootElement[j2];\n              } else {\n                delete $rootElement[j];\n              }\n            }\n            $rootElement.length -= removeCount - 1;\n\n            // If the replaced element is also the jQuery .context then replace it\n            // .context is a deprecated jQuery api, so we should set it only when jQuery set it\n            // http://api.jquery.com/context/\n            if ($rootElement.context === firstElementToRemove) {\n              $rootElement.context = newNode;\n            }\n            break;\n          }\n        }\n      }\n\n      if (parent) {\n        parent.replaceChild(newNode, firstElementToRemove);\n      }\n\n      // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?\n      var fragment = document.createDocumentFragment();\n      fragment.appendChild(firstElementToRemove);\n\n      if (jqLite.hasData(firstElementToRemove)) {\n        // Copy over user data (that includes Angular's $scope etc.). Don't copy private\n        // data here because there's no public interface in jQuery to do that and copying over\n        // event listeners (which is the main use of private data) wouldn't work anyway.\n        jqLite(newNode).data(jqLite(firstElementToRemove).data());\n\n        // Remove data of the replaced element. We cannot just call .remove()\n        // on the element it since that would deallocate scope that is needed\n        // for the new node. Instead, remove the data \"manually\".\n        if (!jQuery) {\n          delete jqLite.cache[firstElementToRemove[jqLite.expando]];\n        } else {\n          // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after\n          // the replaced element. The cleanData version monkey-patched by Angular would cause\n          // the scope to be trashed and we do need the very same scope to work with the new\n          // element. However, we cannot just cache the non-patched version and use it here as\n          // that would break if another library patches the method after Angular does (one\n          // example is jQuery UI). Instead, set a flag indicating scope destroying should be\n          // skipped this one time.\n          skipDestroyOnNextJQueryCleanData = true;\n          jQuery.cleanData([firstElementToRemove]);\n        }\n      }\n\n      for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {\n        var element = elementsToRemove[k];\n        jqLite(element).remove(); // must do this way to clean up expando\n        fragment.appendChild(element);\n        delete elementsToRemove[k];\n      }\n\n      elementsToRemove[0] = newNode;\n      elementsToRemove.length = 1;\n    }\n\n\n    function cloneAndAnnotateFn(fn, annotation) {\n      return extend(function() { return fn.apply(null, arguments); }, fn, annotation);\n    }\n\n\n    function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {\n      try {\n        linkFn(scope, $element, attrs, controllers, transcludeFn);\n      } catch (e) {\n        $exceptionHandler(e, startingTag($element));\n      }\n    }\n\n\n    // Set up $watches for isolate scope and controller bindings. This process\n    // only occurs for isolate scopes and new scopes with controllerAs.\n    function initializeDirectiveBindings(scope, attrs, destination, bindings,\n                                         directive, newScope) {\n      var onNewScopeDestroyed;\n      forEach(bindings, function(definition, scopeName) {\n        var attrName = definition.attrName,\n        optional = definition.optional,\n        mode = definition.mode, // @, =, or &\n        lastValue,\n        parentGet, parentSet, compare;\n\n        switch (mode) {\n\n          case '@':\n            if (!optional && !hasOwnProperty.call(attrs, attrName)) {\n              destination[scopeName] = attrs[attrName] = void 0;\n            }\n            attrs.$observe(attrName, function(value) {\n              if (isString(value)) {\n                destination[scopeName] = value;\n              }\n            });\n            attrs.$$observers[attrName].$$scope = scope;\n            if (isString(attrs[attrName])) {\n              // If the attribute has been provided then we trigger an interpolation to ensure\n              // the value is there for use in the link fn\n              destination[scopeName] = $interpolate(attrs[attrName])(scope);\n            }\n            break;\n\n          case '=':\n            if (!hasOwnProperty.call(attrs, attrName)) {\n              if (optional) break;\n              attrs[attrName] = void 0;\n            }\n            if (optional && !attrs[attrName]) break;\n\n            parentGet = $parse(attrs[attrName]);\n            if (parentGet.literal) {\n              compare = equals;\n            } else {\n              compare = function(a, b) { return a === b || (a !== a && b !== b); };\n            }\n            parentSet = parentGet.assign || function() {\n              // reset the change, or we will throw this exception on every $digest\n              lastValue = destination[scopeName] = parentGet(scope);\n              throw $compileMinErr('nonassign',\n                  \"Expression '{0}' used with directive '{1}' is non-assignable!\",\n                  attrs[attrName], directive.name);\n            };\n            lastValue = destination[scopeName] = parentGet(scope);\n            var parentValueWatch = function parentValueWatch(parentValue) {\n              if (!compare(parentValue, destination[scopeName])) {\n                // we are out of sync and need to copy\n                if (!compare(parentValue, lastValue)) {\n                  // parent changed and it has precedence\n                  destination[scopeName] = parentValue;\n                } else {\n                  // if the parent can be assigned then do so\n                  parentSet(scope, parentValue = destination[scopeName]);\n                }\n              }\n              return lastValue = parentValue;\n            };\n            parentValueWatch.$stateful = true;\n            var unwatch;\n            if (definition.collection) {\n              unwatch = scope.$watchCollection(attrs[attrName], parentValueWatch);\n            } else {\n              unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);\n            }\n            onNewScopeDestroyed = (onNewScopeDestroyed || []);\n            onNewScopeDestroyed.push(unwatch);\n            break;\n\n          case '&':\n            // Don't assign Object.prototype method to scope\n            parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;\n\n            // Don't assign noop to destination if expression is not valid\n            if (parentGet === noop && optional) break;\n\n            destination[scopeName] = function(locals) {\n              return parentGet(scope, locals);\n            };\n            break;\n        }\n      });\n      var destroyBindings = onNewScopeDestroyed ? function destroyBindings() {\n        for (var i = 0, ii = onNewScopeDestroyed.length; i < ii; ++i) {\n          onNewScopeDestroyed[i]();\n        }\n      } : noop;\n      if (newScope && destroyBindings !== noop) {\n        newScope.$on('$destroy', destroyBindings);\n        return noop;\n      }\n      return destroyBindings;\n    }\n  }];\n}\n\nvar PREFIX_REGEXP = /^((?:x|data)[\\:\\-_])/i;\n/**\n * Converts all accepted directives format into proper directive name.\n * @param name Name to normalize\n */\nfunction directiveNormalize(name) {\n  return camelCase(name.replace(PREFIX_REGEXP, ''));\n}\n\n/**\n * @ngdoc type\n * @name $compile.directive.Attributes\n *\n * @description\n * A shared object between directive compile / linking functions which contains normalized DOM\n * element attributes. The values reflect current binding state `{{ }}`. The normalization is\n * needed since all of these are treated as equivalent in Angular:\n *\n * ```\n *    <span ng:bind=\"a\" ng-bind=\"a\" data-ng-bind=\"a\" x-ng-bind=\"a\">\n * ```\n */\n\n/**\n * @ngdoc property\n * @name $compile.directive.Attributes#$attr\n *\n * @description\n * A map of DOM element attribute names to the normalized name. This is\n * needed to do reverse lookup from normalized name back to actual name.\n */\n\n\n/**\n * @ngdoc method\n * @name $compile.directive.Attributes#$set\n * @kind function\n *\n * @description\n * Set DOM element attribute value.\n *\n *\n * @param {string} name Normalized element attribute name of the property to modify. The name is\n *          reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}\n *          property to the original name.\n * @param {string} value Value to set the attribute to. The value can be an interpolated string.\n */\n\n\n\n/**\n * Closure compiler type information\n */\n\nfunction nodesetLinkingFn(\n  /* angular.Scope */ scope,\n  /* NodeList */ nodeList,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction directiveLinkingFn(\n  /* nodesetLinkingFn */ nodesetLinkingFn,\n  /* angular.Scope */ scope,\n  /* Node */ node,\n  /* Element */ rootElement,\n  /* function(Function) */ boundTranscludeFn\n) {}\n\nfunction tokenDifference(str1, str2) {\n  var values = '',\n      tokens1 = str1.split(/\\s+/),\n      tokens2 = str2.split(/\\s+/);\n\n  outer:\n  for (var i = 0; i < tokens1.length; i++) {\n    var token = tokens1[i];\n    for (var j = 0; j < tokens2.length; j++) {\n      if (token == tokens2[j]) continue outer;\n    }\n    values += (values.length > 0 ? ' ' : '') + token;\n  }\n  return values;\n}\n\nfunction removeComments(jqNodes) {\n  jqNodes = jqLite(jqNodes);\n  var i = jqNodes.length;\n\n  if (i <= 1) {\n    return jqNodes;\n  }\n\n  while (i--) {\n    var node = jqNodes[i];\n    if (node.nodeType === NODE_TYPE_COMMENT) {\n      splice.call(jqNodes, i, 1);\n    }\n  }\n  return jqNodes;\n}\n\nvar $controllerMinErr = minErr('$controller');\n\n\nvar CNTRL_REG = /^(\\S+)(\\s+as\\s+(\\w+))?$/;\nfunction identifierForController(controller, ident) {\n  if (ident && isString(ident)) return ident;\n  if (isString(controller)) {\n    var match = CNTRL_REG.exec(controller);\n    if (match) return match[3];\n  }\n}\n\n\n/**\n * @ngdoc provider\n * @name $controllerProvider\n * @description\n * The {@link ng.$controller $controller service} is used by Angular to create new\n * controllers.\n *\n * This provider allows controller registration via the\n * {@link ng.$controllerProvider#register register} method.\n */\nfunction $ControllerProvider() {\n  var controllers = {},\n      globals = false;\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#register\n   * @param {string|Object} name Controller name, or an object map of controllers where the keys are\n   *    the names and the values are the constructors.\n   * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI\n   *    annotations in the array notation).\n   */\n  this.register = function(name, constructor) {\n    assertNotHasOwnProperty(name, 'controller');\n    if (isObject(name)) {\n      extend(controllers, name);\n    } else {\n      controllers[name] = constructor;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $controllerProvider#allowGlobals\n   * @description If called, allows `$controller` to find controller constructors on `window`\n   */\n  this.allowGlobals = function() {\n    globals = true;\n  };\n\n\n  this.$get = ['$injector', '$window', function($injector, $window) {\n\n    /**\n     * @ngdoc service\n     * @name $controller\n     * @requires $injector\n     *\n     * @param {Function|string} constructor If called with a function then it's considered to be the\n     *    controller constructor function. Otherwise it's considered to be a string which is used\n     *    to retrieve the controller constructor using the following steps:\n     *\n     *    * check if a controller with given name is registered via `$controllerProvider`\n     *    * check if evaluating the string on the current scope returns a constructor\n     *    * if $controllerProvider#allowGlobals, check `window[constructor]` on the global\n     *      `window` object (not recommended)\n     *\n     *    The string can use the `controller as property` syntax, where the controller instance is published\n     *    as the specified property on the `scope`; the `scope` must be injected into `locals` param for this\n     *    to work correctly.\n     *\n     * @param {Object} locals Injection locals for Controller.\n     * @return {Object} Instance of given controller.\n     *\n     * @description\n     * `$controller` service is responsible for instantiating controllers.\n     *\n     * It's just a simple call to {@link auto.$injector $injector}, but extracted into\n     * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).\n     */\n    return function(expression, locals, later, ident) {\n      // PRIVATE API:\n      //   param `later` --- indicates that the controller's constructor is invoked at a later time.\n      //                     If true, $controller will allocate the object with the correct\n      //                     prototype chain, but will not invoke the controller until a returned\n      //                     callback is invoked.\n      //   param `ident` --- An optional label which overrides the label parsed from the controller\n      //                     expression, if any.\n      var instance, match, constructor, identifier;\n      later = later === true;\n      if (ident && isString(ident)) {\n        identifier = ident;\n      }\n\n      if (isString(expression)) {\n        match = expression.match(CNTRL_REG);\n        if (!match) {\n          throw $controllerMinErr('ctrlfmt',\n            \"Badly formed controller string '{0}'. \" +\n            \"Must match `__name__ as __id__` or `__name__`.\", expression);\n        }\n        constructor = match[1],\n        identifier = identifier || match[3];\n        expression = controllers.hasOwnProperty(constructor)\n            ? controllers[constructor]\n            : getter(locals.$scope, constructor, true) ||\n                (globals ? getter($window, constructor, true) : undefined);\n\n        assertArgFn(expression, constructor, true);\n      }\n\n      if (later) {\n        // Instantiate controller later:\n        // This machinery is used to create an instance of the object before calling the\n        // controller's constructor itself.\n        //\n        // This allows properties to be added to the controller before the constructor is\n        // invoked. Primarily, this is used for isolate scope bindings in $compile.\n        //\n        // This feature is not intended for use by applications, and is thus not documented\n        // publicly.\n        // Object creation: http://jsperf.com/create-constructor/2\n        var controllerPrototype = (isArray(expression) ?\n          expression[expression.length - 1] : expression).prototype;\n        instance = Object.create(controllerPrototype || null);\n\n        if (identifier) {\n          addIdentifier(locals, identifier, instance, constructor || expression.name);\n        }\n\n        var instantiate;\n        return instantiate = extend(function() {\n          var result = $injector.invoke(expression, instance, locals, constructor);\n          if (result !== instance && (isObject(result) || isFunction(result))) {\n            instance = result;\n            if (identifier) {\n              // If result changed, re-assign controllerAs value to scope.\n              addIdentifier(locals, identifier, instance, constructor || expression.name);\n            }\n          }\n          return instance;\n        }, {\n          instance: instance,\n          identifier: identifier\n        });\n      }\n\n      instance = $injector.instantiate(expression, locals, constructor);\n\n      if (identifier) {\n        addIdentifier(locals, identifier, instance, constructor || expression.name);\n      }\n\n      return instance;\n    };\n\n    function addIdentifier(locals, identifier, instance, name) {\n      if (!(locals && isObject(locals.$scope))) {\n        throw minErr('$controller')('noscp',\n          \"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.\",\n          name, identifier);\n      }\n\n      locals.$scope[identifier] = instance;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $document\n * @requires $window\n *\n * @description\n * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.\n *\n * @example\n   <example module=\"documentExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <p>$document title: <b ng-bind=\"title\"></b></p>\n         <p>window.document title: <b ng-bind=\"windowTitle\"></b></p>\n       </div>\n     </file>\n     <file name=\"script.js\">\n       angular.module('documentExample', [])\n         .controller('ExampleController', ['$scope', '$document', function($scope, $document) {\n           $scope.title = $document[0].title;\n           $scope.windowTitle = angular.element(window.document)[0].title;\n         }]);\n     </file>\n   </example>\n */\nfunction $DocumentProvider() {\n  this.$get = ['$window', function(window) {\n    return jqLite(window.document);\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $exceptionHandler\n * @requires ng.$log\n *\n * @description\n * Any uncaught exception in angular expressions is delegated to this service.\n * The default implementation simply delegates to `$log.error` which logs it into\n * the browser console.\n *\n * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by\n * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.\n *\n * ## Example:\n *\n * ```js\n *   angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {\n *     return function(exception, cause) {\n *       exception.message += ' (caused by \"' + cause + '\")';\n *       throw exception;\n *     };\n *   });\n * ```\n *\n * This example will override the normal action of `$exceptionHandler`, to make angular\n * exceptions fail hard when they happen, instead of just logging to the console.\n *\n * <hr />\n * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`\n * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}\n * (unless executed during a digest).\n *\n * If you wish, you can manually delegate exceptions, e.g.\n * `try { ... } catch(e) { $exceptionHandler(e); }`\n *\n * @param {Error} exception Exception associated with the error.\n * @param {string=} cause optional information about the context in which\n *       the error was thrown.\n *\n */\nfunction $ExceptionHandlerProvider() {\n  this.$get = ['$log', function($log) {\n    return function(exception, cause) {\n      $log.error.apply($log, arguments);\n    };\n  }];\n}\n\nvar $$ForceReflowProvider = function() {\n  this.$get = ['$document', function($document) {\n    return function(domNode) {\n      //the line below will force the browser to perform a repaint so\n      //that all the animated elements within the animation frame will\n      //be properly updated and drawn on screen. This is required to\n      //ensure that the preparation animation is properly flushed so that\n      //the active state picks up from there. DO NOT REMOVE THIS LINE.\n      //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH\n      //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND\n      //WILL TAKE YEARS AWAY FROM YOUR LIFE.\n      if (domNode) {\n        if (!domNode.nodeType && domNode instanceof jqLite) {\n          domNode = domNode[0];\n        }\n      } else {\n        domNode = $document[0].body;\n      }\n      return domNode.offsetWidth + 1;\n    };\n  }];\n};\n\nvar APPLICATION_JSON = 'application/json';\nvar CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};\nvar JSON_START = /^\\[|^\\{(?!\\{)/;\nvar JSON_ENDS = {\n  '[': /]$/,\n  '{': /}$/\n};\nvar JSON_PROTECTION_PREFIX = /^\\)\\]\\}',?\\n/;\nvar $httpMinErr = minErr('$http');\nvar $httpMinErrLegacyFn = function(method) {\n  return function() {\n    throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);\n  };\n};\n\nfunction serializeValue(v) {\n  if (isObject(v)) {\n    return isDate(v) ? v.toISOString() : toJson(v);\n  }\n  return v;\n}\n\n\nfunction $HttpParamSerializerProvider() {\n  /**\n   * @ngdoc service\n   * @name $httpParamSerializer\n   * @description\n   *\n   * Default {@link $http `$http`} params serializer that converts objects to strings\n   * according to the following rules:\n   *\n   * * `{'foo': 'bar'}` results in `foo=bar`\n   * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)\n   * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)\n   * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D\"` (stringified and encoded representation of an object)\n   *\n   * Note that serializer will sort the request parameters alphabetically.\n   * */\n\n  this.$get = function() {\n    return function ngParamSerializer(params) {\n      if (!params) return '';\n      var parts = [];\n      forEachSorted(params, function(value, key) {\n        if (value === null || isUndefined(value)) return;\n        if (isArray(value)) {\n          forEach(value, function(v, k) {\n            parts.push(encodeUriQuery(key)  + '=' + encodeUriQuery(serializeValue(v)));\n          });\n        } else {\n          parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));\n        }\n      });\n\n      return parts.join('&');\n    };\n  };\n}\n\nfunction $HttpParamSerializerJQLikeProvider() {\n  /**\n   * @ngdoc service\n   * @name $httpParamSerializerJQLike\n   * @description\n   *\n   * Alternative {@link $http `$http`} params serializer that follows\n   * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.\n   * The serializer will also sort the params alphabetically.\n   *\n   * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:\n   *\n   * ```js\n   * $http({\n   *   url: myUrl,\n   *   method: 'GET',\n   *   params: myParams,\n   *   paramSerializer: '$httpParamSerializerJQLike'\n   * });\n   * ```\n   *\n   * It is also possible to set it as the default `paramSerializer` in the\n   * {@link $httpProvider#defaults `$httpProvider`}.\n   *\n   * Additionally, you can inject the serializer and use it explicitly, for example to serialize\n   * form data for submission:\n   *\n   * ```js\n   * .controller(function($http, $httpParamSerializerJQLike) {\n   *   //...\n   *\n   *   $http({\n   *     url: myUrl,\n   *     method: 'POST',\n   *     data: $httpParamSerializerJQLike(myData),\n   *     headers: {\n   *       'Content-Type': 'application/x-www-form-urlencoded'\n   *     }\n   *   });\n   *\n   * });\n   * ```\n   *\n   * */\n  this.$get = function() {\n    return function jQueryLikeParamSerializer(params) {\n      if (!params) return '';\n      var parts = [];\n      serialize(params, '', true);\n      return parts.join('&');\n\n      function serialize(toSerialize, prefix, topLevel) {\n        if (toSerialize === null || isUndefined(toSerialize)) return;\n        if (isArray(toSerialize)) {\n          forEach(toSerialize, function(value, index) {\n            serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');\n          });\n        } else if (isObject(toSerialize) && !isDate(toSerialize)) {\n          forEachSorted(toSerialize, function(value, key) {\n            serialize(value, prefix +\n                (topLevel ? '' : '[') +\n                key +\n                (topLevel ? '' : ']'));\n          });\n        } else {\n          parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));\n        }\n      }\n    };\n  };\n}\n\nfunction defaultHttpResponseTransform(data, headers) {\n  if (isString(data)) {\n    // Strip json vulnerability protection prefix and trim whitespace\n    var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();\n\n    if (tempData) {\n      var contentType = headers('Content-Type');\n      if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {\n        data = fromJson(tempData);\n      }\n    }\n  }\n\n  return data;\n}\n\nfunction isJsonLike(str) {\n    var jsonStart = str.match(JSON_START);\n    return jsonStart && JSON_ENDS[jsonStart[0]].test(str);\n}\n\n/**\n * Parse headers into key value object\n *\n * @param {string} headers Raw headers as a string\n * @returns {Object} Parsed headers as key value object\n */\nfunction parseHeaders(headers) {\n  var parsed = createMap(), i;\n\n  function fillInParsed(key, val) {\n    if (key) {\n      parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n    }\n  }\n\n  if (isString(headers)) {\n    forEach(headers.split('\\n'), function(line) {\n      i = line.indexOf(':');\n      fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));\n    });\n  } else if (isObject(headers)) {\n    forEach(headers, function(headerVal, headerKey) {\n      fillInParsed(lowercase(headerKey), trim(headerVal));\n    });\n  }\n\n  return parsed;\n}\n\n\n/**\n * Returns a function that provides access to parsed headers.\n *\n * Headers are lazy parsed when first requested.\n * @see parseHeaders\n *\n * @param {(string|Object)} headers Headers to provide access to.\n * @returns {function(string=)} Returns a getter function which if called with:\n *\n *   - if called with single an argument returns a single header value or null\n *   - if called with no arguments returns an object containing all headers.\n */\nfunction headersGetter(headers) {\n  var headersObj;\n\n  return function(name) {\n    if (!headersObj) headersObj =  parseHeaders(headers);\n\n    if (name) {\n      var value = headersObj[lowercase(name)];\n      if (value === void 0) {\n        value = null;\n      }\n      return value;\n    }\n\n    return headersObj;\n  };\n}\n\n\n/**\n * Chain all given functions\n *\n * This function is used for both request and response transforming\n *\n * @param {*} data Data to transform.\n * @param {function(string=)} headers HTTP headers getter fn.\n * @param {number} status HTTP status code of the response.\n * @param {(Function|Array.<Function>)} fns Function or an array of functions.\n * @returns {*} Transformed data.\n */\nfunction transformData(data, headers, status, fns) {\n  if (isFunction(fns)) {\n    return fns(data, headers, status);\n  }\n\n  forEach(fns, function(fn) {\n    data = fn(data, headers, status);\n  });\n\n  return data;\n}\n\n\nfunction isSuccess(status) {\n  return 200 <= status && status < 300;\n}\n\n\n/**\n * @ngdoc provider\n * @name $httpProvider\n * @description\n * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.\n * */\nfunction $HttpProvider() {\n  /**\n   * @ngdoc property\n   * @name $httpProvider#defaults\n   * @description\n   *\n   * Object containing default values for all {@link ng.$http $http} requests.\n   *\n   * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}\n   * that will provide the cache for all requests who set their `cache` property to `true`.\n   * If you set the `defaults.cache = false` then only requests that specify their own custom\n   * cache object will be cached. See {@link $http#caching $http Caching} for more information.\n   *\n   * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.\n   * Defaults value is `'XSRF-TOKEN'`.\n   *\n   * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the\n   * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.\n   *\n   * - **`defaults.headers`** - {Object} - Default headers for all $http requests.\n   * Refer to {@link ng.$http#setting-http-headers $http} for documentation on\n   * setting default headers.\n   *     - **`defaults.headers.common`**\n   *     - **`defaults.headers.post`**\n   *     - **`defaults.headers.put`**\n   *     - **`defaults.headers.patch`**\n   *\n   *\n   * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function\n   *  used to the prepare string representation of request parameters (specified as an object).\n   *  If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.\n   *  Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.\n   *\n   **/\n  var defaults = this.defaults = {\n    // transform incoming response data\n    transformResponse: [defaultHttpResponseTransform],\n\n    // transform outgoing request data\n    transformRequest: [function(d) {\n      return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;\n    }],\n\n    // default headers\n    headers: {\n      common: {\n        'Accept': 'application/json, text/plain, */*'\n      },\n      post:   shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      put:    shallowCopy(CONTENT_TYPE_APPLICATION_JSON),\n      patch:  shallowCopy(CONTENT_TYPE_APPLICATION_JSON)\n    },\n\n    xsrfCookieName: 'XSRF-TOKEN',\n    xsrfHeaderName: 'X-XSRF-TOKEN',\n\n    paramSerializer: '$httpParamSerializer'\n  };\n\n  var useApplyAsync = false;\n  /**\n   * @ngdoc method\n   * @name $httpProvider#useApplyAsync\n   * @description\n   *\n   * Configure $http service to combine processing of multiple http responses received at around\n   * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in\n   * significant performance improvement for bigger applications that make many HTTP requests\n   * concurrently (common during application bootstrap).\n   *\n   * Defaults to false. If no value is specified, returns the current configured value.\n   *\n   * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred\n   *    \"apply\" on the next tick, giving time for subsequent requests in a roughly ~10ms window\n   *    to load and share the same digest cycle.\n   *\n   * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n   *    otherwise, returns the current configured value.\n   **/\n  this.useApplyAsync = function(value) {\n    if (isDefined(value)) {\n      useApplyAsync = !!value;\n      return this;\n    }\n    return useApplyAsync;\n  };\n\n  var useLegacyPromise = true;\n  /**\n   * @ngdoc method\n   * @name $httpProvider#useLegacyPromiseExtensions\n   * @description\n   *\n   * Configure `$http` service to return promises without the shorthand methods `success` and `error`.\n   * This should be used to make sure that applications work without these methods.\n   *\n   * Defaults to false. If no value is specified, returns the current configured value.\n   *\n   * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.\n   *\n   * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n   *    otherwise, returns the current configured value.\n   **/\n  this.useLegacyPromiseExtensions = function(value) {\n    if (isDefined(value)) {\n      useLegacyPromise = !!value;\n      return this;\n    }\n    return useLegacyPromise;\n  };\n\n  /**\n   * @ngdoc property\n   * @name $httpProvider#interceptors\n   * @description\n   *\n   * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}\n   * pre-processing of request or postprocessing of responses.\n   *\n   * These service factories are ordered by request, i.e. they are applied in the same order as the\n   * array, on request, but reverse order, on response.\n   *\n   * {@link ng.$http#interceptors Interceptors detailed info}\n   **/\n  var interceptorFactories = this.interceptors = [];\n\n  this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',\n      function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {\n\n    var defaultCache = $cacheFactory('$http');\n\n    /**\n     * Make sure that default param serializer is exposed as a function\n     */\n    defaults.paramSerializer = isString(defaults.paramSerializer) ?\n      $injector.get(defaults.paramSerializer) : defaults.paramSerializer;\n\n    /**\n     * Interceptors stored in reverse order. Inner interceptors before outer interceptors.\n     * The reversal is needed so that we can build up the interception chain around the\n     * server request.\n     */\n    var reversedInterceptors = [];\n\n    forEach(interceptorFactories, function(interceptorFactory) {\n      reversedInterceptors.unshift(isString(interceptorFactory)\n          ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));\n    });\n\n    /**\n     * @ngdoc service\n     * @kind function\n     * @name $http\n     * @requires ng.$httpBackend\n     * @requires $cacheFactory\n     * @requires $rootScope\n     * @requires $q\n     * @requires $injector\n     *\n     * @description\n     * The `$http` service is a core Angular service that facilitates communication with the remote\n     * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)\n     * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).\n     *\n     * For unit testing applications that use `$http` service, see\n     * {@link ngMock.$httpBackend $httpBackend mock}.\n     *\n     * For a higher level of abstraction, please check out the {@link ngResource.$resource\n     * $resource} service.\n     *\n     * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by\n     * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage\n     * it is important to familiarize yourself with these APIs and the guarantees they provide.\n     *\n     *\n     * ## General usage\n     * The `$http` service is a function which takes a single argument — a configuration object —\n     * that is used to generate an HTTP request and returns  a {@link ng.$q promise}.\n     *\n     * ```js\n     *   // Simple GET request example :\n     *   $http.get('/someUrl').\n     *     then(function(response) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }, function(response) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     * ```js\n     *   // Simple POST request example (passing data) :\n     *   $http.post('/someUrl', {msg:'hello word!'}).\n     *     then(function(response) {\n     *       // this callback will be called asynchronously\n     *       // when the response is available\n     *     }, function(response) {\n     *       // called asynchronously if an error occurs\n     *       // or server returns response with an error status.\n     *     });\n     * ```\n     *\n     * The response object has these properties:\n     *\n     *   - **data** – `{string|Object}` – The response body transformed with the transform\n     *     functions.\n     *   - **status** – `{number}` – HTTP status code of the response.\n     *   - **headers** – `{function([headerName])}` – Header getter function.\n     *   - **config** – `{Object}` – The configuration object that was used to generate the request.\n     *   - **statusText** – `{string}` – HTTP status text of the response.\n     *\n     * A response status code between 200 and 299 is considered a success status and\n     * will result in the success callback being called. Note that if the response is a redirect,\n     * XMLHttpRequest will transparently follow it, meaning that the error callback will not be\n     * called for such responses.\n     *\n     * ## Writing Unit Tests that use $http\n     * When unit testing (using {@link ngMock ngMock}), it is necessary to call\n     * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending\n     * request using trained responses.\n     *\n     * ```\n     * $httpBackend.expectGET(...);\n     * $http.get(...);\n     * $httpBackend.flush();\n     * ```\n     *\n     * ## Shortcut methods\n     *\n     * Shortcut methods are also available. All shortcut methods require passing in the URL, and\n     * request data must be passed in for POST/PUT requests.\n     *\n     * ```js\n     *   $http.get('/someUrl').then(successCallback);\n     *   $http.post('/someUrl', data).then(successCallback);\n     * ```\n     *\n     * Complete list of shortcut methods:\n     *\n     * - {@link ng.$http#get $http.get}\n     * - {@link ng.$http#head $http.head}\n     * - {@link ng.$http#post $http.post}\n     * - {@link ng.$http#put $http.put}\n     * - {@link ng.$http#delete $http.delete}\n     * - {@link ng.$http#jsonp $http.jsonp}\n     * - {@link ng.$http#patch $http.patch}\n     *\n     *\n     * ## Deprecation Notice\n     * <div class=\"alert alert-danger\">\n     *   The `$http` legacy promise methods `success` and `error` have been deprecated.\n     *   Use the standard `then` method instead.\n     *   If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to\n     *   `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.\n     * </div>\n     *\n     * ## Setting HTTP Headers\n     *\n     * The $http service will automatically add certain HTTP headers to all requests. These defaults\n     * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration\n     * object, which currently contains this default configuration:\n     *\n     * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):\n     *   - `Accept: application/json, text/plain, * / *`\n     * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)\n     *   - `Content-Type: application/json`\n     * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)\n     *   - `Content-Type: application/json`\n     *\n     * To add or overwrite these defaults, simply add or remove a property from these configuration\n     * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object\n     * with the lowercased HTTP method name as the key, e.g.\n     * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.\n     *\n     * The defaults can also be set at runtime via the `$http.defaults` object in the same\n     * fashion. For example:\n     *\n     * ```\n     * module.run(function($http) {\n     *   $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'\n     * });\n     * ```\n     *\n     * In addition, you can supply a `headers` property in the config object passed when\n     * calling `$http(config)`, which overrides the defaults without changing them globally.\n     *\n     * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,\n     * Use the `headers` property, setting the desired header to `undefined`. For example:\n     *\n     * ```js\n     * var req = {\n     *  method: 'POST',\n     *  url: 'http://example.com',\n     *  headers: {\n     *    'Content-Type': undefined\n     *  },\n     *  data: { test: 'test' }\n     * }\n     *\n     * $http(req).then(function(){...}, function(){...});\n     * ```\n     *\n     * ## Transforming Requests and Responses\n     *\n     * Both requests and responses can be transformed using transformation functions: `transformRequest`\n     * and `transformResponse`. These properties can be a single function that returns\n     * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,\n     * which allows you to `push` or `unshift` a new transformation function into the transformation chain.\n     *\n     * ### Default Transformations\n     *\n     * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and\n     * `defaults.transformResponse` properties. If a request does not provide its own transformations\n     * then these will be applied.\n     *\n     * You can augment or replace the default transformations by modifying these properties by adding to or\n     * replacing the array.\n     *\n     * Angular provides the following default transformations:\n     *\n     * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):\n     *\n     * - If the `data` property of the request configuration object contains an object, serialize it\n     *   into JSON format.\n     *\n     * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):\n     *\n     *  - If XSRF prefix is detected, strip it (see Security Considerations section below).\n     *  - If JSON response is detected, deserialize it using a JSON parser.\n     *\n     *\n     * ### Overriding the Default Transformations Per Request\n     *\n     * If you wish override the request/response transformations only for a single request then provide\n     * `transformRequest` and/or `transformResponse` properties on the configuration object passed\n     * into `$http`.\n     *\n     * Note that if you provide these properties on the config object the default transformations will be\n     * overwritten. If you wish to augment the default transformations then you must include them in your\n     * local transformation array.\n     *\n     * The following code demonstrates adding a new response transformation to be run after the default response\n     * transformations have been run.\n     *\n     * ```js\n     * function appendTransform(defaults, transform) {\n     *\n     *   // We can't guarantee that the default transformation is an array\n     *   defaults = angular.isArray(defaults) ? defaults : [defaults];\n     *\n     *   // Append the new transformation to the defaults\n     *   return defaults.concat(transform);\n     * }\n     *\n     * $http({\n     *   url: '...',\n     *   method: 'GET',\n     *   transformResponse: appendTransform($http.defaults.transformResponse, function(value) {\n     *     return doTransform(value);\n     *   })\n     * });\n     * ```\n     *\n     *\n     * ## Caching\n     *\n     * To enable caching, set the request configuration `cache` property to `true` (to use default\n     * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).\n     * When the cache is enabled, `$http` stores the response from the server in the specified\n     * cache. The next time the same request is made, the response is served from the cache without\n     * sending a request to the server.\n     *\n     * Note that even if the response is served from cache, delivery of the data is asynchronous in\n     * the same way that real requests are.\n     *\n     * If there are multiple GET requests for the same URL that should be cached using the same\n     * cache, but the cache is not populated yet, only one request to the server will be made and\n     * the remaining requests will be fulfilled using the response from the first request.\n     *\n     * You can change the default cache to a new object (built with\n     * {@link ng.$cacheFactory `$cacheFactory`}) by updating the\n     * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set\n     * their `cache` property to `true` will now use this cache object.\n     *\n     * If you set the default cache to `false` then only requests that specify their own custom\n     * cache object will be cached.\n     *\n     * ## Interceptors\n     *\n     * Before you start creating interceptors, be sure to understand the\n     * {@link ng.$q $q and deferred/promise APIs}.\n     *\n     * For purposes of global error handling, authentication, or any kind of synchronous or\n     * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be\n     * able to intercept requests before they are handed to the server and\n     * responses before they are handed over to the application code that\n     * initiated these requests. The interceptors leverage the {@link ng.$q\n     * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.\n     *\n     * The interceptors are service factories that are registered with the `$httpProvider` by\n     * adding them to the `$httpProvider.interceptors` array. The factory is called and\n     * injected with dependencies (if specified) and returns the interceptor.\n     *\n     * There are two kinds of interceptors (and two kinds of rejection interceptors):\n     *\n     *   * `request`: interceptors get called with a http `config` object. The function is free to\n     *     modify the `config` object or create a new one. The function needs to return the `config`\n     *     object directly, or a promise containing the `config` or a new `config` object.\n     *   * `requestError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *   * `response`: interceptors get called with http `response` object. The function is free to\n     *     modify the `response` object or create a new one. The function needs to return the `response`\n     *     object directly, or as a promise containing the `response` or a new `response` object.\n     *   * `responseError`: interceptor gets called when a previous interceptor threw an error or\n     *     resolved with a rejection.\n     *\n     *\n     * ```js\n     *   // register the interceptor as a service\n     *   $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {\n     *     return {\n     *       // optional method\n     *       'request': function(config) {\n     *         // do something on success\n     *         return config;\n     *       },\n     *\n     *       // optional method\n     *      'requestError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       },\n     *\n     *\n     *\n     *       // optional method\n     *       'response': function(response) {\n     *         // do something on success\n     *         return response;\n     *       },\n     *\n     *       // optional method\n     *      'responseError': function(rejection) {\n     *         // do something on error\n     *         if (canRecover(rejection)) {\n     *           return responseOrNewPromise\n     *         }\n     *         return $q.reject(rejection);\n     *       }\n     *     };\n     *   });\n     *\n     *   $httpProvider.interceptors.push('myHttpInterceptor');\n     *\n     *\n     *   // alternatively, register the interceptor via an anonymous factory\n     *   $httpProvider.interceptors.push(function($q, dependency1, dependency2) {\n     *     return {\n     *      'request': function(config) {\n     *          // same as above\n     *       },\n     *\n     *       'response': function(response) {\n     *          // same as above\n     *       }\n     *     };\n     *   });\n     * ```\n     *\n     * ## Security Considerations\n     *\n     * When designing web applications, consider security threats from:\n     *\n     * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)\n     *\n     * Both server and the client must cooperate in order to eliminate these threats. Angular comes\n     * pre-configured with strategies that address these issues, but for this to work backend server\n     * cooperation is required.\n     *\n     * ### JSON Vulnerability Protection\n     *\n     * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)\n     * allows third party website to turn your JSON resource URL into\n     * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To\n     * counter this your server can prefix all JSON requests with following string `\")]}',\\n\"`.\n     * Angular will automatically strip the prefix before processing it as JSON.\n     *\n     * For example if your server needs to return:\n     * ```js\n     * ['one','two']\n     * ```\n     *\n     * which is vulnerable to attack, your server can return:\n     * ```js\n     * )]}',\n     * ['one','two']\n     * ```\n     *\n     * Angular will strip the prefix, before processing the JSON.\n     *\n     *\n     * ### Cross Site Request Forgery (XSRF) Protection\n     *\n     * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which\n     * an unauthorized site can gain your user's private data. Angular provides a mechanism\n     * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie\n     * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only\n     * JavaScript that runs on your domain could read the cookie, your server can be assured that\n     * the XHR came from JavaScript running on your domain. The header will not be set for\n     * cross-domain requests.\n     *\n     * To take advantage of this, your server needs to set a token in a JavaScript readable session\n     * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the\n     * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure\n     * that only JavaScript running on your domain could have sent the request. The token must be\n     * unique for each user and must be verifiable by the server (to prevent the JavaScript from\n     * making up its own tokens). We recommend that the token is a digest of your site's\n     * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)\n     * for added security.\n     *\n     * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName\n     * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,\n     * or the per-request config object.\n     *\n     * In order to prevent collisions in environments where multiple Angular apps share the\n     * same domain or subdomain, we recommend that each application uses unique cookie name.\n     *\n     * @param {object} config Object describing the request to be made and how it should be\n     *    processed. The object has following properties:\n     *\n     *    - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)\n     *    - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.\n     *    - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized\n     *      with the `paramSerializer` and appended as GET parameters.\n     *    - **data** – `{string|Object}` – Data to be sent as the request message data.\n     *    - **headers** – `{Object}` – Map of strings or functions which return strings representing\n     *      HTTP headers to send to the server. If the return value of a function is null, the\n     *      header will not be sent. Functions accept a config object as an argument.\n     *    - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.\n     *    - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.\n     *    - **transformRequest** –\n     *      `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      request body and headers and returns its transformed (typically serialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default Transformations}\n     *    - **transformResponse** –\n     *      `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –\n     *      transform function or an array of such functions. The transform function takes the http\n     *      response body, headers and status and returns its transformed (typically deserialized) version.\n     *      See {@link ng.$http#overriding-the-default-transformations-per-request\n     *      Overriding the Default TransformationjqLiks}\n     *    - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to\n     *      prepare the string representation of request parameters (specified as an object).\n     *      If specified as string, it is interpreted as function registered with the\n     *      {@link $injector $injector}, which means you can create your own serializer\n     *      by registering it as a {@link auto.$provide#service service}.\n     *      The default serializer is the {@link $httpParamSerializer $httpParamSerializer};\n     *      alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}\n     *    - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the\n     *      GET request, otherwise if a cache instance built with\n     *      {@link ng.$cacheFactory $cacheFactory}, this cache will be used for\n     *      caching.\n     *    - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}\n     *      that should abort the request when resolved.\n     *    - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the\n     *      XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)\n     *      for more information.\n     *    - **responseType** - `{string}` - see\n     *      [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).\n     *\n     * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object\n     *                        when the request succeeds or fails.\n     *\n     *\n     * @property {Array.<Object>} pendingRequests Array of config objects for currently pending\n     *   requests. This is primarily meant to be used for debugging purposes.\n     *\n     *\n     * @example\n<example module=\"httpExample\">\n<file name=\"index.html\">\n  <div ng-controller=\"FetchController\">\n    <select ng-model=\"method\" aria-label=\"Request method\">\n      <option>GET</option>\n      <option>JSONP</option>\n    </select>\n    <input type=\"text\" ng-model=\"url\" size=\"80\" aria-label=\"URL\" />\n    <button id=\"fetchbtn\" ng-click=\"fetch()\">fetch</button><br>\n    <button id=\"samplegetbtn\" ng-click=\"updateModel('GET', 'http-hello.html')\">Sample GET</button>\n    <button id=\"samplejsonpbtn\"\n      ng-click=\"updateModel('JSONP',\n                    'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')\">\n      Sample JSONP\n    </button>\n    <button id=\"invalidjsonpbtn\"\n      ng-click=\"updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')\">\n        Invalid JSONP\n      </button>\n    <pre>http status code: {{status}}</pre>\n    <pre>http response data: {{data}}</pre>\n  </div>\n</file>\n<file name=\"script.js\">\n  angular.module('httpExample', [])\n    .controller('FetchController', ['$scope', '$http', '$templateCache',\n      function($scope, $http, $templateCache) {\n        $scope.method = 'GET';\n        $scope.url = 'http-hello.html';\n\n        $scope.fetch = function() {\n          $scope.code = null;\n          $scope.response = null;\n\n          $http({method: $scope.method, url: $scope.url, cache: $templateCache}).\n            then(function(response) {\n              $scope.status = response.status;\n              $scope.data = response.data;\n            }, function(response) {\n              $scope.data = response.data || \"Request failed\";\n              $scope.status = response.status;\n          });\n        };\n\n        $scope.updateModel = function(method, url) {\n          $scope.method = method;\n          $scope.url = url;\n        };\n      }]);\n</file>\n<file name=\"http-hello.html\">\n  Hello, $http!\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  var status = element(by.binding('status'));\n  var data = element(by.binding('data'));\n  var fetchBtn = element(by.id('fetchbtn'));\n  var sampleGetBtn = element(by.id('samplegetbtn'));\n  var sampleJsonpBtn = element(by.id('samplejsonpbtn'));\n  var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));\n\n  it('should make an xhr GET request', function() {\n    sampleGetBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('200');\n    expect(data.getText()).toMatch(/Hello, \\$http!/);\n  });\n\n// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185\n// it('should make a JSONP request to angularjs.org', function() {\n//   sampleJsonpBtn.click();\n//   fetchBtn.click();\n//   expect(status.getText()).toMatch('200');\n//   expect(data.getText()).toMatch(/Super Hero!/);\n// });\n\n  it('should make JSONP request to invalid URL and invoke the error handler',\n      function() {\n    invalidJsonpBtn.click();\n    fetchBtn.click();\n    expect(status.getText()).toMatch('0');\n    expect(data.getText()).toMatch('Request failed');\n  });\n</file>\n</example>\n     */\n    function $http(requestConfig) {\n\n      if (!angular.isObject(requestConfig)) {\n        throw minErr('$http')('badreq', 'Http request configuration must be an object.  Received: {0}', requestConfig);\n      }\n\n      var config = extend({\n        method: 'get',\n        transformRequest: defaults.transformRequest,\n        transformResponse: defaults.transformResponse,\n        paramSerializer: defaults.paramSerializer\n      }, requestConfig);\n\n      config.headers = mergeHeaders(requestConfig);\n      config.method = uppercase(config.method);\n      config.paramSerializer = isString(config.paramSerializer) ?\n        $injector.get(config.paramSerializer) : config.paramSerializer;\n\n      var serverRequest = function(config) {\n        var headers = config.headers;\n        var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);\n\n        // strip content-type if data is undefined\n        if (isUndefined(reqData)) {\n          forEach(headers, function(value, header) {\n            if (lowercase(header) === 'content-type') {\n                delete headers[header];\n            }\n          });\n        }\n\n        if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {\n          config.withCredentials = defaults.withCredentials;\n        }\n\n        // send request\n        return sendReq(config, reqData).then(transformResponse, transformResponse);\n      };\n\n      var chain = [serverRequest, undefined];\n      var promise = $q.when(config);\n\n      // apply interceptors\n      forEach(reversedInterceptors, function(interceptor) {\n        if (interceptor.request || interceptor.requestError) {\n          chain.unshift(interceptor.request, interceptor.requestError);\n        }\n        if (interceptor.response || interceptor.responseError) {\n          chain.push(interceptor.response, interceptor.responseError);\n        }\n      });\n\n      while (chain.length) {\n        var thenFn = chain.shift();\n        var rejectFn = chain.shift();\n\n        promise = promise.then(thenFn, rejectFn);\n      }\n\n      if (useLegacyPromise) {\n        promise.success = function(fn) {\n          assertArgFn(fn, 'fn');\n\n          promise.then(function(response) {\n            fn(response.data, response.status, response.headers, config);\n          });\n          return promise;\n        };\n\n        promise.error = function(fn) {\n          assertArgFn(fn, 'fn');\n\n          promise.then(null, function(response) {\n            fn(response.data, response.status, response.headers, config);\n          });\n          return promise;\n        };\n      } else {\n        promise.success = $httpMinErrLegacyFn('success');\n        promise.error = $httpMinErrLegacyFn('error');\n      }\n\n      return promise;\n\n      function transformResponse(response) {\n        // make a copy since the response must be cacheable\n        var resp = extend({}, response);\n        if (!response.data) {\n          resp.data = response.data;\n        } else {\n          resp.data = transformData(response.data, response.headers, response.status, config.transformResponse);\n        }\n        return (isSuccess(response.status))\n          ? resp\n          : $q.reject(resp);\n      }\n\n      function executeHeaderFns(headers, config) {\n        var headerContent, processedHeaders = {};\n\n        forEach(headers, function(headerFn, header) {\n          if (isFunction(headerFn)) {\n            headerContent = headerFn(config);\n            if (headerContent != null) {\n              processedHeaders[header] = headerContent;\n            }\n          } else {\n            processedHeaders[header] = headerFn;\n          }\n        });\n\n        return processedHeaders;\n      }\n\n      function mergeHeaders(config) {\n        var defHeaders = defaults.headers,\n            reqHeaders = extend({}, config.headers),\n            defHeaderName, lowercaseDefHeaderName, reqHeaderName;\n\n        defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);\n\n        // using for-in instead of forEach to avoid unecessary iteration after header has been found\n        defaultHeadersIteration:\n        for (defHeaderName in defHeaders) {\n          lowercaseDefHeaderName = lowercase(defHeaderName);\n\n          for (reqHeaderName in reqHeaders) {\n            if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {\n              continue defaultHeadersIteration;\n            }\n          }\n\n          reqHeaders[defHeaderName] = defHeaders[defHeaderName];\n        }\n\n        // execute if header value is a function for merged headers\n        return executeHeaderFns(reqHeaders, shallowCopy(config));\n      }\n    }\n\n    $http.pendingRequests = [];\n\n    /**\n     * @ngdoc method\n     * @name $http#get\n     *\n     * @description\n     * Shortcut method to perform `GET` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#delete\n     *\n     * @description\n     * Shortcut method to perform `DELETE` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#head\n     *\n     * @description\n     * Shortcut method to perform `HEAD` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#jsonp\n     *\n     * @description\n     * Shortcut method to perform `JSONP` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request.\n     *                     The name of the callback should be the string `JSON_CALLBACK`.\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n    createShortMethods('get', 'delete', 'head', 'jsonp');\n\n    /**\n     * @ngdoc method\n     * @name $http#post\n     *\n     * @description\n     * Shortcut method to perform `POST` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n    /**\n     * @ngdoc method\n     * @name $http#put\n     *\n     * @description\n     * Shortcut method to perform `PUT` request.\n     *\n     * @param {string} url Relative or absolute URL specifying the destination of the request\n     * @param {*} data Request content\n     * @param {Object=} config Optional configuration object\n     * @returns {HttpPromise} Future object\n     */\n\n     /**\n      * @ngdoc method\n      * @name $http#patch\n      *\n      * @description\n      * Shortcut method to perform `PATCH` request.\n      *\n      * @param {string} url Relative or absolute URL specifying the destination of the request\n      * @param {*} data Request content\n      * @param {Object=} config Optional configuration object\n      * @returns {HttpPromise} Future object\n      */\n    createShortMethodsWithData('post', 'put', 'patch');\n\n        /**\n         * @ngdoc property\n         * @name $http#defaults\n         *\n         * @description\n         * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of\n         * default headers, withCredentials as well as request and response transformations.\n         *\n         * See \"Setting HTTP Headers\" and \"Transforming Requests and Responses\" sections above.\n         */\n    $http.defaults = defaults;\n\n\n    return $http;\n\n\n    function createShortMethods(names) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, config) {\n          return $http(extend({}, config || {}, {\n            method: name,\n            url: url\n          }));\n        };\n      });\n    }\n\n\n    function createShortMethodsWithData(name) {\n      forEach(arguments, function(name) {\n        $http[name] = function(url, data, config) {\n          return $http(extend({}, config || {}, {\n            method: name,\n            url: url,\n            data: data\n          }));\n        };\n      });\n    }\n\n\n    /**\n     * Makes the request.\n     *\n     * !!! ACCESSES CLOSURE VARS:\n     * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests\n     */\n    function sendReq(config, reqData) {\n      var deferred = $q.defer(),\n          promise = deferred.promise,\n          cache,\n          cachedResp,\n          reqHeaders = config.headers,\n          url = buildUrl(config.url, config.paramSerializer(config.params));\n\n      $http.pendingRequests.push(config);\n      promise.then(removePendingReq, removePendingReq);\n\n\n      if ((config.cache || defaults.cache) && config.cache !== false &&\n          (config.method === 'GET' || config.method === 'JSONP')) {\n        cache = isObject(config.cache) ? config.cache\n              : isObject(defaults.cache) ? defaults.cache\n              : defaultCache;\n      }\n\n      if (cache) {\n        cachedResp = cache.get(url);\n        if (isDefined(cachedResp)) {\n          if (isPromiseLike(cachedResp)) {\n            // cached request has already been sent, but there is no response yet\n            cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);\n          } else {\n            // serving from cache\n            if (isArray(cachedResp)) {\n              resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);\n            } else {\n              resolvePromise(cachedResp, 200, {}, 'OK');\n            }\n          }\n        } else {\n          // put the promise for the non-transformed response into cache as a placeholder\n          cache.put(url, promise);\n        }\n      }\n\n\n      // if we won't have the response in cache, set the xsrf headers and\n      // send the request to the backend\n      if (isUndefined(cachedResp)) {\n        var xsrfValue = urlIsSameOrigin(config.url)\n            ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]\n            : undefined;\n        if (xsrfValue) {\n          reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;\n        }\n\n        $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,\n            config.withCredentials, config.responseType);\n      }\n\n      return promise;\n\n\n      /**\n       * Callback registered to $httpBackend():\n       *  - caches the response if desired\n       *  - resolves the raw $http promise\n       *  - calls $apply\n       */\n      function done(status, response, headersString, statusText) {\n        if (cache) {\n          if (isSuccess(status)) {\n            cache.put(url, [status, response, parseHeaders(headersString), statusText]);\n          } else {\n            // remove promise from the cache\n            cache.remove(url);\n          }\n        }\n\n        function resolveHttpPromise() {\n          resolvePromise(response, status, headersString, statusText);\n        }\n\n        if (useApplyAsync) {\n          $rootScope.$applyAsync(resolveHttpPromise);\n        } else {\n          resolveHttpPromise();\n          if (!$rootScope.$$phase) $rootScope.$apply();\n        }\n      }\n\n\n      /**\n       * Resolves the raw $http promise.\n       */\n      function resolvePromise(response, status, headers, statusText) {\n        // normalize internal statuses to 0\n        status = Math.max(status, 0);\n\n        (isSuccess(status) ? deferred.resolve : deferred.reject)({\n          data: response,\n          status: status,\n          headers: headersGetter(headers),\n          config: config,\n          statusText: statusText\n        });\n      }\n\n      function resolvePromiseWithResult(result) {\n        resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);\n      }\n\n      function removePendingReq() {\n        var idx = $http.pendingRequests.indexOf(config);\n        if (idx !== -1) $http.pendingRequests.splice(idx, 1);\n      }\n    }\n\n\n    function buildUrl(url, serializedParams) {\n      if (serializedParams.length > 0) {\n        url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;\n      }\n      return url;\n    }\n  }];\n}\n\nfunction createXhr() {\n    return new window.XMLHttpRequest();\n}\n\n/**\n * @ngdoc service\n * @name $httpBackend\n * @requires $window\n * @requires $document\n *\n * @description\n * HTTP backend used by the {@link ng.$http service} that delegates to\n * XMLHttpRequest object or JSONP and deals with browser incompatibilities.\n *\n * You should never need to use this service directly, instead use the higher-level abstractions:\n * {@link ng.$http $http} or {@link ngResource.$resource $resource}.\n *\n * During testing this implementation is swapped with {@link ngMock.$httpBackend mock\n * $httpBackend} which can be trained with responses.\n */\nfunction $HttpBackendProvider() {\n  this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {\n    return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);\n  }];\n}\n\nfunction createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {\n  // TODO(vojta): fix the signature\n  return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {\n    $browser.$$incOutstandingRequestCount();\n    url = url || $browser.url();\n\n    if (lowercase(method) == 'jsonp') {\n      var callbackId = '_' + (callbacks.counter++).toString(36);\n      callbacks[callbackId] = function(data) {\n        callbacks[callbackId].data = data;\n        callbacks[callbackId].called = true;\n      };\n\n      var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),\n          callbackId, function(status, text) {\n        completeRequest(callback, status, callbacks[callbackId].data, \"\", text);\n        callbacks[callbackId] = noop;\n      });\n    } else {\n\n      var xhr = createXhr();\n\n      xhr.open(method, url, true);\n      forEach(headers, function(value, key) {\n        if (isDefined(value)) {\n            xhr.setRequestHeader(key, value);\n        }\n      });\n\n      xhr.onload = function requestLoaded() {\n        var statusText = xhr.statusText || '';\n\n        // responseText is the old-school way of retrieving response (supported by IE9)\n        // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)\n        var response = ('response' in xhr) ? xhr.response : xhr.responseText;\n\n        // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)\n        var status = xhr.status === 1223 ? 204 : xhr.status;\n\n        // fix status code when it is 0 (0 status is undocumented).\n        // Occurs when accessing file resources or on Android 4.1 stock browser\n        // while retrieving files from application cache.\n        if (status === 0) {\n          status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;\n        }\n\n        completeRequest(callback,\n            status,\n            response,\n            xhr.getAllResponseHeaders(),\n            statusText);\n      };\n\n      var requestError = function() {\n        // The response is always empty\n        // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error\n        completeRequest(callback, -1, null, null, '');\n      };\n\n      xhr.onerror = requestError;\n      xhr.onabort = requestError;\n\n      if (withCredentials) {\n        xhr.withCredentials = true;\n      }\n\n      if (responseType) {\n        try {\n          xhr.responseType = responseType;\n        } catch (e) {\n          // WebKit added support for the json responseType value on 09/03/2013\n          // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are\n          // known to throw when setting the value \"json\" as the response type. Other older\n          // browsers implementing the responseType\n          //\n          // The json response type can be ignored if not supported, because JSON payloads are\n          // parsed on the client-side regardless.\n          if (responseType !== 'json') {\n            throw e;\n          }\n        }\n      }\n\n      xhr.send(post);\n    }\n\n    if (timeout > 0) {\n      var timeoutId = $browserDefer(timeoutRequest, timeout);\n    } else if (isPromiseLike(timeout)) {\n      timeout.then(timeoutRequest);\n    }\n\n\n    function timeoutRequest() {\n      jsonpDone && jsonpDone();\n      xhr && xhr.abort();\n    }\n\n    function completeRequest(callback, status, response, headersString, statusText) {\n      // cancel timeout and subsequent timeout promise resolution\n      if (timeoutId !== undefined) {\n        $browserDefer.cancel(timeoutId);\n      }\n      jsonpDone = xhr = null;\n\n      callback(status, response, headersString, statusText);\n      $browser.$$completeOutstandingRequest(noop);\n    }\n  };\n\n  function jsonpReq(url, callbackId, done) {\n    // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:\n    // - fetches local scripts via XHR and evals them\n    // - adds and immediately removes script elements from the document\n    var script = rawDocument.createElement('script'), callback = null;\n    script.type = \"text/javascript\";\n    script.src = url;\n    script.async = true;\n\n    callback = function(event) {\n      removeEventListenerFn(script, \"load\", callback);\n      removeEventListenerFn(script, \"error\", callback);\n      rawDocument.body.removeChild(script);\n      script = null;\n      var status = -1;\n      var text = \"unknown\";\n\n      if (event) {\n        if (event.type === \"load\" && !callbacks[callbackId].called) {\n          event = { type: \"error\" };\n        }\n        text = event.type;\n        status = event.type === \"error\" ? 404 : 200;\n      }\n\n      if (done) {\n        done(status, text);\n      }\n    };\n\n    addEventListenerFn(script, \"load\", callback);\n    addEventListenerFn(script, \"error\", callback);\n    rawDocument.body.appendChild(script);\n    return callback;\n  }\n}\n\nvar $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');\n$interpolateMinErr.throwNoconcat = function(text) {\n  throw $interpolateMinErr('noconcat',\n      \"Error while interpolating: {0}\\nStrict Contextual Escaping disallows \" +\n      \"interpolations that concatenate multiple expressions when a trusted value is \" +\n      \"required.  See http://docs.angularjs.org/api/ng.$sce\", text);\n};\n\n$interpolateMinErr.interr = function(text, err) {\n  return $interpolateMinErr('interr', \"Can't interpolate: {0}\\n{1}\", text, err.toString());\n};\n\n/**\n * @ngdoc provider\n * @name $interpolateProvider\n *\n * @description\n *\n * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.\n *\n * @example\n<example module=\"customInterpolationApp\">\n<file name=\"index.html\">\n<script>\n  var customInterpolationApp = angular.module('customInterpolationApp', []);\n\n  customInterpolationApp.config(function($interpolateProvider) {\n    $interpolateProvider.startSymbol('//');\n    $interpolateProvider.endSymbol('//');\n  });\n\n\n  customInterpolationApp.controller('DemoController', function() {\n      this.label = \"This binding is brought you by // interpolation symbols.\";\n  });\n</script>\n<div ng-app=\"App\" ng-controller=\"DemoController as demo\">\n    //demo.label//\n</div>\n</file>\n<file name=\"protractor.js\" type=\"protractor\">\n  it('should interpolate binding with custom symbols', function() {\n    expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');\n  });\n</file>\n</example>\n */\nfunction $InterpolateProvider() {\n  var startSymbol = '{{';\n  var endSymbol = '}}';\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#startSymbol\n   * @description\n   * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.\n   *\n   * @param {string=} value new value to set the starting symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.startSymbol = function(value) {\n    if (value) {\n      startSymbol = value;\n      return this;\n    } else {\n      return startSymbol;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $interpolateProvider#endSymbol\n   * @description\n   * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n   *\n   * @param {string=} value new value to set the ending symbol to.\n   * @returns {string|self} Returns the symbol when used as getter and self if used as setter.\n   */\n  this.endSymbol = function(value) {\n    if (value) {\n      endSymbol = value;\n      return this;\n    } else {\n      return endSymbol;\n    }\n  };\n\n\n  this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {\n    var startSymbolLength = startSymbol.length,\n        endSymbolLength = endSymbol.length,\n        escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),\n        escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');\n\n    function escape(ch) {\n      return '\\\\\\\\\\\\' + ch;\n    }\n\n    function unescapeText(text) {\n      return text.replace(escapedStartRegexp, startSymbol).\n        replace(escapedEndRegexp, endSymbol);\n    }\n\n    function stringify(value) {\n      if (value == null) { // null || undefined\n        return '';\n      }\n      switch (typeof value) {\n        case 'string':\n          break;\n        case 'number':\n          value = '' + value;\n          break;\n        default:\n          value = toJson(value);\n      }\n\n      return value;\n    }\n\n    /**\n     * @ngdoc service\n     * @name $interpolate\n     * @kind function\n     *\n     * @requires $parse\n     * @requires $sce\n     *\n     * @description\n     *\n     * Compiles a string with markup into an interpolation function. This service is used by the\n     * HTML {@link ng.$compile $compile} service for data binding. See\n     * {@link ng.$interpolateProvider $interpolateProvider} for configuring the\n     * interpolation markup.\n     *\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var exp = $interpolate('Hello {{name | uppercase}}!');\n     *   expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');\n     * ```\n     *\n     * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is\n     * `true`, the interpolation function will return `undefined` unless all embedded expressions\n     * evaluate to a value other than `undefined`.\n     *\n     * ```js\n     *   var $interpolate = ...; // injected\n     *   var context = {greeting: 'Hello', name: undefined };\n     *\n     *   // default \"forgiving\" mode\n     *   var exp = $interpolate('{{greeting}} {{name}}!');\n     *   expect(exp(context)).toEqual('Hello !');\n     *\n     *   // \"allOrNothing\" mode\n     *   exp = $interpolate('{{greeting}} {{name}}!', false, null, true);\n     *   expect(exp(context)).toBeUndefined();\n     *   context.name = 'Angular';\n     *   expect(exp(context)).toEqual('Hello Angular!');\n     * ```\n     *\n     * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.\n     *\n     * ####Escaped Interpolation\n     * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers\n     * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).\n     * It will be rendered as a regular start/end marker, and will not be interpreted as an expression\n     * or binding.\n     *\n     * This enables web-servers to prevent script injection attacks and defacing attacks, to some\n     * degree, while also enabling code examples to work without relying on the\n     * {@link ng.directive:ngNonBindable ngNonBindable} directive.\n     *\n     * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,\n     * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all\n     * interpolation start/end markers with their escaped counterparts.**\n     *\n     * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered\n     * output when the $interpolate service processes the text. So, for HTML elements interpolated\n     * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter\n     * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,\n     * this is typically useful only when user-data is used in rendering a template from the server, or\n     * when otherwise untrusted data is used by a directive.\n     *\n     * <example>\n     *  <file name=\"index.html\">\n     *    <div ng-init=\"username='A user'\">\n     *      <p ng-init=\"apptitle='Escaping demo'\">{{apptitle}}: \\{\\{ username = \"defaced value\"; \\}\\}\n     *        </p>\n     *      <p><strong>{{username}}</strong> attempts to inject code which will deface the\n     *        application, but fails to accomplish their task, because the server has correctly\n     *        escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)\n     *        characters.</p>\n     *      <p>Instead, the result of the attempted script injection is visible, and can be removed\n     *        from the database by an administrator.</p>\n     *    </div>\n     *  </file>\n     * </example>\n     *\n     * @param {string} text The text with markup to interpolate.\n     * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have\n     *    embedded expression in order to return an interpolation function. Strings with no\n     *    embedded expression will return null for the interpolation function.\n     * @param {string=} trustedContext when provided, the returned function passes the interpolated\n     *    result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,\n     *    trustedContext)} before returning it.  Refer to the {@link ng.$sce $sce} service that\n     *    provides Strict Contextual Escaping for details.\n     * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined\n     *    unless all embedded expressions evaluate to a value other than `undefined`.\n     * @returns {function(context)} an interpolation function which is used to compute the\n     *    interpolated string. The function has these parameters:\n     *\n     * - `context`: evaluation context for all expressions embedded in the interpolated text\n     */\n    function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {\n      allOrNothing = !!allOrNothing;\n      var startIndex,\n          endIndex,\n          index = 0,\n          expressions = [],\n          parseFns = [],\n          textLength = text.length,\n          exp,\n          concat = [],\n          expressionPositions = [];\n\n      while (index < textLength) {\n        if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&\n             ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {\n          if (index !== startIndex) {\n            concat.push(unescapeText(text.substring(index, startIndex)));\n          }\n          exp = text.substring(startIndex + startSymbolLength, endIndex);\n          expressions.push(exp);\n          parseFns.push($parse(exp, parseStringifyInterceptor));\n          index = endIndex + endSymbolLength;\n          expressionPositions.push(concat.length);\n          concat.push('');\n        } else {\n          // we did not find an interpolation, so we have to add the remainder to the separators array\n          if (index !== textLength) {\n            concat.push(unescapeText(text.substring(index)));\n          }\n          break;\n        }\n      }\n\n      // Concatenating expressions makes it hard to reason about whether some combination of\n      // concatenated values are unsafe to use and could easily lead to XSS.  By requiring that a\n      // single expression be used for iframe[src], object[src], etc., we ensure that the value\n      // that's used is assigned or constructed by some JS code somewhere that is more testable or\n      // make it obvious that you bound the value to some user controlled value.  This helps reduce\n      // the load when auditing for XSS issues.\n      if (trustedContext && concat.length > 1) {\n          $interpolateMinErr.throwNoconcat(text);\n      }\n\n      if (!mustHaveExpression || expressions.length) {\n        var compute = function(values) {\n          for (var i = 0, ii = expressions.length; i < ii; i++) {\n            if (allOrNothing && isUndefined(values[i])) return;\n            concat[expressionPositions[i]] = values[i];\n          }\n          return concat.join('');\n        };\n\n        var getValue = function(value) {\n          return trustedContext ?\n            $sce.getTrusted(trustedContext, value) :\n            $sce.valueOf(value);\n        };\n\n        return extend(function interpolationFn(context) {\n            var i = 0;\n            var ii = expressions.length;\n            var values = new Array(ii);\n\n            try {\n              for (; i < ii; i++) {\n                values[i] = parseFns[i](context);\n              }\n\n              return compute(values);\n            } catch (err) {\n              $exceptionHandler($interpolateMinErr.interr(text, err));\n            }\n\n          }, {\n          // all of these properties are undocumented for now\n          exp: text, //just for compatibility with regular watchers created via $watch\n          expressions: expressions,\n          $$watchDelegate: function(scope, listener) {\n            var lastValue;\n            return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {\n              var currValue = compute(values);\n              if (isFunction(listener)) {\n                listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);\n              }\n              lastValue = currValue;\n            });\n          }\n        });\n      }\n\n      function parseStringifyInterceptor(value) {\n        try {\n          value = getValue(value);\n          return allOrNothing && !isDefined(value) ? value : stringify(value);\n        } catch (err) {\n          $exceptionHandler($interpolateMinErr.interr(text, err));\n        }\n      }\n    }\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#startSymbol\n     * @description\n     * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.\n     *\n     * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} start symbol.\n     */\n    $interpolate.startSymbol = function() {\n      return startSymbol;\n    };\n\n\n    /**\n     * @ngdoc method\n     * @name $interpolate#endSymbol\n     * @description\n     * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.\n     *\n     * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change\n     * the symbol.\n     *\n     * @returns {string} end symbol.\n     */\n    $interpolate.endSymbol = function() {\n      return endSymbol;\n    };\n\n    return $interpolate;\n  }];\n}\n\nfunction $IntervalProvider() {\n  this.$get = ['$rootScope', '$window', '$q', '$$q',\n       function($rootScope,   $window,   $q,   $$q) {\n    var intervals = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $interval\n      *\n      * @description\n      * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`\n      * milliseconds.\n      *\n      * The return value of registering an interval function is a promise. This promise will be\n      * notified upon each tick of the interval, and will be resolved after `count` iterations, or\n      * run indefinitely if `count` is not defined. The value of the notification will be the\n      * number of iterations that have run.\n      * To cancel an interval, call `$interval.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to\n      * move forward by `millis` milliseconds and trigger any functions scheduled to run in that\n      * time.\n      *\n      * <div class=\"alert alert-warning\">\n      * **Note**: Intervals created by this service must be explicitly destroyed when you are finished\n      * with them.  In particular they are not automatically destroyed when a controller's scope or a\n      * directive's element are destroyed.\n      * You should take this into consideration and make sure to always cancel the interval at the\n      * appropriate moment.  See the example below for more details on how and when to do this.\n      * </div>\n      *\n      * @param {function()} fn A function that should be called repeatedly.\n      * @param {number} delay Number of milliseconds between each function call.\n      * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat\n      *   indefinitely.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @param {...*=} Pass additional parameters to the executed function.\n      * @returns {promise} A promise which will be notified on each iteration.\n      *\n      * @example\n      * <example module=\"intervalExample\">\n      * <file name=\"index.html\">\n      *   <script>\n      *     angular.module('intervalExample', [])\n      *       .controller('ExampleController', ['$scope', '$interval',\n      *         function($scope, $interval) {\n      *           $scope.format = 'M/d/yy h:mm:ss a';\n      *           $scope.blood_1 = 100;\n      *           $scope.blood_2 = 120;\n      *\n      *           var stop;\n      *           $scope.fight = function() {\n      *             // Don't start a new fight if we are already fighting\n      *             if ( angular.isDefined(stop) ) return;\n      *\n      *             stop = $interval(function() {\n      *               if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {\n      *                 $scope.blood_1 = $scope.blood_1 - 3;\n      *                 $scope.blood_2 = $scope.blood_2 - 4;\n      *               } else {\n      *                 $scope.stopFight();\n      *               }\n      *             }, 100);\n      *           };\n      *\n      *           $scope.stopFight = function() {\n      *             if (angular.isDefined(stop)) {\n      *               $interval.cancel(stop);\n      *               stop = undefined;\n      *             }\n      *           };\n      *\n      *           $scope.resetFight = function() {\n      *             $scope.blood_1 = 100;\n      *             $scope.blood_2 = 120;\n      *           };\n      *\n      *           $scope.$on('$destroy', function() {\n      *             // Make sure that the interval is destroyed too\n      *             $scope.stopFight();\n      *           });\n      *         }])\n      *       // Register the 'myCurrentTime' directive factory method.\n      *       // We inject $interval and dateFilter service since the factory method is DI.\n      *       .directive('myCurrentTime', ['$interval', 'dateFilter',\n      *         function($interval, dateFilter) {\n      *           // return the directive link function. (compile function not needed)\n      *           return function(scope, element, attrs) {\n      *             var format,  // date format\n      *                 stopTime; // so that we can cancel the time updates\n      *\n      *             // used to update the UI\n      *             function updateTime() {\n      *               element.text(dateFilter(new Date(), format));\n      *             }\n      *\n      *             // watch the expression, and update the UI on change.\n      *             scope.$watch(attrs.myCurrentTime, function(value) {\n      *               format = value;\n      *               updateTime();\n      *             });\n      *\n      *             stopTime = $interval(updateTime, 1000);\n      *\n      *             // listen on DOM destroy (removal) event, and cancel the next UI update\n      *             // to prevent updating time after the DOM element was removed.\n      *             element.on('$destroy', function() {\n      *               $interval.cancel(stopTime);\n      *             });\n      *           }\n      *         }]);\n      *   </script>\n      *\n      *   <div>\n      *     <div ng-controller=\"ExampleController\">\n      *       <label>Date format: <input ng-model=\"format\"></label> <hr/>\n      *       Current time is: <span my-current-time=\"format\"></span>\n      *       <hr/>\n      *       Blood 1 : <font color='red'>{{blood_1}}</font>\n      *       Blood 2 : <font color='red'>{{blood_2}}</font>\n      *       <button type=\"button\" data-ng-click=\"fight()\">Fight</button>\n      *       <button type=\"button\" data-ng-click=\"stopFight()\">StopFight</button>\n      *       <button type=\"button\" data-ng-click=\"resetFight()\">resetFight</button>\n      *     </div>\n      *   </div>\n      *\n      * </file>\n      * </example>\n      */\n    function interval(fn, delay, count, invokeApply) {\n      var hasParams = arguments.length > 4,\n          args = hasParams ? sliceArgs(arguments, 4) : [],\n          setInterval = $window.setInterval,\n          clearInterval = $window.clearInterval,\n          iteration = 0,\n          skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise;\n\n      count = isDefined(count) ? count : 0;\n\n      promise.then(null, null, (!hasParams) ? fn : function() {\n        fn.apply(null, args);\n      });\n\n      promise.$$intervalId = setInterval(function tick() {\n        deferred.notify(iteration++);\n\n        if (count > 0 && iteration >= count) {\n          deferred.resolve(iteration);\n          clearInterval(promise.$$intervalId);\n          delete intervals[promise.$$intervalId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n\n      }, delay);\n\n      intervals[promise.$$intervalId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $interval#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`.\n      *\n      * @param {Promise=} promise returned by the `$interval` function.\n      * @returns {boolean} Returns `true` if the task was successfully canceled.\n      */\n    interval.cancel = function(promise) {\n      if (promise && promise.$$intervalId in intervals) {\n        intervals[promise.$$intervalId].reject('canceled');\n        $window.clearInterval(promise.$$intervalId);\n        delete intervals[promise.$$intervalId];\n        return true;\n      }\n      return false;\n    };\n\n    return interval;\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $locale\n *\n * @description\n * $locale service provides localization rules for various Angular components. As of right now the\n * only public api is:\n *\n * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)\n */\n\nvar PATH_MATCH = /^([^\\?#]*)(\\?([^#]*))?(#(.*))?$/,\n    DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};\nvar $locationMinErr = minErr('$location');\n\n\n/**\n * Encode path using encodeUriSegment, ignoring forward slashes\n *\n * @param {string} path Path to encode\n * @returns {string}\n */\nfunction encodePath(path) {\n  var segments = path.split('/'),\n      i = segments.length;\n\n  while (i--) {\n    segments[i] = encodeUriSegment(segments[i]);\n  }\n\n  return segments.join('/');\n}\n\nfunction parseAbsoluteUrl(absoluteUrl, locationObj) {\n  var parsedUrl = urlResolve(absoluteUrl);\n\n  locationObj.$$protocol = parsedUrl.protocol;\n  locationObj.$$host = parsedUrl.hostname;\n  locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;\n}\n\n\nfunction parseAppUrl(relativeUrl, locationObj) {\n  var prefixed = (relativeUrl.charAt(0) !== '/');\n  if (prefixed) {\n    relativeUrl = '/' + relativeUrl;\n  }\n  var match = urlResolve(relativeUrl);\n  locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?\n      match.pathname.substring(1) : match.pathname);\n  locationObj.$$search = parseKeyValue(match.search);\n  locationObj.$$hash = decodeURIComponent(match.hash);\n\n  // make sure path starts with '/';\n  if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {\n    locationObj.$$path = '/' + locationObj.$$path;\n  }\n}\n\n\n/**\n *\n * @param {string} begin\n * @param {string} whole\n * @returns {string} returns text from whole after begin or undefined if it does not begin with\n *                   expected string.\n */\nfunction beginsWith(begin, whole) {\n  if (whole.indexOf(begin) === 0) {\n    return whole.substr(begin.length);\n  }\n}\n\n\nfunction stripHash(url) {\n  var index = url.indexOf('#');\n  return index == -1 ? url : url.substr(0, index);\n}\n\nfunction trimEmptyHash(url) {\n  return url.replace(/(#.+)|#$/, '$1');\n}\n\n\nfunction stripFile(url) {\n  return url.substr(0, stripHash(url).lastIndexOf('/') + 1);\n}\n\n/* return the server only (scheme://host:port) */\nfunction serverBase(url) {\n  return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));\n}\n\n\n/**\n * LocationHtml5Url represents an url\n * This object is exposed as $location service when HTML5 mode is enabled and supported\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} basePrefix url path prefix\n */\nfunction LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {\n  this.$$html5 = true;\n  basePrefix = basePrefix || '';\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given html5 (regular) url string into properties\n   * @param {string} url HTML5 url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var pathUrl = beginsWith(appBaseNoFile, url);\n    if (!isString(pathUrl)) {\n      throw $locationMinErr('ipthprfx', 'Invalid url \"{0}\", missing path prefix \"{1}\".', url,\n          appBaseNoFile);\n    }\n\n    parseAppUrl(pathUrl, this);\n\n    if (!this.$$path) {\n      this.$$path = '/';\n    }\n\n    this.$$compose();\n  };\n\n  /**\n   * Compose url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n    var appUrl, prevAppUrl;\n    var rewrittenUrl;\n\n    if ((appUrl = beginsWith(appBase, url)) !== undefined) {\n      prevAppUrl = appUrl;\n      if ((appUrl = beginsWith(basePrefix, appUrl)) !== undefined) {\n        rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);\n      } else {\n        rewrittenUrl = appBase + prevAppUrl;\n      }\n    } else if ((appUrl = beginsWith(appBaseNoFile, url)) !== undefined) {\n      rewrittenUrl = appBaseNoFile + appUrl;\n    } else if (appBaseNoFile == url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when developer doesn't opt into html5 mode.\n * It also serves as the base class for html5 mode fallback on legacy browsers.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {\n\n  parseAbsoluteUrl(appBase, this);\n\n\n  /**\n   * Parse given hashbang url into properties\n   * @param {string} url Hashbang url\n   * @private\n   */\n  this.$$parse = function(url) {\n    var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);\n    var withoutHashUrl;\n\n    if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {\n\n      // The rest of the url starts with a hash so we have\n      // got either a hashbang path or a plain hash fragment\n      withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);\n      if (isUndefined(withoutHashUrl)) {\n        // There was no hashbang prefix so we just have a hash fragment\n        withoutHashUrl = withoutBaseUrl;\n      }\n\n    } else {\n      // There was no hashbang path nor hash fragment:\n      // If we are in HTML5 mode we use what is left as the path;\n      // Otherwise we ignore what is left\n      if (this.$$html5) {\n        withoutHashUrl = withoutBaseUrl;\n      } else {\n        withoutHashUrl = '';\n        if (isUndefined(withoutBaseUrl)) {\n          appBase = url;\n          this.replace();\n        }\n      }\n    }\n\n    parseAppUrl(withoutHashUrl, this);\n\n    this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);\n\n    this.$$compose();\n\n    /*\n     * In Windows, on an anchor node on documents loaded from\n     * the filesystem, the browser will return a pathname\n     * prefixed with the drive name ('/C:/path') when a\n     * pathname without a drive is set:\n     *  * a.setAttribute('href', '/foo')\n     *   * a.pathname === '/C:/foo' //true\n     *\n     * Inside of Angular, we're always using pathnames that\n     * do not include drive names for routing.\n     */\n    function removeWindowsDriveName(path, url, base) {\n      /*\n      Matches paths for file protocol on windows,\n      such as /C:/foo/bar, and captures only /foo/bar.\n      */\n      var windowsFilePathExp = /^\\/[A-Z]:(\\/.*)/;\n\n      var firstPathSegmentMatch;\n\n      //Get the relative path from the input URL.\n      if (url.indexOf(base) === 0) {\n        url = url.replace(base, '');\n      }\n\n      // The input URL intentionally contains a first path segment that ends with a colon.\n      if (windowsFilePathExp.exec(url)) {\n        return path;\n      }\n\n      firstPathSegmentMatch = windowsFilePathExp.exec(path);\n      return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;\n    }\n  };\n\n  /**\n   * Compose hashbang url and update `absUrl` property\n   * @private\n   */\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');\n  };\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (stripHash(appBase) == stripHash(url)) {\n      this.$$parse(url);\n      return true;\n    }\n    return false;\n  };\n}\n\n\n/**\n * LocationHashbangUrl represents url\n * This object is exposed as $location service when html5 history api is enabled but the browser\n * does not support it.\n *\n * @constructor\n * @param {string} appBase application base URL\n * @param {string} appBaseNoFile application base URL stripped of any filename\n * @param {string} hashPrefix hashbang prefix\n */\nfunction LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {\n  this.$$html5 = true;\n  LocationHashbangUrl.apply(this, arguments);\n\n  this.$$parseLinkUrl = function(url, relHref) {\n    if (relHref && relHref[0] === '#') {\n      // special case for links to hash fragments:\n      // keep the old url and only replace the hash fragment\n      this.hash(relHref.slice(1));\n      return true;\n    }\n\n    var rewrittenUrl;\n    var appUrl;\n\n    if (appBase == stripHash(url)) {\n      rewrittenUrl = url;\n    } else if ((appUrl = beginsWith(appBaseNoFile, url))) {\n      rewrittenUrl = appBase + hashPrefix + appUrl;\n    } else if (appBaseNoFile === url + '/') {\n      rewrittenUrl = appBaseNoFile;\n    }\n    if (rewrittenUrl) {\n      this.$$parse(rewrittenUrl);\n    }\n    return !!rewrittenUrl;\n  };\n\n  this.$$compose = function() {\n    var search = toKeyValue(this.$$search),\n        hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';\n\n    this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;\n    // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'\n    this.$$absUrl = appBase + hashPrefix + this.$$url;\n  };\n\n}\n\n\nvar locationPrototype = {\n\n  /**\n   * Are we in html5 mode?\n   * @private\n   */\n  $$html5: false,\n\n  /**\n   * Has any change been replacing?\n   * @private\n   */\n  $$replace: false,\n\n  /**\n   * @ngdoc method\n   * @name $location#absUrl\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return full url representation with all segments encoded according to rules specified in\n   * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var absUrl = $location.absUrl();\n   * // => \"http://example.com/#/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @return {string} full url\n   */\n  absUrl: locationGetter('$$absUrl'),\n\n  /**\n   * @ngdoc method\n   * @name $location#url\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return url (e.g. `/path?a=b#hash`) when called without any parameter.\n   *\n   * Change path, search and hash, when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var url = $location.url();\n   * // => \"/some/path?foo=bar&baz=xoxo\"\n   * ```\n   *\n   * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)\n   * @return {string} url\n   */\n  url: function(url) {\n    if (isUndefined(url)) {\n      return this.$$url;\n    }\n\n    var match = PATH_MATCH.exec(url);\n    if (match[1] || url === '') this.path(decodeURIComponent(match[1]));\n    if (match[2] || match[1] || url === '') this.search(match[3] || '');\n    this.hash(match[5] || '');\n\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#protocol\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return protocol of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var protocol = $location.protocol();\n   * // => \"http\"\n   * ```\n   *\n   * @return {string} protocol of current url\n   */\n  protocol: locationGetter('$$protocol'),\n\n  /**\n   * @ngdoc method\n   * @name $location#host\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return host of current url.\n   *\n   * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var host = $location.host();\n   * // => \"example.com\"\n   *\n   * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo\n   * host = $location.host();\n   * // => \"example.com\"\n   * host = location.host;\n   * // => \"example.com:8080\"\n   * ```\n   *\n   * @return {string} host of current url.\n   */\n  host: locationGetter('$$host'),\n\n  /**\n   * @ngdoc method\n   * @name $location#port\n   *\n   * @description\n   * This method is getter only.\n   *\n   * Return port of current url.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var port = $location.port();\n   * // => 80\n   * ```\n   *\n   * @return {Number} port\n   */\n  port: locationGetter('$$port'),\n\n  /**\n   * @ngdoc method\n   * @name $location#path\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return path of current url when called without any parameter.\n   *\n   * Change path when called with parameter and return `$location`.\n   *\n   * Note: Path should always begin with forward slash (/), this method will add the forward slash\n   * if it is missing.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var path = $location.path();\n   * // => \"/some/path\"\n   * ```\n   *\n   * @param {(string|number)=} path New path\n   * @return {string} path\n   */\n  path: locationGetterSetter('$$path', function(path) {\n    path = path !== null ? path.toString() : '';\n    return path.charAt(0) == '/' ? path : '/' + path;\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#search\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return search part (as object) of current url when called without any parameter.\n   *\n   * Change search part when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo\n   * var searchObject = $location.search();\n   * // => {foo: 'bar', baz: 'xoxo'}\n   *\n   * // set foo to 'yipee'\n   * $location.search('foo', 'yipee');\n   * // $location.search() => {foo: 'yipee', baz: 'xoxo'}\n   * ```\n   *\n   * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or\n   * hash object.\n   *\n   * When called with a single argument the method acts as a setter, setting the `search` component\n   * of `$location` to the specified value.\n   *\n   * If the argument is a hash object containing an array of values, these values will be encoded\n   * as duplicate search parameters in the url.\n   *\n   * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`\n   * will override only a single search property.\n   *\n   * If `paramValue` is an array, it will override the property of the `search` component of\n   * `$location` specified via the first argument.\n   *\n   * If `paramValue` is `null`, the property specified via the first argument will be deleted.\n   *\n   * If `paramValue` is `true`, the property specified via the first argument will be added with no\n   * value nor trailing equal sign.\n   *\n   * @return {Object} If called with no arguments returns the parsed `search` object. If called with\n   * one or more arguments returns `$location` object itself.\n   */\n  search: function(search, paramValue) {\n    switch (arguments.length) {\n      case 0:\n        return this.$$search;\n      case 1:\n        if (isString(search) || isNumber(search)) {\n          search = search.toString();\n          this.$$search = parseKeyValue(search);\n        } else if (isObject(search)) {\n          search = copy(search, {});\n          // remove object undefined or null properties\n          forEach(search, function(value, key) {\n            if (value == null) delete search[key];\n          });\n\n          this.$$search = search;\n        } else {\n          throw $locationMinErr('isrcharg',\n              'The first argument of the `$location#search()` call must be a string or an object.');\n        }\n        break;\n      default:\n        if (isUndefined(paramValue) || paramValue === null) {\n          delete this.$$search[search];\n        } else {\n          this.$$search[search] = paramValue;\n        }\n    }\n\n    this.$$compose();\n    return this;\n  },\n\n  /**\n   * @ngdoc method\n   * @name $location#hash\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return hash fragment when called without any parameter.\n   *\n   * Change hash fragment when called with parameter and return `$location`.\n   *\n   *\n   * ```js\n   * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue\n   * var hash = $location.hash();\n   * // => \"hashValue\"\n   * ```\n   *\n   * @param {(string|number)=} hash New hash fragment\n   * @return {string} hash\n   */\n  hash: locationGetterSetter('$$hash', function(hash) {\n    return hash !== null ? hash.toString() : '';\n  }),\n\n  /**\n   * @ngdoc method\n   * @name $location#replace\n   *\n   * @description\n   * If called, all changes to $location during current `$digest` will be replacing current history\n   * record, instead of adding new one.\n   */\n  replace: function() {\n    this.$$replace = true;\n    return this;\n  }\n};\n\nforEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {\n  Location.prototype = Object.create(locationPrototype);\n\n  /**\n   * @ngdoc method\n   * @name $location#state\n   *\n   * @description\n   * This method is getter / setter.\n   *\n   * Return the history state object when called without any parameter.\n   *\n   * Change the history state object when called with one parameter and return `$location`.\n   * The state object is later passed to `pushState` or `replaceState`.\n   *\n   * NOTE: This method is supported only in HTML5 mode and only in browsers supporting\n   * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support\n   * older browsers (like IE9 or Android < 4.0), don't use this method.\n   *\n   * @param {object=} state State object for pushState or replaceState\n   * @return {object} state\n   */\n  Location.prototype.state = function(state) {\n    if (!arguments.length) {\n      return this.$$state;\n    }\n\n    if (Location !== LocationHtml5Url || !this.$$html5) {\n      throw $locationMinErr('nostate', 'History API state support is available only ' +\n        'in HTML5 mode and only in browsers supporting HTML5 History API');\n    }\n    // The user might modify `stateObject` after invoking `$location.state(stateObject)`\n    // but we're changing the $$state reference to $browser.state() during the $digest\n    // so the modification window is narrow.\n    this.$$state = isUndefined(state) ? null : state;\n\n    return this;\n  };\n});\n\n\nfunction locationGetter(property) {\n  return function() {\n    return this[property];\n  };\n}\n\n\nfunction locationGetterSetter(property, preprocess) {\n  return function(value) {\n    if (isUndefined(value)) {\n      return this[property];\n    }\n\n    this[property] = preprocess(value);\n    this.$$compose();\n\n    return this;\n  };\n}\n\n\n/**\n * @ngdoc service\n * @name $location\n *\n * @requires $rootElement\n *\n * @description\n * The $location service parses the URL in the browser address bar (based on the\n * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL\n * available to your application. Changes to the URL in the address bar are reflected into\n * $location service and changes to $location are reflected into the browser address bar.\n *\n * **The $location service:**\n *\n * - Exposes the current URL in the browser address bar, so you can\n *   - Watch and observe the URL.\n *   - Change the URL.\n * - Synchronizes the URL with the browser when the user\n *   - Changes the address bar.\n *   - Clicks the back or forward button (or clicks a History link).\n *   - Clicks on a link.\n * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).\n *\n * For more information see {@link guide/$location Developer Guide: Using $location}\n */\n\n/**\n * @ngdoc provider\n * @name $locationProvider\n * @description\n * Use the `$locationProvider` to configure how the application deep linking paths are stored.\n */\nfunction $LocationProvider() {\n  var hashPrefix = '',\n      html5Mode = {\n        enabled: false,\n        requireBase: true,\n        rewriteLinks: true\n      };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#hashPrefix\n   * @description\n   * @param {string=} prefix Prefix for hash part (containing path and search)\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.hashPrefix = function(prefix) {\n    if (isDefined(prefix)) {\n      hashPrefix = prefix;\n      return this;\n    } else {\n      return hashPrefix;\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $locationProvider#html5Mode\n   * @description\n   * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.\n   *   If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported\n   *   properties:\n   *   - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to\n   *     change urls where supported. Will fall back to hash-prefixed paths in browsers that do not\n   *     support `pushState`.\n   *   - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies\n   *     whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are\n   *     true, and a base tag is not present, an error will be thrown when `$location` is injected.\n   *     See the {@link guide/$location $location guide for more information}\n   *   - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,\n   *     enables/disables url rewriting for relative links.\n   *\n   * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter\n   */\n  this.html5Mode = function(mode) {\n    if (isBoolean(mode)) {\n      html5Mode.enabled = mode;\n      return this;\n    } else if (isObject(mode)) {\n\n      if (isBoolean(mode.enabled)) {\n        html5Mode.enabled = mode.enabled;\n      }\n\n      if (isBoolean(mode.requireBase)) {\n        html5Mode.requireBase = mode.requireBase;\n      }\n\n      if (isBoolean(mode.rewriteLinks)) {\n        html5Mode.rewriteLinks = mode.rewriteLinks;\n      }\n\n      return this;\n    } else {\n      return html5Mode;\n    }\n  };\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeStart\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted before a URL will change.\n   *\n   * This change can be prevented by calling\n   * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more\n   * details about event object. Upon successful change\n   * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  /**\n   * @ngdoc event\n   * @name $location#$locationChangeSuccess\n   * @eventType broadcast on root scope\n   * @description\n   * Broadcasted after a URL was changed.\n   *\n   * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when\n   * the browser supports the HTML5 History API.\n   *\n   * @param {Object} angularEvent Synthetic event object.\n   * @param {string} newUrl New URL\n   * @param {string=} oldUrl URL that was before it was changed.\n   * @param {string=} newState New history state object\n   * @param {string=} oldState History state object that was before it was changed.\n   */\n\n  this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',\n      function($rootScope, $browser, $sniffer, $rootElement, $window) {\n    var $location,\n        LocationMode,\n        baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''\n        initialUrl = $browser.url(),\n        appBase;\n\n    if (html5Mode.enabled) {\n      if (!baseHref && html5Mode.requireBase) {\n        throw $locationMinErr('nobase',\n          \"$location in HTML5 mode requires a <base> tag to be present!\");\n      }\n      appBase = serverBase(initialUrl) + (baseHref || '/');\n      LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;\n    } else {\n      appBase = stripHash(initialUrl);\n      LocationMode = LocationHashbangUrl;\n    }\n    var appBaseNoFile = stripFile(appBase);\n\n    $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);\n    $location.$$parseLinkUrl(initialUrl, initialUrl);\n\n    $location.$$state = $browser.state();\n\n    var IGNORE_URI_REGEXP = /^\\s*(javascript|mailto):/i;\n\n    function setBrowserUrlWithFallback(url, replace, state) {\n      var oldUrl = $location.url();\n      var oldState = $location.$$state;\n      try {\n        $browser.url(url, replace, state);\n\n        // Make sure $location.state() returns referentially identical (not just deeply equal)\n        // state object; this makes possible quick checking if the state changed in the digest\n        // loop. Checking deep equality would be too expensive.\n        $location.$$state = $browser.state();\n      } catch (e) {\n        // Restore old values if pushState fails\n        $location.url(oldUrl);\n        $location.$$state = oldState;\n\n        throw e;\n      }\n    }\n\n    $rootElement.on('click', function(event) {\n      // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)\n      // currently we open nice url link and redirect then\n\n      if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;\n\n      var elm = jqLite(event.target);\n\n      // traverse the DOM up to find first A tag\n      while (nodeName_(elm[0]) !== 'a') {\n        // ignore rewriting if no A tag (reached root element, or no parent - removed from document)\n        if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;\n      }\n\n      var absHref = elm.prop('href');\n      // get the actual href attribute - see\n      // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx\n      var relHref = elm.attr('href') || elm.attr('xlink:href');\n\n      if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {\n        // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during\n        // an animation.\n        absHref = urlResolve(absHref.animVal).href;\n      }\n\n      // Ignore when url is started with javascript: or mailto:\n      if (IGNORE_URI_REGEXP.test(absHref)) return;\n\n      if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {\n        if ($location.$$parseLinkUrl(absHref, relHref)) {\n          // We do a preventDefault for all urls that are part of the angular application,\n          // in html5mode and also without, so that we are able to abort navigation without\n          // getting double entries in the location history.\n          event.preventDefault();\n          // update location manually\n          if ($location.absUrl() != $browser.url()) {\n            $rootScope.$apply();\n            // hack to work around FF6 bug 684208 when scenario runner clicks on links\n            $window.angular['ff-684208-preventDefault'] = true;\n          }\n        }\n      }\n    });\n\n\n    // rewrite hashbang url <> html5 url\n    if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {\n      $browser.url($location.absUrl(), true);\n    }\n\n    var initializing = true;\n\n    // update $location when $browser url changes\n    $browser.onUrlChange(function(newUrl, newState) {\n\n      if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {\n        // If we are navigating outside of the app then force a reload\n        $window.location.href = newUrl;\n        return;\n      }\n\n      $rootScope.$evalAsync(function() {\n        var oldUrl = $location.absUrl();\n        var oldState = $location.$$state;\n        var defaultPrevented;\n\n        $location.$$parse(newUrl);\n        $location.$$state = newState;\n\n        defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n            newState, oldState).defaultPrevented;\n\n        // if the location was changed by a `$locationChangeStart` handler then stop\n        // processing this location change\n        if ($location.absUrl() !== newUrl) return;\n\n        if (defaultPrevented) {\n          $location.$$parse(oldUrl);\n          $location.$$state = oldState;\n          setBrowserUrlWithFallback(oldUrl, false, oldState);\n        } else {\n          initializing = false;\n          afterLocationChange(oldUrl, oldState);\n        }\n      });\n      if (!$rootScope.$$phase) $rootScope.$digest();\n    });\n\n    // update browser\n    $rootScope.$watch(function $locationWatch() {\n      var oldUrl = trimEmptyHash($browser.url());\n      var newUrl = trimEmptyHash($location.absUrl());\n      var oldState = $browser.state();\n      var currentReplace = $location.$$replace;\n      var urlOrStateChanged = oldUrl !== newUrl ||\n        ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);\n\n      if (initializing || urlOrStateChanged) {\n        initializing = false;\n\n        $rootScope.$evalAsync(function() {\n          var newUrl = $location.absUrl();\n          var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,\n              $location.$$state, oldState).defaultPrevented;\n\n          // if the location was changed by a `$locationChangeStart` handler then stop\n          // processing this location change\n          if ($location.absUrl() !== newUrl) return;\n\n          if (defaultPrevented) {\n            $location.$$parse(oldUrl);\n            $location.$$state = oldState;\n          } else {\n            if (urlOrStateChanged) {\n              setBrowserUrlWithFallback(newUrl, currentReplace,\n                                        oldState === $location.$$state ? null : $location.$$state);\n            }\n            afterLocationChange(oldUrl, oldState);\n          }\n        });\n      }\n\n      $location.$$replace = false;\n\n      // we don't need to return anything because $evalAsync will make the digest loop dirty when\n      // there is a change\n    });\n\n    return $location;\n\n    function afterLocationChange(oldUrl, oldState) {\n      $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,\n        $location.$$state, oldState);\n    }\n}];\n}\n\n/**\n * @ngdoc service\n * @name $log\n * @requires $window\n *\n * @description\n * Simple service for logging. Default implementation safely writes the message\n * into the browser's console (if present).\n *\n * The main purpose of this service is to simplify debugging and troubleshooting.\n *\n * The default is to log `debug` messages. You can use\n * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.\n *\n * @example\n   <example module=\"logExample\">\n     <file name=\"script.js\">\n       angular.module('logExample', [])\n         .controller('LogController', ['$scope', '$log', function($scope, $log) {\n           $scope.$log = $log;\n           $scope.message = 'Hello World!';\n         }]);\n     </file>\n     <file name=\"index.html\">\n       <div ng-controller=\"LogController\">\n         <p>Reload this page with open console, enter text and hit the log button...</p>\n         <label>Message:\n         <input type=\"text\" ng-model=\"message\" /></label>\n         <button ng-click=\"$log.log(message)\">log</button>\n         <button ng-click=\"$log.warn(message)\">warn</button>\n         <button ng-click=\"$log.info(message)\">info</button>\n         <button ng-click=\"$log.error(message)\">error</button>\n         <button ng-click=\"$log.debug(message)\">debug</button>\n       </div>\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc provider\n * @name $logProvider\n * @description\n * Use the `$logProvider` to configure how the application logs messages\n */\nfunction $LogProvider() {\n  var debug = true,\n      self = this;\n\n  /**\n   * @ngdoc method\n   * @name $logProvider#debugEnabled\n   * @description\n   * @param {boolean=} flag enable or disable debug level messages\n   * @returns {*} current value if used as getter or itself (chaining) if used as setter\n   */\n  this.debugEnabled = function(flag) {\n    if (isDefined(flag)) {\n      debug = flag;\n    return this;\n    } else {\n      return debug;\n    }\n  };\n\n  this.$get = ['$window', function($window) {\n    return {\n      /**\n       * @ngdoc method\n       * @name $log#log\n       *\n       * @description\n       * Write a log message\n       */\n      log: consoleLog('log'),\n\n      /**\n       * @ngdoc method\n       * @name $log#info\n       *\n       * @description\n       * Write an information message\n       */\n      info: consoleLog('info'),\n\n      /**\n       * @ngdoc method\n       * @name $log#warn\n       *\n       * @description\n       * Write a warning message\n       */\n      warn: consoleLog('warn'),\n\n      /**\n       * @ngdoc method\n       * @name $log#error\n       *\n       * @description\n       * Write an error message\n       */\n      error: consoleLog('error'),\n\n      /**\n       * @ngdoc method\n       * @name $log#debug\n       *\n       * @description\n       * Write a debug message\n       */\n      debug: (function() {\n        var fn = consoleLog('debug');\n\n        return function() {\n          if (debug) {\n            fn.apply(self, arguments);\n          }\n        };\n      }())\n    };\n\n    function formatError(arg) {\n      if (arg instanceof Error) {\n        if (arg.stack) {\n          arg = (arg.message && arg.stack.indexOf(arg.message) === -1)\n              ? 'Error: ' + arg.message + '\\n' + arg.stack\n              : arg.stack;\n        } else if (arg.sourceURL) {\n          arg = arg.message + '\\n' + arg.sourceURL + ':' + arg.line;\n        }\n      }\n      return arg;\n    }\n\n    function consoleLog(type) {\n      var console = $window.console || {},\n          logFn = console[type] || console.log || noop,\n          hasApply = false;\n\n      // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.\n      // The reason behind this is that console.log has type \"object\" in IE8...\n      try {\n        hasApply = !!logFn.apply;\n      } catch (e) {}\n\n      if (hasApply) {\n        return function() {\n          var args = [];\n          forEach(arguments, function(arg) {\n            args.push(formatError(arg));\n          });\n          return logFn.apply(console, args);\n        };\n      }\n\n      // we are IE which either doesn't have window.console => this is noop and we do nothing,\n      // or we are IE where console.log doesn't have apply so we log at least first 2 args\n      return function(arg1, arg2) {\n        logFn(arg1, arg2 == null ? '' : arg2);\n      };\n    }\n  }];\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $parseMinErr = minErr('$parse');\n\n// Sandboxing Angular Expressions\n// ------------------------------\n// Angular expressions are generally considered safe because these expressions only have direct\n// access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by\n// obtaining a reference to native JS functions such as the Function constructor.\n//\n// As an example, consider the following Angular expression:\n//\n//   {}.toString.constructor('alert(\"evil JS code\")')\n//\n// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits\n// against the expression language, but not to prevent exploits that were enabled by exposing\n// sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good\n// practice and therefore we are not even trying to protect against interaction with an object\n// explicitly exposed in this way.\n//\n// In general, it is not possible to access a Window object from an angular expression unless a\n// window or some DOM object that has a reference to window is published onto a Scope.\n// Similarly we prevent invocations of function known to be dangerous, as well as assignments to\n// native objects.\n//\n// See https://docs.angularjs.org/guide/security\n\n\nfunction ensureSafeMemberName(name, fullExpression) {\n  if (name === \"__defineGetter__\" || name === \"__defineSetter__\"\n      || name === \"__lookupGetter__\" || name === \"__lookupSetter__\"\n      || name === \"__proto__\") {\n    throw $parseMinErr('isecfld',\n        'Attempting to access a disallowed field in Angular expressions! '\n        + 'Expression: {0}', fullExpression);\n  }\n  return name;\n}\n\nfunction ensureSafeObject(obj, fullExpression) {\n  // nifty check if obj is Function that is fast and works across iframes and other contexts\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n          'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isWindow(obj)\n        obj.window === obj) {\n      throw $parseMinErr('isecwindow',\n          'Referencing the Window in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// isElement(obj)\n        obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {\n      throw $parseMinErr('isecdom',\n          'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    } else if (// block Object so that we can't get hold of dangerous Object.* methods\n        obj === Object) {\n      throw $parseMinErr('isecobj',\n          'Referencing Object in Angular expressions is disallowed! Expression: {0}',\n          fullExpression);\n    }\n  }\n  return obj;\n}\n\nvar CALL = Function.prototype.call;\nvar APPLY = Function.prototype.apply;\nvar BIND = Function.prototype.bind;\n\nfunction ensureSafeFunction(obj, fullExpression) {\n  if (obj) {\n    if (obj.constructor === obj) {\n      throw $parseMinErr('isecfn',\n        'Referencing Function in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    } else if (obj === CALL || obj === APPLY || obj === BIND) {\n      throw $parseMinErr('isecff',\n        'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',\n        fullExpression);\n    }\n  }\n}\n\nvar OPERATORS = createMap();\nforEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });\nvar ESCAPE = {\"n\":\"\\n\", \"f\":\"\\f\", \"r\":\"\\r\", \"t\":\"\\t\", \"v\":\"\\v\", \"'\":\"'\", '\"':'\"'};\n\n\n/////////////////////////////////////////\n\n\n/**\n * @constructor\n */\nvar Lexer = function(options) {\n  this.options = options;\n};\n\nLexer.prototype = {\n  constructor: Lexer,\n\n  lex: function(text) {\n    this.text = text;\n    this.index = 0;\n    this.tokens = [];\n\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (ch === '\"' || ch === \"'\") {\n        this.readString(ch);\n      } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {\n        this.readNumber();\n      } else if (this.isIdent(ch)) {\n        this.readIdent();\n      } else if (this.is(ch, '(){}[].,;:?')) {\n        this.tokens.push({index: this.index, text: ch});\n        this.index++;\n      } else if (this.isWhitespace(ch)) {\n        this.index++;\n      } else {\n        var ch2 = ch + this.peek();\n        var ch3 = ch2 + this.peek(2);\n        var op1 = OPERATORS[ch];\n        var op2 = OPERATORS[ch2];\n        var op3 = OPERATORS[ch3];\n        if (op1 || op2 || op3) {\n          var token = op3 ? ch3 : (op2 ? ch2 : ch);\n          this.tokens.push({index: this.index, text: token, operator: true});\n          this.index += token.length;\n        } else {\n          this.throwError('Unexpected next character ', this.index, this.index + 1);\n        }\n      }\n    }\n    return this.tokens;\n  },\n\n  is: function(ch, chars) {\n    return chars.indexOf(ch) !== -1;\n  },\n\n  peek: function(i) {\n    var num = i || 1;\n    return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;\n  },\n\n  isNumber: function(ch) {\n    return ('0' <= ch && ch <= '9') && typeof ch === \"string\";\n  },\n\n  isWhitespace: function(ch) {\n    // IE treats non-breaking space as \\u00A0\n    return (ch === ' ' || ch === '\\r' || ch === '\\t' ||\n            ch === '\\n' || ch === '\\v' || ch === '\\u00A0');\n  },\n\n  isIdent: function(ch) {\n    return ('a' <= ch && ch <= 'z' ||\n            'A' <= ch && ch <= 'Z' ||\n            '_' === ch || ch === '$');\n  },\n\n  isExpOperator: function(ch) {\n    return (ch === '-' || ch === '+' || this.isNumber(ch));\n  },\n\n  throwError: function(error, start, end) {\n    end = end || this.index;\n    var colStr = (isDefined(start)\n            ? 's ' + start +  '-' + this.index + ' [' + this.text.substring(start, end) + ']'\n            : ' ' + end);\n    throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',\n        error, colStr, this.text);\n  },\n\n  readNumber: function() {\n    var number = '';\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = lowercase(this.text.charAt(this.index));\n      if (ch == '.' || this.isNumber(ch)) {\n        number += ch;\n      } else {\n        var peekCh = this.peek();\n        if (ch == 'e' && this.isExpOperator(peekCh)) {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            peekCh && this.isNumber(peekCh) &&\n            number.charAt(number.length - 1) == 'e') {\n          number += ch;\n        } else if (this.isExpOperator(ch) &&\n            (!peekCh || !this.isNumber(peekCh)) &&\n            number.charAt(number.length - 1) == 'e') {\n          this.throwError('Invalid exponent');\n        } else {\n          break;\n        }\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: number,\n      constant: true,\n      value: Number(number)\n    });\n  },\n\n  readIdent: function() {\n    var start = this.index;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      if (!(this.isIdent(ch) || this.isNumber(ch))) {\n        break;\n      }\n      this.index++;\n    }\n    this.tokens.push({\n      index: start,\n      text: this.text.slice(start, this.index),\n      identifier: true\n    });\n  },\n\n  readString: function(quote) {\n    var start = this.index;\n    this.index++;\n    var string = '';\n    var rawString = quote;\n    var escape = false;\n    while (this.index < this.text.length) {\n      var ch = this.text.charAt(this.index);\n      rawString += ch;\n      if (escape) {\n        if (ch === 'u') {\n          var hex = this.text.substring(this.index + 1, this.index + 5);\n          if (!hex.match(/[\\da-f]{4}/i)) {\n            this.throwError('Invalid unicode escape [\\\\u' + hex + ']');\n          }\n          this.index += 4;\n          string += String.fromCharCode(parseInt(hex, 16));\n        } else {\n          var rep = ESCAPE[ch];\n          string = string + (rep || ch);\n        }\n        escape = false;\n      } else if (ch === '\\\\') {\n        escape = true;\n      } else if (ch === quote) {\n        this.index++;\n        this.tokens.push({\n          index: start,\n          text: rawString,\n          constant: true,\n          value: string\n        });\n        return;\n      } else {\n        string += ch;\n      }\n      this.index++;\n    }\n    this.throwError('Unterminated quote', start);\n  }\n};\n\nvar AST = function(lexer, options) {\n  this.lexer = lexer;\n  this.options = options;\n};\n\nAST.Program = 'Program';\nAST.ExpressionStatement = 'ExpressionStatement';\nAST.AssignmentExpression = 'AssignmentExpression';\nAST.ConditionalExpression = 'ConditionalExpression';\nAST.LogicalExpression = 'LogicalExpression';\nAST.BinaryExpression = 'BinaryExpression';\nAST.UnaryExpression = 'UnaryExpression';\nAST.CallExpression = 'CallExpression';\nAST.MemberExpression = 'MemberExpression';\nAST.Identifier = 'Identifier';\nAST.Literal = 'Literal';\nAST.ArrayExpression = 'ArrayExpression';\nAST.Property = 'Property';\nAST.ObjectExpression = 'ObjectExpression';\nAST.ThisExpression = 'ThisExpression';\n\n// Internal use only\nAST.NGValueParameter = 'NGValueParameter';\n\nAST.prototype = {\n  ast: function(text) {\n    this.text = text;\n    this.tokens = this.lexer.lex(text);\n\n    var value = this.program();\n\n    if (this.tokens.length !== 0) {\n      this.throwError('is an unexpected token', this.tokens[0]);\n    }\n\n    return value;\n  },\n\n  program: function() {\n    var body = [];\n    while (true) {\n      if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))\n        body.push(this.expressionStatement());\n      if (!this.expect(';')) {\n        return { type: AST.Program, body: body};\n      }\n    }\n  },\n\n  expressionStatement: function() {\n    return { type: AST.ExpressionStatement, expression: this.filterChain() };\n  },\n\n  filterChain: function() {\n    var left = this.expression();\n    var token;\n    while ((token = this.expect('|'))) {\n      left = this.filter(left);\n    }\n    return left;\n  },\n\n  expression: function() {\n    return this.assignment();\n  },\n\n  assignment: function() {\n    var result = this.ternary();\n    if (this.expect('=')) {\n      result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};\n    }\n    return result;\n  },\n\n  ternary: function() {\n    var test = this.logicalOR();\n    var alternate;\n    var consequent;\n    if (this.expect('?')) {\n      alternate = this.expression();\n      if (this.consume(':')) {\n        consequent = this.expression();\n        return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};\n      }\n    }\n    return test;\n  },\n\n  logicalOR: function() {\n    var left = this.logicalAND();\n    while (this.expect('||')) {\n      left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };\n    }\n    return left;\n  },\n\n  logicalAND: function() {\n    var left = this.equality();\n    while (this.expect('&&')) {\n      left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};\n    }\n    return left;\n  },\n\n  equality: function() {\n    var left = this.relational();\n    var token;\n    while ((token = this.expect('==','!=','===','!=='))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };\n    }\n    return left;\n  },\n\n  relational: function() {\n    var left = this.additive();\n    var token;\n    while ((token = this.expect('<', '>', '<=', '>='))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };\n    }\n    return left;\n  },\n\n  additive: function() {\n    var left = this.multiplicative();\n    var token;\n    while ((token = this.expect('+','-'))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };\n    }\n    return left;\n  },\n\n  multiplicative: function() {\n    var left = this.unary();\n    var token;\n    while ((token = this.expect('*','/','%'))) {\n      left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };\n    }\n    return left;\n  },\n\n  unary: function() {\n    var token;\n    if ((token = this.expect('+', '-', '!'))) {\n      return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };\n    } else {\n      return this.primary();\n    }\n  },\n\n  primary: function() {\n    var primary;\n    if (this.expect('(')) {\n      primary = this.filterChain();\n      this.consume(')');\n    } else if (this.expect('[')) {\n      primary = this.arrayDeclaration();\n    } else if (this.expect('{')) {\n      primary = this.object();\n    } else if (this.constants.hasOwnProperty(this.peek().text)) {\n      primary = copy(this.constants[this.consume().text]);\n    } else if (this.peek().identifier) {\n      primary = this.identifier();\n    } else if (this.peek().constant) {\n      primary = this.constant();\n    } else {\n      this.throwError('not a primary expression', this.peek());\n    }\n\n    var next;\n    while ((next = this.expect('(', '[', '.'))) {\n      if (next.text === '(') {\n        primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };\n        this.consume(')');\n      } else if (next.text === '[') {\n        primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };\n        this.consume(']');\n      } else if (next.text === '.') {\n        primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };\n      } else {\n        this.throwError('IMPOSSIBLE');\n      }\n    }\n    return primary;\n  },\n\n  filter: function(baseExpression) {\n    var args = [baseExpression];\n    var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};\n\n    while (this.expect(':')) {\n      args.push(this.expression());\n    }\n\n    return result;\n  },\n\n  parseArguments: function() {\n    var args = [];\n    if (this.peekToken().text !== ')') {\n      do {\n        args.push(this.expression());\n      } while (this.expect(','));\n    }\n    return args;\n  },\n\n  identifier: function() {\n    var token = this.consume();\n    if (!token.identifier) {\n      this.throwError('is not a valid identifier', token);\n    }\n    return { type: AST.Identifier, name: token.text };\n  },\n\n  constant: function() {\n    // TODO check that it is a constant\n    return { type: AST.Literal, value: this.consume().value };\n  },\n\n  arrayDeclaration: function() {\n    var elements = [];\n    if (this.peekToken().text !== ']') {\n      do {\n        if (this.peek(']')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        elements.push(this.expression());\n      } while (this.expect(','));\n    }\n    this.consume(']');\n\n    return { type: AST.ArrayExpression, elements: elements };\n  },\n\n  object: function() {\n    var properties = [], property;\n    if (this.peekToken().text !== '}') {\n      do {\n        if (this.peek('}')) {\n          // Support trailing commas per ES5.1.\n          break;\n        }\n        property = {type: AST.Property, kind: 'init'};\n        if (this.peek().constant) {\n          property.key = this.constant();\n        } else if (this.peek().identifier) {\n          property.key = this.identifier();\n        } else {\n          this.throwError(\"invalid key\", this.peek());\n        }\n        this.consume(':');\n        property.value = this.expression();\n        properties.push(property);\n      } while (this.expect(','));\n    }\n    this.consume('}');\n\n    return {type: AST.ObjectExpression, properties: properties };\n  },\n\n  throwError: function(msg, token) {\n    throw $parseMinErr('syntax',\n        'Syntax Error: Token \\'{0}\\' {1} at column {2} of the expression [{3}] starting at [{4}].',\n          token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));\n  },\n\n  consume: function(e1) {\n    if (this.tokens.length === 0) {\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    }\n\n    var token = this.expect(e1);\n    if (!token) {\n      this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());\n    }\n    return token;\n  },\n\n  peekToken: function() {\n    if (this.tokens.length === 0) {\n      throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);\n    }\n    return this.tokens[0];\n  },\n\n  peek: function(e1, e2, e3, e4) {\n    return this.peekAhead(0, e1, e2, e3, e4);\n  },\n\n  peekAhead: function(i, e1, e2, e3, e4) {\n    if (this.tokens.length > i) {\n      var token = this.tokens[i];\n      var t = token.text;\n      if (t === e1 || t === e2 || t === e3 || t === e4 ||\n          (!e1 && !e2 && !e3 && !e4)) {\n        return token;\n      }\n    }\n    return false;\n  },\n\n  expect: function(e1, e2, e3, e4) {\n    var token = this.peek(e1, e2, e3, e4);\n    if (token) {\n      this.tokens.shift();\n      return token;\n    }\n    return false;\n  },\n\n\n  /* `undefined` is not a constant, it is an identifier,\n   * but using it as an identifier is not supported\n   */\n  constants: {\n    'true': { type: AST.Literal, value: true },\n    'false': { type: AST.Literal, value: false },\n    'null': { type: AST.Literal, value: null },\n    'undefined': {type: AST.Literal, value: undefined },\n    'this': {type: AST.ThisExpression }\n  }\n};\n\nfunction ifDefined(v, d) {\n  return typeof v !== 'undefined' ? v : d;\n}\n\nfunction plusFn(l, r) {\n  if (typeof l === 'undefined') return r;\n  if (typeof r === 'undefined') return l;\n  return l + r;\n}\n\nfunction isStateless($filter, filterName) {\n  var fn = $filter(filterName);\n  return !fn.$stateful;\n}\n\nfunction findConstantAndWatchExpressions(ast, $filter) {\n  var allConstants;\n  var argsToWatch;\n  switch (ast.type) {\n  case AST.Program:\n    allConstants = true;\n    forEach(ast.body, function(expr) {\n      findConstantAndWatchExpressions(expr.expression, $filter);\n      allConstants = allConstants && expr.expression.constant;\n    });\n    ast.constant = allConstants;\n    break;\n  case AST.Literal:\n    ast.constant = true;\n    ast.toWatch = [];\n    break;\n  case AST.UnaryExpression:\n    findConstantAndWatchExpressions(ast.argument, $filter);\n    ast.constant = ast.argument.constant;\n    ast.toWatch = ast.argument.toWatch;\n    break;\n  case AST.BinaryExpression:\n    findConstantAndWatchExpressions(ast.left, $filter);\n    findConstantAndWatchExpressions(ast.right, $filter);\n    ast.constant = ast.left.constant && ast.right.constant;\n    ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);\n    break;\n  case AST.LogicalExpression:\n    findConstantAndWatchExpressions(ast.left, $filter);\n    findConstantAndWatchExpressions(ast.right, $filter);\n    ast.constant = ast.left.constant && ast.right.constant;\n    ast.toWatch = ast.constant ? [] : [ast];\n    break;\n  case AST.ConditionalExpression:\n    findConstantAndWatchExpressions(ast.test, $filter);\n    findConstantAndWatchExpressions(ast.alternate, $filter);\n    findConstantAndWatchExpressions(ast.consequent, $filter);\n    ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;\n    ast.toWatch = ast.constant ? [] : [ast];\n    break;\n  case AST.Identifier:\n    ast.constant = false;\n    ast.toWatch = [ast];\n    break;\n  case AST.MemberExpression:\n    findConstantAndWatchExpressions(ast.object, $filter);\n    if (ast.computed) {\n      findConstantAndWatchExpressions(ast.property, $filter);\n    }\n    ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);\n    ast.toWatch = [ast];\n    break;\n  case AST.CallExpression:\n    allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;\n    argsToWatch = [];\n    forEach(ast.arguments, function(expr) {\n      findConstantAndWatchExpressions(expr, $filter);\n      allConstants = allConstants && expr.constant;\n      if (!expr.constant) {\n        argsToWatch.push.apply(argsToWatch, expr.toWatch);\n      }\n    });\n    ast.constant = allConstants;\n    ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];\n    break;\n  case AST.AssignmentExpression:\n    findConstantAndWatchExpressions(ast.left, $filter);\n    findConstantAndWatchExpressions(ast.right, $filter);\n    ast.constant = ast.left.constant && ast.right.constant;\n    ast.toWatch = [ast];\n    break;\n  case AST.ArrayExpression:\n    allConstants = true;\n    argsToWatch = [];\n    forEach(ast.elements, function(expr) {\n      findConstantAndWatchExpressions(expr, $filter);\n      allConstants = allConstants && expr.constant;\n      if (!expr.constant) {\n        argsToWatch.push.apply(argsToWatch, expr.toWatch);\n      }\n    });\n    ast.constant = allConstants;\n    ast.toWatch = argsToWatch;\n    break;\n  case AST.ObjectExpression:\n    allConstants = true;\n    argsToWatch = [];\n    forEach(ast.properties, function(property) {\n      findConstantAndWatchExpressions(property.value, $filter);\n      allConstants = allConstants && property.value.constant;\n      if (!property.value.constant) {\n        argsToWatch.push.apply(argsToWatch, property.value.toWatch);\n      }\n    });\n    ast.constant = allConstants;\n    ast.toWatch = argsToWatch;\n    break;\n  case AST.ThisExpression:\n    ast.constant = false;\n    ast.toWatch = [];\n    break;\n  }\n}\n\nfunction getInputs(body) {\n  if (body.length != 1) return;\n  var lastExpression = body[0].expression;\n  var candidate = lastExpression.toWatch;\n  if (candidate.length !== 1) return candidate;\n  return candidate[0] !== lastExpression ? candidate : undefined;\n}\n\nfunction isAssignable(ast) {\n  return ast.type === AST.Identifier || ast.type === AST.MemberExpression;\n}\n\nfunction assignableAST(ast) {\n  if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {\n    return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};\n  }\n}\n\nfunction isLiteral(ast) {\n  return ast.body.length === 0 ||\n      ast.body.length === 1 && (\n      ast.body[0].expression.type === AST.Literal ||\n      ast.body[0].expression.type === AST.ArrayExpression ||\n      ast.body[0].expression.type === AST.ObjectExpression);\n}\n\nfunction isConstant(ast) {\n  return ast.constant;\n}\n\nfunction ASTCompiler(astBuilder, $filter) {\n  this.astBuilder = astBuilder;\n  this.$filter = $filter;\n}\n\nASTCompiler.prototype = {\n  compile: function(expression, expensiveChecks) {\n    var self = this;\n    var ast = this.astBuilder.ast(expression);\n    this.state = {\n      nextId: 0,\n      filters: {},\n      expensiveChecks: expensiveChecks,\n      fn: {vars: [], body: [], own: {}},\n      assign: {vars: [], body: [], own: {}},\n      inputs: []\n    };\n    findConstantAndWatchExpressions(ast, self.$filter);\n    var extra = '';\n    var assignable;\n    this.stage = 'assign';\n    if ((assignable = assignableAST(ast))) {\n      this.state.computing = 'assign';\n      var result = this.nextId();\n      this.recurse(assignable, result);\n      extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');\n    }\n    var toWatch = getInputs(ast.body);\n    self.stage = 'inputs';\n    forEach(toWatch, function(watch, key) {\n      var fnKey = 'fn' + key;\n      self.state[fnKey] = {vars: [], body: [], own: {}};\n      self.state.computing = fnKey;\n      var intoId = self.nextId();\n      self.recurse(watch, intoId);\n      self.return_(intoId);\n      self.state.inputs.push(fnKey);\n      watch.watchId = key;\n    });\n    this.state.computing = 'fn';\n    this.stage = 'main';\n    this.recurse(ast);\n    var fnString =\n      // The build and minification steps remove the string \"use strict\" from the code, but this is done using a regex.\n      // This is a workaround for this until we do a better job at only removing the prefix only when we should.\n      '\"' + this.USE + ' ' + this.STRICT + '\";\\n' +\n      this.filterPrefix() +\n      'var fn=' + this.generateFunction('fn', 's,l,a,i') +\n      extra +\n      this.watchFns() +\n      'return fn;';\n\n    /* jshint -W054 */\n    var fn = (new Function('$filter',\n        'ensureSafeMemberName',\n        'ensureSafeObject',\n        'ensureSafeFunction',\n        'ifDefined',\n        'plus',\n        'text',\n        fnString))(\n          this.$filter,\n          ensureSafeMemberName,\n          ensureSafeObject,\n          ensureSafeFunction,\n          ifDefined,\n          plusFn,\n          expression);\n    /* jshint +W054 */\n    this.state = this.stage = undefined;\n    fn.literal = isLiteral(ast);\n    fn.constant = isConstant(ast);\n    return fn;\n  },\n\n  USE: 'use',\n\n  STRICT: 'strict',\n\n  watchFns: function() {\n    var result = [];\n    var fns = this.state.inputs;\n    var self = this;\n    forEach(fns, function(name) {\n      result.push('var ' + name + '=' + self.generateFunction(name, 's'));\n    });\n    if (fns.length) {\n      result.push('fn.inputs=[' + fns.join(',') + '];');\n    }\n    return result.join('');\n  },\n\n  generateFunction: function(name, params) {\n    return 'function(' + params + '){' +\n        this.varsPrefix(name) +\n        this.body(name) +\n        '};';\n  },\n\n  filterPrefix: function() {\n    var parts = [];\n    var self = this;\n    forEach(this.state.filters, function(id, filter) {\n      parts.push(id + '=$filter(' + self.escape(filter) + ')');\n    });\n    if (parts.length) return 'var ' + parts.join(',') + ';';\n    return '';\n  },\n\n  varsPrefix: function(section) {\n    return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';\n  },\n\n  body: function(section) {\n    return this.state[section].body.join('');\n  },\n\n  recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n    var left, right, self = this, args, expression;\n    recursionFn = recursionFn || noop;\n    if (!skipWatchIdCheck && isDefined(ast.watchId)) {\n      intoId = intoId || this.nextId();\n      this.if_('i',\n        this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),\n        this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)\n      );\n      return;\n    }\n    switch (ast.type) {\n    case AST.Program:\n      forEach(ast.body, function(expression, pos) {\n        self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });\n        if (pos !== ast.body.length - 1) {\n          self.current().body.push(right, ';');\n        } else {\n          self.return_(right);\n        }\n      });\n      break;\n    case AST.Literal:\n      expression = this.escape(ast.value);\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.UnaryExpression:\n      this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });\n      expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.BinaryExpression:\n      this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });\n      this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });\n      if (ast.operator === '+') {\n        expression = this.plus(left, right);\n      } else if (ast.operator === '-') {\n        expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);\n      } else {\n        expression = '(' + left + ')' + ast.operator + '(' + right + ')';\n      }\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.LogicalExpression:\n      intoId = intoId || this.nextId();\n      self.recurse(ast.left, intoId);\n      self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));\n      recursionFn(intoId);\n      break;\n    case AST.ConditionalExpression:\n      intoId = intoId || this.nextId();\n      self.recurse(ast.test, intoId);\n      self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));\n      recursionFn(intoId);\n      break;\n    case AST.Identifier:\n      intoId = intoId || this.nextId();\n      if (nameId) {\n        nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');\n        nameId.computed = false;\n        nameId.name = ast.name;\n      }\n      ensureSafeMemberName(ast.name);\n      self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),\n        function() {\n          self.if_(self.stage === 'inputs' || 's', function() {\n            if (create && create !== 1) {\n              self.if_(\n                self.not(self.nonComputedMember('s', ast.name)),\n                self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));\n            }\n            self.assign(intoId, self.nonComputedMember('s', ast.name));\n          });\n        }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))\n        );\n      if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {\n        self.addEnsureSafeObject(intoId);\n      }\n      recursionFn(intoId);\n      break;\n    case AST.MemberExpression:\n      left = nameId && (nameId.context = this.nextId()) || this.nextId();\n      intoId = intoId || this.nextId();\n      self.recurse(ast.object, left, undefined, function() {\n        self.if_(self.notNull(left), function() {\n          if (ast.computed) {\n            right = self.nextId();\n            self.recurse(ast.property, right);\n            self.addEnsureSafeMemberName(right);\n            if (create && create !== 1) {\n              self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));\n            }\n            expression = self.ensureSafeObject(self.computedMember(left, right));\n            self.assign(intoId, expression);\n            if (nameId) {\n              nameId.computed = true;\n              nameId.name = right;\n            }\n          } else {\n            ensureSafeMemberName(ast.property.name);\n            if (create && create !== 1) {\n              self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));\n            }\n            expression = self.nonComputedMember(left, ast.property.name);\n            if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {\n              expression = self.ensureSafeObject(expression);\n            }\n            self.assign(intoId, expression);\n            if (nameId) {\n              nameId.computed = false;\n              nameId.name = ast.property.name;\n            }\n          }\n        }, function() {\n          self.assign(intoId, 'undefined');\n        });\n        recursionFn(intoId);\n      }, !!create);\n      break;\n    case AST.CallExpression:\n      intoId = intoId || this.nextId();\n      if (ast.filter) {\n        right = self.filter(ast.callee.name);\n        args = [];\n        forEach(ast.arguments, function(expr) {\n          var argument = self.nextId();\n          self.recurse(expr, argument);\n          args.push(argument);\n        });\n        expression = right + '(' + args.join(',') + ')';\n        self.assign(intoId, expression);\n        recursionFn(intoId);\n      } else {\n        right = self.nextId();\n        left = {};\n        args = [];\n        self.recurse(ast.callee, right, left, function() {\n          self.if_(self.notNull(right), function() {\n            self.addEnsureSafeFunction(right);\n            forEach(ast.arguments, function(expr) {\n              self.recurse(expr, self.nextId(), undefined, function(argument) {\n                args.push(self.ensureSafeObject(argument));\n              });\n            });\n            if (left.name) {\n              if (!self.state.expensiveChecks) {\n                self.addEnsureSafeObject(left.context);\n              }\n              expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';\n            } else {\n              expression = right + '(' + args.join(',') + ')';\n            }\n            expression = self.ensureSafeObject(expression);\n            self.assign(intoId, expression);\n          }, function() {\n            self.assign(intoId, 'undefined');\n          });\n          recursionFn(intoId);\n        });\n      }\n      break;\n    case AST.AssignmentExpression:\n      right = this.nextId();\n      left = {};\n      if (!isAssignable(ast.left)) {\n        throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');\n      }\n      this.recurse(ast.left, undefined, left, function() {\n        self.if_(self.notNull(left.context), function() {\n          self.recurse(ast.right, right);\n          self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));\n          expression = self.member(left.context, left.name, left.computed) + ast.operator + right;\n          self.assign(intoId, expression);\n          recursionFn(intoId || expression);\n        });\n      }, 1);\n      break;\n    case AST.ArrayExpression:\n      args = [];\n      forEach(ast.elements, function(expr) {\n        self.recurse(expr, self.nextId(), undefined, function(argument) {\n          args.push(argument);\n        });\n      });\n      expression = '[' + args.join(',') + ']';\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.ObjectExpression:\n      args = [];\n      forEach(ast.properties, function(property) {\n        self.recurse(property.value, self.nextId(), undefined, function(expr) {\n          args.push(self.escape(\n              property.key.type === AST.Identifier ? property.key.name :\n                ('' + property.key.value)) +\n              ':' + expr);\n        });\n      });\n      expression = '{' + args.join(',') + '}';\n      this.assign(intoId, expression);\n      recursionFn(expression);\n      break;\n    case AST.ThisExpression:\n      this.assign(intoId, 's');\n      recursionFn('s');\n      break;\n    case AST.NGValueParameter:\n      this.assign(intoId, 'v');\n      recursionFn('v');\n      break;\n    }\n  },\n\n  getHasOwnProperty: function(element, property) {\n    var key = element + '.' + property;\n    var own = this.current().own;\n    if (!own.hasOwnProperty(key)) {\n      own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');\n    }\n    return own[key];\n  },\n\n  assign: function(id, value) {\n    if (!id) return;\n    this.current().body.push(id, '=', value, ';');\n    return id;\n  },\n\n  filter: function(filterName) {\n    if (!this.state.filters.hasOwnProperty(filterName)) {\n      this.state.filters[filterName] = this.nextId(true);\n    }\n    return this.state.filters[filterName];\n  },\n\n  ifDefined: function(id, defaultValue) {\n    return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';\n  },\n\n  plus: function(left, right) {\n    return 'plus(' + left + ',' + right + ')';\n  },\n\n  return_: function(id) {\n    this.current().body.push('return ', id, ';');\n  },\n\n  if_: function(test, alternate, consequent) {\n    if (test === true) {\n      alternate();\n    } else {\n      var body = this.current().body;\n      body.push('if(', test, '){');\n      alternate();\n      body.push('}');\n      if (consequent) {\n        body.push('else{');\n        consequent();\n        body.push('}');\n      }\n    }\n  },\n\n  not: function(expression) {\n    return '!(' + expression + ')';\n  },\n\n  notNull: function(expression) {\n    return expression + '!=null';\n  },\n\n  nonComputedMember: function(left, right) {\n    return left + '.' + right;\n  },\n\n  computedMember: function(left, right) {\n    return left + '[' + right + ']';\n  },\n\n  member: function(left, right, computed) {\n    if (computed) return this.computedMember(left, right);\n    return this.nonComputedMember(left, right);\n  },\n\n  addEnsureSafeObject: function(item) {\n    this.current().body.push(this.ensureSafeObject(item), ';');\n  },\n\n  addEnsureSafeMemberName: function(item) {\n    this.current().body.push(this.ensureSafeMemberName(item), ';');\n  },\n\n  addEnsureSafeFunction: function(item) {\n    this.current().body.push(this.ensureSafeFunction(item), ';');\n  },\n\n  ensureSafeObject: function(item) {\n    return 'ensureSafeObject(' + item + ',text)';\n  },\n\n  ensureSafeMemberName: function(item) {\n    return 'ensureSafeMemberName(' + item + ',text)';\n  },\n\n  ensureSafeFunction: function(item) {\n    return 'ensureSafeFunction(' + item + ',text)';\n  },\n\n  lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {\n    var self = this;\n    return function() {\n      self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);\n    };\n  },\n\n  lazyAssign: function(id, value) {\n    var self = this;\n    return function() {\n      self.assign(id, value);\n    };\n  },\n\n  stringEscapeRegex: /[^ a-zA-Z0-9]/g,\n\n  stringEscapeFn: function(c) {\n    return '\\\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);\n  },\n\n  escape: function(value) {\n    if (isString(value)) return \"'\" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + \"'\";\n    if (isNumber(value)) return value.toString();\n    if (value === true) return 'true';\n    if (value === false) return 'false';\n    if (value === null) return 'null';\n    if (typeof value === 'undefined') return 'undefined';\n\n    throw $parseMinErr('esc', 'IMPOSSIBLE');\n  },\n\n  nextId: function(skip, init) {\n    var id = 'v' + (this.state.nextId++);\n    if (!skip) {\n      this.current().vars.push(id + (init ? '=' + init : ''));\n    }\n    return id;\n  },\n\n  current: function() {\n    return this.state[this.state.computing];\n  }\n};\n\n\nfunction ASTInterpreter(astBuilder, $filter) {\n  this.astBuilder = astBuilder;\n  this.$filter = $filter;\n}\n\nASTInterpreter.prototype = {\n  compile: function(expression, expensiveChecks) {\n    var self = this;\n    var ast = this.astBuilder.ast(expression);\n    this.expression = expression;\n    this.expensiveChecks = expensiveChecks;\n    findConstantAndWatchExpressions(ast, self.$filter);\n    var assignable;\n    var assign;\n    if ((assignable = assignableAST(ast))) {\n      assign = this.recurse(assignable);\n    }\n    var toWatch = getInputs(ast.body);\n    var inputs;\n    if (toWatch) {\n      inputs = [];\n      forEach(toWatch, function(watch, key) {\n        var input = self.recurse(watch);\n        watch.input = input;\n        inputs.push(input);\n        watch.watchId = key;\n      });\n    }\n    var expressions = [];\n    forEach(ast.body, function(expression) {\n      expressions.push(self.recurse(expression.expression));\n    });\n    var fn = ast.body.length === 0 ? function() {} :\n             ast.body.length === 1 ? expressions[0] :\n             function(scope, locals) {\n               var lastValue;\n               forEach(expressions, function(exp) {\n                 lastValue = exp(scope, locals);\n               });\n               return lastValue;\n             };\n    if (assign) {\n      fn.assign = function(scope, value, locals) {\n        return assign(scope, locals, value);\n      };\n    }\n    if (inputs) {\n      fn.inputs = inputs;\n    }\n    fn.literal = isLiteral(ast);\n    fn.constant = isConstant(ast);\n    return fn;\n  },\n\n  recurse: function(ast, context, create) {\n    var left, right, self = this, args, expression;\n    if (ast.input) {\n      return this.inputs(ast.input, ast.watchId);\n    }\n    switch (ast.type) {\n    case AST.Literal:\n      return this.value(ast.value, context);\n    case AST.UnaryExpression:\n      right = this.recurse(ast.argument);\n      return this['unary' + ast.operator](right, context);\n    case AST.BinaryExpression:\n      left = this.recurse(ast.left);\n      right = this.recurse(ast.right);\n      return this['binary' + ast.operator](left, right, context);\n    case AST.LogicalExpression:\n      left = this.recurse(ast.left);\n      right = this.recurse(ast.right);\n      return this['binary' + ast.operator](left, right, context);\n    case AST.ConditionalExpression:\n      return this['ternary?:'](\n        this.recurse(ast.test),\n        this.recurse(ast.alternate),\n        this.recurse(ast.consequent),\n        context\n      );\n    case AST.Identifier:\n      ensureSafeMemberName(ast.name, self.expression);\n      return self.identifier(ast.name,\n                             self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),\n                             context, create, self.expression);\n    case AST.MemberExpression:\n      left = this.recurse(ast.object, false, !!create);\n      if (!ast.computed) {\n        ensureSafeMemberName(ast.property.name, self.expression);\n        right = ast.property.name;\n      }\n      if (ast.computed) right = this.recurse(ast.property);\n      return ast.computed ?\n        this.computedMember(left, right, context, create, self.expression) :\n        this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);\n    case AST.CallExpression:\n      args = [];\n      forEach(ast.arguments, function(expr) {\n        args.push(self.recurse(expr));\n      });\n      if (ast.filter) right = this.$filter(ast.callee.name);\n      if (!ast.filter) right = this.recurse(ast.callee, true);\n      return ast.filter ?\n        function(scope, locals, assign, inputs) {\n          var values = [];\n          for (var i = 0; i < args.length; ++i) {\n            values.push(args[i](scope, locals, assign, inputs));\n          }\n          var value = right.apply(undefined, values, inputs);\n          return context ? {context: undefined, name: undefined, value: value} : value;\n        } :\n        function(scope, locals, assign, inputs) {\n          var rhs = right(scope, locals, assign, inputs);\n          var value;\n          if (rhs.value != null) {\n            ensureSafeObject(rhs.context, self.expression);\n            ensureSafeFunction(rhs.value, self.expression);\n            var values = [];\n            for (var i = 0; i < args.length; ++i) {\n              values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));\n            }\n            value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);\n          }\n          return context ? {value: value} : value;\n        };\n    case AST.AssignmentExpression:\n      left = this.recurse(ast.left, true, 1);\n      right = this.recurse(ast.right);\n      return function(scope, locals, assign, inputs) {\n        var lhs = left(scope, locals, assign, inputs);\n        var rhs = right(scope, locals, assign, inputs);\n        ensureSafeObject(lhs.value, self.expression);\n        lhs.context[lhs.name] = rhs;\n        return context ? {value: rhs} : rhs;\n      };\n    case AST.ArrayExpression:\n      args = [];\n      forEach(ast.elements, function(expr) {\n        args.push(self.recurse(expr));\n      });\n      return function(scope, locals, assign, inputs) {\n        var value = [];\n        for (var i = 0; i < args.length; ++i) {\n          value.push(args[i](scope, locals, assign, inputs));\n        }\n        return context ? {value: value} : value;\n      };\n    case AST.ObjectExpression:\n      args = [];\n      forEach(ast.properties, function(property) {\n        args.push({key: property.key.type === AST.Identifier ?\n                        property.key.name :\n                        ('' + property.key.value),\n                   value: self.recurse(property.value)\n        });\n      });\n      return function(scope, locals, assign, inputs) {\n        var value = {};\n        for (var i = 0; i < args.length; ++i) {\n          value[args[i].key] = args[i].value(scope, locals, assign, inputs);\n        }\n        return context ? {value: value} : value;\n      };\n    case AST.ThisExpression:\n      return function(scope) {\n        return context ? {value: scope} : scope;\n      };\n    case AST.NGValueParameter:\n      return function(scope, locals, assign, inputs) {\n        return context ? {value: assign} : assign;\n      };\n    }\n  },\n\n  'unary+': function(argument, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = argument(scope, locals, assign, inputs);\n      if (isDefined(arg)) {\n        arg = +arg;\n      } else {\n        arg = 0;\n      }\n      return context ? {value: arg} : arg;\n    };\n  },\n  'unary-': function(argument, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = argument(scope, locals, assign, inputs);\n      if (isDefined(arg)) {\n        arg = -arg;\n      } else {\n        arg = 0;\n      }\n      return context ? {value: arg} : arg;\n    };\n  },\n  'unary!': function(argument, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = !argument(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary+': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      var rhs = right(scope, locals, assign, inputs);\n      var arg = plusFn(lhs, rhs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary-': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      var rhs = right(scope, locals, assign, inputs);\n      var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary*': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary/': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary%': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary===': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary!==': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary==': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary!=': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary<': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary>': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary<=': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary>=': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary&&': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'binary||': function(left, right, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  'ternary?:': function(test, alternate, consequent, context) {\n    return function(scope, locals, assign, inputs) {\n      var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);\n      return context ? {value: arg} : arg;\n    };\n  },\n  value: function(value, context) {\n    return function() { return context ? {context: undefined, name: undefined, value: value} : value; };\n  },\n  identifier: function(name, expensiveChecks, context, create, expression) {\n    return function(scope, locals, assign, inputs) {\n      var base = locals && (name in locals) ? locals : scope;\n      if (create && create !== 1 && base && !(base[name])) {\n        base[name] = {};\n      }\n      var value = base ? base[name] : undefined;\n      if (expensiveChecks) {\n        ensureSafeObject(value, expression);\n      }\n      if (context) {\n        return {context: base, name: name, value: value};\n      } else {\n        return value;\n      }\n    };\n  },\n  computedMember: function(left, right, context, create, expression) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      var rhs;\n      var value;\n      if (lhs != null) {\n        rhs = right(scope, locals, assign, inputs);\n        ensureSafeMemberName(rhs, expression);\n        if (create && create !== 1 && lhs && !(lhs[rhs])) {\n          lhs[rhs] = {};\n        }\n        value = lhs[rhs];\n        ensureSafeObject(value, expression);\n      }\n      if (context) {\n        return {context: lhs, name: rhs, value: value};\n      } else {\n        return value;\n      }\n    };\n  },\n  nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {\n    return function(scope, locals, assign, inputs) {\n      var lhs = left(scope, locals, assign, inputs);\n      if (create && create !== 1 && lhs && !(lhs[right])) {\n        lhs[right] = {};\n      }\n      var value = lhs != null ? lhs[right] : undefined;\n      if (expensiveChecks || isPossiblyDangerousMemberName(right)) {\n        ensureSafeObject(value, expression);\n      }\n      if (context) {\n        return {context: lhs, name: right, value: value};\n      } else {\n        return value;\n      }\n    };\n  },\n  inputs: function(input, watchId) {\n    return function(scope, value, locals, inputs) {\n      if (inputs) return inputs[watchId];\n      return input(scope, value, locals);\n    };\n  }\n};\n\n/**\n * @constructor\n */\nvar Parser = function(lexer, $filter, options) {\n  this.lexer = lexer;\n  this.$filter = $filter;\n  this.options = options;\n  this.ast = new AST(this.lexer);\n  this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :\n                                   new ASTCompiler(this.ast, $filter);\n};\n\nParser.prototype = {\n  constructor: Parser,\n\n  parse: function(text) {\n    return this.astCompiler.compile(text, this.options.expensiveChecks);\n  }\n};\n\nvar getterFnCacheDefault = createMap();\nvar getterFnCacheExpensive = createMap();\n\nfunction isPossiblyDangerousMemberName(name) {\n  return name == 'constructor';\n}\n\nvar objectValueOf = Object.prototype.valueOf;\n\nfunction getValueOf(value) {\n  return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);\n}\n\n///////////////////////////////////\n\n/**\n * @ngdoc service\n * @name $parse\n * @kind function\n *\n * @description\n *\n * Converts Angular {@link guide/expression expression} into a function.\n *\n * ```js\n *   var getter = $parse('user.name');\n *   var setter = getter.assign;\n *   var context = {user:{name:'angular'}};\n *   var locals = {user:{name:'local'}};\n *\n *   expect(getter(context)).toEqual('angular');\n *   setter(context, 'newValue');\n *   expect(context.user.name).toEqual('newValue');\n *   expect(getter(context, locals)).toEqual('local');\n * ```\n *\n *\n * @param {string} expression String expression to compile.\n * @returns {function(context, locals)} a function which represents the compiled expression:\n *\n *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n *      are evaluated against (typically a scope object).\n *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n *      `context`.\n *\n *    The returned function also has the following properties:\n *      * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript\n *        literal.\n *      * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript\n *        constant literals.\n *      * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be\n *        set to a function to change its value on the given context.\n *\n */\n\n\n/**\n * @ngdoc provider\n * @name $parseProvider\n *\n * @description\n * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}\n *  service.\n */\nfunction $ParseProvider() {\n  var cacheDefault = createMap();\n  var cacheExpensive = createMap();\n\n  this.$get = ['$filter', function($filter) {\n    var noUnsafeEval = csp().noUnsafeEval;\n    var $parseOptions = {\n          csp: noUnsafeEval,\n          expensiveChecks: false\n        },\n        $parseOptionsExpensive = {\n          csp: noUnsafeEval,\n          expensiveChecks: true\n        };\n\n    return function $parse(exp, interceptorFn, expensiveChecks) {\n      var parsedExpression, oneTime, cacheKey;\n\n      switch (typeof exp) {\n        case 'string':\n          exp = exp.trim();\n          cacheKey = exp;\n\n          var cache = (expensiveChecks ? cacheExpensive : cacheDefault);\n          parsedExpression = cache[cacheKey];\n\n          if (!parsedExpression) {\n            if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {\n              oneTime = true;\n              exp = exp.substring(2);\n            }\n            var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;\n            var lexer = new Lexer(parseOptions);\n            var parser = new Parser(lexer, $filter, parseOptions);\n            parsedExpression = parser.parse(exp);\n            if (parsedExpression.constant) {\n              parsedExpression.$$watchDelegate = constantWatchDelegate;\n            } else if (oneTime) {\n              parsedExpression.$$watchDelegate = parsedExpression.literal ?\n                  oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;\n            } else if (parsedExpression.inputs) {\n              parsedExpression.$$watchDelegate = inputsWatchDelegate;\n            }\n            cache[cacheKey] = parsedExpression;\n          }\n          return addInterceptor(parsedExpression, interceptorFn);\n\n        case 'function':\n          return addInterceptor(exp, interceptorFn);\n\n        default:\n          return noop;\n      }\n    };\n\n    function expressionInputDirtyCheck(newValue, oldValueOfValue) {\n\n      if (newValue == null || oldValueOfValue == null) { // null/undefined\n        return newValue === oldValueOfValue;\n      }\n\n      if (typeof newValue === 'object') {\n\n        // attempt to convert the value to a primitive type\n        // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can\n        //             be cheaply dirty-checked\n        newValue = getValueOf(newValue);\n\n        if (typeof newValue === 'object') {\n          // objects/arrays are not supported - deep-watching them would be too expensive\n          return false;\n        }\n\n        // fall-through to the primitive equality check\n      }\n\n      //Primitive or NaN\n      return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);\n    }\n\n    function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {\n      var inputExpressions = parsedExpression.inputs;\n      var lastResult;\n\n      if (inputExpressions.length === 1) {\n        var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails\n        inputExpressions = inputExpressions[0];\n        return scope.$watch(function expressionInputWatch(scope) {\n          var newInputValue = inputExpressions(scope);\n          if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {\n            lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);\n            oldInputValueOf = newInputValue && getValueOf(newInputValue);\n          }\n          return lastResult;\n        }, listener, objectEquality, prettyPrintExpression);\n      }\n\n      var oldInputValueOfValues = [];\n      var oldInputValues = [];\n      for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n        oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails\n        oldInputValues[i] = null;\n      }\n\n      return scope.$watch(function expressionInputsWatch(scope) {\n        var changed = false;\n\n        for (var i = 0, ii = inputExpressions.length; i < ii; i++) {\n          var newInputValue = inputExpressions[i](scope);\n          if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {\n            oldInputValues[i] = newInputValue;\n            oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);\n          }\n        }\n\n        if (changed) {\n          lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);\n        }\n\n        return lastResult;\n      }, listener, objectEquality, prettyPrintExpression);\n    }\n\n    function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        if (isDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isDefined(lastValue)) {\n              unwatch();\n            }\n          });\n        }\n      }, objectEquality);\n    }\n\n    function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch, lastValue;\n      return unwatch = scope.$watch(function oneTimeWatch(scope) {\n        return parsedExpression(scope);\n      }, function oneTimeListener(value, old, scope) {\n        lastValue = value;\n        if (isFunction(listener)) {\n          listener.call(this, value, old, scope);\n        }\n        if (isAllDefined(value)) {\n          scope.$$postDigest(function() {\n            if (isAllDefined(lastValue)) unwatch();\n          });\n        }\n      }, objectEquality);\n\n      function isAllDefined(value) {\n        var allDefined = true;\n        forEach(value, function(val) {\n          if (!isDefined(val)) allDefined = false;\n        });\n        return allDefined;\n      }\n    }\n\n    function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {\n      var unwatch;\n      return unwatch = scope.$watch(function constantWatch(scope) {\n        return parsedExpression(scope);\n      }, function constantListener(value, old, scope) {\n        if (isFunction(listener)) {\n          listener.apply(this, arguments);\n        }\n        unwatch();\n      }, objectEquality);\n    }\n\n    function addInterceptor(parsedExpression, interceptorFn) {\n      if (!interceptorFn) return parsedExpression;\n      var watchDelegate = parsedExpression.$$watchDelegate;\n\n      var regularWatch =\n          watchDelegate !== oneTimeLiteralWatchDelegate &&\n          watchDelegate !== oneTimeWatchDelegate;\n\n      var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {\n        var value = parsedExpression(scope, locals, assign, inputs);\n        return interceptorFn(value, scope, locals);\n      } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {\n        var value = parsedExpression(scope, locals, assign, inputs);\n        var result = interceptorFn(value, scope, locals);\n        // we only return the interceptor's result if the\n        // initial value is defined (for bind-once)\n        return isDefined(value) ? result : value;\n      };\n\n      // Propagate $$watchDelegates other then inputsWatchDelegate\n      if (parsedExpression.$$watchDelegate &&\n          parsedExpression.$$watchDelegate !== inputsWatchDelegate) {\n        fn.$$watchDelegate = parsedExpression.$$watchDelegate;\n      } else if (!interceptorFn.$stateful) {\n        // If there is an interceptor, but no watchDelegate then treat the interceptor like\n        // we treat filters - it is assumed to be a pure function unless flagged with $stateful\n        fn.$$watchDelegate = inputsWatchDelegate;\n        fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];\n      }\n\n      return fn;\n    }\n  }];\n}\n\n/**\n * @ngdoc service\n * @name $q\n * @requires $rootScope\n *\n * @description\n * A service that helps you run functions asynchronously, and use their return values (or exceptions)\n * when they are done processing.\n *\n * This is an implementation of promises/deferred objects inspired by\n * [Kris Kowal's Q](https://github.com/kriskowal/q).\n *\n * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred\n * implementations, and the other which resembles ES6 promises to some degree.\n *\n * # $q constructor\n *\n * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`\n * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,\n * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).\n *\n * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are\n * available yet.\n *\n * It can be used like so:\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     // perform some asynchronous operation, resolve or reject the promise when appropriate.\n *     return $q(function(resolve, reject) {\n *       setTimeout(function() {\n *         if (okToGreet(name)) {\n *           resolve('Hello, ' + name + '!');\n *         } else {\n *           reject('Greeting ' + name + ' is not allowed.');\n *         }\n *       }, 1000);\n *     });\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   });\n * ```\n *\n * Note: progress/notify callbacks are not currently supported via the ES6-style interface.\n *\n * However, the more traditional CommonJS-style usage is still available, and documented below.\n *\n * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an\n * interface for interacting with an object that represents the result of an action that is\n * performed asynchronously, and may or may not be finished at any given point in time.\n *\n * From the perspective of dealing with error handling, deferred and promise APIs are to\n * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.\n *\n * ```js\n *   // for the purpose of this example let's assume that variables `$q` and `okToGreet`\n *   // are available in the current lexical scope (they could have been injected or passed in).\n *\n *   function asyncGreet(name) {\n *     var deferred = $q.defer();\n *\n *     setTimeout(function() {\n *       deferred.notify('About to greet ' + name + '.');\n *\n *       if (okToGreet(name)) {\n *         deferred.resolve('Hello, ' + name + '!');\n *       } else {\n *         deferred.reject('Greeting ' + name + ' is not allowed.');\n *       }\n *     }, 1000);\n *\n *     return deferred.promise;\n *   }\n *\n *   var promise = asyncGreet('Robin Hood');\n *   promise.then(function(greeting) {\n *     alert('Success: ' + greeting);\n *   }, function(reason) {\n *     alert('Failed: ' + reason);\n *   }, function(update) {\n *     alert('Got notification: ' + update);\n *   });\n * ```\n *\n * At first it might not be obvious why this extra complexity is worth the trouble. The payoff\n * comes in the way of guarantees that promise and deferred APIs make, see\n * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.\n *\n * Additionally the promise api allows for composition that is very hard to do with the\n * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.\n * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the\n * section on serial or parallel joining of promises.\n *\n * # The Deferred API\n *\n * A new instance of deferred is constructed by calling `$q.defer()`.\n *\n * The purpose of the deferred object is to expose the associated Promise instance as well as APIs\n * that can be used for signaling the successful or unsuccessful completion, as well as the status\n * of the task.\n *\n * **Methods**\n *\n * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection\n *   constructed via `$q.reject`, the promise will be rejected instead.\n * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to\n *   resolving it with a rejection constructed via `$q.reject`.\n * - `notify(value)` - provides updates on the status of the promise's execution. This may be called\n *   multiple times before the promise is either resolved or rejected.\n *\n * **Properties**\n *\n * - promise – `{Promise}` – promise object associated with this deferred.\n *\n *\n * # The Promise API\n *\n * A new promise instance is created when a deferred instance is created and can be retrieved by\n * calling `deferred.promise`.\n *\n * The purpose of the promise object is to allow for interested parties to get access to the result\n * of the deferred task when it completes.\n *\n * **Methods**\n *\n * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or\n *   will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously\n *   as soon as the result is available. The callbacks are called with a single argument: the result\n *   or rejection reason. Additionally, the notify callback may be called zero or more times to\n *   provide a progress indication, before the promise is resolved or rejected.\n *\n *   This method *returns a new promise* which is resolved or rejected via the return value of the\n *   `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved\n *   with the value which is resolved in that promise using\n *   [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).\n *   It also notifies via the return value of the `notifyCallback` method. The promise cannot be\n *   resolved or rejected from the notifyCallback method.\n *\n * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`\n *\n * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,\n *   but to do so without modifying the final value. This is useful to release resources or do some\n *   clean-up that needs to be done whether the promise was rejected or resolved. See the [full\n *   specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for\n *   more information.\n *\n * # Chaining promises\n *\n * Because calling the `then` method of a promise returns a new derived promise, it is easily\n * possible to create a chain of promises:\n *\n * ```js\n *   promiseB = promiseA.then(function(result) {\n *     return result + 1;\n *   });\n *\n *   // promiseB will be resolved immediately after promiseA is resolved and its value\n *   // will be the result of promiseA incremented by 1\n * ```\n *\n * It is possible to create chains of any length and since a promise can be resolved with another\n * promise (which will defer its resolution further), it is possible to pause/defer resolution of\n * the promises at any point in the chain. This makes it possible to implement powerful APIs like\n * $http's response interceptors.\n *\n *\n * # Differences between Kris Kowal's Q and $q\n *\n *  There are two main differences:\n *\n * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation\n *   mechanism in angular, which means faster propagation of resolution or rejection into your\n *   models and avoiding unnecessary browser repaints, which would result in flickering UI.\n * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains\n *   all the important functionality needed for common async tasks.\n *\n *  # Testing\n *\n *  ```js\n *    it('should simulate promise', inject(function($q, $rootScope) {\n *      var deferred = $q.defer();\n *      var promise = deferred.promise;\n *      var resolvedValue;\n *\n *      promise.then(function(value) { resolvedValue = value; });\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Simulate resolving of promise\n *      deferred.resolve(123);\n *      // Note that the 'then' function does not get called synchronously.\n *      // This is because we want the promise API to always be async, whether or not\n *      // it got called synchronously or asynchronously.\n *      expect(resolvedValue).toBeUndefined();\n *\n *      // Propagate promise resolution to 'then' functions using $apply().\n *      $rootScope.$apply();\n *      expect(resolvedValue).toEqual(123);\n *    }));\n *  ```\n *\n * @param {function(function, function)} resolver Function which is responsible for resolving or\n *   rejecting the newly created promise. The first parameter is a function which resolves the\n *   promise, the second parameter is a function which rejects the promise.\n *\n * @returns {Promise} The newly created promise.\n */\nfunction $QProvider() {\n\n  this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $rootScope.$evalAsync(callback);\n    }, $exceptionHandler);\n  }];\n}\n\nfunction $$QProvider() {\n  this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {\n    return qFactory(function(callback) {\n      $browser.defer(callback);\n    }, $exceptionHandler);\n  }];\n}\n\n/**\n * Constructs a promise manager.\n *\n * @param {function(function)} nextTick Function for executing functions in the next turn.\n * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for\n *     debugging purposes.\n * @returns {object} Promise manager.\n */\nfunction qFactory(nextTick, exceptionHandler) {\n  var $qMinErr = minErr('$q', TypeError);\n  function callOnce(self, resolveFn, rejectFn) {\n    var called = false;\n    function wrap(fn) {\n      return function(value) {\n        if (called) return;\n        called = true;\n        fn.call(self, value);\n      };\n    }\n\n    return [wrap(resolveFn), wrap(rejectFn)];\n  }\n\n  /**\n   * @ngdoc method\n   * @name ng.$q#defer\n   * @kind function\n   *\n   * @description\n   * Creates a `Deferred` object which represents a task which will finish in the future.\n   *\n   * @returns {Deferred} Returns a new instance of deferred.\n   */\n  var defer = function() {\n    return new Deferred();\n  };\n\n  function Promise() {\n    this.$$state = { status: 0 };\n  }\n\n  extend(Promise.prototype, {\n    then: function(onFulfilled, onRejected, progressBack) {\n      if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {\n        return this;\n      }\n      var result = new Deferred();\n\n      this.$$state.pending = this.$$state.pending || [];\n      this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);\n      if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);\n\n      return result.promise;\n    },\n\n    \"catch\": function(callback) {\n      return this.then(null, callback);\n    },\n\n    \"finally\": function(callback, progressBack) {\n      return this.then(function(value) {\n        return handleCallback(value, true, callback);\n      }, function(error) {\n        return handleCallback(error, false, callback);\n      }, progressBack);\n    }\n  });\n\n  //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native\n  function simpleBind(context, fn) {\n    return function(value) {\n      fn.call(context, value);\n    };\n  }\n\n  function processQueue(state) {\n    var fn, deferred, pending;\n\n    pending = state.pending;\n    state.processScheduled = false;\n    state.pending = undefined;\n    for (var i = 0, ii = pending.length; i < ii; ++i) {\n      deferred = pending[i][0];\n      fn = pending[i][state.status];\n      try {\n        if (isFunction(fn)) {\n          deferred.resolve(fn(state.value));\n        } else if (state.status === 1) {\n          deferred.resolve(state.value);\n        } else {\n          deferred.reject(state.value);\n        }\n      } catch (e) {\n        deferred.reject(e);\n        exceptionHandler(e);\n      }\n    }\n  }\n\n  function scheduleProcessQueue(state) {\n    if (state.processScheduled || !state.pending) return;\n    state.processScheduled = true;\n    nextTick(function() { processQueue(state); });\n  }\n\n  function Deferred() {\n    this.promise = new Promise();\n    //Necessary to support unbound execution :/\n    this.resolve = simpleBind(this, this.resolve);\n    this.reject = simpleBind(this, this.reject);\n    this.notify = simpleBind(this, this.notify);\n  }\n\n  extend(Deferred.prototype, {\n    resolve: function(val) {\n      if (this.promise.$$state.status) return;\n      if (val === this.promise) {\n        this.$$reject($qMinErr(\n          'qcycle',\n          \"Expected promise to be resolved with value other than itself '{0}'\",\n          val));\n      } else {\n        this.$$resolve(val);\n      }\n\n    },\n\n    $$resolve: function(val) {\n      var then, fns;\n\n      fns = callOnce(this, this.$$resolve, this.$$reject);\n      try {\n        if ((isObject(val) || isFunction(val))) then = val && val.then;\n        if (isFunction(then)) {\n          this.promise.$$state.status = -1;\n          then.call(val, fns[0], fns[1], this.notify);\n        } else {\n          this.promise.$$state.value = val;\n          this.promise.$$state.status = 1;\n          scheduleProcessQueue(this.promise.$$state);\n        }\n      } catch (e) {\n        fns[1](e);\n        exceptionHandler(e);\n      }\n    },\n\n    reject: function(reason) {\n      if (this.promise.$$state.status) return;\n      this.$$reject(reason);\n    },\n\n    $$reject: function(reason) {\n      this.promise.$$state.value = reason;\n      this.promise.$$state.status = 2;\n      scheduleProcessQueue(this.promise.$$state);\n    },\n\n    notify: function(progress) {\n      var callbacks = this.promise.$$state.pending;\n\n      if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {\n        nextTick(function() {\n          var callback, result;\n          for (var i = 0, ii = callbacks.length; i < ii; i++) {\n            result = callbacks[i][0];\n            callback = callbacks[i][3];\n            try {\n              result.notify(isFunction(callback) ? callback(progress) : progress);\n            } catch (e) {\n              exceptionHandler(e);\n            }\n          }\n        });\n      }\n    }\n  });\n\n  /**\n   * @ngdoc method\n   * @name $q#reject\n   * @kind function\n   *\n   * @description\n   * Creates a promise that is resolved as rejected with the specified `reason`. This api should be\n   * used to forward rejection in a chain of promises. If you are dealing with the last promise in\n   * a promise chain, you don't need to worry about it.\n   *\n   * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of\n   * `reject` as the `throw` keyword in JavaScript. This also means that if you \"catch\" an error via\n   * a promise error callback and you want to forward the error to the promise derived from the\n   * current promise, you have to \"rethrow\" the error by returning a rejection constructed via\n   * `reject`.\n   *\n   * ```js\n   *   promiseB = promiseA.then(function(result) {\n   *     // success: do something and resolve promiseB\n   *     //          with the old or a new result\n   *     return result;\n   *   }, function(reason) {\n   *     // error: handle the error if possible and\n   *     //        resolve promiseB with newPromiseOrValue,\n   *     //        otherwise forward the rejection to promiseB\n   *     if (canHandle(reason)) {\n   *      // handle the error and recover\n   *      return newPromiseOrValue;\n   *     }\n   *     return $q.reject(reason);\n   *   });\n   * ```\n   *\n   * @param {*} reason Constant, message, exception or an object representing the rejection reason.\n   * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.\n   */\n  var reject = function(reason) {\n    var result = new Deferred();\n    result.reject(reason);\n    return result.promise;\n  };\n\n  var makePromise = function makePromise(value, resolved) {\n    var result = new Deferred();\n    if (resolved) {\n      result.resolve(value);\n    } else {\n      result.reject(value);\n    }\n    return result.promise;\n  };\n\n  var handleCallback = function handleCallback(value, isResolved, callback) {\n    var callbackOutput = null;\n    try {\n      if (isFunction(callback)) callbackOutput = callback();\n    } catch (e) {\n      return makePromise(e, false);\n    }\n    if (isPromiseLike(callbackOutput)) {\n      return callbackOutput.then(function() {\n        return makePromise(value, isResolved);\n      }, function(error) {\n        return makePromise(error, false);\n      });\n    } else {\n      return makePromise(value, isResolved);\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#when\n   * @kind function\n   *\n   * @description\n   * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.\n   * This is useful when you are dealing with an object that might or might not be a promise, or if\n   * the promise comes from a source that can't be trusted.\n   *\n   * @param {*} value Value or a promise\n   * @param {Function=} successCallback\n   * @param {Function=} errorCallback\n   * @param {Function=} progressCallback\n   * @returns {Promise} Returns a promise of the passed value or promise\n   */\n\n\n  var when = function(value, callback, errback, progressBack) {\n    var result = new Deferred();\n    result.resolve(value);\n    return result.promise.then(callback, errback, progressBack);\n  };\n\n  /**\n   * @ngdoc method\n   * @name $q#resolve\n   * @kind function\n   *\n   * @description\n   * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.\n   *\n   * @param {*} value Value or a promise\n   * @param {Function=} successCallback\n   * @param {Function=} errorCallback\n   * @param {Function=} progressCallback\n   * @returns {Promise} Returns a promise of the passed value or promise\n   */\n  var resolve = when;\n\n  /**\n   * @ngdoc method\n   * @name $q#all\n   * @kind function\n   *\n   * @description\n   * Combines multiple promises into a single promise that is resolved when all of the input\n   * promises are resolved.\n   *\n   * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.\n   * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,\n   *   each value corresponding to the promise at the same index/key in the `promises` array/hash.\n   *   If any of the promises is resolved with a rejection, this resulting promise will be rejected\n   *   with the same rejection value.\n   */\n\n  function all(promises) {\n    var deferred = new Deferred(),\n        counter = 0,\n        results = isArray(promises) ? [] : {};\n\n    forEach(promises, function(promise, key) {\n      counter++;\n      when(promise).then(function(value) {\n        if (results.hasOwnProperty(key)) return;\n        results[key] = value;\n        if (!(--counter)) deferred.resolve(results);\n      }, function(reason) {\n        if (results.hasOwnProperty(key)) return;\n        deferred.reject(reason);\n      });\n    });\n\n    if (counter === 0) {\n      deferred.resolve(results);\n    }\n\n    return deferred.promise;\n  }\n\n  var $Q = function Q(resolver) {\n    if (!isFunction(resolver)) {\n      throw $qMinErr('norslvr', \"Expected resolverFn, got '{0}'\", resolver);\n    }\n\n    if (!(this instanceof Q)) {\n      // More useful when $Q is the Promise itself.\n      return new Q(resolver);\n    }\n\n    var deferred = new Deferred();\n\n    function resolveFn(value) {\n      deferred.resolve(value);\n    }\n\n    function rejectFn(reason) {\n      deferred.reject(reason);\n    }\n\n    resolver(resolveFn, rejectFn);\n\n    return deferred.promise;\n  };\n\n  $Q.defer = defer;\n  $Q.reject = reject;\n  $Q.when = when;\n  $Q.resolve = resolve;\n  $Q.all = all;\n\n  return $Q;\n}\n\nfunction $$RAFProvider() { //rAF\n  this.$get = ['$window', '$timeout', function($window, $timeout) {\n    var requestAnimationFrame = $window.requestAnimationFrame ||\n                                $window.webkitRequestAnimationFrame;\n\n    var cancelAnimationFrame = $window.cancelAnimationFrame ||\n                               $window.webkitCancelAnimationFrame ||\n                               $window.webkitCancelRequestAnimationFrame;\n\n    var rafSupported = !!requestAnimationFrame;\n    var rafFn = rafSupported\n      ? function(fn) {\n          var id = requestAnimationFrame(fn);\n          return function() {\n            cancelAnimationFrame(id);\n          };\n        }\n      : function(fn) {\n          var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666\n          return function() {\n            $timeout.cancel(timer);\n          };\n        };\n\n    queueFn.supported = rafSupported;\n\n    var cancelLastRAF;\n    var taskCount = 0;\n    var taskQueue = [];\n    return queueFn;\n\n    function flush() {\n      for (var i = 0; i < taskQueue.length; i++) {\n        var task = taskQueue[i];\n        if (task) {\n          taskQueue[i] = null;\n          task();\n        }\n      }\n      taskCount = taskQueue.length = 0;\n    }\n\n    function queueFn(asyncFn) {\n      var index = taskQueue.length;\n\n      taskCount++;\n      taskQueue.push(asyncFn);\n\n      if (index === 0) {\n        cancelLastRAF = rafFn(flush);\n      }\n\n      return function cancelQueueFn() {\n        if (index >= 0) {\n          taskQueue[index] = null;\n          index = null;\n\n          if (--taskCount === 0 && cancelLastRAF) {\n            cancelLastRAF();\n            cancelLastRAF = null;\n            taskQueue.length = 0;\n          }\n        }\n      };\n    }\n  }];\n}\n\n/**\n * DESIGN NOTES\n *\n * The design decisions behind the scope are heavily favored for speed and memory consumption.\n *\n * The typical use of scope is to watch the expressions, which most of the time return the same\n * value as last time so we optimize the operation.\n *\n * Closures construction is expensive in terms of speed as well as memory:\n *   - No closures, instead use prototypical inheritance for API\n *   - Internal state needs to be stored on scope directly, which means that private state is\n *     exposed as $$____ properties\n *\n * Loop operations are optimized by using while(count--) { ... }\n *   - this means that in order to keep the same order of execution as addition we have to add\n *     items to the array at the beginning (unshift) instead of at the end (push)\n *\n * Child scopes are created and removed often\n *   - Using an array would be slow since inserts in middle are expensive so we use linked list\n *\n * There are few watches then a lot of observers. This is why you don't want the observer to be\n * implemented in the same way as watch. Watch requires return of initialization function which\n * are expensive to construct.\n */\n\n\n/**\n * @ngdoc provider\n * @name $rootScopeProvider\n * @description\n *\n * Provider for the $rootScope service.\n */\n\n/**\n * @ngdoc method\n * @name $rootScopeProvider#digestTtl\n * @description\n *\n * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and\n * assuming that the model is unstable.\n *\n * The current default is 10 iterations.\n *\n * In complex applications it's possible that the dependencies between `$watch`s will result in\n * several digest iterations. However if an application needs more than the default 10 digest\n * iterations for its model to stabilize then you should investigate what is causing the model to\n * continuously change during the digest.\n *\n * Increasing the TTL could have performance implications, so you should not change it without\n * proper justification.\n *\n * @param {number} limit The number of digest iterations.\n */\n\n\n/**\n * @ngdoc service\n * @name $rootScope\n * @description\n *\n * Every application has a single root {@link ng.$rootScope.Scope scope}.\n * All other scopes are descendant scopes of the root scope. Scopes provide separation\n * between the model and the view, via a mechanism for watching the model for changes.\n * They also provide an event emission/broadcast and subscription facility. See the\n * {@link guide/scope developer guide on scopes}.\n */\nfunction $RootScopeProvider() {\n  var TTL = 10;\n  var $rootScopeMinErr = minErr('$rootScope');\n  var lastDirtyWatch = null;\n  var applyAsyncId = null;\n\n  this.digestTtl = function(value) {\n    if (arguments.length) {\n      TTL = value;\n    }\n    return TTL;\n  };\n\n  function createChildScopeClass(parent) {\n    function ChildScope() {\n      this.$$watchers = this.$$nextSibling =\n          this.$$childHead = this.$$childTail = null;\n      this.$$listeners = {};\n      this.$$listenerCount = {};\n      this.$$watchersCount = 0;\n      this.$id = nextUid();\n      this.$$ChildScope = null;\n    }\n    ChildScope.prototype = parent;\n    return ChildScope;\n  }\n\n  this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',\n      function($injector, $exceptionHandler, $parse, $browser) {\n\n    function destroyChildScope($event) {\n        $event.currentScope.$$destroyed = true;\n    }\n\n    /**\n     * @ngdoc type\n     * @name $rootScope.Scope\n     *\n     * @description\n     * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the\n     * {@link auto.$injector $injector}. Child scopes are created using the\n     * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when\n     * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for\n     * an in-depth introduction and usage examples.\n     *\n     *\n     * # Inheritance\n     * A scope can inherit from a parent scope, as in this example:\n     * ```js\n         var parent = $rootScope;\n         var child = parent.$new();\n\n         parent.salutation = \"Hello\";\n         expect(child.salutation).toEqual('Hello');\n\n         child.salutation = \"Welcome\";\n         expect(child.salutation).toEqual('Welcome');\n         expect(parent.salutation).toEqual('Hello');\n     * ```\n     *\n     * When interacting with `Scope` in tests, additional helper methods are available on the\n     * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional\n     * details.\n     *\n     *\n     * @param {Object.<string, function()>=} providers Map of service factory which need to be\n     *                                       provided for the current scope. Defaults to {@link ng}.\n     * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should\n     *                              append/override services provided by `providers`. This is handy\n     *                              when unit-testing and having the need to override a default\n     *                              service.\n     * @returns {Object} Newly created scope.\n     *\n     */\n    function Scope() {\n      this.$id = nextUid();\n      this.$$phase = this.$parent = this.$$watchers =\n                     this.$$nextSibling = this.$$prevSibling =\n                     this.$$childHead = this.$$childTail = null;\n      this.$root = this;\n      this.$$destroyed = false;\n      this.$$listeners = {};\n      this.$$listenerCount = {};\n      this.$$watchersCount = 0;\n      this.$$isolateBindings = null;\n    }\n\n    /**\n     * @ngdoc property\n     * @name $rootScope.Scope#$id\n     *\n     * @description\n     * Unique scope ID (monotonically increasing) useful for debugging.\n     */\n\n     /**\n      * @ngdoc property\n      * @name $rootScope.Scope#$parent\n      *\n      * @description\n      * Reference to the parent scope.\n      */\n\n      /**\n       * @ngdoc property\n       * @name $rootScope.Scope#$root\n       *\n       * @description\n       * Reference to the root scope.\n       */\n\n    Scope.prototype = {\n      constructor: Scope,\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$new\n       * @kind function\n       *\n       * @description\n       * Creates a new child {@link ng.$rootScope.Scope scope}.\n       *\n       * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.\n       * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.\n       *\n       * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is\n       * desired for the scope and its child scopes to be permanently detached from the parent and\n       * thus stop participating in model change detection and listener notification by invoking.\n       *\n       * @param {boolean} isolate If true, then the scope does not prototypically inherit from the\n       *         parent scope. The scope is isolated, as it can not see parent scope properties.\n       *         When creating widgets, it is useful for the widget to not accidentally read parent\n       *         state.\n       *\n       * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`\n       *                              of the newly created scope. Defaults to `this` scope if not provided.\n       *                              This is used when creating a transclude scope to correctly place it\n       *                              in the scope hierarchy while maintaining the correct prototypical\n       *                              inheritance.\n       *\n       * @returns {Object} The newly created child scope.\n       *\n       */\n      $new: function(isolate, parent) {\n        var child;\n\n        parent = parent || this;\n\n        if (isolate) {\n          child = new Scope();\n          child.$root = this.$root;\n        } else {\n          // Only create a child scope class if somebody asks for one,\n          // but cache it to allow the VM to optimize lookups.\n          if (!this.$$ChildScope) {\n            this.$$ChildScope = createChildScopeClass(this);\n          }\n          child = new this.$$ChildScope();\n        }\n        child.$parent = parent;\n        child.$$prevSibling = parent.$$childTail;\n        if (parent.$$childHead) {\n          parent.$$childTail.$$nextSibling = child;\n          parent.$$childTail = child;\n        } else {\n          parent.$$childHead = parent.$$childTail = child;\n        }\n\n        // When the new scope is not isolated or we inherit from `this`, and\n        // the parent scope is destroyed, the property `$$destroyed` is inherited\n        // prototypically. In all other cases, this property needs to be set\n        // when the parent scope is destroyed.\n        // The listener needs to be added after the parent is set\n        if (isolate || parent != this) child.$on('$destroy', destroyChildScope);\n\n        return child;\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watch\n       * @kind function\n       *\n       * @description\n       * Registers a `listener` callback to be executed whenever the `watchExpression` changes.\n       *\n       * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest\n       *   $digest()} and should return the value that will be watched. (Since\n       *   {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the\n       *   `watchExpression` can execute multiple times per\n       *   {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)\n       * - The `listener` is called only when the value from the current `watchExpression` and the\n       *   previous call to `watchExpression` are not equal (with the exception of the initial run,\n       *   see below). Inequality is determined according to reference inequality,\n       *   [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)\n       *    via the `!==` Javascript operator, unless `objectEquality == true`\n       *   (see next point)\n       * - When `objectEquality == true`, inequality of the `watchExpression` is determined\n       *   according to the {@link angular.equals} function. To save the value of the object for\n       *   later comparison, the {@link angular.copy} function is used. This therefore means that\n       *   watching complex objects will have adverse memory and performance implications.\n       * - The watch `listener` may change the model, which may trigger other `listener`s to fire.\n       *   This is achieved by rerunning the watchers until no changes are detected. The rerun\n       *   iteration limit is 10 to prevent an infinite loop deadlock.\n       *\n       *\n       * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,\n       * you can register a `watchExpression` function with no `listener`. (Be prepared for\n       * multiple calls to your `watchExpression` because it will execute multiple times in a\n       * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)\n       *\n       * After a watcher is registered with the scope, the `listener` fn is called asynchronously\n       * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the\n       * watcher. In rare cases, this is undesirable because the listener is called when the result\n       * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you\n       * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the\n       * listener was called due to initialization.\n       *\n       *\n       *\n       * # Example\n       * ```js\n           // let's assume that scope was dependency injected as the $rootScope\n           var scope = $rootScope;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n\n\n\n           // Using a function as a watchExpression\n           var food;\n           scope.foodCounter = 0;\n           expect(scope.foodCounter).toEqual(0);\n           scope.$watch(\n             // This function returns the value being watched. It is called for each turn of the $digest loop\n             function() { return food; },\n             // This is the change listener, called when the value returned from the above function changes\n             function(newValue, oldValue) {\n               if ( newValue !== oldValue ) {\n                 // Only increment the counter if the value changed\n                 scope.foodCounter = scope.foodCounter + 1;\n               }\n             }\n           );\n           // No digest has been run so the counter will be zero\n           expect(scope.foodCounter).toEqual(0);\n\n           // Run the digest but since food has not changed count will still be zero\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(0);\n\n           // Update food and run digest.  Now the counter will increment\n           food = 'cheeseburger';\n           scope.$digest();\n           expect(scope.foodCounter).toEqual(1);\n\n       * ```\n       *\n       *\n       *\n       * @param {(function()|string)} watchExpression Expression that is evaluated on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers\n       *    a call to the `listener`.\n       *\n       *    - `string`: Evaluated as {@link guide/expression expression}\n       *    - `function(scope)`: called with current `scope` as a parameter.\n       * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value\n       *    of `watchExpression` changes.\n       *\n       *    - `newVal` contains the current value of the `watchExpression`\n       *    - `oldVal` contains the previous value of the `watchExpression`\n       *    - `scope` refers to the current scope\n       * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of\n       *     comparing for reference equality.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {\n        var get = $parse(watchExp);\n\n        if (get.$$watchDelegate) {\n          return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);\n        }\n        var scope = this,\n            array = scope.$$watchers,\n            watcher = {\n              fn: listener,\n              last: initWatchVal,\n              get: get,\n              exp: prettyPrintExpression || watchExp,\n              eq: !!objectEquality\n            };\n\n        lastDirtyWatch = null;\n\n        if (!isFunction(listener)) {\n          watcher.fn = noop;\n        }\n\n        if (!array) {\n          array = scope.$$watchers = [];\n        }\n        // we use unshift since we use a while loop in $digest for speed.\n        // the while loop reads in reverse order.\n        array.unshift(watcher);\n        incrementWatchersCount(this, 1);\n\n        return function deregisterWatch() {\n          if (arrayRemove(array, watcher) >= 0) {\n            incrementWatchersCount(scope, -1);\n          }\n          lastDirtyWatch = null;\n        };\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchGroup\n       * @kind function\n       *\n       * @description\n       * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.\n       * If any one expression in the collection changes the `listener` is executed.\n       *\n       * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every\n       *   call to $digest() to see if any items changes.\n       * - The `listener` is called whenever any expression in the `watchExpressions` array changes.\n       *\n       * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually\n       * watched using {@link ng.$rootScope.Scope#$watch $watch()}\n       *\n       * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any\n       *    expression in `watchExpressions` changes\n       *    The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching\n       *    those of `watchExpression`\n       *    The `scope` refers to the current scope.\n       * @returns {function()} Returns a de-registration function for all listeners.\n       */\n      $watchGroup: function(watchExpressions, listener) {\n        var oldValues = new Array(watchExpressions.length);\n        var newValues = new Array(watchExpressions.length);\n        var deregisterFns = [];\n        var self = this;\n        var changeReactionScheduled = false;\n        var firstRun = true;\n\n        if (!watchExpressions.length) {\n          // No expressions means we call the listener ASAP\n          var shouldCall = true;\n          self.$evalAsync(function() {\n            if (shouldCall) listener(newValues, newValues, self);\n          });\n          return function deregisterWatchGroup() {\n            shouldCall = false;\n          };\n        }\n\n        if (watchExpressions.length === 1) {\n          // Special case size of one\n          return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {\n            newValues[0] = value;\n            oldValues[0] = oldValue;\n            listener(newValues, (value === oldValue) ? newValues : oldValues, scope);\n          });\n        }\n\n        forEach(watchExpressions, function(expr, i) {\n          var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {\n            newValues[i] = value;\n            oldValues[i] = oldValue;\n            if (!changeReactionScheduled) {\n              changeReactionScheduled = true;\n              self.$evalAsync(watchGroupAction);\n            }\n          });\n          deregisterFns.push(unwatchFn);\n        });\n\n        function watchGroupAction() {\n          changeReactionScheduled = false;\n\n          if (firstRun) {\n            firstRun = false;\n            listener(newValues, newValues, self);\n          } else {\n            listener(newValues, oldValues, self);\n          }\n        }\n\n        return function deregisterWatchGroup() {\n          while (deregisterFns.length) {\n            deregisterFns.shift()();\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$watchCollection\n       * @kind function\n       *\n       * @description\n       * Shallow watches the properties of an object and fires whenever any of the properties change\n       * (for arrays, this implies watching the array items; for object maps, this implies watching\n       * the properties). If a change is detected, the `listener` callback is fired.\n       *\n       * - The `obj` collection is observed via standard $watch operation and is examined on every\n       *   call to $digest() to see if any items have been added, removed, or moved.\n       * - The `listener` is called whenever anything within the `obj` has changed. Examples include\n       *   adding, removing, and moving items belonging to an object or array.\n       *\n       *\n       * # Example\n       * ```js\n          $scope.names = ['igor', 'matias', 'misko', 'james'];\n          $scope.dataCount = 4;\n\n          $scope.$watchCollection('names', function(newNames, oldNames) {\n            $scope.dataCount = newNames.length;\n          });\n\n          expect($scope.dataCount).toEqual(4);\n          $scope.$digest();\n\n          //still at 4 ... no changes\n          expect($scope.dataCount).toEqual(4);\n\n          $scope.names.pop();\n          $scope.$digest();\n\n          //now there's been a change\n          expect($scope.dataCount).toEqual(3);\n       * ```\n       *\n       *\n       * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The\n       *    expression value should evaluate to an object or an array which is observed on each\n       *    {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the\n       *    collection will trigger a call to the `listener`.\n       *\n       * @param {function(newCollection, oldCollection, scope)} listener a callback function called\n       *    when a change is detected.\n       *    - The `newCollection` object is the newly modified data obtained from the `obj` expression\n       *    - The `oldCollection` object is a copy of the former collection data.\n       *      Due to performance considerations, the`oldCollection` value is computed only if the\n       *      `listener` function declares two or more arguments.\n       *    - The `scope` argument refers to the current scope.\n       *\n       * @returns {function()} Returns a de-registration function for this listener. When the\n       *    de-registration function is executed, the internal watch operation is terminated.\n       */\n      $watchCollection: function(obj, listener) {\n        $watchCollectionInterceptor.$stateful = true;\n\n        var self = this;\n        // the current value, updated on each dirty-check run\n        var newValue;\n        // a shallow copy of the newValue from the last dirty-check run,\n        // updated to match newValue during dirty-check run\n        var oldValue;\n        // a shallow copy of the newValue from when the last change happened\n        var veryOldValue;\n        // only track veryOldValue if the listener is asking for it\n        var trackVeryOldValue = (listener.length > 1);\n        var changeDetected = 0;\n        var changeDetector = $parse(obj, $watchCollectionInterceptor);\n        var internalArray = [];\n        var internalObject = {};\n        var initRun = true;\n        var oldLength = 0;\n\n        function $watchCollectionInterceptor(_value) {\n          newValue = _value;\n          var newLength, key, bothNaN, newItem, oldItem;\n\n          // If the new value is undefined, then return undefined as the watch may be a one-time watch\n          if (isUndefined(newValue)) return;\n\n          if (!isObject(newValue)) { // if primitive\n            if (oldValue !== newValue) {\n              oldValue = newValue;\n              changeDetected++;\n            }\n          } else if (isArrayLike(newValue)) {\n            if (oldValue !== internalArray) {\n              // we are transitioning from something which was not an array into array.\n              oldValue = internalArray;\n              oldLength = oldValue.length = 0;\n              changeDetected++;\n            }\n\n            newLength = newValue.length;\n\n            if (oldLength !== newLength) {\n              // if lengths do not match we need to trigger change notification\n              changeDetected++;\n              oldValue.length = oldLength = newLength;\n            }\n            // copy the items to oldValue and look for changes.\n            for (var i = 0; i < newLength; i++) {\n              oldItem = oldValue[i];\n              newItem = newValue[i];\n\n              bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n              if (!bothNaN && (oldItem !== newItem)) {\n                changeDetected++;\n                oldValue[i] = newItem;\n              }\n            }\n          } else {\n            if (oldValue !== internalObject) {\n              // we are transitioning from something which was not an object into object.\n              oldValue = internalObject = {};\n              oldLength = 0;\n              changeDetected++;\n            }\n            // copy the items to oldValue and look for changes.\n            newLength = 0;\n            for (key in newValue) {\n              if (newValue.hasOwnProperty(key)) {\n                newLength++;\n                newItem = newValue[key];\n                oldItem = oldValue[key];\n\n                if (key in oldValue) {\n                  bothNaN = (oldItem !== oldItem) && (newItem !== newItem);\n                  if (!bothNaN && (oldItem !== newItem)) {\n                    changeDetected++;\n                    oldValue[key] = newItem;\n                  }\n                } else {\n                  oldLength++;\n                  oldValue[key] = newItem;\n                  changeDetected++;\n                }\n              }\n            }\n            if (oldLength > newLength) {\n              // we used to have more keys, need to find them and destroy them.\n              changeDetected++;\n              for (key in oldValue) {\n                if (!newValue.hasOwnProperty(key)) {\n                  oldLength--;\n                  delete oldValue[key];\n                }\n              }\n            }\n          }\n          return changeDetected;\n        }\n\n        function $watchCollectionAction() {\n          if (initRun) {\n            initRun = false;\n            listener(newValue, newValue, self);\n          } else {\n            listener(newValue, veryOldValue, self);\n          }\n\n          // make a copy for the next time a collection is changed\n          if (trackVeryOldValue) {\n            if (!isObject(newValue)) {\n              //primitive\n              veryOldValue = newValue;\n            } else if (isArrayLike(newValue)) {\n              veryOldValue = new Array(newValue.length);\n              for (var i = 0; i < newValue.length; i++) {\n                veryOldValue[i] = newValue[i];\n              }\n            } else { // if object\n              veryOldValue = {};\n              for (var key in newValue) {\n                if (hasOwnProperty.call(newValue, key)) {\n                  veryOldValue[key] = newValue[key];\n                }\n              }\n            }\n          }\n        }\n\n        return this.$watch(changeDetector, $watchCollectionAction);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$digest\n       * @kind function\n       *\n       * @description\n       * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and\n       * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change\n       * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}\n       * until no more listeners are firing. This means that it is possible to get into an infinite\n       * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of\n       * iterations exceeds 10.\n       *\n       * Usually, you don't call `$digest()` directly in\n       * {@link ng.directive:ngController controllers} or in\n       * {@link ng.$compileProvider#directive directives}.\n       * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within\n       * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.\n       *\n       * If you want to be notified whenever `$digest()` is called,\n       * you can register a `watchExpression` function with\n       * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.\n       *\n       * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.\n       *\n       * # Example\n       * ```js\n           var scope = ...;\n           scope.name = 'misko';\n           scope.counter = 0;\n\n           expect(scope.counter).toEqual(0);\n           scope.$watch('name', function(newValue, oldValue) {\n             scope.counter = scope.counter + 1;\n           });\n           expect(scope.counter).toEqual(0);\n\n           scope.$digest();\n           // the listener is always called during the first $digest loop after it was registered\n           expect(scope.counter).toEqual(1);\n\n           scope.$digest();\n           // but now it will not be called unless the value changes\n           expect(scope.counter).toEqual(1);\n\n           scope.name = 'adam';\n           scope.$digest();\n           expect(scope.counter).toEqual(2);\n       * ```\n       *\n       */\n      $digest: function() {\n        var watch, value, last,\n            watchers,\n            length,\n            dirty, ttl = TTL,\n            next, current, target = this,\n            watchLog = [],\n            logIdx, logMsg, asyncTask;\n\n        beginPhase('$digest');\n        // Check for changes to browser url that happened in sync before the call to $digest\n        $browser.$$checkUrlChange();\n\n        if (this === $rootScope && applyAsyncId !== null) {\n          // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then\n          // cancel the scheduled $apply and flush the queue of expressions to be evaluated.\n          $browser.defer.cancel(applyAsyncId);\n          flushApplyAsync();\n        }\n\n        lastDirtyWatch = null;\n\n        do { // \"while dirty\" loop\n          dirty = false;\n          current = target;\n\n          while (asyncQueue.length) {\n            try {\n              asyncTask = asyncQueue.shift();\n              asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n            lastDirtyWatch = null;\n          }\n\n          traverseScopesLoop:\n          do { // \"traverse the scopes\" loop\n            if ((watchers = current.$$watchers)) {\n              // process our watches\n              length = watchers.length;\n              while (length--) {\n                try {\n                  watch = watchers[length];\n                  // Most common watches are on primitives, in which case we can short\n                  // circuit it with === operator, only when === fails do we use .equals\n                  if (watch) {\n                    if ((value = watch.get(current)) !== (last = watch.last) &&\n                        !(watch.eq\n                            ? equals(value, last)\n                            : (typeof value === 'number' && typeof last === 'number'\n                               && isNaN(value) && isNaN(last)))) {\n                      dirty = true;\n                      lastDirtyWatch = watch;\n                      watch.last = watch.eq ? copy(value, null) : value;\n                      watch.fn(value, ((last === initWatchVal) ? value : last), current);\n                      if (ttl < 5) {\n                        logIdx = 4 - ttl;\n                        if (!watchLog[logIdx]) watchLog[logIdx] = [];\n                        watchLog[logIdx].push({\n                          msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,\n                          newVal: value,\n                          oldVal: last\n                        });\n                      }\n                    } else if (watch === lastDirtyWatch) {\n                      // If the most recently dirty watcher is now clean, short circuit since the remaining watchers\n                      // have already been tested.\n                      dirty = false;\n                      break traverseScopesLoop;\n                    }\n                  }\n                } catch (e) {\n                  $exceptionHandler(e);\n                }\n              }\n            }\n\n            // Insanity Warning: scope depth-first traversal\n            // yes, this code is a bit crazy, but it works and we have tests to prove it!\n            // this piece should be kept in sync with the traversal in $broadcast\n            if (!(next = ((current.$$watchersCount && current.$$childHead) ||\n                (current !== target && current.$$nextSibling)))) {\n              while (current !== target && !(next = current.$$nextSibling)) {\n                current = current.$parent;\n              }\n            }\n          } while ((current = next));\n\n          // `break traverseScopesLoop;` takes us to here\n\n          if ((dirty || asyncQueue.length) && !(ttl--)) {\n            clearPhase();\n            throw $rootScopeMinErr('infdig',\n                '{0} $digest() iterations reached. Aborting!\\n' +\n                'Watchers fired in the last 5 iterations: {1}',\n                TTL, watchLog);\n          }\n\n        } while (dirty || asyncQueue.length);\n\n        clearPhase();\n\n        while (postDigestQueue.length) {\n          try {\n            postDigestQueue.shift()();\n          } catch (e) {\n            $exceptionHandler(e);\n          }\n        }\n      },\n\n\n      /**\n       * @ngdoc event\n       * @name $rootScope.Scope#$destroy\n       * @eventType broadcast on scope being destroyed\n       *\n       * @description\n       * Broadcasted when a scope and its children are being destroyed.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$destroy\n       * @kind function\n       *\n       * @description\n       * Removes the current scope (and all of its children) from the parent scope. Removal implies\n       * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer\n       * propagate to the current scope and its children. Removal also implies that the current\n       * scope is eligible for garbage collection.\n       *\n       * The `$destroy()` is usually used by directives such as\n       * {@link ng.directive:ngRepeat ngRepeat} for managing the\n       * unrolling of the loop.\n       *\n       * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.\n       * Application code can register a `$destroy` event handler that will give it a chance to\n       * perform any necessary cleanup.\n       *\n       * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to\n       * clean up DOM bindings before an element is removed from the DOM.\n       */\n      $destroy: function() {\n        // We can't destroy a scope that has been already destroyed.\n        if (this.$$destroyed) return;\n        var parent = this.$parent;\n\n        this.$broadcast('$destroy');\n        this.$$destroyed = true;\n\n        if (this === $rootScope) {\n          //Remove handlers attached to window when $rootScope is removed\n          $browser.$$applicationDestroyed();\n        }\n\n        incrementWatchersCount(this, -this.$$watchersCount);\n        for (var eventName in this.$$listenerCount) {\n          decrementListenerCount(this, this.$$listenerCount[eventName], eventName);\n        }\n\n        // sever all the references to parent scopes (after this cleanup, the current scope should\n        // not be retained by any of our references and should be eligible for garbage collection)\n        if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;\n        if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;\n        if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;\n        if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;\n\n        // Disable listeners, watchers and apply/digest methods\n        this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;\n        this.$on = this.$watch = this.$watchGroup = function() { return noop; };\n        this.$$listeners = {};\n\n        // All of the code below is bogus code that works around V8's memory leak via optimized code\n        // and inline caches.\n        //\n        // see:\n        // - https://code.google.com/p/v8/issues/detail?id=2073#c26\n        // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909\n        // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451\n\n        this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =\n            this.$$childTail = this.$root = this.$$watchers = null;\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$eval\n       * @kind function\n       *\n       * @description\n       * Executes the `expression` on the current scope and returns the result. Any exceptions in\n       * the expression are propagated (uncaught). This is useful when evaluating Angular\n       * expressions.\n       *\n       * # Example\n       * ```js\n           var scope = ng.$rootScope.Scope();\n           scope.a = 1;\n           scope.b = 2;\n\n           expect(scope.$eval('a+b')).toEqual(3);\n           expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);\n       * ```\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in  {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       * @returns {*} The result of evaluating the expression.\n       */\n      $eval: function(expr, locals) {\n        return $parse(expr)(this, locals);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$evalAsync\n       * @kind function\n       *\n       * @description\n       * Executes the expression on the current scope at a later point in time.\n       *\n       * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only\n       * that:\n       *\n       *   - it will execute after the function that scheduled the evaluation (preferably before DOM\n       *     rendering).\n       *   - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after\n       *     `expression` execution.\n       *\n       * Any exceptions from the execution of the expression are forwarded to the\n       * {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle\n       * will be scheduled. However, it is encouraged to always call code that changes the model\n       * from within an `$apply` call. That includes code evaluated via `$evalAsync`.\n       *\n       * @param {(string|function())=} expression An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with the current `scope` parameter.\n       *\n       * @param {(object)=} locals Local variables object, useful for overriding values in scope.\n       */\n      $evalAsync: function(expr, locals) {\n        // if we are outside of an $digest loop and this is the first time we are scheduling async\n        // task also schedule async auto-flush\n        if (!$rootScope.$$phase && !asyncQueue.length) {\n          $browser.defer(function() {\n            if (asyncQueue.length) {\n              $rootScope.$digest();\n            }\n          });\n        }\n\n        asyncQueue.push({scope: this, expression: expr, locals: locals});\n      },\n\n      $$postDigest: function(fn) {\n        postDigestQueue.push(fn);\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$apply\n       * @kind function\n       *\n       * @description\n       * `$apply()` is used to execute an expression in angular from outside of the angular\n       * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).\n       * Because we are calling into the angular framework we need to perform proper scope life\n       * cycle of {@link ng.$exceptionHandler exception handling},\n       * {@link ng.$rootScope.Scope#$digest executing watches}.\n       *\n       * ## Life cycle\n       *\n       * # Pseudo-Code of `$apply()`\n       * ```js\n           function $apply(expr) {\n             try {\n               return $eval(expr);\n             } catch (e) {\n               $exceptionHandler(e);\n             } finally {\n               $root.$digest();\n             }\n           }\n       * ```\n       *\n       *\n       * Scope's `$apply()` method transitions through the following stages:\n       *\n       * 1. The {@link guide/expression expression} is executed using the\n       *    {@link ng.$rootScope.Scope#$eval $eval()} method.\n       * 2. Any exceptions from the execution of the expression are forwarded to the\n       *    {@link ng.$exceptionHandler $exceptionHandler} service.\n       * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the\n       *    expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.\n       *\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       *\n       * @returns {*} The result of evaluating the expression.\n       */\n      $apply: function(expr) {\n        try {\n          beginPhase('$apply');\n          try {\n            return this.$eval(expr);\n          } finally {\n            clearPhase();\n          }\n        } catch (e) {\n          $exceptionHandler(e);\n        } finally {\n          try {\n            $rootScope.$digest();\n          } catch (e) {\n            $exceptionHandler(e);\n            throw e;\n          }\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$applyAsync\n       * @kind function\n       *\n       * @description\n       * Schedule the invocation of $apply to occur at a later time. The actual time difference\n       * varies across browsers, but is typically around ~10 milliseconds.\n       *\n       * This can be used to queue up multiple expressions which need to be evaluated in the same\n       * digest.\n       *\n       * @param {(string|function())=} exp An angular expression to be executed.\n       *\n       *    - `string`: execute using the rules as defined in {@link guide/expression expression}.\n       *    - `function(scope)`: execute the function with current `scope` parameter.\n       */\n      $applyAsync: function(expr) {\n        var scope = this;\n        expr && applyAsyncQueue.push($applyAsyncExpression);\n        scheduleApplyAsync();\n\n        function $applyAsyncExpression() {\n          scope.$eval(expr);\n        }\n      },\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$on\n       * @kind function\n       *\n       * @description\n       * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for\n       * discussion of event life cycle.\n       *\n       * The event listener function format is: `function(event, args...)`. The `event` object\n       * passed into the listener has the following attributes:\n       *\n       *   - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or\n       *     `$broadcast`-ed.\n       *   - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the\n       *     event propagates through the scope hierarchy, this property is set to null.\n       *   - `name` - `{string}`: name of the event.\n       *   - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel\n       *     further event propagation (available only for events that were `$emit`-ed).\n       *   - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag\n       *     to true.\n       *   - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.\n       *\n       * @param {string} name Event name to listen on.\n       * @param {function(event, ...args)} listener Function to call when the event is emitted.\n       * @returns {function()} Returns a deregistration function for this listener.\n       */\n      $on: function(name, listener) {\n        var namedListeners = this.$$listeners[name];\n        if (!namedListeners) {\n          this.$$listeners[name] = namedListeners = [];\n        }\n        namedListeners.push(listener);\n\n        var current = this;\n        do {\n          if (!current.$$listenerCount[name]) {\n            current.$$listenerCount[name] = 0;\n          }\n          current.$$listenerCount[name]++;\n        } while ((current = current.$parent));\n\n        var self = this;\n        return function() {\n          var indexOfListener = namedListeners.indexOf(listener);\n          if (indexOfListener !== -1) {\n            namedListeners[indexOfListener] = null;\n            decrementListenerCount(self, 1, name);\n          }\n        };\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$emit\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` upwards through the scope hierarchy notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$emit` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event traverses upwards toward the root scope and calls all\n       * registered listeners along the way. The event will stop propagating if one of the listeners\n       * cancels it.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to emit.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).\n       */\n      $emit: function(name, args) {\n        var empty = [],\n            namedListeners,\n            scope = this,\n            stopPropagation = false,\n            event = {\n              name: name,\n              targetScope: scope,\n              stopPropagation: function() {stopPropagation = true;},\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            },\n            listenerArgs = concat([event], arguments, 1),\n            i, length;\n\n        do {\n          namedListeners = scope.$$listeners[name] || empty;\n          event.currentScope = scope;\n          for (i = 0, length = namedListeners.length; i < length; i++) {\n\n            // if listeners were deregistered, defragment the array\n            if (!namedListeners[i]) {\n              namedListeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n            try {\n              //allow all listeners attached to the current scope to run\n              namedListeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n          //if any listener on the current scope stops propagation, prevent bubbling\n          if (stopPropagation) {\n            event.currentScope = null;\n            return event;\n          }\n          //traverse upwards\n          scope = scope.$parent;\n        } while (scope);\n\n        event.currentScope = null;\n\n        return event;\n      },\n\n\n      /**\n       * @ngdoc method\n       * @name $rootScope.Scope#$broadcast\n       * @kind function\n       *\n       * @description\n       * Dispatches an event `name` downwards to all child scopes (and their children) notifying the\n       * registered {@link ng.$rootScope.Scope#$on} listeners.\n       *\n       * The event life cycle starts at the scope on which `$broadcast` was called. All\n       * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get\n       * notified. Afterwards, the event propagates to all direct and indirect scopes of the current\n       * scope and calls all registered listeners along the way. The event cannot be canceled.\n       *\n       * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed\n       * onto the {@link ng.$exceptionHandler $exceptionHandler} service.\n       *\n       * @param {string} name Event name to broadcast.\n       * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.\n       * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}\n       */\n      $broadcast: function(name, args) {\n        var target = this,\n            current = target,\n            next = target,\n            event = {\n              name: name,\n              targetScope: target,\n              preventDefault: function() {\n                event.defaultPrevented = true;\n              },\n              defaultPrevented: false\n            };\n\n        if (!target.$$listenerCount[name]) return event;\n\n        var listenerArgs = concat([event], arguments, 1),\n            listeners, i, length;\n\n        //down while you can, then up and next sibling or up and next sibling until back at root\n        while ((current = next)) {\n          event.currentScope = current;\n          listeners = current.$$listeners[name] || [];\n          for (i = 0, length = listeners.length; i < length; i++) {\n            // if listeners were deregistered, defragment the array\n            if (!listeners[i]) {\n              listeners.splice(i, 1);\n              i--;\n              length--;\n              continue;\n            }\n\n            try {\n              listeners[i].apply(null, listenerArgs);\n            } catch (e) {\n              $exceptionHandler(e);\n            }\n          }\n\n          // Insanity Warning: scope depth-first traversal\n          // yes, this code is a bit crazy, but it works and we have tests to prove it!\n          // this piece should be kept in sync with the traversal in $digest\n          // (though it differs due to having the extra check for $$listenerCount)\n          if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||\n              (current !== target && current.$$nextSibling)))) {\n            while (current !== target && !(next = current.$$nextSibling)) {\n              current = current.$parent;\n            }\n          }\n        }\n\n        event.currentScope = null;\n        return event;\n      }\n    };\n\n    var $rootScope = new Scope();\n\n    //The internal queues. Expose them on the $rootScope for debugging/testing purposes.\n    var asyncQueue = $rootScope.$$asyncQueue = [];\n    var postDigestQueue = $rootScope.$$postDigestQueue = [];\n    var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];\n\n    return $rootScope;\n\n\n    function beginPhase(phase) {\n      if ($rootScope.$$phase) {\n        throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);\n      }\n\n      $rootScope.$$phase = phase;\n    }\n\n    function clearPhase() {\n      $rootScope.$$phase = null;\n    }\n\n    function incrementWatchersCount(current, count) {\n      do {\n        current.$$watchersCount += count;\n      } while ((current = current.$parent));\n    }\n\n    function decrementListenerCount(current, count, name) {\n      do {\n        current.$$listenerCount[name] -= count;\n\n        if (current.$$listenerCount[name] === 0) {\n          delete current.$$listenerCount[name];\n        }\n      } while ((current = current.$parent));\n    }\n\n    /**\n     * function used as an initial value for watchers.\n     * because it's unique we can easily tell it apart from other values\n     */\n    function initWatchVal() {}\n\n    function flushApplyAsync() {\n      while (applyAsyncQueue.length) {\n        try {\n          applyAsyncQueue.shift()();\n        } catch (e) {\n          $exceptionHandler(e);\n        }\n      }\n      applyAsyncId = null;\n    }\n\n    function scheduleApplyAsync() {\n      if (applyAsyncId === null) {\n        applyAsyncId = $browser.defer(function() {\n          $rootScope.$apply(flushApplyAsync);\n        });\n      }\n    }\n  }];\n}\n\n/**\n * @description\n * Private service to sanitize uris for links and images. Used by $compile and $sanitize.\n */\nfunction $$SanitizeUriProvider() {\n  var aHrefSanitizationWhitelist = /^\\s*(https?|ftp|mailto|tel|file):/,\n    imgSrcSanitizationWhitelist = /^\\s*((https?|ftp|file|blob):|data:image\\/)/;\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during a[href] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to a[href] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.aHrefSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      aHrefSanitizationWhitelist = regexp;\n      return this;\n    }\n    return aHrefSanitizationWhitelist;\n  };\n\n\n  /**\n   * @description\n   * Retrieves or overrides the default regular expression that is used for whitelisting of safe\n   * urls during img[src] sanitization.\n   *\n   * The sanitization is a security measure aimed at prevent XSS attacks via html links.\n   *\n   * Any url about to be assigned to img[src] via data-binding is first normalized and turned into\n   * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`\n   * regular expression. If a match is found, the original url is written into the dom. Otherwise,\n   * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.\n   *\n   * @param {RegExp=} regexp New regexp to whitelist urls with.\n   * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for\n   *    chaining otherwise.\n   */\n  this.imgSrcSanitizationWhitelist = function(regexp) {\n    if (isDefined(regexp)) {\n      imgSrcSanitizationWhitelist = regexp;\n      return this;\n    }\n    return imgSrcSanitizationWhitelist;\n  };\n\n  this.$get = function() {\n    return function sanitizeUri(uri, isImage) {\n      var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;\n      var normalizedVal;\n      normalizedVal = urlResolve(uri).href;\n      if (normalizedVal !== '' && !normalizedVal.match(regex)) {\n        return 'unsafe:' + normalizedVal;\n      }\n      return uri;\n    };\n  };\n}\n\n/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n *     Any commits to this file should be reviewed with security in mind.  *\n *   Changes to this file can potentially create security vulnerabilities. *\n *          An approval from 2 Core members with history of modifying      *\n *                         this file is required.                          *\n *                                                                         *\n *  Does the change somehow allow for arbitrary javascript to be executed? *\n *    Or allows for someone to change the prototype of built-in objects?   *\n *     Or gives undesired access to variables likes document or window?    *\n * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */\n\nvar $sceMinErr = minErr('$sce');\n\nvar SCE_CONTEXTS = {\n  HTML: 'html',\n  CSS: 'css',\n  URL: 'url',\n  // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a\n  // url.  (e.g. ng-include, script src, templateUrl)\n  RESOURCE_URL: 'resourceUrl',\n  JS: 'js'\n};\n\n// Helper functions follow.\n\nfunction adjustMatcher(matcher) {\n  if (matcher === 'self') {\n    return matcher;\n  } else if (isString(matcher)) {\n    // Strings match exactly except for 2 wildcards - '*' and '**'.\n    // '*' matches any character except those from the set ':/.?&'.\n    // '**' matches any character (like .* in a RegExp).\n    // More than 2 *'s raises an error as it's ill defined.\n    if (matcher.indexOf('***') > -1) {\n      throw $sceMinErr('iwcard',\n          'Illegal sequence *** in string matcher.  String: {0}', matcher);\n    }\n    matcher = escapeForRegexp(matcher).\n                  replace('\\\\*\\\\*', '.*').\n                  replace('\\\\*', '[^:/.?&;]*');\n    return new RegExp('^' + matcher + '$');\n  } else if (isRegExp(matcher)) {\n    // The only other type of matcher allowed is a Regexp.\n    // Match entire URL / disallow partial matches.\n    // Flags are reset (i.e. no global, ignoreCase or multiline)\n    return new RegExp('^' + matcher.source + '$');\n  } else {\n    throw $sceMinErr('imatcher',\n        'Matchers may only be \"self\", string patterns or RegExp objects');\n  }\n}\n\n\nfunction adjustMatchers(matchers) {\n  var adjustedMatchers = [];\n  if (isDefined(matchers)) {\n    forEach(matchers, function(matcher) {\n      adjustedMatchers.push(adjustMatcher(matcher));\n    });\n  }\n  return adjustedMatchers;\n}\n\n\n/**\n * @ngdoc service\n * @name $sceDelegate\n * @kind function\n *\n * @description\n *\n * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict\n * Contextual Escaping (SCE)} services to AngularJS.\n *\n * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of\n * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS.  This is\n * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to\n * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things\n * work because `$sce` delegates to `$sceDelegate` for these operations.\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.\n *\n * The default instance of `$sceDelegate` should work out of the box with little pain.  While you\n * can override it completely to change the behavior of `$sce`, the common case would\n * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting\n * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as\n * templates.  Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist\n * $sceDelegateProvider.resourceUrlWhitelist} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n */\n\n/**\n * @ngdoc provider\n * @name $sceDelegateProvider\n * @description\n *\n * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate\n * $sceDelegate} service.  This allows one to get/set the whitelists and blacklists used to ensure\n * that the URLs used for sourcing Angular templates are safe.  Refer {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and\n * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}\n *\n * For the general details about this service in Angular, read the main page for {@link ng.$sce\n * Strict Contextual Escaping (SCE)}.\n *\n * **Example**:  Consider the following case. <a name=\"example\"></a>\n *\n * - your app is hosted at url `http://myapp.example.com/`\n * - but some of your templates are hosted on other domains you control such as\n *   `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.\n * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.\n *\n * Here is what a secure configuration for this scenario might look like:\n *\n * ```\n *  angular.module('myApp', []).config(function($sceDelegateProvider) {\n *    $sceDelegateProvider.resourceUrlWhitelist([\n *      // Allow same origin resource loads.\n *      'self',\n *      // Allow loading from our assets domain.  Notice the difference between * and **.\n *      'http://srv*.assets.example.com/**'\n *    ]);\n *\n *    // The blacklist overrides the whitelist so the open redirect here is blocked.\n *    $sceDelegateProvider.resourceUrlBlacklist([\n *      'http://myapp.example.com/clickThru**'\n *    ]);\n *  });\n * ```\n */\n\nfunction $SceDelegateProvider() {\n  this.SCE_CONTEXTS = SCE_CONTEXTS;\n\n  // Resource URLs can also be trusted by policy.\n  var resourceUrlWhitelist = ['self'],\n      resourceUrlBlacklist = [];\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlWhitelist\n   * @kind function\n   *\n   * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     Note: **an empty whitelist array will block all URLs**!\n   *\n   * @return {Array} the currently set whitelist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is `['self']` allowing only\n   * same origin resource requests.\n   *\n   * @description\n   * Sets/Gets the whitelist of trusted resource URLs.\n   */\n  this.resourceUrlWhitelist = function(value) {\n    if (arguments.length) {\n      resourceUrlWhitelist = adjustMatchers(value);\n    }\n    return resourceUrlWhitelist;\n  };\n\n  /**\n   * @ngdoc method\n   * @name $sceDelegateProvider#resourceUrlBlacklist\n   * @kind function\n   *\n   * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value\n   *     provided.  This must be an array or null.  A snapshot of this array is used so further\n   *     changes to the array are ignored.\n   *\n   *     Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items\n   *     allowed in this array.\n   *\n   *     The typical usage for the blacklist is to **block\n   *     [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as\n   *     these would otherwise be trusted but actually return content from the redirected domain.\n   *\n   *     Finally, **the blacklist overrides the whitelist** and has the final say.\n   *\n   * @return {Array} the currently set blacklist array.\n   *\n   * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there\n   * is no blacklist.)\n   *\n   * @description\n   * Sets/Gets the blacklist of trusted resource URLs.\n   */\n\n  this.resourceUrlBlacklist = function(value) {\n    if (arguments.length) {\n      resourceUrlBlacklist = adjustMatchers(value);\n    }\n    return resourceUrlBlacklist;\n  };\n\n  this.$get = ['$injector', function($injector) {\n\n    var htmlSanitizer = function htmlSanitizer(html) {\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    };\n\n    if ($injector.has('$sanitize')) {\n      htmlSanitizer = $injector.get('$sanitize');\n    }\n\n\n    function matchUrl(matcher, parsedUrl) {\n      if (matcher === 'self') {\n        return urlIsSameOrigin(parsedUrl);\n      } else {\n        // definitely a regex.  See adjustMatchers()\n        return !!matcher.exec(parsedUrl.href);\n      }\n    }\n\n    function isResourceUrlAllowedByPolicy(url) {\n      var parsedUrl = urlResolve(url.toString());\n      var i, n, allowed = false;\n      // Ensure that at least one item from the whitelist allows this url.\n      for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {\n        if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {\n          allowed = true;\n          break;\n        }\n      }\n      if (allowed) {\n        // Ensure that no item from the blacklist blocked this url.\n        for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {\n          if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {\n            allowed = false;\n            break;\n          }\n        }\n      }\n      return allowed;\n    }\n\n    function generateHolderType(Base) {\n      var holderType = function TrustedValueHolderType(trustedValue) {\n        this.$$unwrapTrustedValue = function() {\n          return trustedValue;\n        };\n      };\n      if (Base) {\n        holderType.prototype = new Base();\n      }\n      holderType.prototype.valueOf = function sceValueOf() {\n        return this.$$unwrapTrustedValue();\n      };\n      holderType.prototype.toString = function sceToString() {\n        return this.$$unwrapTrustedValue().toString();\n      };\n      return holderType;\n    }\n\n    var trustedValueHolderBase = generateHolderType(),\n        byType = {};\n\n    byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);\n    byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#trustAs\n     *\n     * @description\n     * Returns an object that is trusted by angular for use in specified strict\n     * contextual escaping contexts (such as ng-bind-html, ng-include, any src\n     * attribute interpolation, any dom event binding attribute interpolation\n     * such as for onclick,  etc.) that uses the provided value.\n     * See {@link ng.$sce $sce} for enabling strict contextual escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resourceUrl, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n    function trustAs(type, trustedValue) {\n      var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (!Constructor) {\n        throw $sceMinErr('icontext',\n            'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',\n            type, trustedValue);\n      }\n      if (trustedValue === null || trustedValue === undefined || trustedValue === '') {\n        return trustedValue;\n      }\n      // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting\n      // mutable objects, we ensure here that the value passed in is actually a string.\n      if (typeof trustedValue !== 'string') {\n        throw $sceMinErr('itype',\n            'Attempted to trust a non-string value in a content requiring a string: Context: {0}',\n            type);\n      }\n      return new Constructor(trustedValue);\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#valueOf\n     *\n     * @description\n     * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs\n     * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.\n     *\n     * If the passed parameter is not a value that had been returned by {@link\n     * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.\n     *\n     * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}\n     *      call or anything else.\n     * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if `value` is the result of such a call.  Otherwise, returns\n     *     `value` unchanged.\n     */\n    function valueOf(maybeTrusted) {\n      if (maybeTrusted instanceof trustedValueHolderBase) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      } else {\n        return maybeTrusted;\n      }\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sceDelegate#getTrusted\n     *\n     * @description\n     * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and\n     * returns the originally supplied value if the queried context type is a supertype of the\n     * created type.  If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} call.\n     * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs\n     *     `$sceDelegate.trustAs`} if valid in this context.  Otherwise, throws an exception.\n     */\n    function getTrusted(type, maybeTrusted) {\n      if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {\n        return maybeTrusted;\n      }\n      var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);\n      if (constructor && maybeTrusted instanceof constructor) {\n        return maybeTrusted.$$unwrapTrustedValue();\n      }\n      // If we get here, then we may only take one of two actions.\n      // 1. sanitize the value for the requested type, or\n      // 2. throw an exception.\n      if (type === SCE_CONTEXTS.RESOURCE_URL) {\n        if (isResourceUrlAllowedByPolicy(maybeTrusted)) {\n          return maybeTrusted;\n        } else {\n          throw $sceMinErr('insecurl',\n              'Blocked loading resource from url not allowed by $sceDelegate policy.  URL: {0}',\n              maybeTrusted.toString());\n        }\n      } else if (type === SCE_CONTEXTS.HTML) {\n        return htmlSanitizer(maybeTrusted);\n      }\n      throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');\n    }\n\n    return { trustAs: trustAs,\n             getTrusted: getTrusted,\n             valueOf: valueOf };\n  }];\n}\n\n\n/**\n * @ngdoc provider\n * @name $sceProvider\n * @description\n *\n * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.\n * -   enable/disable Strict Contextual Escaping (SCE) in a module\n * -   override the default implementation with a custom delegate\n *\n * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.\n */\n\n/* jshint maxlen: false*/\n\n/**\n * @ngdoc service\n * @name $sce\n * @kind function\n *\n * @description\n *\n * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.\n *\n * # Strict Contextual Escaping\n *\n * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain\n * contexts to result in a value that is marked as safe to use for that context.  One example of\n * such a context is binding arbitrary html controlled by the user via `ng-bind-html`.  We refer\n * to these contexts as privileged or SCE contexts.\n *\n * As of version 1.2, Angular ships with SCE enabled by default.\n *\n * Note:  When enabled (the default), IE<11 in quirks mode is not supported.  In this mode, IE<11 allow\n * one to execute arbitrary javascript by the use of the expression() syntax.  Refer\n * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.\n * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`\n * to the top of your HTML document.\n *\n * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for\n * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.\n *\n * Here's an example of a binding in a privileged context:\n *\n * ```\n * <input ng-model=\"userHtml\" aria-label=\"User input\">\n * <div ng-bind-html=\"userHtml\"></div>\n * ```\n *\n * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user.  With SCE\n * disabled, this application allows the user to render arbitrary HTML into the DIV.\n * In a more realistic example, one may be rendering user comments, blog articles, etc. via\n * bindings.  (HTML is just one example of a context where rendering user controlled input creates\n * security vulnerabilities.)\n *\n * For the case of HTML, you might use a library, either on the client side, or on the server side,\n * to sanitize unsafe HTML before binding to the value and rendering it in the document.\n *\n * How would you ensure that every place that used these types of bindings was bound to a value that\n * was sanitized by your library (or returned as safe for rendering by your server?)  How can you\n * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some\n * properties/fields and forgot to update the binding to the sanitized value?\n *\n * To be secure by default, you want to ensure that any such bindings are disallowed unless you can\n * determine that something explicitly says it's safe to use a value for binding in that\n * context.  You can then audit your code (a simple grep would do) to ensure that this is only done\n * for those values that you can easily tell are safe - because they were received from your server,\n * sanitized by your library, etc.  You can organize your codebase to help with this - perhaps\n * allowing only the files in a specific directory to do this.  Ensuring that the internal API\n * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.\n *\n * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}\n * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to\n * obtain values that will be accepted by SCE / privileged contexts.\n *\n *\n * ## How does it work?\n *\n * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted\n * $sce.getTrusted(context, value)} rather than to the value directly.  Directives use {@link\n * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the\n * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.\n *\n * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link\n * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}.  Here's the actual code (slightly\n * simplified):\n *\n * ```\n * var ngBindHtmlDirective = ['$sce', function($sce) {\n *   return function(scope, element, attr) {\n *     scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {\n *       element.html(value || '');\n *     });\n *   };\n * }];\n * ```\n *\n * ## Impact on loading templates\n *\n * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as\n * `templateUrl`'s specified by {@link guide/directive directives}.\n *\n * By default, Angular only loads templates from the same domain and protocol as the application\n * document.  This is done by calling {@link ng.$sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on the template URL.  To load templates from other domains and/or\n * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist\n * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.\n *\n * *Please note*:\n * The browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy apply in addition to this and may further restrict whether the template is successfully\n * loaded.  This means that without the right CORS policy, loading templates from a different domain\n * won't work on all browsers.  Also, loading templates from `file://` URL does not work on some\n * browsers.\n *\n * ## This feels like too much overhead\n *\n * It's important to remember that SCE only applies to interpolation expressions.\n *\n * If your expressions are constant literals, they're automatically trusted and you don't need to\n * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.\n * `<div ng-bind-html=\"'<b>implicitly trusted</b>'\"></div>`) just works.\n *\n * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them\n * through {@link ng.$sce#getTrusted $sce.getTrusted}.  SCE doesn't play a role here.\n *\n * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load\n * templates in `ng-include` from your application's domain without having to even know about SCE.\n * It blocks loading templates from other domains or loading templates over http from an https\n * served document.  You can change these by setting your own custom {@link\n * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link\n * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.\n *\n * This significantly reduces the overhead.  It is far easier to pay the small overhead and have an\n * application that's secure and can be audited to verify that with much more ease than bolting\n * security onto an application later.\n *\n * <a name=\"contexts\"></a>\n * ## What trusted context types are supported?\n *\n * | Context             | Notes          |\n * |---------------------|----------------|\n * | `$sce.HTML`         | For HTML that's safe to source into the application.  The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |\n * | `$sce.CSS`          | For CSS that's safe to source into the application.  Currently unused.  Feel free to use it in your own directives. |\n * | `$sce.URL`          | For URLs that are safe to follow as links.  Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |\n * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application.  Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.)  <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |\n * | `$sce.JS`           | For JavaScript that is safe to execute in your application's context.  Currently unused.  Feel free to use it in your own directives. |\n *\n * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name=\"resourceUrlPatternItem\"></a>\n *\n *  Each element in these arrays must be one of the following:\n *\n *  - **'self'**\n *    - The special **string**, `'self'`, can be used to match against all URLs of the **same\n *      domain** as the application document using the **same protocol**.\n *  - **String** (except the special value `'self'`)\n *    - The string is matched against the full *normalized / absolute URL* of the resource\n *      being tested (substring matches are not good enough.)\n *    - There are exactly **two wildcard sequences** - `*` and `**`.  All other characters\n *      match themselves.\n *    - `*`: matches zero or more occurrences of any character other than one of the following 6\n *      characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'.  It's a useful wildcard for use\n *      in a whitelist.\n *    - `**`: matches zero or more occurrences of *any* character.  As such, it's not\n *      appropriate for use in a scheme, domain, etc. as it would match too much.  (e.g.\n *      http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might\n *      not have been the intention.)  Its usage at the very end of the path is ok.  (e.g.\n *      http://foo.example.com/templates/**).\n *  - **RegExp** (*see caveat below*)\n *    - *Caveat*:  While regular expressions are powerful and offer great flexibility,  their syntax\n *      (and all the inevitable escaping) makes them *harder to maintain*.  It's easy to\n *      accidentally introduce a bug when one updates a complex expression (imho, all regexes should\n *      have good test coverage).  For instance, the use of `.` in the regex is correct only in a\n *      small number of cases.  A `.` character in the regex used when matching the scheme or a\n *      subdomain could be matched against a `:` or literal `.` that was likely not intended.   It\n *      is highly recommended to use the string patterns and only fall back to regular expressions\n *      as a last resort.\n *    - The regular expression must be an instance of RegExp (i.e. not a string.)  It is\n *      matched against the **entire** *normalized / absolute URL* of the resource being tested\n *      (even when the RegExp did not have the `^` and `$` codes.)  In addition, any flags\n *      present on the RegExp (such as multiline, global, ignoreCase) are ignored.\n *    - If you are generating your JavaScript from some other templating engine (not\n *      recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),\n *      remember to escape your regular expression (and be aware that you might need more than\n *      one level of escaping depending on your templating engine and the way you interpolated\n *      the value.)  Do make use of your platform's escaping mechanism as it might be good\n *      enough before coding your own.  E.g. Ruby has\n *      [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)\n *      and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).\n *      Javascript lacks a similar built in function for escaping.  Take a look at Google\n *      Closure library's [goog.string.regExpEscape(s)](\n *      http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).\n *\n * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.\n *\n * ## Show me an example using SCE.\n *\n * <example module=\"mySceApp\" deps=\"angular-sanitize.js\">\n * <file name=\"index.html\">\n *   <div ng-controller=\"AppController as myCtrl\">\n *     <i ng-bind-html=\"myCtrl.explicitlyTrustedHtml\" id=\"explicitlyTrustedHtml\"></i><br><br>\n *     <b>User comments</b><br>\n *     By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when\n *     $sanitize is available.  If $sanitize isn't available, this results in an error instead of an\n *     exploit.\n *     <div class=\"well\">\n *       <div ng-repeat=\"userComment in myCtrl.userComments\">\n *         <b>{{userComment.name}}</b>:\n *         <span ng-bind-html=\"userComment.htmlComment\" class=\"htmlComment\"></span>\n *         <br>\n *       </div>\n *     </div>\n *   </div>\n * </file>\n *\n * <file name=\"script.js\">\n *   angular.module('mySceApp', ['ngSanitize'])\n *     .controller('AppController', ['$http', '$templateCache', '$sce',\n *       function($http, $templateCache, $sce) {\n *         var self = this;\n *         $http.get(\"test_data.json\", {cache: $templateCache}).success(function(userComments) {\n *           self.userComments = userComments;\n *         });\n *         self.explicitlyTrustedHtml = $sce.trustAsHtml(\n *             '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *             'sanitization.&quot;\">Hover over this text.</span>');\n *       }]);\n * </file>\n *\n * <file name=\"test_data.json\">\n * [\n *   { \"name\": \"Alice\",\n *     \"htmlComment\":\n *         \"<span onmouseover='this.textContent=\\\"PWN3D!\\\"'>Is <i>anyone</i> reading this?</span>\"\n *   },\n *   { \"name\": \"Bob\",\n *     \"htmlComment\": \"<i>Yes!</i>  Am I the only other one?\"\n *   }\n * ]\n * </file>\n *\n * <file name=\"protractor.js\" type=\"protractor\">\n *   describe('SCE doc demo', function() {\n *     it('should sanitize untrusted values', function() {\n *       expect(element.all(by.css('.htmlComment')).first().getInnerHtml())\n *           .toBe('<span>Is <i>anyone</i> reading this?</span>');\n *     });\n *\n *     it('should NOT sanitize explicitly trusted values', function() {\n *       expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(\n *           '<span onmouseover=\"this.textContent=&quot;Explicitly trusted HTML bypasses ' +\n *           'sanitization.&quot;\">Hover over this text.</span>');\n *     });\n *   });\n * </file>\n * </example>\n *\n *\n *\n * ## Can I disable SCE completely?\n *\n * Yes, you can.  However, this is strongly discouraged.  SCE gives you a lot of security benefits\n * for little coding overhead.  It will be much harder to take an SCE disabled application and\n * either secure it on your own or enable SCE at a later stage.  It might make sense to disable SCE\n * for cases where you have a lot of existing code that was written before SCE was introduced and\n * you're migrating them a module at a time.\n *\n * That said, here's how you can completely disable SCE:\n *\n * ```\n * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {\n *   // Completely disable SCE.  For demonstration purposes only!\n *   // Do not use in new projects.\n *   $sceProvider.enabled(false);\n * });\n * ```\n *\n */\n/* jshint maxlen: 100 */\n\nfunction $SceProvider() {\n  var enabled = true;\n\n  /**\n   * @ngdoc method\n   * @name $sceProvider#enabled\n   * @kind function\n   *\n   * @param {boolean=} value If provided, then enables/disables SCE.\n   * @return {boolean} true if SCE is enabled, false otherwise.\n   *\n   * @description\n   * Enables/disables SCE and returns the current value.\n   */\n  this.enabled = function(value) {\n    if (arguments.length) {\n      enabled = !!value;\n    }\n    return enabled;\n  };\n\n\n  /* Design notes on the default implementation for SCE.\n   *\n   * The API contract for the SCE delegate\n   * -------------------------------------\n   * The SCE delegate object must provide the following 3 methods:\n   *\n   * - trustAs(contextEnum, value)\n   *     This method is used to tell the SCE service that the provided value is OK to use in the\n   *     contexts specified by contextEnum.  It must return an object that will be accepted by\n   *     getTrusted() for a compatible contextEnum and return this value.\n   *\n   * - valueOf(value)\n   *     For values that were not produced by trustAs(), return them as is.  For values that were\n   *     produced by trustAs(), return the corresponding input value to trustAs.  Basically, if\n   *     trustAs is wrapping the given values into some type, this operation unwraps it when given\n   *     such a value.\n   *\n   * - getTrusted(contextEnum, value)\n   *     This function should return the a value that is safe to use in the context specified by\n   *     contextEnum or throw and exception otherwise.\n   *\n   * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be\n   * opaque or wrapped in some holder object.  That happens to be an implementation detail.  For\n   * instance, an implementation could maintain a registry of all trusted objects by context.  In\n   * such a case, trustAs() would return the same object that was passed in.  getTrusted() would\n   * return the same object passed in if it was found in the registry under a compatible context or\n   * throw an exception otherwise.  An implementation might only wrap values some of the time based\n   * on some criteria.  getTrusted() might return a value and not throw an exception for special\n   * constants or objects even if not wrapped.  All such implementations fulfill this contract.\n   *\n   *\n   * A note on the inheritance model for SCE contexts\n   * ------------------------------------------------\n   * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types.  This\n   * is purely an implementation details.\n   *\n   * The contract is simply this:\n   *\n   *     getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)\n   *     will also succeed.\n   *\n   * Inheritance happens to capture this in a natural way.  In some future, we\n   * may not use inheritance anymore.  That is OK because no code outside of\n   * sce.js and sceSpecs.js would need to be aware of this detail.\n   */\n\n  this.$get = ['$parse', '$sceDelegate', function(\n                $parse,   $sceDelegate) {\n    // Prereq: Ensure that we're not running in IE<11 quirks mode.  In that mode, IE < 11 allow\n    // the \"expression(javascript expression)\" syntax which is insecure.\n    if (enabled && msie < 8) {\n      throw $sceMinErr('iequirks',\n        'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +\n        'mode.  You can fix this by adding the text <!doctype html> to the top of your HTML ' +\n        'document.  See http://docs.angularjs.org/api/ng.$sce for more information.');\n    }\n\n    var sce = shallowCopy(SCE_CONTEXTS);\n\n    /**\n     * @ngdoc method\n     * @name $sce#isEnabled\n     * @kind function\n     *\n     * @return {Boolean} true if SCE is enabled, false otherwise.  If you want to set the value, you\n     * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.\n     *\n     * @description\n     * Returns a boolean indicating if SCE is enabled.\n     */\n    sce.isEnabled = function() {\n      return enabled;\n    };\n    sce.trustAs = $sceDelegate.trustAs;\n    sce.getTrusted = $sceDelegate.getTrusted;\n    sce.valueOf = $sceDelegate.valueOf;\n\n    if (!enabled) {\n      sce.trustAs = sce.getTrusted = function(type, value) { return value; };\n      sce.valueOf = identity;\n    }\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAs\n     *\n     * @description\n     * Converts Angular {@link guide/expression expression} into a function.  This is like {@link\n     * ng.$parse $parse} and is identical when the expression is a literal constant.  Otherwise, it\n     * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,\n     * *result*)}\n     *\n     * @param {string} type The kind of SCE context in which this result will be used.\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n    sce.parseAs = function sceParseAs(type, expr) {\n      var parsed = $parse(expr);\n      if (parsed.literal && parsed.constant) {\n        return parsed;\n      } else {\n        return $parse(expr, function(value) {\n          return sce.getTrusted(type, value);\n        });\n      }\n    };\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAs\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.  As such,\n     * returns an object that is trusted by angular for use in specified strict contextual\n     * escaping contexts (such as ng-bind-html, ng-include, any src attribute\n     * interpolation, any dom event binding attribute interpolation such as for onclick,  etc.)\n     * that uses the provided value.  See * {@link ng.$sce $sce} for enabling strict contextual\n     * escaping.\n     *\n     * @param {string} type The kind of context in which this value is safe for use.  e.g. url,\n     *   resourceUrl, html, js and css.\n     * @param {*} value The value that that should be considered trusted/safe.\n     * @returns {*} A value that can be used to stand in for the provided `value` in places\n     * where Angular expects a $sce.trustAs() return value.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsHtml(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml\n     *     $sce.getTrustedHtml(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl\n     *     $sce.getTrustedUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl\n     *     $sce.getTrustedResourceUrl(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the return\n     *     value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#trustAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.trustAsJs(value)` →\n     *     {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}\n     *\n     * @param {*} value The value to trustAs.\n     * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs\n     *     $sce.getTrustedJs(value)} to obtain the original value.  (privileged directives\n     *     only accept expressions that are either literal constants or are the\n     *     return value of {@link ng.$sce#trustAs $sce.trustAs}.)\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrusted\n     *\n     * @description\n     * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}.  As such,\n     * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the\n     * originally supplied value if the queried context type is a supertype of the created type.\n     * If this condition isn't satisfied, throws an exception.\n     *\n     * @param {string} type The kind of context in which this value is to be used.\n     * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}\n     *                         call.\n     * @returns {*} The value the was originally provided to\n     *              {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.\n     *              Otherwise, throws an exception.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedHtml(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedCss\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedCss(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedResourceUrl(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}\n     *\n     * @param {*} value The value to pass to `$sceDelegate.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#getTrustedJs\n     *\n     * @description\n     * Shorthand method.  `$sce.getTrustedJs(value)` →\n     *     {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}\n     *\n     * @param {*} value The value to pass to `$sce.getTrusted`.\n     * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsHtml\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsHtml(expression string)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsCss\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsCss(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsResourceUrl\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsResourceUrl(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    /**\n     * @ngdoc method\n     * @name $sce#parseAsJs\n     *\n     * @description\n     * Shorthand method.  `$sce.parseAsJs(value)` →\n     *     {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}\n     *\n     * @param {string} expression String expression to compile.\n     * @returns {function(context, locals)} a function which represents the compiled expression:\n     *\n     *    * `context` – `{object}` – an object against which any expressions embedded in the strings\n     *      are evaluated against (typically a scope object).\n     *    * `locals` – `{object=}` – local variables context object, useful for overriding values in\n     *      `context`.\n     */\n\n    // Shorthand delegations.\n    var parse = sce.parseAs,\n        getTrusted = sce.getTrusted,\n        trustAs = sce.trustAs;\n\n    forEach(SCE_CONTEXTS, function(enumValue, name) {\n      var lName = lowercase(name);\n      sce[camelCase(\"parse_as_\" + lName)] = function(expr) {\n        return parse(enumValue, expr);\n      };\n      sce[camelCase(\"get_trusted_\" + lName)] = function(value) {\n        return getTrusted(enumValue, value);\n      };\n      sce[camelCase(\"trust_as_\" + lName)] = function(value) {\n        return trustAs(enumValue, value);\n      };\n    });\n\n    return sce;\n  }];\n}\n\n/**\n * !!! This is an undocumented \"private\" service !!!\n *\n * @name $sniffer\n * @requires $window\n * @requires $document\n *\n * @property {boolean} history Does the browser support html5 history api ?\n * @property {boolean} transitions Does the browser support CSS transition events ?\n * @property {boolean} animations Does the browser support CSS animation events ?\n *\n * @description\n * This is very simple implementation of testing browser's features.\n */\nfunction $SnifferProvider() {\n  this.$get = ['$window', '$document', function($window, $document) {\n    var eventSupport = {},\n        android =\n          toInt((/android (\\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),\n        boxee = /Boxee/i.test(($window.navigator || {}).userAgent),\n        document = $document[0] || {},\n        vendorPrefix,\n        vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,\n        bodyStyle = document.body && document.body.style,\n        transitions = false,\n        animations = false,\n        match;\n\n    if (bodyStyle) {\n      for (var prop in bodyStyle) {\n        if (match = vendorRegex.exec(prop)) {\n          vendorPrefix = match[0];\n          vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);\n          break;\n        }\n      }\n\n      if (!vendorPrefix) {\n        vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';\n      }\n\n      transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));\n      animations  = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));\n\n      if (android && (!transitions ||  !animations)) {\n        transitions = isString(bodyStyle.webkitTransition);\n        animations = isString(bodyStyle.webkitAnimation);\n      }\n    }\n\n\n    return {\n      // Android has history.pushState, but it does not update location correctly\n      // so let's not use the history API at all.\n      // http://code.google.com/p/android/issues/detail?id=17471\n      // https://github.com/angular/angular.js/issues/904\n\n      // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has\n      // so let's not use the history API also\n      // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined\n      // jshint -W018\n      history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),\n      // jshint +W018\n      hasEvent: function(event) {\n        // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have\n        // it. In particular the event is not fired when backspace or delete key are pressed or\n        // when cut operation is performed.\n        // IE10+ implements 'input' event but it erroneously fires under various situations,\n        // e.g. when placeholder changes, or a form is focused.\n        if (event === 'input' && msie <= 11) return false;\n\n        if (isUndefined(eventSupport[event])) {\n          var divElm = document.createElement('div');\n          eventSupport[event] = 'on' + event in divElm;\n        }\n\n        return eventSupport[event];\n      },\n      csp: csp(),\n      vendorPrefix: vendorPrefix,\n      transitions: transitions,\n      animations: animations,\n      android: android\n    };\n  }];\n}\n\nvar $compileMinErr = minErr('$compile');\n\n/**\n * @ngdoc service\n * @name $templateRequest\n *\n * @description\n * The `$templateRequest` service runs security checks then downloads the provided template using\n * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request\n * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the\n * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the\n * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted\n * when `tpl` is of type string and `$templateCache` has the matching entry.\n *\n * @param {string|TrustedResourceUrl} tpl The HTTP request template URL\n * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty\n *\n * @return {Promise} a promise for the HTTP response data of the given URL.\n *\n * @property {number} totalPendingRequests total amount of pending template requests being downloaded.\n */\nfunction $TemplateRequestProvider() {\n  this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {\n    function handleRequestFn(tpl, ignoreRequestError) {\n      handleRequestFn.totalPendingRequests++;\n\n      // We consider the template cache holds only trusted templates, so\n      // there's no need to go through whitelisting again for keys that already\n      // are included in there. This also makes Angular accept any script\n      // directive, no matter its name. However, we still need to unwrap trusted\n      // types.\n      if (!isString(tpl) || !$templateCache.get(tpl)) {\n        tpl = $sce.getTrustedResourceUrl(tpl);\n      }\n\n      var transformResponse = $http.defaults && $http.defaults.transformResponse;\n\n      if (isArray(transformResponse)) {\n        transformResponse = transformResponse.filter(function(transformer) {\n          return transformer !== defaultHttpResponseTransform;\n        });\n      } else if (transformResponse === defaultHttpResponseTransform) {\n        transformResponse = null;\n      }\n\n      var httpOptions = {\n        cache: $templateCache,\n        transformResponse: transformResponse\n      };\n\n      return $http.get(tpl, httpOptions)\n        ['finally'](function() {\n          handleRequestFn.totalPendingRequests--;\n        })\n        .then(function(response) {\n          $templateCache.put(tpl, response.data);\n          return response.data;\n        }, handleError);\n\n      function handleError(resp) {\n        if (!ignoreRequestError) {\n          throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',\n            tpl, resp.status, resp.statusText);\n        }\n        return $q.reject(resp);\n      }\n    }\n\n    handleRequestFn.totalPendingRequests = 0;\n\n    return handleRequestFn;\n  }];\n}\n\nfunction $$TestabilityProvider() {\n  this.$get = ['$rootScope', '$browser', '$location',\n       function($rootScope,   $browser,   $location) {\n\n    /**\n     * @name $testability\n     *\n     * @description\n     * The private $$testability service provides a collection of methods for use when debugging\n     * or by automated test and debugging tools.\n     */\n    var testability = {};\n\n    /**\n     * @name $$testability#findBindings\n     *\n     * @description\n     * Returns an array of elements that are bound (via ng-bind or {{}})\n     * to expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The binding expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression. Filters and whitespace are ignored.\n     */\n    testability.findBindings = function(element, expression, opt_exactMatch) {\n      var bindings = element.getElementsByClassName('ng-binding');\n      var matches = [];\n      forEach(bindings, function(binding) {\n        var dataBinding = angular.element(binding).data('$binding');\n        if (dataBinding) {\n          forEach(dataBinding, function(bindingName) {\n            if (opt_exactMatch) {\n              var matcher = new RegExp('(^|\\\\s)' + escapeForRegexp(expression) + '(\\\\s|\\\\||$)');\n              if (matcher.test(bindingName)) {\n                matches.push(binding);\n              }\n            } else {\n              if (bindingName.indexOf(expression) != -1) {\n                matches.push(binding);\n              }\n            }\n          });\n        }\n      });\n      return matches;\n    };\n\n    /**\n     * @name $$testability#findModels\n     *\n     * @description\n     * Returns an array of elements that are two-way found via ng-model to\n     * expressions matching the input.\n     *\n     * @param {Element} element The element root to search from.\n     * @param {string} expression The model expression to match.\n     * @param {boolean} opt_exactMatch If true, only returns exact matches\n     *     for the expression.\n     */\n    testability.findModels = function(element, expression, opt_exactMatch) {\n      var prefixes = ['ng-', 'data-ng-', 'ng\\\\:'];\n      for (var p = 0; p < prefixes.length; ++p) {\n        var attributeEquals = opt_exactMatch ? '=' : '*=';\n        var selector = '[' + prefixes[p] + 'model' + attributeEquals + '\"' + expression + '\"]';\n        var elements = element.querySelectorAll(selector);\n        if (elements.length) {\n          return elements;\n        }\n      }\n    };\n\n    /**\n     * @name $$testability#getLocation\n     *\n     * @description\n     * Shortcut for getting the location in a browser agnostic way. Returns\n     *     the path, search, and hash. (e.g. /path?a=b#hash)\n     */\n    testability.getLocation = function() {\n      return $location.url();\n    };\n\n    /**\n     * @name $$testability#setLocation\n     *\n     * @description\n     * Shortcut for navigating to a location without doing a full page reload.\n     *\n     * @param {string} url The location url (path, search and hash,\n     *     e.g. /path?a=b#hash) to go to.\n     */\n    testability.setLocation = function(url) {\n      if (url !== $location.url()) {\n        $location.url(url);\n        $rootScope.$digest();\n      }\n    };\n\n    /**\n     * @name $$testability#whenStable\n     *\n     * @description\n     * Calls the callback when $timeout and $http requests are completed.\n     *\n     * @param {function} callback\n     */\n    testability.whenStable = function(callback) {\n      $browser.notifyWhenNoOutstandingRequests(callback);\n    };\n\n    return testability;\n  }];\n}\n\nfunction $TimeoutProvider() {\n  this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',\n       function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {\n\n    var deferreds = {};\n\n\n     /**\n      * @ngdoc service\n      * @name $timeout\n      *\n      * @description\n      * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch\n      * block and delegates any exceptions to\n      * {@link ng.$exceptionHandler $exceptionHandler} service.\n      *\n      * The return value of calling `$timeout` is a promise, which will be resolved when\n      * the delay has passed and the timeout function, if provided, is executed.\n      *\n      * To cancel a timeout request, call `$timeout.cancel(promise)`.\n      *\n      * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to\n      * synchronously flush the queue of deferred functions.\n      *\n      * If you only want a promise that will be resolved after some specified delay\n      * then you can call `$timeout` without the `fn` function.\n      *\n      * @param {function()=} fn A function, whose execution should be delayed.\n      * @param {number=} [delay=0] Delay in milliseconds.\n      * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise\n      *   will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.\n      * @param {...*=} Pass additional parameters to the executed function.\n      * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this\n      *   promise will be resolved with is the return value of the `fn` function.\n      *\n      */\n    function timeout(fn, delay, invokeApply) {\n      if (!isFunction(fn)) {\n        invokeApply = delay;\n        delay = fn;\n        fn = noop;\n      }\n\n      var args = sliceArgs(arguments, 3),\n          skipApply = (isDefined(invokeApply) && !invokeApply),\n          deferred = (skipApply ? $$q : $q).defer(),\n          promise = deferred.promise,\n          timeoutId;\n\n      timeoutId = $browser.defer(function() {\n        try {\n          deferred.resolve(fn.apply(null, args));\n        } catch (e) {\n          deferred.reject(e);\n          $exceptionHandler(e);\n        }\n        finally {\n          delete deferreds[promise.$$timeoutId];\n        }\n\n        if (!skipApply) $rootScope.$apply();\n      }, delay);\n\n      promise.$$timeoutId = timeoutId;\n      deferreds[timeoutId] = deferred;\n\n      return promise;\n    }\n\n\n     /**\n      * @ngdoc method\n      * @name $timeout#cancel\n      *\n      * @description\n      * Cancels a task associated with the `promise`. As a result of this, the promise will be\n      * resolved with a rejection.\n      *\n      * @param {Promise=} promise Promise returned by the `$timeout` function.\n      * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully\n      *   canceled.\n      */\n    timeout.cancel = function(promise) {\n      if (promise && promise.$$timeoutId in deferreds) {\n        deferreds[promise.$$timeoutId].reject('canceled');\n        delete deferreds[promise.$$timeoutId];\n        return $browser.defer.cancel(promise.$$timeoutId);\n      }\n      return false;\n    };\n\n    return timeout;\n  }];\n}\n\n// NOTE:  The usage of window and document instead of $window and $document here is\n// deliberate.  This service depends on the specific behavior of anchor nodes created by the\n// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and\n// cause us to break tests.  In addition, when the browser resolves a URL for XHR, it\n// doesn't know about mocked locations and resolves URLs to the real document - which is\n// exactly the behavior needed here.  There is little value is mocking these out for this\n// service.\nvar urlParsingNode = document.createElement(\"a\");\nvar originUrl = urlResolve(window.location.href);\n\n\n/**\n *\n * Implementation Notes for non-IE browsers\n * ----------------------------------------\n * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,\n * results both in the normalizing and parsing of the URL.  Normalizing means that a relative\n * URL will be resolved into an absolute URL in the context of the application document.\n * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related\n * properties are all populated to reflect the normalized URL.  This approach has wide\n * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc.  See\n * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *\n * Implementation Notes for IE\n * ---------------------------\n * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other\n * browsers.  However, the parsed components will not be set if the URL assigned did not specify\n * them.  (e.g. if you assign a.href = \"foo\", then a.protocol, a.host, etc. will be empty.)  We\n * work around that by performing the parsing in a 2nd step by taking a previously normalized\n * URL (e.g. by assigning to a.href) and assigning it a.href again.  This correctly populates the\n * properties such as protocol, hostname, port, etc.\n *\n * References:\n *   http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement\n *   http://www.aptana.com/reference/html/api/HTMLAnchorElement.html\n *   http://url.spec.whatwg.org/#urlutils\n *   https://github.com/angular/angular.js/pull/2902\n *   http://james.padolsey.com/javascript/parsing-urls-with-the-dom/\n *\n * @kind function\n * @param {string} url The URL to be parsed.\n * @description Normalizes and parses a URL.\n * @returns {object} Returns the normalized URL as a dictionary.\n *\n *   | member name   | Description    |\n *   |---------------|----------------|\n *   | href          | A normalized version of the provided URL if it was not an absolute URL |\n *   | protocol      | The protocol including the trailing colon                              |\n *   | host          | The host and port (if the port is non-default) of the normalizedUrl    |\n *   | search        | The search params, minus the question mark                             |\n *   | hash          | The hash string, minus the hash symbol\n *   | hostname      | The hostname\n *   | port          | The port, without \":\"\n *   | pathname      | The pathname, beginning with \"/\"\n *\n */\nfunction urlResolve(url) {\n  var href = url;\n\n  if (msie) {\n    // Normalize before parse.  Refer Implementation Notes on why this is\n    // done in two steps on IE.\n    urlParsingNode.setAttribute(\"href\", href);\n    href = urlParsingNode.href;\n  }\n\n  urlParsingNode.setAttribute('href', href);\n\n  // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils\n  return {\n    href: urlParsingNode.href,\n    protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',\n    host: urlParsingNode.host,\n    search: urlParsingNode.search ? urlParsingNode.search.replace(/^\\?/, '') : '',\n    hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',\n    hostname: urlParsingNode.hostname,\n    port: urlParsingNode.port,\n    pathname: (urlParsingNode.pathname.charAt(0) === '/')\n      ? urlParsingNode.pathname\n      : '/' + urlParsingNode.pathname\n  };\n}\n\n/**\n * Parse a request URL and determine whether this is a same-origin request as the application document.\n *\n * @param {string|object} requestUrl The url of the request as a string that will be resolved\n * or a parsed URL object.\n * @returns {boolean} Whether the request is for the same origin as the application document.\n */\nfunction urlIsSameOrigin(requestUrl) {\n  var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;\n  return (parsed.protocol === originUrl.protocol &&\n          parsed.host === originUrl.host);\n}\n\n/**\n * @ngdoc service\n * @name $window\n *\n * @description\n * A reference to the browser's `window` object. While `window`\n * is globally available in JavaScript, it causes testability problems, because\n * it is a global variable. In angular we always refer to it through the\n * `$window` service, so it may be overridden, removed or mocked for testing.\n *\n * Expressions, like the one defined for the `ngClick` directive in the example\n * below, are evaluated with respect to the current scope.  Therefore, there is\n * no risk of inadvertently coding in a dependency on a global value in such an\n * expression.\n *\n * @example\n   <example module=\"windowExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('windowExample', [])\n           .controller('ExampleController', ['$scope', '$window', function($scope, $window) {\n             $scope.greeting = 'Hello, World!';\n             $scope.doGreeting = function(greeting) {\n               $window.alert(greeting);\n             };\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"text\" ng-model=\"greeting\" aria-label=\"greeting\" />\n         <button ng-click=\"doGreeting(greeting)\">ALERT</button>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n      it('should display the greeting in the input box', function() {\n       element(by.model('greeting')).sendKeys('Hello, E2E Tests');\n       // If we click the button it will block the test runner\n       // element(':button').click();\n      });\n     </file>\n   </example>\n */\nfunction $WindowProvider() {\n  this.$get = valueFn(window);\n}\n\n/**\n * @name $$cookieReader\n * @requires $document\n *\n * @description\n * This is a private service for reading cookies used by $http and ngCookies\n *\n * @return {Object} a key/value map of the current cookies\n */\nfunction $$CookieReader($document) {\n  var rawDocument = $document[0] || {};\n  var lastCookies = {};\n  var lastCookieString = '';\n\n  function safeDecodeURIComponent(str) {\n    try {\n      return decodeURIComponent(str);\n    } catch (e) {\n      return str;\n    }\n  }\n\n  return function() {\n    var cookieArray, cookie, i, index, name;\n    var currentCookieString = rawDocument.cookie || '';\n\n    if (currentCookieString !== lastCookieString) {\n      lastCookieString = currentCookieString;\n      cookieArray = lastCookieString.split('; ');\n      lastCookies = {};\n\n      for (i = 0; i < cookieArray.length; i++) {\n        cookie = cookieArray[i];\n        index = cookie.indexOf('=');\n        if (index > 0) { //ignore nameless cookies\n          name = safeDecodeURIComponent(cookie.substring(0, index));\n          // the first value that is seen for a cookie is the most\n          // specific one.  values for the same cookie name that\n          // follow are for less specific paths.\n          if (lastCookies[name] === undefined) {\n            lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));\n          }\n        }\n      }\n    }\n    return lastCookies;\n  };\n}\n\n$$CookieReader.$inject = ['$document'];\n\nfunction $$CookieReaderProvider() {\n  this.$get = $$CookieReader;\n}\n\n/* global currencyFilter: true,\n dateFilter: true,\n filterFilter: true,\n jsonFilter: true,\n limitToFilter: true,\n lowercaseFilter: true,\n numberFilter: true,\n orderByFilter: true,\n uppercaseFilter: true,\n */\n\n/**\n * @ngdoc provider\n * @name $filterProvider\n * @description\n *\n * Filters are just functions which transform input to an output. However filters need to be\n * Dependency Injected. To achieve this a filter definition consists of a factory function which is\n * annotated with dependencies and is responsible for creating a filter function.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n * (`myapp_subsection_filterx`).\n * </div>\n *\n * ```js\n *   // Filter registration\n *   function MyModule($provide, $filterProvider) {\n *     // create a service to demonstrate injection (not always needed)\n *     $provide.value('greet', function(name){\n *       return 'Hello ' + name + '!';\n *     });\n *\n *     // register a filter factory which uses the\n *     // greet service to demonstrate DI.\n *     $filterProvider.register('greet', function(greet){\n *       // return the filter function which uses the greet service\n *       // to generate salutation\n *       return function(text) {\n *         // filters need to be forgiving so check input validity\n *         return text && greet(text) || text;\n *       };\n *     });\n *   }\n * ```\n *\n * The filter function is registered with the `$injector` under the filter name suffix with\n * `Filter`.\n *\n * ```js\n *   it('should be the same instance', inject(\n *     function($filterProvider) {\n *       $filterProvider.register('reverse', function(){\n *         return ...;\n *       });\n *     },\n *     function($filter, reverseFilter) {\n *       expect($filter('reverse')).toBe(reverseFilter);\n *     });\n * ```\n *\n *\n * For more information about how angular filters work, and how to create your own filters, see\n * {@link guide/filter Filters} in the Angular Developer Guide.\n */\n\n/**\n * @ngdoc service\n * @name $filter\n * @kind function\n * @description\n * Filters are used for formatting data displayed to the user.\n *\n * The general syntax in templates is as follows:\n *\n *         {{ expression [| filter_name[:parameter_value] ... ] }}\n *\n * @param {String} name Name of the filter function to retrieve\n * @return {Function} the filter function\n * @example\n   <example name=\"$filter\" module=\"filterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"MainCtrl\">\n        <h3>{{ originalText }}</h3>\n        <h3>{{ filteredText }}</h3>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n      angular.module('filterExample', [])\n      .controller('MainCtrl', function($scope, $filter) {\n        $scope.originalText = 'hello';\n        $scope.filteredText = $filter('uppercase')($scope.originalText);\n      });\n     </file>\n   </example>\n  */\n$FilterProvider.$inject = ['$provide'];\nfunction $FilterProvider($provide) {\n  var suffix = 'Filter';\n\n  /**\n   * @ngdoc method\n   * @name $filterProvider#register\n   * @param {string|Object} name Name of the filter function, or an object map of filters where\n   *    the keys are the filter names and the values are the filter factories.\n   *\n   *    <div class=\"alert alert-warning\">\n   *    **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.\n   *    Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace\n   *    your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores\n   *    (`myapp_subsection_filterx`).\n   *    </div>\n    * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.\n   * @returns {Object} Registered filter instance, or if a map of filters was provided then a map\n   *    of the registered filter instances.\n   */\n  function register(name, factory) {\n    if (isObject(name)) {\n      var filters = {};\n      forEach(name, function(filter, key) {\n        filters[key] = register(key, filter);\n      });\n      return filters;\n    } else {\n      return $provide.factory(name + suffix, factory);\n    }\n  }\n  this.register = register;\n\n  this.$get = ['$injector', function($injector) {\n    return function(name) {\n      return $injector.get(name + suffix);\n    };\n  }];\n\n  ////////////////////////////////////////\n\n  /* global\n    currencyFilter: false,\n    dateFilter: false,\n    filterFilter: false,\n    jsonFilter: false,\n    limitToFilter: false,\n    lowercaseFilter: false,\n    numberFilter: false,\n    orderByFilter: false,\n    uppercaseFilter: false,\n  */\n\n  register('currency', currencyFilter);\n  register('date', dateFilter);\n  register('filter', filterFilter);\n  register('json', jsonFilter);\n  register('limitTo', limitToFilter);\n  register('lowercase', lowercaseFilter);\n  register('number', numberFilter);\n  register('orderBy', orderByFilter);\n  register('uppercase', uppercaseFilter);\n}\n\n/**\n * @ngdoc filter\n * @name filter\n * @kind function\n *\n * @description\n * Selects a subset of items from `array` and returns it as a new array.\n *\n * @param {Array} array The source array.\n * @param {string|Object|function()} expression The predicate to be used for selecting items from\n *   `array`.\n *\n *   Can be one of:\n *\n *   - `string`: The string is used for matching against the contents of the `array`. All strings or\n *     objects with string properties in `array` that match this string will be returned. This also\n *     applies to nested object properties.\n *     The predicate can be negated by prefixing the string with `!`.\n *\n *   - `Object`: A pattern object can be used to filter specific properties on objects contained\n *     by `array`. For example `{name:\"M\", phone:\"1\"}` predicate will return an array of items\n *     which have property `name` containing \"M\" and property `phone` containing \"1\". A special\n *     property name `$` can be used (as in `{$:\"text\"}`) to accept a match against any\n *     property of the object or its nested object properties. That's equivalent to the simple\n *     substring match with a `string` as described above. The predicate can be negated by prefixing\n *     the string with `!`.\n *     For example `{name: \"!M\"}` predicate will return an array of items which have property `name`\n *     not containing \"M\".\n *\n *     Note that a named property will match properties on the same level only, while the special\n *     `$` property will match properties on the same level or deeper. E.g. an array item like\n *     `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but\n *     **will** be matched by `{$: 'John'}`.\n *\n *   - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.\n *     The function is called for each element of the array, with the element, its index, and\n *     the entire array itself as arguments.\n *\n *     The final result is an array of those elements that the predicate returned true for.\n *\n * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in\n *     determining if the expected value (from the filter expression) and actual value (from\n *     the object in the array) should be considered a match.\n *\n *   Can be one of:\n *\n *   - `function(actual, expected)`:\n *     The function will be given the object value and the predicate value to compare and\n *     should return true if both values should be considered equal.\n *\n *   - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.\n *     This is essentially strict comparison of expected and actual.\n *\n *   - `false|undefined`: A short hand for a function which will look for a substring match in case\n *     insensitive way.\n *\n *     Primitive values are converted to strings. Objects are not compared against primitives,\n *     unless they have a custom `toString` method (e.g. `Date` objects).\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <div ng-init=\"friends = [{name:'John', phone:'555-1276'},\n                                {name:'Mary', phone:'800-BIG-MARY'},\n                                {name:'Mike', phone:'555-4321'},\n                                {name:'Adam', phone:'555-5678'},\n                                {name:'Julie', phone:'555-8765'},\n                                {name:'Juliette', phone:'555-5678'}]\"></div>\n\n       <label>Search: <input ng-model=\"searchText\"></label>\n       <table id=\"searchTextResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friend in friends | filter:searchText\">\n           <td>{{friend.name}}</td>\n           <td>{{friend.phone}}</td>\n         </tr>\n       </table>\n       <hr>\n       <label>Any: <input ng-model=\"search.$\"></label> <br>\n       <label>Name only <input ng-model=\"search.name\"></label><br>\n       <label>Phone only <input ng-model=\"search.phone\"></label><br>\n       <label>Equality <input type=\"checkbox\" ng-model=\"strict\"></label><br>\n       <table id=\"searchObjResults\">\n         <tr><th>Name</th><th>Phone</th></tr>\n         <tr ng-repeat=\"friendObj in friends | filter:search:strict\">\n           <td>{{friendObj.name}}</td>\n           <td>{{friendObj.phone}}</td>\n         </tr>\n       </table>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var expectFriendNames = function(expectedNames, key) {\n         element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {\n           arr.forEach(function(wd, i) {\n             expect(wd.getText()).toMatch(expectedNames[i]);\n           });\n         });\n       };\n\n       it('should search across all fields when filtering with a string', function() {\n         var searchText = element(by.model('searchText'));\n         searchText.clear();\n         searchText.sendKeys('m');\n         expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');\n\n         searchText.clear();\n         searchText.sendKeys('76');\n         expectFriendNames(['John', 'Julie'], 'friend');\n       });\n\n       it('should search in specific fields when filtering with a predicate object', function() {\n         var searchAny = element(by.model('search.$'));\n         searchAny.clear();\n         searchAny.sendKeys('i');\n         expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');\n       });\n       it('should use a equal comparison when comparator is true', function() {\n         var searchName = element(by.model('search.name'));\n         var strict = element(by.model('strict'));\n         searchName.clear();\n         searchName.sendKeys('Julie');\n         strict.click();\n         expectFriendNames(['Julie'], 'friendObj');\n       });\n     </file>\n   </example>\n */\nfunction filterFilter() {\n  return function(array, expression, comparator) {\n    if (!isArrayLike(array)) {\n      if (array == null) {\n        return array;\n      } else {\n        throw minErr('filter')('notarray', 'Expected array but received: {0}', array);\n      }\n    }\n\n    var expressionType = getTypeForFilter(expression);\n    var predicateFn;\n    var matchAgainstAnyProp;\n\n    switch (expressionType) {\n      case 'function':\n        predicateFn = expression;\n        break;\n      case 'boolean':\n      case 'null':\n      case 'number':\n      case 'string':\n        matchAgainstAnyProp = true;\n        //jshint -W086\n      case 'object':\n        //jshint +W086\n        predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);\n        break;\n      default:\n        return array;\n    }\n\n    return Array.prototype.filter.call(array, predicateFn);\n  };\n}\n\n// Helper functions for `filterFilter`\nfunction createPredicateFn(expression, comparator, matchAgainstAnyProp) {\n  var shouldMatchPrimitives = isObject(expression) && ('$' in expression);\n  var predicateFn;\n\n  if (comparator === true) {\n    comparator = equals;\n  } else if (!isFunction(comparator)) {\n    comparator = function(actual, expected) {\n      if (isUndefined(actual)) {\n        // No substring matching against `undefined`\n        return false;\n      }\n      if ((actual === null) || (expected === null)) {\n        // No substring matching against `null`; only match against `null`\n        return actual === expected;\n      }\n      if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {\n        // Should not compare primitives against objects, unless they have custom `toString` method\n        return false;\n      }\n\n      actual = lowercase('' + actual);\n      expected = lowercase('' + expected);\n      return actual.indexOf(expected) !== -1;\n    };\n  }\n\n  predicateFn = function(item) {\n    if (shouldMatchPrimitives && !isObject(item)) {\n      return deepCompare(item, expression.$, comparator, false);\n    }\n    return deepCompare(item, expression, comparator, matchAgainstAnyProp);\n  };\n\n  return predicateFn;\n}\n\nfunction deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {\n  var actualType = getTypeForFilter(actual);\n  var expectedType = getTypeForFilter(expected);\n\n  if ((expectedType === 'string') && (expected.charAt(0) === '!')) {\n    return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);\n  } else if (isArray(actual)) {\n    // In case `actual` is an array, consider it a match\n    // if ANY of it's items matches `expected`\n    return actual.some(function(item) {\n      return deepCompare(item, expected, comparator, matchAgainstAnyProp);\n    });\n  }\n\n  switch (actualType) {\n    case 'object':\n      var key;\n      if (matchAgainstAnyProp) {\n        for (key in actual) {\n          if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {\n            return true;\n          }\n        }\n        return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);\n      } else if (expectedType === 'object') {\n        for (key in expected) {\n          var expectedVal = expected[key];\n          if (isFunction(expectedVal) || isUndefined(expectedVal)) {\n            continue;\n          }\n\n          var matchAnyProperty = key === '$';\n          var actualVal = matchAnyProperty ? actual : actual[key];\n          if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {\n            return false;\n          }\n        }\n        return true;\n      } else {\n        return comparator(actual, expected);\n      }\n      break;\n    case 'function':\n      return false;\n    default:\n      return comparator(actual, expected);\n  }\n}\n\n// Used for easily differentiating between `null` and actual `object`\nfunction getTypeForFilter(val) {\n  return (val === null) ? 'null' : typeof val;\n}\n\n/**\n * @ngdoc filter\n * @name currency\n * @kind function\n *\n * @description\n * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default\n * symbol for current locale is used.\n *\n * @param {number} amount Input to filter.\n * @param {string=} symbol Currency symbol or identifier to be displayed.\n * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\n * @returns {string} Formatted number.\n *\n *\n * @example\n   <example module=\"currencyExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('currencyExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.amount = 1234.56;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input type=\"number\" ng-model=\"amount\" aria-label=\"amount\"> <br>\n         default currency symbol ($): <span id=\"currency-default\">{{amount | currency}}</span><br>\n         custom currency identifier (USD$): <span id=\"currency-custom\">{{amount | currency:\"USD$\"}}</span>\n         no fractions (0): <span id=\"currency-no-fractions\">{{amount | currency:\"USD$\":0}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should init with 1234.56', function() {\n         expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');\n         expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');\n       });\n       it('should update', function() {\n         if (browser.params.browser == 'safari') {\n           // Safari does not understand the minus key. See\n           // https://github.com/angular/protractor/issues/481\n           return;\n         }\n         element(by.model('amount')).clear();\n         element(by.model('amount')).sendKeys('-1234');\n         expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');\n         expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');\n         expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');\n       });\n     </file>\n   </example>\n */\ncurrencyFilter.$inject = ['$locale'];\nfunction currencyFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(amount, currencySymbol, fractionSize) {\n    if (isUndefined(currencySymbol)) {\n      currencySymbol = formats.CURRENCY_SYM;\n    }\n\n    if (isUndefined(fractionSize)) {\n      fractionSize = formats.PATTERNS[1].maxFrac;\n    }\n\n    // if null or undefined pass it through\n    return (amount == null)\n        ? amount\n        : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).\n            replace(/\\u00A4/g, currencySymbol);\n  };\n}\n\n/**\n * @ngdoc filter\n * @name number\n * @kind function\n *\n * @description\n * Formats a number as text.\n *\n * If the input is null or undefined, it will just be returned.\n * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.\n * If the input is not a number an empty string is returned.\n *\n *\n * @param {number|string} number Number to format.\n * @param {(number|string)=} fractionSize Number of decimal places to round the number to.\n * If this is not provided then the fraction size is computed from the current locale's number\n * formatting pattern. In the case of the default locale, it will be 3.\n * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.\n *\n * @example\n   <example module=\"numberFilterExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('numberFilterExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.val = 1234.56789;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <label>Enter number: <input ng-model='val'></label><br>\n         Default formatting: <span id='number-default'>{{val | number}}</span><br>\n         No fractions: <span>{{val | number:0}}</span><br>\n         Negative number: <span>{{-val | number:4}}</span>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format numbers', function() {\n         expect(element(by.id('number-default')).getText()).toBe('1,234.568');\n         expect(element(by.binding('val | number:0')).getText()).toBe('1,235');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');\n       });\n\n       it('should update', function() {\n         element(by.model('val')).clear();\n         element(by.model('val')).sendKeys('3374.333');\n         expect(element(by.id('number-default')).getText()).toBe('3,374.333');\n         expect(element(by.binding('val | number:0')).getText()).toBe('3,374');\n         expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');\n      });\n     </file>\n   </example>\n */\n\n\nnumberFilter.$inject = ['$locale'];\nfunction numberFilter($locale) {\n  var formats = $locale.NUMBER_FORMATS;\n  return function(number, fractionSize) {\n\n    // if null or undefined pass it through\n    return (number == null)\n        ? number\n        : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,\n                       fractionSize);\n  };\n}\n\nvar DECIMAL_SEP = '.';\nfunction formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {\n  if (isObject(number)) return '';\n\n  var isNegative = number < 0;\n  number = Math.abs(number);\n\n  var isInfinity = number === Infinity;\n  if (!isInfinity && !isFinite(number)) return '';\n\n  var numStr = number + '',\n      formatedText = '',\n      hasExponent = false,\n      parts = [];\n\n  if (isInfinity) formatedText = '\\u221e';\n\n  if (!isInfinity && numStr.indexOf('e') !== -1) {\n    var match = numStr.match(/([\\d\\.]+)e(-?)(\\d+)/);\n    if (match && match[2] == '-' && match[3] > fractionSize + 1) {\n      number = 0;\n    } else {\n      formatedText = numStr;\n      hasExponent = true;\n    }\n  }\n\n  if (!isInfinity && !hasExponent) {\n    var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;\n\n    // determine fractionSize if it is not specified\n    if (isUndefined(fractionSize)) {\n      fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);\n    }\n\n    // safely round numbers in JS without hitting imprecisions of floating-point arithmetics\n    // inspired by:\n    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round\n    number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);\n\n    var fraction = ('' + number).split(DECIMAL_SEP);\n    var whole = fraction[0];\n    fraction = fraction[1] || '';\n\n    var i, pos = 0,\n        lgroup = pattern.lgSize,\n        group = pattern.gSize;\n\n    if (whole.length >= (lgroup + group)) {\n      pos = whole.length - lgroup;\n      for (i = 0; i < pos; i++) {\n        if ((pos - i) % group === 0 && i !== 0) {\n          formatedText += groupSep;\n        }\n        formatedText += whole.charAt(i);\n      }\n    }\n\n    for (i = pos; i < whole.length; i++) {\n      if ((whole.length - i) % lgroup === 0 && i !== 0) {\n        formatedText += groupSep;\n      }\n      formatedText += whole.charAt(i);\n    }\n\n    // format fraction part.\n    while (fraction.length < fractionSize) {\n      fraction += '0';\n    }\n\n    if (fractionSize && fractionSize !== \"0\") formatedText += decimalSep + fraction.substr(0, fractionSize);\n  } else {\n    if (fractionSize > 0 && number < 1) {\n      formatedText = number.toFixed(fractionSize);\n      number = parseFloat(formatedText);\n    }\n  }\n\n  if (number === 0) {\n    isNegative = false;\n  }\n\n  parts.push(isNegative ? pattern.negPre : pattern.posPre,\n             formatedText,\n             isNegative ? pattern.negSuf : pattern.posSuf);\n  return parts.join('');\n}\n\nfunction padNumber(num, digits, trim) {\n  var neg = '';\n  if (num < 0) {\n    neg =  '-';\n    num = -num;\n  }\n  num = '' + num;\n  while (num.length < digits) num = '0' + num;\n  if (trim) {\n    num = num.substr(num.length - digits);\n  }\n  return neg + num;\n}\n\n\nfunction dateGetter(name, size, offset, trim) {\n  offset = offset || 0;\n  return function(date) {\n    var value = date['get' + name]();\n    if (offset > 0 || value > -offset) {\n      value += offset;\n    }\n    if (value === 0 && offset == -12) value = 12;\n    return padNumber(value, size, trim);\n  };\n}\n\nfunction dateStrGetter(name, shortForm) {\n  return function(date, formats) {\n    var value = date['get' + name]();\n    var get = uppercase(shortForm ? ('SHORT' + name) : name);\n\n    return formats[get][value];\n  };\n}\n\nfunction timeZoneGetter(date, formats, offset) {\n  var zone = -1 * offset;\n  var paddedZone = (zone >= 0) ? \"+\" : \"\";\n\n  paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +\n                padNumber(Math.abs(zone % 60), 2);\n\n  return paddedZone;\n}\n\nfunction getFirstThursdayOfYear(year) {\n    // 0 = index of January\n    var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();\n    // 4 = index of Thursday (+1 to account for 1st = 5)\n    // 11 = index of *next* Thursday (+1 account for 1st = 12)\n    return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);\n}\n\nfunction getThursdayThisWeek(datetime) {\n    return new Date(datetime.getFullYear(), datetime.getMonth(),\n      // 4 = index of Thursday\n      datetime.getDate() + (4 - datetime.getDay()));\n}\n\nfunction weekGetter(size) {\n   return function(date) {\n      var firstThurs = getFirstThursdayOfYear(date.getFullYear()),\n         thisThurs = getThursdayThisWeek(date);\n\n      var diff = +thisThurs - +firstThurs,\n         result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week\n\n      return padNumber(result, size);\n   };\n}\n\nfunction ampmGetter(date, formats) {\n  return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];\n}\n\nfunction eraGetter(date, formats) {\n  return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];\n}\n\nfunction longEraGetter(date, formats) {\n  return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];\n}\n\nvar DATE_FORMATS = {\n  yyyy: dateGetter('FullYear', 4),\n    yy: dateGetter('FullYear', 2, 0, true),\n     y: dateGetter('FullYear', 1),\n  MMMM: dateStrGetter('Month'),\n   MMM: dateStrGetter('Month', true),\n    MM: dateGetter('Month', 2, 1),\n     M: dateGetter('Month', 1, 1),\n    dd: dateGetter('Date', 2),\n     d: dateGetter('Date', 1),\n    HH: dateGetter('Hours', 2),\n     H: dateGetter('Hours', 1),\n    hh: dateGetter('Hours', 2, -12),\n     h: dateGetter('Hours', 1, -12),\n    mm: dateGetter('Minutes', 2),\n     m: dateGetter('Minutes', 1),\n    ss: dateGetter('Seconds', 2),\n     s: dateGetter('Seconds', 1),\n     // while ISO 8601 requires fractions to be prefixed with `.` or `,`\n     // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions\n   sss: dateGetter('Milliseconds', 3),\n  EEEE: dateStrGetter('Day'),\n   EEE: dateStrGetter('Day', true),\n     a: ampmGetter,\n     Z: timeZoneGetter,\n    ww: weekGetter(2),\n     w: weekGetter(1),\n     G: eraGetter,\n     GG: eraGetter,\n     GGG: eraGetter,\n     GGGG: longEraGetter\n};\n\nvar DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,\n    NUMBER_STRING = /^\\-?\\d+$/;\n\n/**\n * @ngdoc filter\n * @name date\n * @kind function\n *\n * @description\n *   Formats `date` to a string based on the requested `format`.\n *\n *   `format` string can be composed of the following elements:\n *\n *   * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)\n *   * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)\n *   * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)\n *   * `'MMMM'`: Month in year (January-December)\n *   * `'MMM'`: Month in year (Jan-Dec)\n *   * `'MM'`: Month in year, padded (01-12)\n *   * `'M'`: Month in year (1-12)\n *   * `'dd'`: Day in month, padded (01-31)\n *   * `'d'`: Day in month (1-31)\n *   * `'EEEE'`: Day in Week,(Sunday-Saturday)\n *   * `'EEE'`: Day in Week, (Sun-Sat)\n *   * `'HH'`: Hour in day, padded (00-23)\n *   * `'H'`: Hour in day (0-23)\n *   * `'hh'`: Hour in AM/PM, padded (01-12)\n *   * `'h'`: Hour in AM/PM, (1-12)\n *   * `'mm'`: Minute in hour, padded (00-59)\n *   * `'m'`: Minute in hour (0-59)\n *   * `'ss'`: Second in minute, padded (00-59)\n *   * `'s'`: Second in minute (0-59)\n *   * `'sss'`: Millisecond in second, padded (000-999)\n *   * `'a'`: AM/PM marker\n *   * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)\n *   * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year\n *   * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year\n *   * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')\n *   * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')\n *\n *   `format` string can also be one of the following predefined\n *   {@link guide/i18n localizable formats}:\n *\n *   * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale\n *     (e.g. Sep 3, 2010 12:05:08 PM)\n *   * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US  locale (e.g. 9/3/10 12:05 PM)\n *   * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US  locale\n *     (e.g. Friday, September 3, 2010)\n *   * `'longDate'`: equivalent to `'MMMM d, y'` for en_US  locale (e.g. September 3, 2010)\n *   * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US  locale (e.g. Sep 3, 2010)\n *   * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)\n *   * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)\n *   * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)\n *\n *   `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.\n *   `\"h 'in the morning'\"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence\n *   (e.g. `\"h 'o''clock'\"`).\n *\n * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or\n *    number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its\n *    shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is\n *    specified in the string input, the time is considered to be in the local timezone.\n * @param {string=} format Formatting rules (see Description). If not specified,\n *    `mediumDate` is used.\n * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the\n *    continental US time zone abbreviations, but for general use, use a time zone offset, for\n *    example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n *    If not specified, the timezone of the browser will be used.\n * @returns {string} Formatted string or the input if input is not recognized as date/millis.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:\n           <span>{{1288323623006 | date:'medium'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:\n          <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:\n          <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>\n       <span ng-non-bindable>{{1288323623006 | date:\"MM/dd/yyyy 'at' h:mma\"}}</span>:\n          <span>{{'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"}}</span><br>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should format date', function() {\n         expect(element(by.binding(\"1288323623006 | date:'medium'\")).getText()).\n            toMatch(/Oct 2\\d, 2010 \\d{1,2}:\\d{2}:\\d{2} (AM|PM)/);\n         expect(element(by.binding(\"1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'\")).getText()).\n            toMatch(/2010\\-10\\-2\\d \\d{2}:\\d{2}:\\d{2} (\\-|\\+)?\\d{4}/);\n         expect(element(by.binding(\"'1288323623006' | date:'MM/dd/yyyy @ h:mma'\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 @ \\d{1,2}:\\d{2}(AM|PM)/);\n         expect(element(by.binding(\"'1288323623006' | date:\\\"MM/dd/yyyy 'at' h:mma\\\"\")).getText()).\n            toMatch(/10\\/2\\d\\/2010 at \\d{1,2}:\\d{2}(AM|PM)/);\n       });\n     </file>\n   </example>\n */\ndateFilter.$inject = ['$locale'];\nfunction dateFilter($locale) {\n\n\n  var R_ISO8601_STR = /^(\\d{4})-?(\\d\\d)-?(\\d\\d)(?:T(\\d\\d)(?::?(\\d\\d)(?::?(\\d\\d)(?:\\.(\\d+))?)?)?(Z|([+-])(\\d\\d):?(\\d\\d))?)?$/;\n                     // 1        2       3         4          5          6          7          8  9     10      11\n  function jsonStringToDate(string) {\n    var match;\n    if (match = string.match(R_ISO8601_STR)) {\n      var date = new Date(0),\n          tzHour = 0,\n          tzMin  = 0,\n          dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,\n          timeSetter = match[8] ? date.setUTCHours : date.setHours;\n\n      if (match[9]) {\n        tzHour = toInt(match[9] + match[10]);\n        tzMin = toInt(match[9] + match[11]);\n      }\n      dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));\n      var h = toInt(match[4] || 0) - tzHour;\n      var m = toInt(match[5] || 0) - tzMin;\n      var s = toInt(match[6] || 0);\n      var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);\n      timeSetter.call(date, h, m, s, ms);\n      return date;\n    }\n    return string;\n  }\n\n\n  return function(date, format, timezone) {\n    var text = '',\n        parts = [],\n        fn, match;\n\n    format = format || 'mediumDate';\n    format = $locale.DATETIME_FORMATS[format] || format;\n    if (isString(date)) {\n      date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);\n    }\n\n    if (isNumber(date)) {\n      date = new Date(date);\n    }\n\n    if (!isDate(date) || !isFinite(date.getTime())) {\n      return date;\n    }\n\n    while (format) {\n      match = DATE_FORMATS_SPLIT.exec(format);\n      if (match) {\n        parts = concat(parts, match, 1);\n        format = parts.pop();\n      } else {\n        parts.push(format);\n        format = null;\n      }\n    }\n\n    var dateTimezoneOffset = date.getTimezoneOffset();\n    if (timezone) {\n      dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());\n      date = convertTimezoneToLocal(date, timezone, true);\n    }\n    forEach(parts, function(value) {\n      fn = DATE_FORMATS[value];\n      text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)\n                 : value.replace(/(^'|'$)/g, '').replace(/''/g, \"'\");\n    });\n\n    return text;\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name json\n * @kind function\n *\n * @description\n *   Allows you to convert a JavaScript object into JSON string.\n *\n *   This filter is mostly useful for debugging. When using the double curly {{value}} notation\n *   the binding is automatically converted to JSON.\n *\n * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.\n * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.\n * @returns {string} JSON string.\n *\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <pre id=\"default-spacing\">{{ {'name':'value'} | json }}</pre>\n       <pre id=\"custom-spacing\">{{ {'name':'value'} | json:4 }}</pre>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should jsonify filtered objects', function() {\n         expect(element(by.id('default-spacing')).getText()).toMatch(/\\{\\n  \"name\": ?\"value\"\\n}/);\n         expect(element(by.id('custom-spacing')).getText()).toMatch(/\\{\\n    \"name\": ?\"value\"\\n}/);\n       });\n     </file>\n   </example>\n *\n */\nfunction jsonFilter() {\n  return function(object, spacing) {\n    if (isUndefined(spacing)) {\n        spacing = 2;\n    }\n    return toJson(object, spacing);\n  };\n}\n\n\n/**\n * @ngdoc filter\n * @name lowercase\n * @kind function\n * @description\n * Converts string to lowercase.\n * @see angular.lowercase\n */\nvar lowercaseFilter = valueFn(lowercase);\n\n\n/**\n * @ngdoc filter\n * @name uppercase\n * @kind function\n * @description\n * Converts string to uppercase.\n * @see angular.uppercase\n */\nvar uppercaseFilter = valueFn(uppercase);\n\n/**\n * @ngdoc filter\n * @name limitTo\n * @kind function\n *\n * @description\n * Creates a new array or string containing only a specified number of elements. The elements\n * are taken from either the beginning or the end of the source array, string or number, as specified by\n * the value and sign (positive or negative) of `limit`. If a number is used as input, it is\n * converted to a string.\n *\n * @param {Array|string|number} input Source array, string or number to be limited.\n * @param {string|number} limit The length of the returned array or string. If the `limit` number\n *     is positive, `limit` number of items from the beginning of the source array/string are copied.\n *     If the number is negative, `limit` number  of items from the end of the source array/string\n *     are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,\n *     the input will be returned unchanged.\n * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`\n *     indicates an offset from the end of `input`. Defaults to `0`.\n * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array\n *     had less than `limit` elements.\n *\n * @example\n   <example module=\"limitToExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('limitToExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.numbers = [1,2,3,4,5,6,7,8,9];\n             $scope.letters = \"abcdefghi\";\n             $scope.longNumber = 2345432342;\n             $scope.numLimit = 3;\n             $scope.letterLimit = 3;\n             $scope.longNumberLimit = 3;\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <label>\n            Limit {{numbers}} to:\n            <input type=\"number\" step=\"1\" ng-model=\"numLimit\">\n         </label>\n         <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>\n         <label>\n            Limit {{letters}} to:\n            <input type=\"number\" step=\"1\" ng-model=\"letterLimit\">\n         </label>\n         <p>Output letters: {{ letters | limitTo:letterLimit }}</p>\n         <label>\n            Limit {{longNumber}} to:\n            <input type=\"number\" step=\"1\" ng-model=\"longNumberLimit\">\n         </label>\n         <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var numLimitInput = element(by.model('numLimit'));\n       var letterLimitInput = element(by.model('letterLimit'));\n       var longNumberLimitInput = element(by.model('longNumberLimit'));\n       var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));\n       var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));\n       var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));\n\n       it('should limit the number array to first three items', function() {\n         expect(numLimitInput.getAttribute('value')).toBe('3');\n         expect(letterLimitInput.getAttribute('value')).toBe('3');\n         expect(longNumberLimitInput.getAttribute('value')).toBe('3');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abc');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 234');\n       });\n\n       // There is a bug in safari and protractor that doesn't like the minus key\n       // it('should update the output when -3 is entered', function() {\n       //   numLimitInput.clear();\n       //   numLimitInput.sendKeys('-3');\n       //   letterLimitInput.clear();\n       //   letterLimitInput.sendKeys('-3');\n       //   longNumberLimitInput.clear();\n       //   longNumberLimitInput.sendKeys('-3');\n       //   expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');\n       //   expect(limitedLetters.getText()).toEqual('Output letters: ghi');\n       //   expect(limitedLongNumber.getText()).toEqual('Output long number: 342');\n       // });\n\n       it('should not exceed the maximum size of input array', function() {\n         numLimitInput.clear();\n         numLimitInput.sendKeys('100');\n         letterLimitInput.clear();\n         letterLimitInput.sendKeys('100');\n         longNumberLimitInput.clear();\n         longNumberLimitInput.sendKeys('100');\n         expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');\n         expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');\n         expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');\n       });\n     </file>\n   </example>\n*/\nfunction limitToFilter() {\n  return function(input, limit, begin) {\n    if (Math.abs(Number(limit)) === Infinity) {\n      limit = Number(limit);\n    } else {\n      limit = toInt(limit);\n    }\n    if (isNaN(limit)) return input;\n\n    if (isNumber(input)) input = input.toString();\n    if (!isArray(input) && !isString(input)) return input;\n\n    begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);\n    begin = (begin < 0 && begin >= -input.length) ? input.length + begin : begin;\n\n    if (limit >= 0) {\n      return input.slice(begin, begin + limit);\n    } else {\n      if (begin === 0) {\n        return input.slice(limit, input.length);\n      } else {\n        return input.slice(Math.max(0, begin + limit), begin);\n      }\n    }\n  };\n}\n\n/**\n * @ngdoc filter\n * @name orderBy\n * @kind function\n *\n * @description\n * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically\n * for strings and numerically for numbers. Note: if you notice numbers are not being sorted\n * as expected, make sure they are actually being saved as numbers and not strings.\n *\n * @param {Array} array The array to sort.\n * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be\n *    used by the comparator to determine the order of elements.\n *\n *    Can be one of:\n *\n *    - `function`: Getter function. The result of this function will be sorted using the\n *      `<`, `===`, `>` operator.\n *    - `string`: An Angular expression. The result of this expression is used to compare elements\n *      (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by\n *      3 first characters of a property called `name`). The result of a constant expression\n *      is interpreted as a property name to be used in comparisons (for example `\"special name\"`\n *      to sort object by the value of their `special name` property). An expression can be\n *      optionally prefixed with `+` or `-` to control ascending or descending sort order\n *      (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array\n *      element itself is used to compare where sorting.\n *    - `Array`: An array of function or string predicates. The first predicate in the array\n *      is used for sorting, but when two items are equivalent, the next predicate is used.\n *\n *    If the predicate is missing or empty then it defaults to `'+'`.\n *\n * @param {boolean=} reverse Reverse the order of the array.\n * @returns {Array} Sorted copy of the source array.\n *\n *\n * @example\n * The example below demonstrates a simple ngRepeat, where the data is sorted\n * by age in descending order (predicate is set to `'-age'`).\n * `reverse` is not set, which means it defaults to `false`.\n   <example module=\"orderByExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('orderByExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.friends =\n                 [{name:'John', phone:'555-1212', age:10},\n                  {name:'Mary', phone:'555-9876', age:19},\n                  {name:'Mike', phone:'555-4321', age:21},\n                  {name:'Adam', phone:'555-5678', age:35},\n                  {name:'Julie', phone:'555-8765', age:29}];\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <table class=\"friend\">\n           <tr>\n             <th>Name</th>\n             <th>Phone Number</th>\n             <th>Age</th>\n           </tr>\n           <tr ng-repeat=\"friend in friends | orderBy:'-age'\">\n             <td>{{friend.name}}</td>\n             <td>{{friend.phone}}</td>\n             <td>{{friend.age}}</td>\n           </tr>\n         </table>\n       </div>\n     </file>\n   </example>\n *\n * The predicate and reverse parameters can be controlled dynamically through scope properties,\n * as shown in the next example.\n * @example\n   <example module=\"orderByExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('orderByExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.friends =\n                 [{name:'John', phone:'555-1212', age:10},\n                  {name:'Mary', phone:'555-9876', age:19},\n                  {name:'Mike', phone:'555-4321', age:21},\n                  {name:'Adam', phone:'555-5678', age:35},\n                  {name:'Julie', phone:'555-8765', age:29}];\n             $scope.predicate = 'age';\n             $scope.reverse = true;\n             $scope.order = function(predicate) {\n               $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;\n               $scope.predicate = predicate;\n             };\n           }]);\n       </script>\n       <style type=\"text/css\">\n         .sortorder:after {\n           content: '\\25b2';\n         }\n         .sortorder.reverse:after {\n           content: '\\25bc';\n         }\n       </style>\n       <div ng-controller=\"ExampleController\">\n         <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>\n         <hr/>\n         [ <a href=\"\" ng-click=\"predicate=''\">unsorted</a> ]\n         <table class=\"friend\">\n           <tr>\n             <th>\n               <a href=\"\" ng-click=\"order('name')\">Name</a>\n               <span class=\"sortorder\" ng-show=\"predicate === 'name'\" ng-class=\"{reverse:reverse}\"></span>\n             </th>\n             <th>\n               <a href=\"\" ng-click=\"order('phone')\">Phone Number</a>\n               <span class=\"sortorder\" ng-show=\"predicate === 'phone'\" ng-class=\"{reverse:reverse}\"></span>\n             </th>\n             <th>\n               <a href=\"\" ng-click=\"order('age')\">Age</a>\n               <span class=\"sortorder\" ng-show=\"predicate === 'age'\" ng-class=\"{reverse:reverse}\"></span>\n             </th>\n           </tr>\n           <tr ng-repeat=\"friend in friends | orderBy:predicate:reverse\">\n             <td>{{friend.name}}</td>\n             <td>{{friend.phone}}</td>\n             <td>{{friend.age}}</td>\n           </tr>\n         </table>\n       </div>\n     </file>\n   </example>\n *\n * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the\n * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the\n * desired parameters.\n *\n * Example:\n *\n * @example\n  <example module=\"orderByExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <table class=\"friend\">\n          <tr>\n            <th><a href=\"\" ng-click=\"reverse=false;order('name', false)\">Name</a>\n              (<a href=\"\" ng-click=\"order('-name',false)\">^</a>)</th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('phone', reverse)\">Phone Number</a></th>\n            <th><a href=\"\" ng-click=\"reverse=!reverse;order('age',reverse)\">Age</a></th>\n          </tr>\n          <tr ng-repeat=\"friend in friends\">\n            <td>{{friend.name}}</td>\n            <td>{{friend.phone}}</td>\n            <td>{{friend.age}}</td>\n          </tr>\n        </table>\n      </div>\n    </file>\n\n    <file name=\"script.js\">\n      angular.module('orderByExample', [])\n        .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {\n          var orderBy = $filter('orderBy');\n          $scope.friends = [\n            { name: 'John',    phone: '555-1212',    age: 10 },\n            { name: 'Mary',    phone: '555-9876',    age: 19 },\n            { name: 'Mike',    phone: '555-4321',    age: 21 },\n            { name: 'Adam',    phone: '555-5678',    age: 35 },\n            { name: 'Julie',   phone: '555-8765',    age: 29 }\n          ];\n          $scope.order = function(predicate, reverse) {\n            $scope.friends = orderBy($scope.friends, predicate, reverse);\n          };\n          $scope.order('-age',false);\n        }]);\n    </file>\n</example>\n */\norderByFilter.$inject = ['$parse'];\nfunction orderByFilter($parse) {\n  return function(array, sortPredicate, reverseOrder) {\n\n    if (!(isArrayLike(array))) return array;\n\n    if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }\n    if (sortPredicate.length === 0) { sortPredicate = ['+']; }\n\n    var predicates = processPredicates(sortPredicate, reverseOrder);\n    // Add a predicate at the end that evaluates to the element index. This makes the\n    // sort stable as it works as a tie-breaker when all the input predicates cannot\n    // distinguish between two elements.\n    predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});\n\n    // The next three lines are a version of a Swartzian Transform idiom from Perl\n    // (sometimes called the Decorate-Sort-Undecorate idiom)\n    // See https://en.wikipedia.org/wiki/Schwartzian_transform\n    var compareValues = Array.prototype.map.call(array, getComparisonObject);\n    compareValues.sort(doComparison);\n    array = compareValues.map(function(item) { return item.value; });\n\n    return array;\n\n    function getComparisonObject(value, index) {\n      return {\n        value: value,\n        predicateValues: predicates.map(function(predicate) {\n          return getPredicateValue(predicate.get(value), index);\n        })\n      };\n    }\n\n    function doComparison(v1, v2) {\n      var result = 0;\n      for (var index=0, length = predicates.length; index < length; ++index) {\n        result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;\n        if (result) break;\n      }\n      return result;\n    }\n  };\n\n  function processPredicates(sortPredicate, reverseOrder) {\n    reverseOrder = reverseOrder ? -1 : 1;\n    return sortPredicate.map(function(predicate) {\n      var descending = 1, get = identity;\n\n      if (isFunction(predicate)) {\n        get = predicate;\n      } else if (isString(predicate)) {\n        if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {\n          descending = predicate.charAt(0) == '-' ? -1 : 1;\n          predicate = predicate.substring(1);\n        }\n        if (predicate !== '') {\n          get = $parse(predicate);\n          if (get.constant) {\n            var key = get();\n            get = function(value) { return value[key]; };\n          }\n        }\n      }\n      return { get: get, descending: descending * reverseOrder };\n    });\n  }\n\n  function isPrimitive(value) {\n    switch (typeof value) {\n      case 'number': /* falls through */\n      case 'boolean': /* falls through */\n      case 'string':\n        return true;\n      default:\n        return false;\n    }\n  }\n\n  function objectValue(value, index) {\n    // If `valueOf` is a valid function use that\n    if (typeof value.valueOf === 'function') {\n      value = value.valueOf();\n      if (isPrimitive(value)) return value;\n    }\n    // If `toString` is a valid function and not the one from `Object.prototype` use that\n    if (hasCustomToString(value)) {\n      value = value.toString();\n      if (isPrimitive(value)) return value;\n    }\n    // We have a basic object so we use the position of the object in the collection\n    return index;\n  }\n\n  function getPredicateValue(value, index) {\n    var type = typeof value;\n    if (value === null) {\n      type = 'string';\n      value = 'null';\n    } else if (type === 'string') {\n      value = value.toLowerCase();\n    } else if (type === 'object') {\n      value = objectValue(value, index);\n    }\n    return { value: value, type: type };\n  }\n\n  function compare(v1, v2) {\n    var result = 0;\n    if (v1.type === v2.type) {\n      if (v1.value !== v2.value) {\n        result = v1.value < v2.value ? -1 : 1;\n      }\n    } else {\n      result = v1.type < v2.type ? -1 : 1;\n    }\n    return result;\n  }\n}\n\nfunction ngDirective(directive) {\n  if (isFunction(directive)) {\n    directive = {\n      link: directive\n    };\n  }\n  directive.restrict = directive.restrict || 'AC';\n  return valueFn(directive);\n}\n\n/**\n * @ngdoc directive\n * @name a\n * @restrict E\n *\n * @description\n * Modifies the default behavior of the html A tag so that the default action is prevented when\n * the href attribute is empty.\n *\n * This change permits the easy creation of action links with the `ngClick` directive\n * without changing the location or causing page reloads, e.g.:\n * `<a href=\"\" ng-click=\"list.addItem()\">Add Item</a>`\n */\nvar htmlAnchorDirective = valueFn({\n  restrict: 'E',\n  compile: function(element, attr) {\n    if (!attr.href && !attr.xlinkHref) {\n      return function(scope, element) {\n        // If the linked element is not an anchor tag anymore, do nothing\n        if (element[0].nodeName.toLowerCase() !== 'a') return;\n\n        // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.\n        var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?\n                   'xlink:href' : 'href';\n        element.on('click', function(event) {\n          // if we have no href url, then don't navigate anywhere.\n          if (!element.attr(href)) {\n            event.preventDefault();\n          }\n        });\n      };\n    }\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngHref\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in an href attribute will\n * make the link go to the wrong URL if the user clicks it before\n * Angular has a chance to replace the `{{hash}}` markup with its\n * value. Until Angular replaces the markup the link will be broken\n * and will most likely return a 404 error. The `ngHref` directive\n * solves this problem.\n *\n * The wrong way to write it:\n * ```html\n * <a href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <a ng-href=\"http://www.gravatar.com/avatar/{{hash}}\">link1</a>\n * ```\n *\n * @element A\n * @param {template} ngHref any string which can contain `{{}}` markup.\n *\n * @example\n * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes\n * in links and their different behaviors:\n    <example>\n      <file name=\"index.html\">\n        <input ng-model=\"value\" /><br />\n        <a id=\"link-1\" href ng-click=\"value = 1\">link 1</a> (link, don't reload)<br />\n        <a id=\"link-2\" href=\"\" ng-click=\"value = 2\">link 2</a> (link, don't reload)<br />\n        <a id=\"link-3\" ng-href=\"/{{'123'}}\">link 3</a> (link, reload!)<br />\n        <a id=\"link-4\" href=\"\" name=\"xx\" ng-click=\"value = 4\">anchor</a> (link, don't reload)<br />\n        <a id=\"link-5\" name=\"xxx\" ng-click=\"value = 5\">anchor</a> (no link)<br />\n        <a id=\"link-6\" ng-href=\"{{value}}\">link</a> (link, change location)\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should execute ng-click but not reload when href without value', function() {\n          element(by.id('link-1')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('1');\n          expect(element(by.id('link-1')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when href empty string', function() {\n          element(by.id('link-2')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('2');\n          expect(element(by.id('link-2')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click and change url when ng-href specified', function() {\n          expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\\/123$/);\n\n          element(by.id('link-3')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/123$/);\n            });\n          }, 5000, 'page should navigate to /123');\n        });\n\n        it('should execute ng-click but not reload when href empty string and name specified', function() {\n          element(by.id('link-4')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('4');\n          expect(element(by.id('link-4')).getAttribute('href')).toBe('');\n        });\n\n        it('should execute ng-click but not reload when no href but name specified', function() {\n          element(by.id('link-5')).click();\n          expect(element(by.model('value')).getAttribute('value')).toEqual('5');\n          expect(element(by.id('link-5')).getAttribute('href')).toBe(null);\n        });\n\n        it('should only change url when only ng-href', function() {\n          element(by.model('value')).clear();\n          element(by.model('value')).sendKeys('6');\n          expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\\/6$/);\n\n          element(by.id('link-6')).click();\n\n          // At this point, we navigate away from an Angular page, so we need\n          // to use browser.driver to get the base webdriver.\n          browser.wait(function() {\n            return browser.driver.getCurrentUrl().then(function(url) {\n              return url.match(/\\/6$/);\n            });\n          }, 5000, 'page should navigate to /6');\n        });\n      </file>\n    </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngSrc\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `src` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrc` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img src=\"http://www.gravatar.com/avatar/{{hash}}\" alt=\"Description\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-src=\"http://www.gravatar.com/avatar/{{hash}}\" alt=\"Description\" />\n * ```\n *\n * @element IMG\n * @param {template} ngSrc any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngSrcset\n * @restrict A\n * @priority 99\n *\n * @description\n * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't\n * work right: The browser will fetch from the URL with the literal\n * text `{{hash}}` until Angular replaces the expression inside\n * `{{hash}}`. The `ngSrcset` directive solves this problem.\n *\n * The buggy way to write it:\n * ```html\n * <img srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\" alt=\"Description\"/>\n * ```\n *\n * The correct way to write it:\n * ```html\n * <img ng-srcset=\"http://www.gravatar.com/avatar/{{hash}} 2x\" alt=\"Description\" />\n * ```\n *\n * @element IMG\n * @param {template} ngSrcset any string which can contain `{{}}` markup.\n */\n\n/**\n * @ngdoc directive\n * @name ngDisabled\n * @restrict A\n * @priority 100\n *\n * @description\n *\n * This directive sets the `disabled` attribute on the element if the\n * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.\n *\n * A special directive is necessary because we cannot use interpolation inside the `disabled`\n * attribute.  The following example would make the button enabled on Chrome/Firefox\n * but not on older IEs:\n *\n * ```html\n * <!-- See below for an example of ng-disabled being used correctly -->\n * <div ng-init=\"isDisabled = false\">\n *  <button disabled=\"{{isDisabled}}\">Disabled</button>\n * </div>\n * ```\n *\n * This is because the HTML specification does not require browsers to preserve the values of\n * boolean attributes such as `disabled` (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Click me to toggle: <input type=\"checkbox\" ng-model=\"checked\"></label><br/>\n        <button ng-model=\"button\" ng-disabled=\"checked\">Button</button>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle button', function() {\n          expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,\n *     then the `disabled` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngChecked\n * @restrict A\n * @priority 100\n *\n * @description\n * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.\n *\n * Note that this directive should not be used together with {@link ngModel `ngModel`},\n * as this can lead to unexpected behavior.\n *\n * ### Why do we need `ngChecked`?\n *\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as checked. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngChecked` directive solves this problem for the `checked` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Check me to check both: <input type=\"checkbox\" ng-model=\"master\"></label><br/>\n        <input id=\"checkSlave\" type=\"checkbox\" ng-checked=\"master\" aria-label=\"Slave input\">\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should check both checkBoxes', function() {\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();\n          element(by.model('master')).click();\n          expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,\n *     then the `checked` attribute will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngReadonly\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as readonly. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngReadonly` directive solves this problem for the `readonly` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Check me to make text readonly: <input type=\"checkbox\" ng-model=\"checked\"></label><br/>\n        <input type=\"text\" ng-readonly=\"checked\" value=\"I'm Angular\" aria-label=\"Readonly field\" />\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should toggle readonly attr', function() {\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeFalsy();\n          element(by.model('checked')).click();\n          expect(element(by.css('[type=\"text\"]')).getAttribute('readonly')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element INPUT\n * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,\n *     then special attribute \"readonly\" will be set on the element\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSelected\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as selected. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngSelected` directive solves this problem for the `selected` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <label>Check me to select: <input type=\"checkbox\" ng-model=\"selected\"></label><br/>\n        <select aria-label=\"ngSelected demo\">\n          <option>Hello!</option>\n          <option id=\"greet\" ng-selected=\"selected\">Greetings!</option>\n        </select>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should select Greetings!', function() {\n          expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();\n          element(by.model('selected')).click();\n          expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();\n        });\n      </file>\n    </example>\n *\n * @element OPTION\n * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,\n *     then special attribute \"selected\" will be set on the element\n */\n\n/**\n * @ngdoc directive\n * @name ngOpen\n * @restrict A\n * @priority 100\n *\n * @description\n * The HTML specification does not require browsers to preserve the values of boolean attributes\n * such as open. (Their presence means true and their absence means false.)\n * If we put an Angular interpolation expression into such an attribute then the\n * binding information would be lost when the browser removes the attribute.\n * The `ngOpen` directive solves this problem for the `open` attribute.\n * This complementary directive is not removed by the browser and so provides\n * a permanent reliable place to store the binding information.\n * @example\n     <example>\n       <file name=\"index.html\">\n         <label>Check me check multiple: <input type=\"checkbox\" ng-model=\"open\"></label><br/>\n         <details id=\"details\" ng-open=\"open\">\n            <summary>Show/Hide me</summary>\n         </details>\n       </file>\n       <file name=\"protractor.js\" type=\"protractor\">\n         it('should toggle open', function() {\n           expect(element(by.id('details')).getAttribute('open')).toBeFalsy();\n           element(by.model('open')).click();\n           expect(element(by.id('details')).getAttribute('open')).toBeTruthy();\n         });\n       </file>\n     </example>\n *\n * @element DETAILS\n * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,\n *     then special attribute \"open\" will be set on the element\n */\n\nvar ngAttributeAliasDirectives = {};\n\n// boolean attrs are evaluated\nforEach(BOOLEAN_ATTR, function(propName, attrName) {\n  // binding to multiple is not supported\n  if (propName == \"multiple\") return;\n\n  function defaultLinkFn(scope, element, attr) {\n    scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {\n      attr.$set(attrName, !!value);\n    });\n  }\n\n  var normalized = directiveNormalize('ng-' + attrName);\n  var linkFn = defaultLinkFn;\n\n  if (propName === 'checked') {\n    linkFn = function(scope, element, attr) {\n      // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input\n      if (attr.ngModel !== attr[normalized]) {\n        defaultLinkFn(scope, element, attr);\n      }\n    };\n  }\n\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      restrict: 'A',\n      priority: 100,\n      link: linkFn\n    };\n  };\n});\n\n// aliased input attrs are evaluated\nforEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {\n  ngAttributeAliasDirectives[ngAttr] = function() {\n    return {\n      priority: 100,\n      link: function(scope, element, attr) {\n        //special case ngPattern when a literal regular expression value\n        //is used as the expression (this way we don't have to watch anything).\n        if (ngAttr === \"ngPattern\" && attr.ngPattern.charAt(0) == \"/\") {\n          var match = attr.ngPattern.match(REGEX_STRING_REGEXP);\n          if (match) {\n            attr.$set(\"ngPattern\", new RegExp(match[1], match[2]));\n            return;\n          }\n        }\n\n        scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {\n          attr.$set(ngAttr, value);\n        });\n      }\n    };\n  };\n});\n\n// ng-src, ng-srcset, ng-href are interpolated\nforEach(['src', 'srcset', 'href'], function(attrName) {\n  var normalized = directiveNormalize('ng-' + attrName);\n  ngAttributeAliasDirectives[normalized] = function() {\n    return {\n      priority: 99, // it needs to run after the attributes are interpolated\n      link: function(scope, element, attr) {\n        var propName = attrName,\n            name = attrName;\n\n        if (attrName === 'href' &&\n            toString.call(element.prop('href')) === '[object SVGAnimatedString]') {\n          name = 'xlinkHref';\n          attr.$attr[name] = 'xlink:href';\n          propName = null;\n        }\n\n        attr.$observe(normalized, function(value) {\n          if (!value) {\n            if (attrName === 'href') {\n              attr.$set(name, null);\n            }\n            return;\n          }\n\n          attr.$set(name, value);\n\n          // on IE, if \"ng:src\" directive declaration is used and \"src\" attribute doesn't exist\n          // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need\n          // to set the property as well to achieve the desired effect.\n          // we use attr[attrName] value since $set can sanitize the url.\n          if (msie && propName) element.prop(propName, attr[name]);\n        });\n      }\n    };\n  };\n});\n\n/* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true\n */\nvar nullFormCtrl = {\n  $addControl: noop,\n  $$renameControl: nullFormRenameControl,\n  $removeControl: noop,\n  $setValidity: noop,\n  $setDirty: noop,\n  $setPristine: noop,\n  $setSubmitted: noop\n},\nSUBMITTED_CLASS = 'ng-submitted';\n\nfunction nullFormRenameControl(control, name) {\n  control.$name = name;\n}\n\n/**\n * @ngdoc type\n * @name form.FormController\n *\n * @property {boolean} $pristine True if user has not interacted with the form yet.\n * @property {boolean} $dirty True if user has already interacted with the form.\n * @property {boolean} $valid True if all of the containing forms and controls are valid.\n * @property {boolean} $invalid True if at least one containing control or form is invalid.\n * @property {boolean} $submitted True if user has submitted the form even if its invalid.\n *\n * @property {Object} $error Is an object hash, containing references to controls or\n *  forms with failing validators, where:\n *\n *  - keys are validation tokens (error names),\n *  - values are arrays of controls or forms that have a failing validator for given error name.\n *\n *  Built-in validation tokens:\n *\n *  - `email`\n *  - `max`\n *  - `maxlength`\n *  - `min`\n *  - `minlength`\n *  - `number`\n *  - `pattern`\n *  - `required`\n *  - `url`\n *  - `date`\n *  - `datetimelocal`\n *  - `time`\n *  - `week`\n *  - `month`\n *\n * @description\n * `FormController` keeps track of all its controls and nested forms as well as the state of them,\n * such as being valid/invalid or dirty/pristine.\n *\n * Each {@link ng.directive:form form} directive creates an instance\n * of `FormController`.\n *\n */\n//asks for $scope to fool the BC controller module\nFormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];\nfunction FormController(element, attrs, $scope, $animate, $interpolate) {\n  var form = this,\n      controls = [];\n\n  var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;\n\n  // init state\n  form.$error = {};\n  form.$$success = {};\n  form.$pending = undefined;\n  form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);\n  form.$dirty = false;\n  form.$pristine = true;\n  form.$valid = true;\n  form.$invalid = false;\n  form.$submitted = false;\n\n  parentForm.$addControl(form);\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$rollbackViewValue\n   *\n   * @description\n   * Rollback all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is typically needed by the reset button of\n   * a form that uses `ng-model-options` to pend updates.\n   */\n  form.$rollbackViewValue = function() {\n    forEach(controls, function(control) {\n      control.$rollbackViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$commitViewValue\n   *\n   * @description\n   * Commit all form controls pending updates to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  form.$commitViewValue = function() {\n    forEach(controls, function(control) {\n      control.$commitViewValue();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$addControl\n   *\n   * @description\n   * Register a control with the form.\n   *\n   * Input elements using ngModelController do this automatically when they are linked.\n   */\n  form.$addControl = function(control) {\n    // Breaking change - before, inputs whose name was \"hasOwnProperty\" were quietly ignored\n    // and not added to the scope.  Now we throw an error.\n    assertNotHasOwnProperty(control.$name, 'input');\n    controls.push(control);\n\n    if (control.$name) {\n      form[control.$name] = control;\n    }\n  };\n\n  // Private API: rename a form control\n  form.$$renameControl = function(control, newName) {\n    var oldName = control.$name;\n\n    if (form[oldName] === control) {\n      delete form[oldName];\n    }\n    form[newName] = control;\n    control.$name = newName;\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$removeControl\n   *\n   * @description\n   * Deregister a control from the form.\n   *\n   * Input elements using ngModelController do this automatically when they are destroyed.\n   */\n  form.$removeControl = function(control) {\n    if (control.$name && form[control.$name] === control) {\n      delete form[control.$name];\n    }\n    forEach(form.$pending, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$error, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n    forEach(form.$$success, function(value, name) {\n      form.$setValidity(name, null, control);\n    });\n\n    arrayRemove(controls, control);\n  };\n\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setValidity\n   *\n   * @description\n   * Sets the validity of a form control.\n   *\n   * This method will also propagate to parent forms.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: element,\n    set: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        object[property] = [controller];\n      } else {\n        var index = list.indexOf(controller);\n        if (index === -1) {\n          list.push(controller);\n        }\n      }\n    },\n    unset: function(object, property, controller) {\n      var list = object[property];\n      if (!list) {\n        return;\n      }\n      arrayRemove(list, controller);\n      if (list.length === 0) {\n        delete object[property];\n      }\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setDirty\n   *\n   * @description\n   * Sets the form to a dirty state.\n   *\n   * This method can be called to add the 'ng-dirty' class and set the form to a dirty\n   * state (ng-dirty class). This method will also propagate to parent forms.\n   */\n  form.$setDirty = function() {\n    $animate.removeClass(element, PRISTINE_CLASS);\n    $animate.addClass(element, DIRTY_CLASS);\n    form.$dirty = true;\n    form.$pristine = false;\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setPristine\n   *\n   * @description\n   * Sets the form to its pristine state.\n   *\n   * This method can be called to remove the 'ng-dirty' class and set the form to its pristine\n   * state (ng-pristine class). This method will also propagate to all the controls contained\n   * in this form.\n   *\n   * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after\n   * saving or resetting it.\n   */\n  form.$setPristine = function() {\n    $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);\n    form.$dirty = false;\n    form.$pristine = true;\n    form.$submitted = false;\n    forEach(controls, function(control) {\n      control.$setPristine();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setUntouched\n   *\n   * @description\n   * Sets the form to its untouched state.\n   *\n   * This method can be called to remove the 'ng-touched' class and set the form controls to their\n   * untouched state (ng-untouched class).\n   *\n   * Setting a form controls back to their untouched state is often useful when setting the form\n   * back to its pristine state.\n   */\n  form.$setUntouched = function() {\n    forEach(controls, function(control) {\n      control.$setUntouched();\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name form.FormController#$setSubmitted\n   *\n   * @description\n   * Sets the form to its submitted state.\n   */\n  form.$setSubmitted = function() {\n    $animate.addClass(element, SUBMITTED_CLASS);\n    form.$submitted = true;\n    parentForm.$setSubmitted();\n  };\n}\n\n/**\n * @ngdoc directive\n * @name ngForm\n * @restrict EAC\n *\n * @description\n * Nestable alias of {@link ng.directive:form `form`} directive. HTML\n * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a\n * sub-group of controls needs to be determined.\n *\n * Note: the purpose of `ngForm` is to group controls,\n * but not to be a replacement for the `<form>` tag with all of its capabilities\n * (e.g. posting to the server, ...).\n *\n * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n *\n */\n\n /**\n * @ngdoc directive\n * @name form\n * @restrict E\n *\n * @description\n * Directive that instantiates\n * {@link form.FormController FormController}.\n *\n * If the `name` attribute is specified, the form controller is published onto the current scope under\n * this name.\n *\n * # Alias: {@link ng.directive:ngForm `ngForm`}\n *\n * In Angular, forms can be nested. This means that the outer form is valid when all of the child\n * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so\n * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to\n * `<form>` but can be nested.  This allows you to have nested forms, which is very useful when\n * using Angular validation directives in forms that are dynamically generated using the\n * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`\n * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an\n * `ngForm` directive and nest these in an outer `form` element.\n *\n *\n * # CSS classes\n *  - `ng-valid` is set if the form is valid.\n *  - `ng-invalid` is set if the form is invalid.\n *  - `ng-pristine` is set if the form is pristine.\n *  - `ng-dirty` is set if the form is dirty.\n *  - `ng-submitted` is set if the form was submitted.\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n *\n * # Submitting a form and preventing the default action\n *\n * Since the role of forms in client-side Angular applications is different than in classical\n * roundtrip apps, it is desirable for the browser not to translate the form submission into a full\n * page reload that sends the data to the server. Instead some javascript logic should be triggered\n * to handle the form submission in an application-specific way.\n *\n * For this reason, Angular prevents the default action (form submission to the server) unless the\n * `<form>` element has an `action` attribute specified.\n *\n * You can use one of the following two ways to specify what javascript method should be called when\n * a form is submitted:\n *\n * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element\n * - {@link ng.directive:ngClick ngClick} directive on the first\n  *  button or input field of type submit (input[type=submit])\n *\n * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}\n * or {@link ng.directive:ngClick ngClick} directives.\n * This is because of the following form submission rules in the HTML specification:\n *\n * - If a form has only one input field then hitting enter in this field triggers form submit\n * (`ngSubmit`)\n * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter\n * doesn't trigger submit\n * - if a form has one or more input fields and one or more buttons or input[type=submit] then\n * hitting enter in any of the input fields will trigger the click handler on the *first* button or\n * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)\n *\n * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is\n * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * ## Animation Hooks\n *\n * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.\n * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any\n * other validations that are performed within the form. Animations in ngForm are similar to how\n * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well\n * as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style a form element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-form {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-form.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n    <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"formExample\">\n      <file name=\"index.html\">\n       <script>\n         angular.module('formExample', [])\n           .controller('FormController', ['$scope', function($scope) {\n             $scope.userType = 'guest';\n           }]);\n       </script>\n       <style>\n        .my-form {\n          -webkit-transition:all linear 0.5s;\n          transition:all linear 0.5s;\n          background: transparent;\n        }\n        .my-form.ng-invalid {\n          background: red;\n        }\n       </style>\n       <form name=\"myForm\" ng-controller=\"FormController\" class=\"my-form\">\n         userType: <input name=\"input\" ng-model=\"userType\" required>\n         <span class=\"error\" ng-show=\"myForm.input.$error.required\">Required!</span><br>\n         <code>userType = {{userType}}</code><br>\n         <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>\n         <code>myForm.input.$error = {{myForm.input.$error}}</code><br>\n         <code>myForm.$valid = {{myForm.$valid}}</code><br>\n         <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should initialize to model', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n\n          expect(userType.getText()).toContain('guest');\n          expect(valid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty', function() {\n          var userType = element(by.binding('userType'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var userInput = element(by.model('userType'));\n\n          userInput.clear();\n          userInput.sendKeys('');\n\n          expect(userType.getText()).toEqual('userType =');\n          expect(valid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n *\n * @param {string=} name Name of the form. If specified, the form controller will be published into\n *                       related scope, under this name.\n */\nvar formDirectiveFactory = function(isNgForm) {\n  return ['$timeout', '$parse', function($timeout, $parse) {\n    var formDirective = {\n      name: 'form',\n      restrict: isNgForm ? 'EAC' : 'E',\n      controller: FormController,\n      compile: function ngFormCompile(formElement, attr) {\n        // Setup initial state of the control\n        formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);\n\n        var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);\n\n        return {\n          pre: function ngFormPreLink(scope, formElement, attr, controller) {\n            // if `action` attr is not present on the form, prevent the default action (submission)\n            if (!('action' in attr)) {\n              // we can't use jq events because if a form is destroyed during submission the default\n              // action is not prevented. see #1238\n              //\n              // IE 9 is not affected because it doesn't fire a submit event and try to do a full\n              // page reload if the form was destroyed by submission of the form via a click handler\n              // on a button in the form. Looks like an IE9 specific bug.\n              var handleFormSubmission = function(event) {\n                scope.$apply(function() {\n                  controller.$commitViewValue();\n                  controller.$setSubmitted();\n                });\n\n                event.preventDefault();\n              };\n\n              addEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n\n              // unregister the preventDefault listener so that we don't not leak memory but in a\n              // way that will achieve the prevention of the default action.\n              formElement.on('$destroy', function() {\n                $timeout(function() {\n                  removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);\n                }, 0, false);\n              });\n            }\n\n            var parentFormCtrl = controller.$$parentForm;\n            var setter = nameAttr ? getSetter(controller.$name) : noop;\n\n            if (nameAttr) {\n              setter(scope, controller);\n              attr.$observe(nameAttr, function(newValue) {\n                if (controller.$name === newValue) return;\n                setter(scope, undefined);\n                parentFormCtrl.$$renameControl(controller, newValue);\n                setter = getSetter(controller.$name);\n                setter(scope, controller);\n              });\n            }\n            formElement.on('$destroy', function() {\n              parentFormCtrl.$removeControl(controller);\n              setter(scope, undefined);\n              extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards\n            });\n          }\n        };\n      }\n    };\n\n    return formDirective;\n\n    function getSetter(expression) {\n      if (expression === '') {\n        //create an assignable expression, so forms with an empty name can be renamed later\n        return $parse('this[\"\"]').assign;\n      }\n      return $parse(expression).assign || noop;\n    }\n  }];\n};\n\nvar formDirective = formDirectiveFactory();\nvar ngFormDirective = formDirectiveFactory(true);\n\n/* global VALID_CLASS: false,\n  INVALID_CLASS: false,\n  PRISTINE_CLASS: false,\n  DIRTY_CLASS: false,\n  UNTOUCHED_CLASS: false,\n  TOUCHED_CLASS: false,\n  ngModelMinErr: false,\n*/\n\n// Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231\nvar ISO_DATE_REGEXP = /\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)/;\nvar URL_REGEXP = /^(ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?$/;\nvar EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;\nvar NUMBER_REGEXP = /^\\s*(\\-|\\+)?(\\d+|(\\d*(\\.\\d*)))([eE][+-]?\\d+)?\\s*$/;\nvar DATE_REGEXP = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nvar DATETIMELOCAL_REGEXP = /^(\\d{4})-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\nvar WEEK_REGEXP = /^(\\d{4})-W(\\d\\d)$/;\nvar MONTH_REGEXP = /^(\\d{4})-(\\d\\d)$/;\nvar TIME_REGEXP = /^(\\d\\d):(\\d\\d)(?::(\\d\\d)(\\.\\d{1,3})?)?$/;\n\nvar inputType = {\n\n  /**\n   * @ngdoc input\n   * @name input[text]\n   *\n   * @description\n   * Standard HTML text input with angular data binding, inherited by most of the `input` elements.\n   *\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Adds `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n   *    This parameter is ignored for input[type=password] controls, which will never trim the\n   *    input.\n   *\n   * @example\n      <example name=\"text-input-directive\" module=\"textInputExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('textInputExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 text: 'guest',\n                 word: /^\\s*\\w*\\s*$/\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>Single word:\n             <input type=\"text\" name=\"input\" ng-model=\"example.text\"\n                    ng-pattern=\"example.word\" required ng-trim=\"false\">\n           </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.pattern\">\n               Single word only!</span>\n           </div>\n           <tt>text = {{example.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('example.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('guest');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if multi word', function() {\n            input.clear();\n            input.sendKeys('hello world');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'text': textInputType,\n\n    /**\n     * @ngdoc input\n     * @name input[date]\n     *\n     * @description\n     * Input with date validation and transformation. In browsers that do not yet support\n     * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601\n     * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many\n     * modern browsers do not yet support this input type, it is important to provide cues to users on the\n     * expected input format via a placeholder or label.\n     *\n     * The model must always be a Date object, otherwise Angular will throw an error.\n     * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n     *\n     * The timezone to be used to read/write the `Date` instance in the model can be defined using\n     * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n     *\n     * @param {string} ngModel Assignable angular expression to data-bind to.\n     * @param {string=} name Property name of the form under which the control is published.\n     * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n     * valid ISO date string (yyyy-MM-dd).\n     * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n     * a valid ISO date string (yyyy-MM-dd).\n     * @param {string=} required Sets `required` validation error key if the value is not entered.\n     * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n     *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n     *    `required` when you want to data-bind to the `required` attribute.\n     * @param {string=} ngChange Angular expression to be executed when input changes due to user\n     *    interaction with the input element.\n     *\n     * @example\n     <example name=\"date-input-directive\" module=\"dateInputExample\">\n     <file name=\"index.html\">\n       <script>\n          angular.module('dateInputExample', [])\n            .controller('DateController', ['$scope', function($scope) {\n              $scope.example = {\n                value: new Date(2013, 9, 22)\n              };\n            }]);\n       </script>\n       <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n          <label for=\"exampleInput\">Pick a date in 2013:</label>\n          <input type=\"date\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n              placeholder=\"yyyy-MM-dd\" min=\"2013-01-01\" max=\"2013-12-31\" required />\n          <div role=\"alert\">\n            <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n                Required!</span>\n            <span class=\"error\" ng-show=\"myForm.input.$error.date\">\n                Not a valid date!</span>\n           </div>\n           <tt>value = {{example.value | date: \"yyyy-MM-dd\"}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n       </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        var value = element(by.binding('example.value | date: \"yyyy-MM-dd\"'));\n        var valid = element(by.binding('myForm.input.$valid'));\n        var input = element(by.model('example.value'));\n\n        // currently protractor/webdriver does not support\n        // sending keys to all known HTML5 input controls\n        // for various browsers (see https://github.com/angular/protractor/issues/562).\n        function setInput(val) {\n          // set the value of the element and force validation.\n          var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n          \"ipt.value = '\" + val + \"';\" +\n          \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n          browser.executeScript(scr);\n        }\n\n        it('should initialize to model', function() {\n          expect(value.getText()).toContain('2013-10-22');\n          expect(valid.getText()).toContain('myForm.input.$valid = true');\n        });\n\n        it('should be invalid if empty', function() {\n          setInput('');\n          expect(value.getText()).toEqual('value =');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n\n        it('should be invalid if over max', function() {\n          setInput('2015-01-01');\n          expect(value.getText()).toContain('');\n          expect(valid.getText()).toContain('myForm.input.$valid = false');\n        });\n     </file>\n     </example>\n     */\n  'date': createDateInputType('date', DATE_REGEXP,\n         createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),\n         'yyyy-MM-dd'),\n\n   /**\n    * @ngdoc input\n    * @name input[datetime-local]\n    *\n    * @description\n    * Input with datetime validation and transformation. In browsers that do not yet support\n    * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"datetimelocal-input-directive\" module=\"dateExample\">\n    <file name=\"index.html\">\n      <script>\n        angular.module('dateExample', [])\n          .controller('DateController', ['$scope', function($scope) {\n            $scope.example = {\n              value: new Date(2010, 11, 28, 14, 57)\n            };\n          }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        <label for=\"exampleInput\">Pick a date between in 2013:</label>\n        <input type=\"datetime-local\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"yyyy-MM-ddTHH:mm:ss\" min=\"2001-01-01T00:00:00\" max=\"2013-12-31T00:00:00\" required />\n        <div role=\"alert\">\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.datetimelocal\">\n              Not a valid date!</span>\n        </div>\n        <tt>value = {{example.value | date: \"yyyy-MM-ddTHH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM-ddTHH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2010-12-28T14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01-01T23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,\n      createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),\n      'yyyy-MM-ddTHH:mm:ss.sss'),\n\n  /**\n   * @ngdoc input\n   * @name input[time]\n   *\n   * @description\n   * Input with time validation and transformation. In browsers that do not yet support\n   * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a\n   * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a\n   * valid ISO time format (HH:mm:ss).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"time-input-directive\" module=\"timeExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('timeExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(1970, 0, 1, 14, 57, 0)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        <label for=\"exampleInput\">Pick a between 8am and 5pm:</label>\n        <input type=\"time\" id=\"exampleInput\" name=\"input\" ng-model=\"example.value\"\n            placeholder=\"HH:mm:ss\" min=\"08:00:00\" max=\"17:00:00\" required />\n        <div role=\"alert\">\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.time\">\n              Not a valid date!</span>\n        </div>\n        <tt>value = {{example.value | date: \"HH:mm:ss\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"HH:mm:ss\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('14:57:00');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('23:59:00');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'time': createDateInputType('time', TIME_REGEXP,\n      createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),\n     'HH:mm:ss.sss'),\n\n   /**\n    * @ngdoc input\n    * @name input[week]\n    *\n    * @description\n    * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support\n    * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n    * week format (yyyy-W##), for example: `2013-W02`.\n    *\n    * The model must always be a Date object, otherwise Angular will throw an error.\n    * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n    *\n    * The timezone to be used to read/write the `Date` instance in the model can be defined using\n    * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n    *\n    * @param {string} ngModel Assignable angular expression to data-bind to.\n    * @param {string=} name Property name of the form under which the control is published.\n    * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a\n    * valid ISO week format (yyyy-W##).\n    * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be\n    * a valid ISO week format (yyyy-W##).\n    * @param {string=} required Sets `required` validation error key if the value is not entered.\n    * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n    *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n    *    `required` when you want to data-bind to the `required` attribute.\n    * @param {string=} ngChange Angular expression to be executed when input changes due to user\n    *    interaction with the input element.\n    *\n    * @example\n    <example name=\"week-input-directive\" module=\"weekExample\">\n    <file name=\"index.html\">\n      <script>\n      angular.module('weekExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 0, 3)\n          };\n        }]);\n      </script>\n      <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n        <label>Pick a date between in 2013:\n          <input id=\"exampleInput\" type=\"week\" name=\"input\" ng-model=\"example.value\"\n                 placeholder=\"YYYY-W##\" min=\"2012-W32\"\n                 max=\"2013-W52\" required />\n        </label>\n        <div role=\"alert\">\n          <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n              Required!</span>\n          <span class=\"error\" ng-show=\"myForm.input.$error.week\">\n              Not a valid date!</span>\n        </div>\n        <tt>value = {{example.value | date: \"yyyy-Www\"}}</tt><br/>\n        <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n        <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n        <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n        <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-Www\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-W01');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-W01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n    </file>\n    </example>\n    */\n  'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),\n\n  /**\n   * @ngdoc input\n   * @name input[month]\n   *\n   * @description\n   * Input with month validation and transformation. In browsers that do not yet support\n   * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601\n   * month format (yyyy-MM), for example: `2009-01`.\n   *\n   * The model must always be a Date object, otherwise Angular will throw an error.\n   * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.\n   * If the model is not set to the first of the month, the next view to model update will set it\n   * to the first of the month.\n   *\n   * The timezone to be used to read/write the `Date` instance in the model can be defined using\n   * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be\n   * a valid ISO month format (yyyy-MM).\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must\n   * be a valid ISO month format (yyyy-MM).\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n   <example name=\"month-input-directive\" module=\"monthExample\">\n   <file name=\"index.html\">\n     <script>\n      angular.module('monthExample', [])\n        .controller('DateController', ['$scope', function($scope) {\n          $scope.example = {\n            value: new Date(2013, 9, 1)\n          };\n        }]);\n     </script>\n     <form name=\"myForm\" ng-controller=\"DateController as dateCtrl\">\n       <label for=\"exampleInput\">Pick a month in 2013:</label>\n       <input id=\"exampleInput\" type=\"month\" name=\"input\" ng-model=\"example.value\"\n          placeholder=\"yyyy-MM\" min=\"2013-01\" max=\"2013-12\" required />\n       <div role=\"alert\">\n         <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n            Required!</span>\n         <span class=\"error\" ng-show=\"myForm.input.$error.month\">\n            Not a valid month!</span>\n       </div>\n       <tt>value = {{example.value | date: \"yyyy-MM\"}}</tt><br/>\n       <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n       <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n       <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n       <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n     </form>\n   </file>\n   <file name=\"protractor.js\" type=\"protractor\">\n      var value = element(by.binding('example.value | date: \"yyyy-MM\"'));\n      var valid = element(by.binding('myForm.input.$valid'));\n      var input = element(by.model('example.value'));\n\n      // currently protractor/webdriver does not support\n      // sending keys to all known HTML5 input controls\n      // for various browsers (https://github.com/angular/protractor/issues/562).\n      function setInput(val) {\n        // set the value of the element and force validation.\n        var scr = \"var ipt = document.getElementById('exampleInput'); \" +\n        \"ipt.value = '\" + val + \"';\" +\n        \"angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('\" + val + \"'); });\";\n        browser.executeScript(scr);\n      }\n\n      it('should initialize to model', function() {\n        expect(value.getText()).toContain('2013-10');\n        expect(valid.getText()).toContain('myForm.input.$valid = true');\n      });\n\n      it('should be invalid if empty', function() {\n        setInput('');\n        expect(value.getText()).toEqual('value =');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n\n      it('should be invalid if over max', function() {\n        setInput('2015-01');\n        expect(value.getText()).toContain('');\n        expect(valid.getText()).toContain('myForm.input.$valid = false');\n      });\n   </file>\n   </example>\n   */\n  'month': createDateInputType('month', MONTH_REGEXP,\n     createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),\n     'yyyy-MM'),\n\n  /**\n   * @ngdoc input\n   * @name input[number]\n   *\n   * @description\n   * Text input with number validation and transformation. Sets the `number` validation\n   * error if not a valid number.\n   *\n   * <div class=\"alert alert-warning\">\n   * The model must always be of type `number` otherwise Angular will throw an error.\n   * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}\n   * error docs for more information and an example of how to convert your model if necessary.\n   * </div>\n   *\n   * ## Issues with HTML5 constraint validation\n   *\n   * In browsers that follow the\n   * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),\n   * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.\n   * If a non-number is entered in the input, the browser will report the value as an empty string,\n   * which means the view / model values in `ngModel` and subsequently the scope value\n   * will also be an empty string.\n   *\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.\n   * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"number-input-directive\" module=\"numberExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('numberExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.example = {\n                 value: 12\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>Number:\n             <input type=\"number\" name=\"input\" ng-model=\"example.value\"\n                    min=\"0\" max=\"99\" required>\n          </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.number\">\n               Not valid number!</span>\n           </div>\n           <tt>value = {{example.value}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var value = element(by.binding('example.value'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('example.value'));\n\n          it('should initialize to model', function() {\n            expect(value.getText()).toContain('12');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if over max', function() {\n            input.clear();\n            input.sendKeys('123');\n            expect(value.getText()).toEqual('value =');\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'number': numberInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[url]\n   *\n   * @description\n   * Text input with URL validation. Sets the `url` validation error key if the content is not a\n   * valid URL.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex\n   * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify\n   * the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"url-input-directive\" module=\"urlExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('urlExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.url = {\n                 text: 'http://google.com'\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>URL:\n             <input type=\"url\" name=\"input\" ng-model=\"url.text\" required>\n           <label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n               Required!</span>\n             <span class=\"error\" ng-show=\"myForm.input.$error.url\">\n               Not valid url!</span>\n           </div>\n           <tt>text = {{url.text}}</tt><br/>\n           <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n           <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n           <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n           <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n           <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('url.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('url.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('http://google.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not url', function() {\n            input.clear();\n            input.sendKeys('box');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'url': urlInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[email]\n   *\n   * @description\n   * Text input with email validation. Sets the `email` validation error key if not a valid email\n   * address.\n   *\n   * <div class=\"alert alert-warning\">\n   * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex\n   * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can\n   * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})\n   * </div>\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} required Sets `required` validation error key if the value is not entered.\n   * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n   *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n   *    `required` when you want to data-bind to the `required` attribute.\n   * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n   *    minlength.\n   * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n   *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of\n   *    any length.\n   * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string\n   *    that contains the regular expression body that will be converted to a regular expression\n   *    as in the ngPattern directive.\n   * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n   *    a RegExp found by evaluating the Angular expression given in the attribute value.\n   *    If the expression evaluates to a RegExp object, then this is used directly.\n   *    If the expression evaluates to a string, then it will be converted to a RegExp\n   *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n   *    `new RegExp('^abc$')`.<br />\n   *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n   *    start at the index of the last search's match, thus not taking the whole input value into\n   *    account.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"email-input-directive\" module=\"emailExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('emailExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.email = {\n                 text: 'me@example.com'\n               };\n             }]);\n         </script>\n           <form name=\"myForm\" ng-controller=\"ExampleController\">\n             <label>Email:\n               <input type=\"email\" name=\"input\" ng-model=\"email.text\" required>\n             </label>\n             <div role=\"alert\">\n               <span class=\"error\" ng-show=\"myForm.input.$error.required\">\n                 Required!</span>\n               <span class=\"error\" ng-show=\"myForm.input.$error.email\">\n                 Not valid email!</span>\n             </div>\n             <tt>text = {{email.text}}</tt><br/>\n             <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>\n             <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>\n             <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n             <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n             <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>\n           </form>\n         </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var text = element(by.binding('email.text'));\n          var valid = element(by.binding('myForm.input.$valid'));\n          var input = element(by.model('email.text'));\n\n          it('should initialize to model', function() {\n            expect(text.getText()).toContain('me@example.com');\n            expect(valid.getText()).toContain('true');\n          });\n\n          it('should be invalid if empty', function() {\n            input.clear();\n            input.sendKeys('');\n            expect(text.getText()).toEqual('text =');\n            expect(valid.getText()).toContain('false');\n          });\n\n          it('should be invalid if not email', function() {\n            input.clear();\n            input.sendKeys('xxx');\n\n            expect(valid.getText()).toContain('false');\n          });\n        </file>\n      </example>\n   */\n  'email': emailInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[radio]\n   *\n   * @description\n   * HTML radio button.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string} value The value to which the `ngModel` expression should be set when selected.\n   *    Note that `value` only supports `string` values, i.e. the scope model needs to be a string,\n   *    too. Use `ngValue` if you need complex models (`number`, `object`, ...).\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio\n   *    is selected. Should be used instead of the `value` attribute if you need\n   *    a non-string `ngModel` (`boolean`, `array`, ...).\n   *\n   * @example\n      <example name=\"radio-input-directive\" module=\"radioExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('radioExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.color = {\n                 name: 'blue'\n               };\n               $scope.specialValue = {\n                 \"id\": \"12345\",\n                 \"value\": \"green\"\n               };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>\n             <input type=\"radio\" ng-model=\"color.name\" value=\"red\">\n             Red\n           </label><br/>\n           <label>\n             <input type=\"radio\" ng-model=\"color.name\" ng-value=\"specialValue\">\n             Green\n           </label><br/>\n           <label>\n             <input type=\"radio\" ng-model=\"color.name\" value=\"blue\">\n             Blue\n           </label><br/>\n           <tt>color = {{color.name | json}}</tt><br/>\n          </form>\n          Note that `ng-value=\"specialValue\"` sets radio item's value to be the value of `$scope.specialValue`.\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var color = element(by.binding('color.name'));\n\n            expect(color.getText()).toContain('blue');\n\n            element.all(by.model('color.name')).get(0).click();\n\n            expect(color.getText()).toContain('red');\n          });\n        </file>\n      </example>\n   */\n  'radio': radioInputType,\n\n\n  /**\n   * @ngdoc input\n   * @name input[checkbox]\n   *\n   * @description\n   * HTML checkbox.\n   *\n   * @param {string} ngModel Assignable angular expression to data-bind to.\n   * @param {string=} name Property name of the form under which the control is published.\n   * @param {expression=} ngTrueValue The value to which the expression should be set when selected.\n   * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.\n   * @param {string=} ngChange Angular expression to be executed when input changes due to user\n   *    interaction with the input element.\n   *\n   * @example\n      <example name=\"checkbox-input-directive\" module=\"checkboxExample\">\n        <file name=\"index.html\">\n         <script>\n           angular.module('checkboxExample', [])\n             .controller('ExampleController', ['$scope', function($scope) {\n               $scope.checkboxModel = {\n                value1 : true,\n                value2 : 'YES'\n              };\n             }]);\n         </script>\n         <form name=\"myForm\" ng-controller=\"ExampleController\">\n           <label>Value1:\n             <input type=\"checkbox\" ng-model=\"checkboxModel.value1\">\n           </label><br/>\n           <label>Value2:\n             <input type=\"checkbox\" ng-model=\"checkboxModel.value2\"\n                    ng-true-value=\"'YES'\" ng-false-value=\"'NO'\">\n            </label><br/>\n           <tt>value1 = {{checkboxModel.value1}}</tt><br/>\n           <tt>value2 = {{checkboxModel.value2}}</tt><br/>\n          </form>\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          it('should change state', function() {\n            var value1 = element(by.binding('checkboxModel.value1'));\n            var value2 = element(by.binding('checkboxModel.value2'));\n\n            expect(value1.getText()).toContain('true');\n            expect(value2.getText()).toContain('YES');\n\n            element(by.model('checkboxModel.value1')).click();\n            element(by.model('checkboxModel.value2')).click();\n\n            expect(value1.getText()).toContain('false');\n            expect(value2.getText()).toContain('NO');\n          });\n        </file>\n      </example>\n   */\n  'checkbox': checkboxInputType,\n\n  'hidden': noop,\n  'button': noop,\n  'submit': noop,\n  'reset': noop,\n  'file': noop\n};\n\nfunction stringBasedInputType(ctrl) {\n  ctrl.$formatters.push(function(value) {\n    return ctrl.$isEmpty(value) ? value : value.toString();\n  });\n}\n\nfunction textInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n}\n\nfunction baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  var type = lowercase(element[0].type);\n\n  // In composition mode, users are still inputing intermediate text buffer,\n  // hold the listener until composition is done.\n  // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent\n  if (!$sniffer.android) {\n    var composing = false;\n\n    element.on('compositionstart', function(data) {\n      composing = true;\n    });\n\n    element.on('compositionend', function() {\n      composing = false;\n      listener();\n    });\n  }\n\n  var listener = function(ev) {\n    if (timeout) {\n      $browser.defer.cancel(timeout);\n      timeout = null;\n    }\n    if (composing) return;\n    var value = element.val(),\n        event = ev && ev.type;\n\n    // By default we will trim the value\n    // If the attribute ng-trim exists we will avoid trimming\n    // If input type is 'password', the value is never trimmed\n    if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {\n      value = trim(value);\n    }\n\n    // If a control is suffering from bad input (due to native validators), browsers discard its\n    // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the\n    // control's value is the same empty value twice in a row.\n    if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {\n      ctrl.$setViewValue(value, event);\n    }\n  };\n\n  // if the browser does support \"input\" event, we are fine - except on IE9 which doesn't fire the\n  // input event on backspace, delete or cut\n  if ($sniffer.hasEvent('input')) {\n    element.on('input', listener);\n  } else {\n    var timeout;\n\n    var deferListener = function(ev, input, origValue) {\n      if (!timeout) {\n        timeout = $browser.defer(function() {\n          timeout = null;\n          if (!input || input.value !== origValue) {\n            listener(ev);\n          }\n        });\n      }\n    };\n\n    element.on('keydown', function(event) {\n      var key = event.keyCode;\n\n      // ignore\n      //    command            modifiers                   arrows\n      if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;\n\n      deferListener(event, this, this.value);\n    });\n\n    // if user modifies input value using context menu in IE, we need \"paste\" and \"cut\" events to catch it\n    if ($sniffer.hasEvent('paste')) {\n      element.on('paste cut', deferListener);\n    }\n  }\n\n  // if user paste into input using mouse on older browser\n  // or form autocomplete on newer browser, we need \"change\" event to catch it\n  element.on('change', listener);\n\n  ctrl.$render = function() {\n    // Workaround for Firefox validation #12102.\n    var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;\n    if (element.val() !== value) {\n      element.val(value);\n    }\n  };\n}\n\nfunction weekParser(isoWeek, existingDate) {\n  if (isDate(isoWeek)) {\n    return isoWeek;\n  }\n\n  if (isString(isoWeek)) {\n    WEEK_REGEXP.lastIndex = 0;\n    var parts = WEEK_REGEXP.exec(isoWeek);\n    if (parts) {\n      var year = +parts[1],\n          week = +parts[2],\n          hours = 0,\n          minutes = 0,\n          seconds = 0,\n          milliseconds = 0,\n          firstThurs = getFirstThursdayOfYear(year),\n          addDays = (week - 1) * 7;\n\n      if (existingDate) {\n        hours = existingDate.getHours();\n        minutes = existingDate.getMinutes();\n        seconds = existingDate.getSeconds();\n        milliseconds = existingDate.getMilliseconds();\n      }\n\n      return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);\n    }\n  }\n\n  return NaN;\n}\n\nfunction createDateParser(regexp, mapping) {\n  return function(iso, date) {\n    var parts, map;\n\n    if (isDate(iso)) {\n      return iso;\n    }\n\n    if (isString(iso)) {\n      // When a date is JSON'ified to wraps itself inside of an extra\n      // set of double quotes. This makes the date parsing code unable\n      // to match the date string and parse it as a date.\n      if (iso.charAt(0) == '\"' && iso.charAt(iso.length - 1) == '\"') {\n        iso = iso.substring(1, iso.length - 1);\n      }\n      if (ISO_DATE_REGEXP.test(iso)) {\n        return new Date(iso);\n      }\n      regexp.lastIndex = 0;\n      parts = regexp.exec(iso);\n\n      if (parts) {\n        parts.shift();\n        if (date) {\n          map = {\n            yyyy: date.getFullYear(),\n            MM: date.getMonth() + 1,\n            dd: date.getDate(),\n            HH: date.getHours(),\n            mm: date.getMinutes(),\n            ss: date.getSeconds(),\n            sss: date.getMilliseconds() / 1000\n          };\n        } else {\n          map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };\n        }\n\n        forEach(parts, function(part, index) {\n          if (index < mapping.length) {\n            map[mapping[index]] = +part;\n          }\n        });\n        return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);\n      }\n    }\n\n    return NaN;\n  };\n}\n\nfunction createDateInputType(type, regexp, parseDate, format) {\n  return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {\n    badInputChecker(scope, element, attr, ctrl);\n    baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n    var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;\n    var previousDate;\n\n    ctrl.$$parserName = type;\n    ctrl.$parsers.push(function(value) {\n      if (ctrl.$isEmpty(value)) return null;\n      if (regexp.test(value)) {\n        // Note: We cannot read ctrl.$modelValue, as there might be a different\n        // parser/formatter in the processing chain so that the model\n        // contains some different data format!\n        var parsedDate = parseDate(value, previousDate);\n        if (timezone) {\n          parsedDate = convertTimezoneToLocal(parsedDate, timezone);\n        }\n        return parsedDate;\n      }\n      return undefined;\n    });\n\n    ctrl.$formatters.push(function(value) {\n      if (value && !isDate(value)) {\n        throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);\n      }\n      if (isValidDate(value)) {\n        previousDate = value;\n        if (previousDate && timezone) {\n          previousDate = convertTimezoneToLocal(previousDate, timezone, true);\n        }\n        return $filter('date')(value, format, timezone);\n      } else {\n        previousDate = null;\n        return '';\n      }\n    });\n\n    if (isDefined(attr.min) || attr.ngMin) {\n      var minVal;\n      ctrl.$validators.min = function(value) {\n        return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;\n      };\n      attr.$observe('min', function(val) {\n        minVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    if (isDefined(attr.max) || attr.ngMax) {\n      var maxVal;\n      ctrl.$validators.max = function(value) {\n        return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;\n      };\n      attr.$observe('max', function(val) {\n        maxVal = parseObservedDateValue(val);\n        ctrl.$validate();\n      });\n    }\n\n    function isValidDate(value) {\n      // Invalid Date: getTime() returns NaN\n      return value && !(value.getTime && value.getTime() !== value.getTime());\n    }\n\n    function parseObservedDateValue(val) {\n      return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;\n    }\n  };\n}\n\nfunction badInputChecker(scope, element, attr, ctrl) {\n  var node = element[0];\n  var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);\n  if (nativeValidation) {\n    ctrl.$parsers.push(function(value) {\n      var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};\n      // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):\n      // - also sets validity.badInput (should only be validity.typeMismatch).\n      // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)\n      // - can ignore this case as we can still read out the erroneous email...\n      return validity.badInput && !validity.typeMismatch ? undefined : value;\n    });\n  }\n}\n\nfunction numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  badInputChecker(scope, element, attr, ctrl);\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n\n  ctrl.$$parserName = 'number';\n  ctrl.$parsers.push(function(value) {\n    if (ctrl.$isEmpty(value))      return null;\n    if (NUMBER_REGEXP.test(value)) return parseFloat(value);\n    return undefined;\n  });\n\n  ctrl.$formatters.push(function(value) {\n    if (!ctrl.$isEmpty(value)) {\n      if (!isNumber(value)) {\n        throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);\n      }\n      value = value.toString();\n    }\n    return value;\n  });\n\n  if (isDefined(attr.min) || attr.ngMin) {\n    var minVal;\n    ctrl.$validators.min = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;\n    };\n\n    attr.$observe('min', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      minVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n\n  if (isDefined(attr.max) || attr.ngMax) {\n    var maxVal;\n    ctrl.$validators.max = function(value) {\n      return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;\n    };\n\n    attr.$observe('max', function(val) {\n      if (isDefined(val) && !isNumber(val)) {\n        val = parseFloat(val, 10);\n      }\n      maxVal = isNumber(val) && !isNaN(val) ? val : undefined;\n      // TODO(matsko): implement validateLater to reduce number of validations\n      ctrl.$validate();\n    });\n  }\n}\n\nfunction urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'url';\n  ctrl.$validators.url = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || URL_REGEXP.test(value);\n  };\n}\n\nfunction emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {\n  // Note: no badInputChecker here by purpose as `url` is only a validation\n  // in browsers, i.e. we can always read out input.value even if it is not valid!\n  baseInputType(scope, element, attr, ctrl, $sniffer, $browser);\n  stringBasedInputType(ctrl);\n\n  ctrl.$$parserName = 'email';\n  ctrl.$validators.email = function(modelValue, viewValue) {\n    var value = modelValue || viewValue;\n    return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);\n  };\n}\n\nfunction radioInputType(scope, element, attr, ctrl) {\n  // make the name unique, if not defined\n  if (isUndefined(attr.name)) {\n    element.attr('name', nextUid());\n  }\n\n  var listener = function(ev) {\n    if (element[0].checked) {\n      ctrl.$setViewValue(attr.value, ev && ev.type);\n    }\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    var value = attr.value;\n    element[0].checked = (value == ctrl.$viewValue);\n  };\n\n  attr.$observe('value', ctrl.$render);\n}\n\nfunction parseConstantExpr($parse, context, name, expression, fallback) {\n  var parseFn;\n  if (isDefined(expression)) {\n    parseFn = $parse(expression);\n    if (!parseFn.constant) {\n      throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +\n                                   '`{1}`.', name, expression);\n    }\n    return parseFn(context);\n  }\n  return fallback;\n}\n\nfunction checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {\n  var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);\n  var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);\n\n  var listener = function(ev) {\n    ctrl.$setViewValue(element[0].checked, ev && ev.type);\n  };\n\n  element.on('click', listener);\n\n  ctrl.$render = function() {\n    element[0].checked = ctrl.$viewValue;\n  };\n\n  // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`\n  // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert\n  // it to a boolean.\n  ctrl.$isEmpty = function(value) {\n    return value === false;\n  };\n\n  ctrl.$formatters.push(function(value) {\n    return equals(value, trueValue);\n  });\n\n  ctrl.$parsers.push(function(value) {\n    return value ? trueValue : falseValue;\n  });\n}\n\n\n/**\n * @ngdoc directive\n * @name textarea\n * @restrict E\n *\n * @description\n * HTML textarea element control with angular data-binding. The data-binding and validation\n * properties of this element are exactly the same as those of the\n * {@link ng.directive:input input element}.\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n *    a RegExp found by evaluating the Angular expression given in the attribute value.\n *    If the expression evaluates to a RegExp object, then this is used directly.\n *    If the expression evaluates to a string, then it will be converted to a RegExp\n *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n *    `new RegExp('^abc$')`.<br />\n *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n *    start at the index of the last search's match, thus not taking the whole input value into\n *    account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n */\n\n\n/**\n * @ngdoc directive\n * @name input\n * @restrict E\n *\n * @description\n * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,\n * input state control, and validation.\n * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.\n *\n * <div class=\"alert alert-warning\">\n * **Note:** Not every feature offered is available for all input types.\n * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.\n * </div>\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required Sets `required` validation error key if the value is not entered.\n * @param {boolean=} ngRequired Sets `required` attribute if set to true\n * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than\n *    minlength.\n * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than\n *    maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any\n *    length.\n * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match\n *    a RegExp found by evaluating the Angular expression given in the attribute value.\n *    If the expression evaluates to a RegExp object, then this is used directly.\n *    If the expression evaluates to a string, then it will be converted to a RegExp\n *    after wrapping it in `^` and `$` characters. For instance, `\"abc\"` will be converted to\n *    `new RegExp('^abc$')`.<br />\n *    **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to\n *    start at the index of the last search's match, thus not taking the whole input value into\n *    account.\n * @param {string=} ngChange Angular expression to be executed when input changes due to user\n *    interaction with the input element.\n * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.\n *    This parameter is ignored for input[type=password] controls, which will never trim the\n *    input.\n *\n * @example\n    <example name=\"input-directive\" module=\"inputExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('inputExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.user = {name: 'guest', last: 'visitor'};\n            }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <form name=\"myForm\">\n           <label>\n              User name:\n              <input type=\"text\" name=\"userName\" ng-model=\"user.name\" required>\n           </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.userName.$error.required\">\n              Required!</span>\n           </div>\n           <label>\n              Last name:\n              <input type=\"text\" name=\"lastName\" ng-model=\"user.last\"\n              ng-minlength=\"3\" ng-maxlength=\"10\">\n           </label>\n           <div role=\"alert\">\n             <span class=\"error\" ng-show=\"myForm.lastName.$error.minlength\">\n               Too short!</span>\n             <span class=\"error\" ng-show=\"myForm.lastName.$error.maxlength\">\n               Too long!</span>\n           </div>\n         </form>\n         <hr>\n         <tt>user = {{user}}</tt><br/>\n         <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>\n         <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>\n         <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>\n         <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>\n         <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n         <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n         <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>\n         <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>\n       </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var user = element(by.exactBinding('user'));\n        var userNameValid = element(by.binding('myForm.userName.$valid'));\n        var lastNameValid = element(by.binding('myForm.lastName.$valid'));\n        var lastNameError = element(by.binding('myForm.lastName.$error'));\n        var formValid = element(by.binding('myForm.$valid'));\n        var userNameInput = element(by.model('user.name'));\n        var userLastInput = element(by.model('user.last'));\n\n        it('should initialize to model', function() {\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if empty when required', function() {\n          userNameInput.clear();\n          userNameInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"last\":\"visitor\"}');\n          expect(userNameValid.getText()).toContain('false');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be valid if empty when min length is set', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\",\"last\":\"\"}');\n          expect(lastNameValid.getText()).toContain('true');\n          expect(formValid.getText()).toContain('true');\n        });\n\n        it('should be invalid if less than required min length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('xx');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('minlength');\n          expect(formValid.getText()).toContain('false');\n        });\n\n        it('should be invalid if longer than max length', function() {\n          userLastInput.clear();\n          userLastInput.sendKeys('some ridiculously long name');\n\n          expect(user.getText()).toContain('{\"name\":\"guest\"}');\n          expect(lastNameValid.getText()).toContain('false');\n          expect(lastNameError.getText()).toContain('maxlength');\n          expect(formValid.getText()).toContain('false');\n        });\n      </file>\n    </example>\n */\nvar inputDirective = ['$browser', '$sniffer', '$filter', '$parse',\n    function($browser, $sniffer, $filter, $parse) {\n  return {\n    restrict: 'E',\n    require: ['?ngModel'],\n    link: {\n      pre: function(scope, element, attr, ctrls) {\n        if (ctrls[0]) {\n          (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,\n                                                              $browser, $filter, $parse);\n        }\n      }\n    }\n  };\n}];\n\n\n\nvar CONSTANT_VALUE_REGEXP = /^(true|false|\\d+)$/;\n/**\n * @ngdoc directive\n * @name ngValue\n *\n * @description\n * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},\n * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to\n * the bound value.\n *\n * `ngValue` is useful when dynamically generating lists of radio buttons using\n * {@link ngRepeat `ngRepeat`}, as shown below.\n *\n * Likewise, `ngValue` can be used to generate `<option>` elements for\n * the {@link select `select`} element. In that case however, only strings are supported\n * for the `value `attribute, so the resulting `ngModel` will always be a string.\n * Support for `select` models with non-string values is available via `ngOptions`.\n *\n * @element input\n * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute\n *   of the `input` element\n *\n * @example\n    <example name=\"ngValue-directive\" module=\"valueExample\">\n      <file name=\"index.html\">\n       <script>\n          angular.module('valueExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.names = ['pizza', 'unicorns', 'robots'];\n              $scope.my = { favorite: 'unicorns' };\n            }]);\n       </script>\n        <form ng-controller=\"ExampleController\">\n          <h2>Which is your favorite?</h2>\n            <label ng-repeat=\"name in names\" for=\"{{name}}\">\n              {{name}}\n              <input type=\"radio\"\n                     ng-model=\"my.favorite\"\n                     ng-value=\"name\"\n                     id=\"{{name}}\"\n                     name=\"favorite\">\n            </label>\n          <div>You chose {{my.favorite}}</div>\n        </form>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        var favorite = element(by.binding('my.favorite'));\n\n        it('should initialize to model', function() {\n          expect(favorite.getText()).toContain('unicorns');\n        });\n        it('should bind the values to the inputs', function() {\n          element.all(by.model('my.favorite')).get(0).click();\n          expect(favorite.getText()).toContain('pizza');\n        });\n      </file>\n    </example>\n */\nvar ngValueDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    compile: function(tpl, tplAttr) {\n      if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {\n        return function ngValueConstantLink(scope, elm, attr) {\n          attr.$set('value', scope.$eval(attr.ngValue));\n        };\n      } else {\n        return function ngValueLink(scope, elm, attr) {\n          scope.$watch(attr.ngValue, function valueWatchAction(value) {\n            attr.$set('value', value);\n          });\n        };\n      }\n    }\n  };\n};\n\n/**\n * @ngdoc directive\n * @name ngBind\n * @restrict AC\n *\n * @description\n * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element\n * with the value of a given expression, and to update the text content when the value of that\n * expression changes.\n *\n * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like\n * `{{ expression }}` which is similar but less verbose.\n *\n * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily\n * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an\n * element attribute, it makes the bindings invisible to the user while the page is loading.\n *\n * An alternative solution to this problem would be using the\n * {@link ng.directive:ngCloak ngCloak} directive.\n *\n *\n * @element ANY\n * @param {expression} ngBind {@link guide/expression Expression} to evaluate.\n *\n * @example\n * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.name = 'Whirled';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <label>Enter name: <input type=\"text\" ng-model=\"name\"></label><br>\n         Hello <span ng-bind=\"name\"></span>!\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var nameInput = element(by.model('name'));\n\n         expect(element(by.binding('name')).getText()).toBe('Whirled');\n         nameInput.clear();\n         nameInput.sendKeys('world');\n         expect(element(by.binding('name')).getText()).toBe('world');\n       });\n     </file>\n   </example>\n */\nvar ngBindDirective = ['$compile', function($compile) {\n  return {\n    restrict: 'AC',\n    compile: function ngBindCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBind);\n        element = element[0];\n        scope.$watch(attr.ngBind, function ngBindWatchAction(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindTemplate\n *\n * @description\n * The `ngBindTemplate` directive specifies that the element\n * text content should be replaced with the interpolation of the template\n * in the `ngBindTemplate` attribute.\n * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`\n * expressions. This directive is needed since some HTML elements\n * (such as TITLE and OPTION) cannot contain SPAN elements.\n *\n * @element ANY\n * @param {string} ngBindTemplate template of form\n *   <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.\n *\n * @example\n * Try it here: enter text in text box and watch the greeting change.\n   <example module=\"bindExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('bindExample', [])\n           .controller('ExampleController', ['$scope', function($scope) {\n             $scope.salutation = 'Hello';\n             $scope.name = 'World';\n           }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n        <label>Salutation: <input type=\"text\" ng-model=\"salutation\"></label><br>\n        <label>Name: <input type=\"text\" ng-model=\"name\"></label><br>\n        <pre ng-bind-template=\"{{salutation}} {{name}}!\"></pre>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind', function() {\n         var salutationElem = element(by.binding('salutation'));\n         var salutationInput = element(by.model('salutation'));\n         var nameInput = element(by.model('name'));\n\n         expect(salutationElem.getText()).toBe('Hello World!');\n\n         salutationInput.clear();\n         salutationInput.sendKeys('Greetings');\n         nameInput.clear();\n         nameInput.sendKeys('user');\n\n         expect(salutationElem.getText()).toBe('Greetings user!');\n       });\n     </file>\n   </example>\n */\nvar ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {\n  return {\n    compile: function ngBindTemplateCompile(templateElement) {\n      $compile.$$addBindingClass(templateElement);\n      return function ngBindTemplateLink(scope, element, attr) {\n        var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));\n        $compile.$$addBindingInfo(element, interpolateFn.expressions);\n        element = element[0];\n        attr.$observe('ngBindTemplate', function(value) {\n          element.textContent = value === undefined ? '' : value;\n        });\n      };\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngBindHtml\n *\n * @description\n * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,\n * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.\n * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link\n * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}\n * in your module's dependencies, you need to include \"angular-sanitize.js\" in your application.\n *\n * You may also bypass sanitization for values you know are safe. To do so, bind to\n * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}.  See the example\n * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.\n *\n * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you\n * will have an exception (instead of an exploit.)\n *\n * @element ANY\n * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.\n *\n * @example\n\n   <example module=\"bindHtmlExample\" deps=\"angular-sanitize.js\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n        <p ng-bind-html=\"myHTML\"></p>\n       </div>\n     </file>\n\n     <file name=\"script.js\">\n       angular.module('bindHtmlExample', ['ngSanitize'])\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.myHTML =\n              'I am an <code>HTML</code>string with ' +\n              '<a href=\"#\">links!</a> and other <em>stuff</em>';\n         }]);\n     </file>\n\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-bind-html', function() {\n         expect(element(by.binding('myHTML')).getText()).toBe(\n             'I am an HTMLstring with links! and other stuff');\n       });\n     </file>\n   </example>\n */\nvar ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {\n  return {\n    restrict: 'A',\n    compile: function ngBindHtmlCompile(tElement, tAttrs) {\n      var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);\n      var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {\n        return (value || '').toString();\n      });\n      $compile.$$addBindingClass(tElement);\n\n      return function ngBindHtmlLink(scope, element, attr) {\n        $compile.$$addBindingInfo(element, attr.ngBindHtml);\n\n        scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {\n          // we re-evaluate the expr because we want a TrustedValueHolderType\n          // for $sce, not a string\n          element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');\n        });\n      };\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngChange\n *\n * @description\n * Evaluate the given expression when the user changes the input.\n * The expression is evaluated immediately, unlike the JavaScript onchange event\n * which only triggers at the end of a change (usually, when the user leaves the\n * form element or presses the return key).\n *\n * The `ngChange` expression is only evaluated when a change in the input value causes\n * a new value to be committed to the model.\n *\n * It will not be evaluated:\n * * if the value returned from the `$parsers` transformation pipeline has not changed\n * * if the input has continued to be invalid since the model will stay `null`\n * * if the model is changed programmatically and not by a change to the input value\n *\n *\n * Note, this directive requires `ngModel` to be present.\n *\n * @element input\n * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change\n * in input value.\n *\n * @example\n * <example name=\"ngChange-directive\" module=\"changeExample\">\n *   <file name=\"index.html\">\n *     <script>\n *       angular.module('changeExample', [])\n *         .controller('ExampleController', ['$scope', function($scope) {\n *           $scope.counter = 0;\n *           $scope.change = function() {\n *             $scope.counter++;\n *           };\n *         }]);\n *     </script>\n *     <div ng-controller=\"ExampleController\">\n *       <input type=\"checkbox\" ng-model=\"confirmed\" ng-change=\"change()\" id=\"ng-change-example1\" />\n *       <input type=\"checkbox\" ng-model=\"confirmed\" id=\"ng-change-example2\" />\n *       <label for=\"ng-change-example2\">Confirmed</label><br />\n *       <tt>debug = {{confirmed}}</tt><br/>\n *       <tt>counter = {{counter}}</tt><br/>\n *     </div>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var counter = element(by.binding('counter'));\n *     var debug = element(by.binding('confirmed'));\n *\n *     it('should evaluate the expression if changing from view', function() {\n *       expect(counter.getText()).toContain('0');\n *\n *       element(by.id('ng-change-example1')).click();\n *\n *       expect(counter.getText()).toContain('1');\n *       expect(debug.getText()).toContain('true');\n *     });\n *\n *     it('should not evaluate the expression if changing from model', function() {\n *       element(by.id('ng-change-example2')).click();\n\n *       expect(counter.getText()).toContain('0');\n *       expect(debug.getText()).toContain('true');\n *     });\n *   </file>\n * </example>\n */\nvar ngChangeDirective = valueFn({\n  restrict: 'A',\n  require: 'ngModel',\n  link: function(scope, element, attr, ctrl) {\n    ctrl.$viewChangeListeners.push(function() {\n      scope.$eval(attr.ngChange);\n    });\n  }\n});\n\nfunction classDirective(name, selector) {\n  name = 'ngClass' + name;\n  return ['$animate', function($animate) {\n    return {\n      restrict: 'AC',\n      link: function(scope, element, attr) {\n        var oldVal;\n\n        scope.$watch(attr[name], ngClassWatchAction, true);\n\n        attr.$observe('class', function(value) {\n          ngClassWatchAction(scope.$eval(attr[name]));\n        });\n\n\n        if (name !== 'ngClass') {\n          scope.$watch('$index', function($index, old$index) {\n            // jshint bitwise: false\n            var mod = $index & 1;\n            if (mod !== (old$index & 1)) {\n              var classes = arrayClasses(scope.$eval(attr[name]));\n              mod === selector ?\n                addClasses(classes) :\n                removeClasses(classes);\n            }\n          });\n        }\n\n        function addClasses(classes) {\n          var newClasses = digestClassCounts(classes, 1);\n          attr.$addClass(newClasses);\n        }\n\n        function removeClasses(classes) {\n          var newClasses = digestClassCounts(classes, -1);\n          attr.$removeClass(newClasses);\n        }\n\n        function digestClassCounts(classes, count) {\n          // Use createMap() to prevent class assumptions involving property\n          // names in Object.prototype\n          var classCounts = element.data('$classCounts') || createMap();\n          var classesToUpdate = [];\n          forEach(classes, function(className) {\n            if (count > 0 || classCounts[className]) {\n              classCounts[className] = (classCounts[className] || 0) + count;\n              if (classCounts[className] === +(count > 0)) {\n                classesToUpdate.push(className);\n              }\n            }\n          });\n          element.data('$classCounts', classCounts);\n          return classesToUpdate.join(' ');\n        }\n\n        function updateClasses(oldClasses, newClasses) {\n          var toAdd = arrayDifference(newClasses, oldClasses);\n          var toRemove = arrayDifference(oldClasses, newClasses);\n          toAdd = digestClassCounts(toAdd, 1);\n          toRemove = digestClassCounts(toRemove, -1);\n          if (toAdd && toAdd.length) {\n            $animate.addClass(element, toAdd);\n          }\n          if (toRemove && toRemove.length) {\n            $animate.removeClass(element, toRemove);\n          }\n        }\n\n        function ngClassWatchAction(newVal) {\n          if (selector === true || scope.$index % 2 === selector) {\n            var newClasses = arrayClasses(newVal || []);\n            if (!oldVal) {\n              addClasses(newClasses);\n            } else if (!equals(newVal,oldVal)) {\n              var oldClasses = arrayClasses(oldVal);\n              updateClasses(oldClasses, newClasses);\n            }\n          }\n          oldVal = shallowCopy(newVal);\n        }\n      }\n    };\n\n    function arrayDifference(tokens1, tokens2) {\n      var values = [];\n\n      outer:\n      for (var i = 0; i < tokens1.length; i++) {\n        var token = tokens1[i];\n        for (var j = 0; j < tokens2.length; j++) {\n          if (token == tokens2[j]) continue outer;\n        }\n        values.push(token);\n      }\n      return values;\n    }\n\n    function arrayClasses(classVal) {\n      var classes = [];\n      if (isArray(classVal)) {\n        forEach(classVal, function(v) {\n          classes = classes.concat(arrayClasses(v));\n        });\n        return classes;\n      } else if (isString(classVal)) {\n        return classVal.split(' ');\n      } else if (isObject(classVal)) {\n        forEach(classVal, function(v, k) {\n          if (v) {\n            classes = classes.concat(k.split(' '));\n          }\n        });\n        return classes;\n      }\n      return classVal;\n    }\n  }];\n}\n\n/**\n * @ngdoc directive\n * @name ngClass\n * @restrict AC\n *\n * @description\n * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding\n * an expression that represents all classes to be added.\n *\n * The directive operates in three different ways, depending on which of three types the expression\n * evaluates to:\n *\n * 1. If the expression evaluates to a string, the string should be one or more space-delimited class\n * names.\n *\n * 2. If the expression evaluates to an object, then for each key-value pair of the\n * object with a truthy value the corresponding key is used as a class name.\n *\n * 3. If the expression evaluates to an array, each element of the array should either be a string as in\n * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array\n * to give you more control over what CSS classes appear. See the code below for an example of this.\n *\n *\n * The directive won't add duplicate classes if a particular class was already set.\n *\n * When the expression changes, the previously added classes are removed and only then are the\n * new classes added.\n *\n * @animations\n * **add** - happens just before the class is applied to the elements\n *\n * **remove** - happens just before the class is removed from the element\n *\n * @element ANY\n * @param {expression} ngClass {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class\n *   names, an array, or a map of class names to boolean values. In the case of a map, the\n *   names of the properties whose values are truthy will be added as css classes to the\n *   element.\n *\n * @example Example that demonstrates basic bindings via ngClass directive.\n   <example>\n     <file name=\"index.html\">\n       <p ng-class=\"{strike: deleted, bold: important, 'has-error': error}\">Map Syntax Example</p>\n       <label>\n          <input type=\"checkbox\" ng-model=\"deleted\">\n          deleted (apply \"strike\" class)\n       </label><br>\n       <label>\n          <input type=\"checkbox\" ng-model=\"important\">\n          important (apply \"bold\" class)\n       </label><br>\n       <label>\n          <input type=\"checkbox\" ng-model=\"error\">\n          error (apply \"has-error\" class)\n       </label>\n       <hr>\n       <p ng-class=\"style\">Using String Syntax</p>\n       <input type=\"text\" ng-model=\"style\"\n              placeholder=\"Type: bold strike red\" aria-label=\"Type: bold strike red\">\n       <hr>\n       <p ng-class=\"[style1, style2, style3]\">Using Array Syntax</p>\n       <input ng-model=\"style1\"\n              placeholder=\"Type: bold, strike or red\" aria-label=\"Type: bold, strike or red\"><br>\n       <input ng-model=\"style2\"\n              placeholder=\"Type: bold, strike or red\" aria-label=\"Type: bold, strike or red 2\"><br>\n       <input ng-model=\"style3\"\n              placeholder=\"Type: bold, strike or red\" aria-label=\"Type: bold, strike or red 3\"><br>\n       <hr>\n       <p ng-class=\"[style4, {orange: warning}]\">Using Array and Map Syntax</p>\n       <input ng-model=\"style4\" placeholder=\"Type: bold, strike\" aria-label=\"Type: bold, strike\"><br>\n       <label><input type=\"checkbox\" ng-model=\"warning\"> warning (apply \"orange\" class)</label>\n     </file>\n     <file name=\"style.css\">\n       .strike {\n           text-decoration: line-through;\n       }\n       .bold {\n           font-weight: bold;\n       }\n       .red {\n           color: red;\n       }\n       .has-error {\n           color: red;\n           background-color: yellow;\n       }\n       .orange {\n           color: orange;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var ps = element.all(by.css('p'));\n\n       it('should let you toggle the class', function() {\n\n         expect(ps.first().getAttribute('class')).not.toMatch(/bold/);\n         expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);\n\n         element(by.model('important')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/bold/);\n\n         element(by.model('error')).click();\n         expect(ps.first().getAttribute('class')).toMatch(/has-error/);\n       });\n\n       it('should let you toggle string example', function() {\n         expect(ps.get(1).getAttribute('class')).toBe('');\n         element(by.model('style')).clear();\n         element(by.model('style')).sendKeys('red');\n         expect(ps.get(1).getAttribute('class')).toBe('red');\n       });\n\n       it('array example should have 3 classes', function() {\n         expect(ps.get(2).getAttribute('class')).toBe('');\n         element(by.model('style1')).sendKeys('bold');\n         element(by.model('style2')).sendKeys('strike');\n         element(by.model('style3')).sendKeys('red');\n         expect(ps.get(2).getAttribute('class')).toBe('bold strike red');\n       });\n\n       it('array with map example should have 2 classes', function() {\n         expect(ps.last().getAttribute('class')).toBe('');\n         element(by.model('style4')).sendKeys('bold');\n         element(by.model('warning')).click();\n         expect(ps.last().getAttribute('class')).toBe('bold orange');\n       });\n     </file>\n   </example>\n\n   ## Animations\n\n   The example below demonstrates how to perform animations using ngClass.\n\n   <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n     <file name=\"index.html\">\n      <input id=\"setbtn\" type=\"button\" value=\"set\" ng-click=\"myVar='my-class'\">\n      <input id=\"clearbtn\" type=\"button\" value=\"clear\" ng-click=\"myVar=''\">\n      <br>\n      <span class=\"base-class\" ng-class=\"myVar\">Sample Text</span>\n     </file>\n     <file name=\"style.css\">\n       .base-class {\n         -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n         transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n       }\n\n       .base-class.my-class {\n         color: red;\n         font-size:3em;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class', function() {\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n\n         element(by.id('setbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).\n           toMatch(/my-class/);\n\n         element(by.id('clearbtn')).click();\n\n         expect(element(by.css('.base-class')).getAttribute('class')).not.\n           toMatch(/my-class/);\n       });\n     </file>\n   </example>\n\n\n   ## ngClass and pre-existing CSS3 Transitions/Animations\n   The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.\n   Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder\n   any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure\n   to view the step by step details of {@link $animate#addClass $animate.addClass} and\n   {@link $animate#removeClass $animate.removeClass}.\n */\nvar ngClassDirective = classDirective('', true);\n\n/**\n * @ngdoc directive\n * @name ngClassOdd\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result\n *   of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}}\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassOddDirective = classDirective('Odd', 0);\n\n/**\n * @ngdoc directive\n * @name ngClassEven\n * @restrict AC\n *\n * @description\n * The `ngClassOdd` and `ngClassEven` directives work exactly as\n * {@link ng.directive:ngClass ngClass}, except they work in\n * conjunction with `ngRepeat` and take effect only on odd (even) rows.\n *\n * This directive can be applied only within the scope of an\n * {@link ng.directive:ngRepeat ngRepeat}.\n *\n * @element ANY\n * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The\n *   result of the evaluation can be a string representing space delimited class names or an array.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <ol ng-init=\"names=['John', 'Mary', 'Cate', 'Suz']\">\n          <li ng-repeat=\"name in names\">\n           <span ng-class-odd=\"'odd'\" ng-class-even=\"'even'\">\n             {{name}} &nbsp; &nbsp; &nbsp;\n           </span>\n          </li>\n        </ol>\n     </file>\n     <file name=\"style.css\">\n       .odd {\n         color: red;\n       }\n       .even {\n         color: blue;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-class-odd and ng-class-even', function() {\n         expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).\n           toMatch(/odd/);\n         expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).\n           toMatch(/even/);\n       });\n     </file>\n   </example>\n */\nvar ngClassEvenDirective = classDirective('Even', 1);\n\n/**\n * @ngdoc directive\n * @name ngCloak\n * @restrict AC\n *\n * @description\n * The `ngCloak` directive is used to prevent the Angular html template from being briefly\n * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this\n * directive to avoid the undesirable flicker effect caused by the html template display.\n *\n * The directive can be applied to the `<body>` element, but the preferred usage is to apply\n * multiple `ngCloak` directives to small portions of the page to permit progressive rendering\n * of the browser view.\n *\n * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and\n * `angular.min.js`.\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```css\n * [ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {\n *   display: none !important;\n * }\n * ```\n *\n * When this css rule is loaded by the browser, all html elements (including their children) that\n * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive\n * during the compilation of the template it deletes the `ngCloak` element attribute, making\n * the compiled element visible.\n *\n * For the best result, the `angular.js` script must be loaded in the head section of the html\n * document; alternatively, the css rule above must be included in the external stylesheet of the\n * application.\n *\n * @element ANY\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <div id=\"template1\" ng-cloak>{{ 'hello' }}</div>\n        <div id=\"template2\" class=\"ng-cloak\">{{ 'world' }}</div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should remove the template directive and css class', function() {\n         expect($('#template1').getAttribute('ng-cloak')).\n           toBeNull();\n         expect($('#template2').getAttribute('ng-cloak')).\n           toBeNull();\n       });\n     </file>\n   </example>\n *\n */\nvar ngCloakDirective = ngDirective({\n  compile: function(element, attr) {\n    attr.$set('ngCloak', undefined);\n    element.removeClass('ng-cloak');\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngController\n *\n * @description\n * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular\n * supports the principles behind the Model-View-Controller design pattern.\n *\n * MVC components in angular:\n *\n * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties\n *   are accessed through bindings.\n * * View — The template (HTML with data bindings) that is rendered into the View.\n * * Controller — The `ngController` directive specifies a Controller class; the class contains business\n *   logic behind the application to decorate the scope with functions and values\n *\n * Note that you can also attach controllers to the DOM by declaring it in a route definition\n * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller\n * again using `ng-controller` in the template itself.  This will cause the controller to be attached\n * and executed twice.\n *\n * @element ANY\n * @scope\n * @priority 500\n * @param {expression} ngController Name of a constructor function registered with the current\n * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}\n * that on the current scope evaluates to a constructor function.\n *\n * The controller instance can be published into a scope property by specifying\n * `ng-controller=\"as propertyName\"`.\n *\n * If the current `$controllerProvider` is configured to use globals (via\n * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may\n * also be the name of a globally accessible constructor function (not recommended).\n *\n * @example\n * Here is a simple form for editing user contact information. Adding, removing, clearing, and\n * greeting are methods declared on the controller (see source tab). These methods can\n * easily be called from the angular markup. Any changes to the data are automatically reflected\n * in the View without the need for a manual update.\n *\n * Two different declaration styles are included below:\n *\n * * one binds methods and properties directly onto the controller using `this`:\n * `ng-controller=\"SettingsController1 as settings\"`\n * * one injects `$scope` into the controller:\n * `ng-controller=\"SettingsController2\"`\n *\n * The second option is more common in the Angular community, and is generally used in boilerplates\n * and in this guide. However, there are advantages to binding properties directly to the controller\n * and avoiding scope.\n *\n * * Using `controller as` makes it obvious which controller you are accessing in the template when\n * multiple controllers apply to an element.\n * * If you are writing your controllers as classes you have easier access to the properties and\n * methods, which will appear on the scope, from inside the controller code.\n * * Since there is always a `.` in the bindings, you don't have to worry about prototypal\n * inheritance masking primitives.\n *\n * This example demonstrates the `controller as` syntax.\n *\n * <example name=\"ngControllerAs\" module=\"controllerAsExample\">\n *   <file name=\"index.html\">\n *    <div id=\"ctrl-as-exmpl\" ng-controller=\"SettingsController1 as settings\">\n *      <label>Name: <input type=\"text\" ng-model=\"settings.name\"/></label>\n *      <button ng-click=\"settings.greet()\">greet</button><br/>\n *      Contact:\n *      <ul>\n *        <li ng-repeat=\"contact in settings.contacts\">\n *          <select ng-model=\"contact.type\" aria-label=\"Contact method\" id=\"select_{{$index}}\">\n *             <option>phone</option>\n *             <option>email</option>\n *          </select>\n *          <input type=\"text\" ng-model=\"contact.value\" aria-labelledby=\"select_{{$index}}\" />\n *          <button ng-click=\"settings.clearContact(contact)\">clear</button>\n *          <button ng-click=\"settings.removeContact(contact)\" aria-label=\"Remove\">X</button>\n *        </li>\n *        <li><button ng-click=\"settings.addContact()\">add</button></li>\n *     </ul>\n *    </div>\n *   </file>\n *   <file name=\"app.js\">\n *    angular.module('controllerAsExample', [])\n *      .controller('SettingsController1', SettingsController1);\n *\n *    function SettingsController1() {\n *      this.name = \"John Smith\";\n *      this.contacts = [\n *        {type: 'phone', value: '408 555 1212'},\n *        {type: 'email', value: 'john.smith@example.org'} ];\n *    }\n *\n *    SettingsController1.prototype.greet = function() {\n *      alert(this.name);\n *    };\n *\n *    SettingsController1.prototype.addContact = function() {\n *      this.contacts.push({type: 'email', value: 'yourname@example.org'});\n *    };\n *\n *    SettingsController1.prototype.removeContact = function(contactToRemove) {\n *     var index = this.contacts.indexOf(contactToRemove);\n *      this.contacts.splice(index, 1);\n *    };\n *\n *    SettingsController1.prototype.clearContact = function(contact) {\n *      contact.type = 'phone';\n *      contact.value = '';\n *    };\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it('should check controller as', function() {\n *       var container = element(by.id('ctrl-as-exmpl'));\n *         expect(container.element(by.model('settings.name'))\n *           .getAttribute('value')).toBe('John Smith');\n *\n *       var firstRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(0));\n *       var secondRepeat =\n *           container.element(by.repeater('contact in settings.contacts').row(1));\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('408 555 1212');\n *\n *       expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('john.smith@example.org');\n *\n *       firstRepeat.element(by.buttonText('clear')).click();\n *\n *       expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *           .toBe('');\n *\n *       container.element(by.buttonText('add')).click();\n *\n *       expect(container.element(by.repeater('contact in settings.contacts').row(2))\n *           .element(by.model('contact.value'))\n *           .getAttribute('value'))\n *           .toBe('yourname@example.org');\n *     });\n *   </file>\n * </example>\n *\n * This example demonstrates the \"attach to `$scope`\" style of controller.\n *\n * <example name=\"ngController\" module=\"controllerExample\">\n *  <file name=\"index.html\">\n *   <div id=\"ctrl-exmpl\" ng-controller=\"SettingsController2\">\n *     <label>Name: <input type=\"text\" ng-model=\"name\"/></label>\n *     <button ng-click=\"greet()\">greet</button><br/>\n *     Contact:\n *     <ul>\n *       <li ng-repeat=\"contact in contacts\">\n *         <select ng-model=\"contact.type\" id=\"select_{{$index}}\">\n *            <option>phone</option>\n *            <option>email</option>\n *         </select>\n *         <input type=\"text\" ng-model=\"contact.value\" aria-labelledby=\"select_{{$index}}\" />\n *         <button ng-click=\"clearContact(contact)\">clear</button>\n *         <button ng-click=\"removeContact(contact)\">X</button>\n *       </li>\n *       <li>[ <button ng-click=\"addContact()\">add</button> ]</li>\n *    </ul>\n *   </div>\n *  </file>\n *  <file name=\"app.js\">\n *   angular.module('controllerExample', [])\n *     .controller('SettingsController2', ['$scope', SettingsController2]);\n *\n *   function SettingsController2($scope) {\n *     $scope.name = \"John Smith\";\n *     $scope.contacts = [\n *       {type:'phone', value:'408 555 1212'},\n *       {type:'email', value:'john.smith@example.org'} ];\n *\n *     $scope.greet = function() {\n *       alert($scope.name);\n *     };\n *\n *     $scope.addContact = function() {\n *       $scope.contacts.push({type:'email', value:'yourname@example.org'});\n *     };\n *\n *     $scope.removeContact = function(contactToRemove) {\n *       var index = $scope.contacts.indexOf(contactToRemove);\n *       $scope.contacts.splice(index, 1);\n *     };\n *\n *     $scope.clearContact = function(contact) {\n *       contact.type = 'phone';\n *       contact.value = '';\n *     };\n *   }\n *  </file>\n *  <file name=\"protractor.js\" type=\"protractor\">\n *    it('should check controller', function() {\n *      var container = element(by.id('ctrl-exmpl'));\n *\n *      expect(container.element(by.model('name'))\n *          .getAttribute('value')).toBe('John Smith');\n *\n *      var firstRepeat =\n *          container.element(by.repeater('contact in contacts').row(0));\n *      var secondRepeat =\n *          container.element(by.repeater('contact in contacts').row(1));\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('408 555 1212');\n *      expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('john.smith@example.org');\n *\n *      firstRepeat.element(by.buttonText('clear')).click();\n *\n *      expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))\n *          .toBe('');\n *\n *      container.element(by.buttonText('add')).click();\n *\n *      expect(container.element(by.repeater('contact in contacts').row(2))\n *          .element(by.model('contact.value'))\n *          .getAttribute('value'))\n *          .toBe('yourname@example.org');\n *    });\n *  </file>\n *</example>\n\n */\nvar ngControllerDirective = [function() {\n  return {\n    restrict: 'A',\n    scope: true,\n    controller: '@',\n    priority: 500\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngCsp\n *\n * @element html\n * @description\n *\n * Angular has some features that can break certain\n * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.\n *\n * If you intend to implement these rules then you must tell Angular not to use these features.\n *\n * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.\n *\n *\n * The following rules affect Angular:\n *\n * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions\n * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%\n * increase in the speed of evaluating Angular expressions.\n *\n * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular\n * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).\n * To make these directives work when a CSP rule is blocking inline styles, you must link to the\n * `angular-csp.css` in your HTML manually.\n *\n * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval\n * and automatically deactivates this feature in the {@link $parse} service. This autodetection,\n * however, triggers a CSP error to be logged in the console:\n *\n * ```\n * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of\n * script in the following Content Security Policy directive: \"default-src 'self'\". Note that\n * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.\n * ```\n *\n * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`\n * directive on an element of the HTML document that appears before the `<script>` tag that loads\n * the `angular.js` file.\n *\n * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*\n *\n * You can specify which of the CSP related Angular features should be deactivated by providing\n * a value for the `ng-csp` attribute. The options are as follows:\n *\n * * no-inline-style: this stops Angular from injecting CSS styles into the DOM\n *\n * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings\n *\n * You can use these values in the following combinations:\n *\n *\n * * No declaration means that Angular will assume that you can do inline styles, but it will do\n * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions\n * of Angular.\n *\n * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline\n * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions\n * of Angular.\n *\n * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject\n * inline styles. E.g. `<body ng-csp=\"no-unsafe-eval\">`.\n *\n * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can\n * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp=\"no-inline-style\">`\n *\n * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject\n * styles nor use eval, which is the same as an empty: ng-csp.\n * E.g.`<body ng-csp=\"no-inline-style;no-unsafe-eval\">`\n *\n * @example\n * This example shows how to apply the `ngCsp` directive to the `html` tag.\n   ```html\n     <!doctype html>\n     <html ng-app ng-csp>\n     ...\n     ...\n     </html>\n   ```\n  * @example\n      // Note: the suffix `.csp` in the example name triggers\n      // csp mode in our http server!\n      <example name=\"example.csp\" module=\"cspExample\" ng-csp=\"true\">\n        <file name=\"index.html\">\n          <div ng-controller=\"MainController as ctrl\">\n            <div>\n              <button ng-click=\"ctrl.inc()\" id=\"inc\">Increment</button>\n              <span id=\"counter\">\n                {{ctrl.counter}}\n              </span>\n            </div>\n\n            <div>\n              <button ng-click=\"ctrl.evil()\" id=\"evil\">Evil</button>\n              <span id=\"evilError\">\n                {{ctrl.evilError}}\n              </span>\n            </div>\n          </div>\n        </file>\n        <file name=\"script.js\">\n           angular.module('cspExample', [])\n             .controller('MainController', function() {\n                this.counter = 0;\n                this.inc = function() {\n                  this.counter++;\n                };\n                this.evil = function() {\n                  // jshint evil:true\n                  try {\n                    eval('1+2');\n                  } catch (e) {\n                    this.evilError = e.message;\n                  }\n                };\n              });\n        </file>\n        <file name=\"protractor.js\" type=\"protractor\">\n          var util, webdriver;\n\n          var incBtn = element(by.id('inc'));\n          var counter = element(by.id('counter'));\n          var evilBtn = element(by.id('evil'));\n          var evilError = element(by.id('evilError'));\n\n          function getAndClearSevereErrors() {\n            return browser.manage().logs().get('browser').then(function(browserLog) {\n              return browserLog.filter(function(logEntry) {\n                return logEntry.level.value > webdriver.logging.Level.WARNING.value;\n              });\n            });\n          }\n\n          function clearErrors() {\n            getAndClearSevereErrors();\n          }\n\n          function expectNoErrors() {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              expect(filteredLog.length).toEqual(0);\n              if (filteredLog.length) {\n                console.log('browser console errors: ' + util.inspect(filteredLog));\n              }\n            });\n          }\n\n          function expectError(regex) {\n            getAndClearSevereErrors().then(function(filteredLog) {\n              var found = false;\n              filteredLog.forEach(function(log) {\n                if (log.message.match(regex)) {\n                  found = true;\n                }\n              });\n              if (!found) {\n                throw new Error('expected an error that matches ' + regex);\n              }\n            });\n          }\n\n          beforeEach(function() {\n            util = require('util');\n            webdriver = require('protractor/node_modules/selenium-webdriver');\n          });\n\n          // For now, we only test on Chrome,\n          // as Safari does not load the page with Protractor's injected scripts,\n          // and Firefox webdriver always disables content security policy (#6358)\n          if (browser.params.browser !== 'chrome') {\n            return;\n          }\n\n          it('should not report errors when the page is loaded', function() {\n            // clear errors so we are not dependent on previous tests\n            clearErrors();\n            // Need to reload the page as the page is already loaded when\n            // we come here\n            browser.driver.getCurrentUrl().then(function(url) {\n              browser.get(url);\n            });\n            expectNoErrors();\n          });\n\n          it('should evaluate expressions', function() {\n            expect(counter.getText()).toEqual('0');\n            incBtn.click();\n            expect(counter.getText()).toEqual('1');\n            expectNoErrors();\n          });\n\n          it('should throw and report an error when using \"eval\"', function() {\n            evilBtn.click();\n            expect(evilError.getText()).toMatch(/Content Security Policy/);\n            expectError(/Content Security Policy/);\n          });\n        </file>\n      </example>\n  */\n\n// ngCsp is not implemented as a proper directive any more, because we need it be processed while we\n// bootstrap the system (before $parse is instantiated), for this reason we just have\n// the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc\n\n/**\n * @ngdoc directive\n * @name ngClick\n *\n * @description\n * The ngClick directive allows you to specify custom behavior when\n * an element is clicked.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon\n * click. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-click=\"count = count + 1\" ng-init=\"count=0\">\n        Increment\n      </button>\n      <span>\n        count: {{count}}\n      </span>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-click', function() {\n         expect(element(by.binding('count')).getText()).toMatch('0');\n         element(by.css('button')).click();\n         expect(element(by.binding('count')).getText()).toMatch('1');\n       });\n     </file>\n   </example>\n */\n/*\n * A collection of directives that allows creation of custom event handlers that are defined as\n * angular expressions and are compiled and executed within the current scope.\n */\nvar ngEventDirectives = {};\n\n// For events that might fire synchronously during DOM manipulation\n// we need to execute their event handlers asynchronously using $evalAsync,\n// so that they are not executed in an inconsistent state.\nvar forceAsyncEvents = {\n  'blur': true,\n  'focus': true\n};\nforEach(\n  'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),\n  function(eventName) {\n    var directiveName = directiveNormalize('ng-' + eventName);\n    ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {\n      return {\n        restrict: 'A',\n        compile: function($element, attr) {\n          // We expose the powerful $event object on the scope that provides access to the Window,\n          // etc. that isn't protected by the fast paths in $parse.  We explicitly request better\n          // checks at the cost of speed since event handler expressions are not executed as\n          // frequently as regular change detection.\n          var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);\n          return function ngEventHandler(scope, element) {\n            element.on(eventName, function(event) {\n              var callback = function() {\n                fn(scope, {$event:event});\n              };\n              if (forceAsyncEvents[eventName] && $rootScope.$$phase) {\n                scope.$evalAsync(callback);\n              } else {\n                scope.$apply(callback);\n              }\n            });\n          };\n        }\n      };\n    }];\n  }\n);\n\n/**\n * @ngdoc directive\n * @name ngDblclick\n *\n * @description\n * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon\n * a dblclick. (The Event object is available as `$event`)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-dblclick=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on double click)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousedown\n *\n * @description\n * The ngMousedown directive allows you to specify custom behavior on mousedown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon\n * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousedown=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse down)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseup\n *\n * @description\n * Specify custom behavior on mouseup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon\n * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseup=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (on mouse up)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngMouseover\n *\n * @description\n * Specify custom behavior on mouseover event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon\n * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseover=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse is over)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseenter\n *\n * @description\n * Specify custom behavior on mouseenter event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon\n * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseenter=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse enters)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMouseleave\n *\n * @description\n * Specify custom behavior on mouseleave event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon\n * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mouseleave=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse leaves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngMousemove\n *\n * @description\n * Specify custom behavior on mousemove event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon\n * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <button ng-mousemove=\"count = count + 1\" ng-init=\"count=0\">\n        Increment (when mouse moves)\n      </button>\n      count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeydown\n *\n * @description\n * Specify custom behavior on keydown event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon\n * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keydown=\"count = count + 1\" ng-init=\"count=0\">\n      key down count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeyup\n *\n * @description\n * Specify custom behavior on keyup event.\n *\n * @element ANY\n * @priority 0\n * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon\n * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n       <p>Typing in the input box below updates the key count</p>\n       <input ng-keyup=\"count = count + 1\" ng-init=\"count=0\"> key up count: {{count}}\n\n       <p>Typing in the input box below updates the keycode</p>\n       <input ng-keyup=\"event=$event\">\n       <p>event keyCode: {{ event.keyCode }}</p>\n       <p>event altKey: {{ event.altKey }}</p>\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngKeypress\n *\n * @description\n * Specify custom behavior on keypress event.\n *\n * @element ANY\n * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon\n * keypress. ({@link guide/expression#-event- Event object is available as `$event`}\n * and can be interrogated for keyCode, altKey, etc.)\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-keypress=\"count = count + 1\" ng-init=\"count=0\">\n      key press count: {{count}}\n     </file>\n   </example>\n */\n\n\n/**\n * @ngdoc directive\n * @name ngSubmit\n *\n * @description\n * Enables binding angular expressions to onsubmit events.\n *\n * Additionally it prevents the default action (which for form means sending the request to the\n * server and reloading the current page), but only if the form does not contain `action`,\n * `data-action`, or `x-action` attributes.\n *\n * <div class=\"alert alert-warning\">\n * **Warning:** Be careful not to cause \"double-submission\" by using both the `ngClick` and\n * `ngSubmit` handlers together. See the\n * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}\n * for a detailed discussion of when `ngSubmit` may be triggered.\n * </div>\n *\n * @element form\n * @priority 0\n * @param {expression} ngSubmit {@link guide/expression Expression} to eval.\n * ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example module=\"submitExample\">\n     <file name=\"index.html\">\n      <script>\n        angular.module('submitExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.list = [];\n            $scope.text = 'hello';\n            $scope.submit = function() {\n              if ($scope.text) {\n                $scope.list.push(this.text);\n                $scope.text = '';\n              }\n            };\n          }]);\n      </script>\n      <form ng-submit=\"submit()\" ng-controller=\"ExampleController\">\n        Enter text and hit enter:\n        <input type=\"text\" ng-model=\"text\" name=\"text\" />\n        <input type=\"submit\" id=\"submit\" value=\"Submit\" />\n        <pre>list={{list}}</pre>\n      </form>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-submit', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n         expect(element(by.model('text')).getAttribute('value')).toBe('');\n       });\n       it('should ignore empty strings', function() {\n         expect(element(by.binding('list')).getText()).toBe('list=[]');\n         element(by.css('#submit')).click();\n         element(by.css('#submit')).click();\n         expect(element(by.binding('list')).getText()).toContain('hello');\n        });\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngFocus\n *\n * @description\n * Specify custom behavior on focus event.\n *\n * Note: As the `focus` event is executed synchronously when calling `input.focus()`\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon\n * focus. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngBlur\n *\n * @description\n * Specify custom behavior on blur event.\n *\n * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when\n * an element has lost focus.\n *\n * Note: As the `blur` event is executed synchronously also during DOM manipulations\n * (e.g. removing a focussed input),\n * AngularJS executes the expression using `scope.$evalAsync` if the event is fired\n * during an `$apply` to ensure a consistent state.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon\n * blur. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n * See {@link ng.directive:ngClick ngClick}\n */\n\n/**\n * @ngdoc directive\n * @name ngCopy\n *\n * @description\n * Specify custom behavior on copy event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon\n * copy. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-copy=\"copied=true\" ng-init=\"copied=false; value='copy me'\" ng-model=\"value\">\n      copied: {{copied}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngCut\n *\n * @description\n * Specify custom behavior on cut event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon\n * cut. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-cut=\"cut=true\" ng-init=\"cut=false; value='cut me'\" ng-model=\"value\">\n      cut: {{cut}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngPaste\n *\n * @description\n * Specify custom behavior on paste event.\n *\n * @element window, input, select, textarea, a\n * @priority 0\n * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon\n * paste. ({@link guide/expression#-event- Event object is available as `$event`})\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n      <input ng-paste=\"paste=true\" ng-init=\"paste=false\" placeholder='paste here'>\n      pasted: {{paste}}\n     </file>\n   </example>\n */\n\n/**\n * @ngdoc directive\n * @name ngIf\n * @restrict A\n * @multiElement\n *\n * @description\n * The `ngIf` directive removes or recreates a portion of the DOM tree based on an\n * {expression}. If the expression assigned to `ngIf` evaluates to a false\n * value then the element is removed from the DOM, otherwise a clone of the\n * element is reinserted into the DOM.\n *\n * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the\n * element in the DOM rather than changing its visibility via the `display` css property.  A common\n * case when this difference is significant is when using css selectors that rely on an element's\n * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.\n *\n * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope\n * is created when the element is restored.  The scope created within `ngIf` inherits from\n * its parent scope using\n * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).\n * An important implication of this is if `ngModel` is used within `ngIf` to bind to\n * a javascript primitive defined in the parent scope. In this case any modifications made to the\n * variable within the child scope will override (hide) the value in the parent scope.\n *\n * Also, `ngIf` recreates elements using their compiled state. An example of this behavior\n * is if an element's class attribute is directly modified after it's compiled, using something like\n * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element\n * the added class will be lost because the original compiled state is used to regenerate the element.\n *\n * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`\n * and `leave` effects.\n *\n * @animations\n * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container\n * leave - happens just before the `ngIf` contents are removed from the DOM\n *\n * @element ANY\n * @scope\n * @priority 600\n * @param {expression} ngIf If the {@link guide/expression expression} is falsy then\n *     the element is removed from the DOM tree. If it is truthy a copy of the compiled\n *     element is added to the DOM tree.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <label>Click me: <input type=\"checkbox\" ng-model=\"checked\" ng-init=\"checked=true\" /></label><br/>\n      Show when checked:\n      <span ng-if=\"checked\" class=\"animate-if\">\n        This is removed when the checkbox is unchecked.\n      </span>\n    </file>\n    <file name=\"animations.css\">\n      .animate-if {\n        background:white;\n        border:1px solid black;\n        padding:10px;\n      }\n\n      .animate-if.ng-enter, .animate-if.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n      }\n\n      .animate-if.ng-enter,\n      .animate-if.ng-leave.ng-leave-active {\n        opacity:0;\n      }\n\n      .animate-if.ng-leave,\n      .animate-if.ng-enter.ng-enter-active {\n        opacity:1;\n      }\n    </file>\n  </example>\n */\nvar ngIfDirective = ['$animate', function($animate) {\n  return {\n    multiElement: true,\n    transclude: 'element',\n    priority: 600,\n    terminal: true,\n    restrict: 'A',\n    $$tlb: true,\n    link: function($scope, $element, $attr, ctrl, $transclude) {\n        var block, childScope, previousElements;\n        $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {\n\n          if (value) {\n            if (!childScope) {\n              $transclude(function(clone, newScope) {\n                childScope = newScope;\n                clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block = {\n                  clone: clone\n                };\n                $animate.enter(clone, $element.parent(), $element);\n              });\n            }\n          } else {\n            if (previousElements) {\n              previousElements.remove();\n              previousElements = null;\n            }\n            if (childScope) {\n              childScope.$destroy();\n              childScope = null;\n            }\n            if (block) {\n              previousElements = getBlockNodes(block.clone);\n              $animate.leave(previousElements).then(function() {\n                previousElements = null;\n              });\n              block = null;\n            }\n          }\n        });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngInclude\n * @restrict ECA\n *\n * @description\n * Fetches, compiles and includes an external HTML fragment.\n *\n * By default, the template URL is restricted to the same domain and protocol as the\n * application document. This is done by calling {@link $sce#getTrustedResourceUrl\n * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols\n * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or\n * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link\n * ng.$sce Strict Contextual Escaping}.\n *\n * In addition, the browser's\n * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)\n * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)\n * policy may further restrict whether the template is successfully loaded.\n * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`\n * access on some browsers.\n *\n * @animations\n * enter - animation is used to bring new content into the browser.\n * leave - animation is used to animate existing content away.\n *\n * The enter and leave animation occur concurrently.\n *\n * @scope\n * @priority 400\n *\n * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,\n *                 make sure you wrap it in **single** quotes, e.g. `src=\"'myPartialTemplate.html'\"`.\n * @param {string=} onload Expression to evaluate when a new partial is loaded.\n *\n * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll\n *                  $anchorScroll} to scroll the viewport after the content is loaded.\n *\n *                  - If the attribute is not set, disable scrolling.\n *                  - If the attribute is set without value, enable scrolling.\n *                  - Otherwise enable scrolling only if the expression evaluates to truthy value.\n *\n * @example\n  <example module=\"includeExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n     <div ng-controller=\"ExampleController\">\n       <select ng-model=\"template\" ng-options=\"t.name for t in templates\">\n        <option value=\"\">(blank)</option>\n       </select>\n       url of the template: <code>{{template.url}}</code>\n       <hr/>\n       <div class=\"slide-animate-container\">\n         <div class=\"slide-animate\" ng-include=\"template.url\"></div>\n       </div>\n     </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('includeExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.templates =\n            [ { name: 'template1.html', url: 'template1.html'},\n              { name: 'template2.html', url: 'template2.html'} ];\n          $scope.template = $scope.templates[0];\n        }]);\n     </file>\n    <file name=\"template1.html\">\n      Content of template1.html\n    </file>\n    <file name=\"template2.html\">\n      Content of template2.html\n    </file>\n    <file name=\"animations.css\">\n      .slide-animate-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .slide-animate {\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter, .slide-animate.ng-leave {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n        display:block;\n        padding:10px;\n      }\n\n      .slide-animate.ng-enter {\n        top:-50px;\n      }\n      .slide-animate.ng-enter.ng-enter-active {\n        top:0;\n      }\n\n      .slide-animate.ng-leave {\n        top:0;\n      }\n      .slide-animate.ng-leave.ng-leave-active {\n        top:50px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var templateSelect = element(by.model('template'));\n      var includeElem = element(by.css('[ng-include]'));\n\n      it('should load template1.html', function() {\n        expect(includeElem.getText()).toMatch(/Content of template1.html/);\n      });\n\n      it('should load template2.html', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          // See https://github.com/angular/protractor/issues/480\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(2).click();\n        expect(includeElem.getText()).toMatch(/Content of template2.html/);\n      });\n\n      it('should change to blank', function() {\n        if (browser.params.browser == 'firefox') {\n          // Firefox can't handle using selects\n          return;\n        }\n        templateSelect.click();\n        templateSelect.all(by.css('option')).get(0).click();\n        expect(includeElem.isPresent()).toBe(false);\n      });\n    </file>\n  </example>\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentRequested\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted every time the ngInclude content is requested.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentLoaded\n * @eventType emit on the current ngInclude scope\n * @description\n * Emitted every time the ngInclude content is reloaded.\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\n\n\n/**\n * @ngdoc event\n * @name ngInclude#$includeContentError\n * @eventType emit on the scope ngInclude was declared in\n * @description\n * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)\n *\n * @param {Object} angularEvent Synthetic event object.\n * @param {String} src URL of content to load.\n */\nvar ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',\n                  function($templateRequest,   $anchorScroll,   $animate) {\n  return {\n    restrict: 'ECA',\n    priority: 400,\n    terminal: true,\n    transclude: 'element',\n    controller: angular.noop,\n    compile: function(element, attr) {\n      var srcExp = attr.ngInclude || attr.src,\n          onloadExp = attr.onload || '',\n          autoScrollExp = attr.autoscroll;\n\n      return function(scope, $element, $attr, ctrl, $transclude) {\n        var changeCounter = 0,\n            currentScope,\n            previousElement,\n            currentElement;\n\n        var cleanupLastIncludeContent = function() {\n          if (previousElement) {\n            previousElement.remove();\n            previousElement = null;\n          }\n          if (currentScope) {\n            currentScope.$destroy();\n            currentScope = null;\n          }\n          if (currentElement) {\n            $animate.leave(currentElement).then(function() {\n              previousElement = null;\n            });\n            previousElement = currentElement;\n            currentElement = null;\n          }\n        };\n\n        scope.$watch(srcExp, function ngIncludeWatchAction(src) {\n          var afterAnimation = function() {\n            if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {\n              $anchorScroll();\n            }\n          };\n          var thisChangeId = ++changeCounter;\n\n          if (src) {\n            //set the 2nd param to true to ignore the template request error so that the inner\n            //contents and scope can be cleaned up.\n            $templateRequest(src, true).then(function(response) {\n              if (thisChangeId !== changeCounter) return;\n              var newScope = scope.$new();\n              ctrl.template = response;\n\n              // Note: This will also link all children of ng-include that were contained in the original\n              // html. If that content contains controllers, ... they could pollute/change the scope.\n              // However, using ng-include on an element with additional content does not make sense...\n              // Note: We can't remove them in the cloneAttchFn of $transclude as that\n              // function is called before linking the content, which would apply child\n              // directives to non existing elements.\n              var clone = $transclude(newScope, function(clone) {\n                cleanupLastIncludeContent();\n                $animate.enter(clone, null, $element).then(afterAnimation);\n              });\n\n              currentScope = newScope;\n              currentElement = clone;\n\n              currentScope.$emit('$includeContentLoaded', src);\n              scope.$eval(onloadExp);\n            }, function() {\n              if (thisChangeId === changeCounter) {\n                cleanupLastIncludeContent();\n                scope.$emit('$includeContentError', src);\n              }\n            });\n            scope.$emit('$includeContentRequested', src);\n          } else {\n            cleanupLastIncludeContent();\n            ctrl.template = null;\n          }\n        });\n      };\n    }\n  };\n}];\n\n// This directive is called during the $transclude call of the first `ngInclude` directive.\n// It will replace and compile the content of the element with the loaded template.\n// We need this directive so that the element content is already filled when\n// the link function of another directive on the same element as ngInclude\n// is called.\nvar ngIncludeFillContentDirective = ['$compile',\n  function($compile) {\n    return {\n      restrict: 'ECA',\n      priority: -400,\n      require: 'ngInclude',\n      link: function(scope, $element, $attr, ctrl) {\n        if (/SVG/.test($element[0].toString())) {\n          // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not\n          // support innerHTML, so detect this here and try to generate the contents\n          // specially.\n          $element.empty();\n          $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,\n              function namespaceAdaptedClone(clone) {\n            $element.append(clone);\n          }, {futureParentElement: $element});\n          return;\n        }\n\n        $element.html(ctrl.template);\n        $compile($element.contents())(scope);\n      }\n    };\n  }];\n\n/**\n * @ngdoc directive\n * @name ngInit\n * @restrict AC\n *\n * @description\n * The `ngInit` directive allows you to evaluate an expression in the\n * current scope.\n *\n * <div class=\"alert alert-danger\">\n * The only appropriate use of `ngInit` is for aliasing special properties of\n * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you\n * should use {@link guide/controller controllers} rather than `ngInit`\n * to initialize values on a scope.\n * </div>\n * <div class=\"alert alert-warning\">\n * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make\n * sure you have parenthesis for correct precedence:\n * <pre class=\"prettyprint\">\n * `<div ng-init=\"test1 = (data | orderBy:'name')\"></div>`\n * </pre>\n * </div>\n *\n * @priority 450\n *\n * @element ANY\n * @param {expression} ngInit {@link guide/expression Expression} to eval.\n *\n * @example\n   <example module=\"initExample\">\n     <file name=\"index.html\">\n   <script>\n     angular.module('initExample', [])\n       .controller('ExampleController', ['$scope', function($scope) {\n         $scope.list = [['a', 'b'], ['c', 'd']];\n       }]);\n   </script>\n   <div ng-controller=\"ExampleController\">\n     <div ng-repeat=\"innerList in list\" ng-init=\"outerIndex = $index\">\n       <div ng-repeat=\"value in innerList\" ng-init=\"innerIndex = $index\">\n          <span class=\"example-init\">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>\n       </div>\n     </div>\n   </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       it('should alias index positions', function() {\n         var elements = element.all(by.css('.example-init'));\n         expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');\n         expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');\n         expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');\n         expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');\n       });\n     </file>\n   </example>\n */\nvar ngInitDirective = ngDirective({\n  priority: 450,\n  compile: function() {\n    return {\n      pre: function(scope, element, attrs) {\n        scope.$eval(attrs.ngInit);\n      }\n    };\n  }\n});\n\n/**\n * @ngdoc directive\n * @name ngList\n *\n * @description\n * Text input that converts between a delimited string and an array of strings. The default\n * delimiter is a comma followed by a space - equivalent to `ng-list=\", \"`. You can specify a custom\n * delimiter as the value of the `ngList` attribute - for example, `ng-list=\" | \"`.\n *\n * The behaviour of the directive is affected by the use of the `ngTrim` attribute.\n * * If `ngTrim` is set to `\"false\"` then whitespace around both the separator and each\n *   list item is respected. This implies that the user of the directive is responsible for\n *   dealing with whitespace but also allows you to use whitespace as a delimiter, such as a\n *   tab or newline character.\n * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected\n *   when joining the list items back together) and whitespace around each list item is stripped\n *   before it is added to the model.\n *\n * ### Example with Validation\n *\n * <example name=\"ngList-directive\" module=\"listExample\">\n *   <file name=\"app.js\">\n *      angular.module('listExample', [])\n *        .controller('ExampleController', ['$scope', function($scope) {\n *          $scope.names = ['morpheus', 'neo', 'trinity'];\n *        }]);\n *   </file>\n *   <file name=\"index.html\">\n *    <form name=\"myForm\" ng-controller=\"ExampleController\">\n *      <label>List: <input name=\"namesInput\" ng-model=\"names\" ng-list required></label>\n *      <span role=\"alert\">\n *        <span class=\"error\" ng-show=\"myForm.namesInput.$error.required\">\n *        Required!</span>\n *      </span>\n *      <br>\n *      <tt>names = {{names}}</tt><br/>\n *      <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>\n *      <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>\n *      <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>\n *      <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>\n *     </form>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     var listInput = element(by.model('names'));\n *     var names = element(by.exactBinding('names'));\n *     var valid = element(by.binding('myForm.namesInput.$valid'));\n *     var error = element(by.css('span.error'));\n *\n *     it('should initialize to model', function() {\n *       expect(names.getText()).toContain('[\"morpheus\",\"neo\",\"trinity\"]');\n *       expect(valid.getText()).toContain('true');\n *       expect(error.getCssValue('display')).toBe('none');\n *     });\n *\n *     it('should be invalid if empty', function() {\n *       listInput.clear();\n *       listInput.sendKeys('');\n *\n *       expect(names.getText()).toContain('');\n *       expect(valid.getText()).toContain('false');\n *       expect(error.getCssValue('display')).not.toBe('none');\n *     });\n *   </file>\n * </example>\n *\n * ### Example - splitting on whitespace\n * <example name=\"ngList-directive-newlines\">\n *   <file name=\"index.html\">\n *    <textarea ng-model=\"list\" ng-list=\"&#10;\" ng-trim=\"false\"></textarea>\n *    <pre>{{ list | json }}</pre>\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it(\"should split the text by newlines\", function() {\n *       var listInput = element(by.model('list'));\n *       var output = element(by.binding('list | json'));\n *       listInput.sendKeys('abc\\ndef\\nghi');\n *       expect(output.getText()).toContain('[\\n  \"abc\",\\n  \"def\",\\n  \"ghi\"\\n]');\n *     });\n *   </file>\n * </example>\n *\n * @element input\n * @param {string=} ngList optional delimiter that should be used to split the value.\n */\nvar ngListDirective = function() {\n  return {\n    restrict: 'A',\n    priority: 100,\n    require: 'ngModel',\n    link: function(scope, element, attr, ctrl) {\n      // We want to control whitespace trimming so we use this convoluted approach\n      // to access the ngList attribute, which doesn't pre-trim the attribute\n      var ngList = element.attr(attr.$attr.ngList) || ', ';\n      var trimValues = attr.ngTrim !== 'false';\n      var separator = trimValues ? trim(ngList) : ngList;\n\n      var parse = function(viewValue) {\n        // If the viewValue is invalid (say required but empty) it will be `undefined`\n        if (isUndefined(viewValue)) return;\n\n        var list = [];\n\n        if (viewValue) {\n          forEach(viewValue.split(separator), function(value) {\n            if (value) list.push(trimValues ? trim(value) : value);\n          });\n        }\n\n        return list;\n      };\n\n      ctrl.$parsers.push(parse);\n      ctrl.$formatters.push(function(value) {\n        if (isArray(value)) {\n          return value.join(ngList);\n        }\n\n        return undefined;\n      });\n\n      // Override the standard $isEmpty because an empty array means the input is empty.\n      ctrl.$isEmpty = function(value) {\n        return !value || !value.length;\n      };\n    }\n  };\n};\n\n/* global VALID_CLASS: true,\n  INVALID_CLASS: true,\n  PRISTINE_CLASS: true,\n  DIRTY_CLASS: true,\n  UNTOUCHED_CLASS: true,\n  TOUCHED_CLASS: true,\n*/\n\nvar VALID_CLASS = 'ng-valid',\n    INVALID_CLASS = 'ng-invalid',\n    PRISTINE_CLASS = 'ng-pristine',\n    DIRTY_CLASS = 'ng-dirty',\n    UNTOUCHED_CLASS = 'ng-untouched',\n    TOUCHED_CLASS = 'ng-touched',\n    PENDING_CLASS = 'ng-pending';\n\nvar ngModelMinErr = minErr('ngModel');\n\n/**\n * @ngdoc type\n * @name ngModel.NgModelController\n *\n * @property {string} $viewValue Actual string value in the view.\n * @property {*} $modelValue The value in the model that the control is bound to.\n * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever\n       the control reads value from the DOM. The functions are called in array order, each passing\n       its return value through to the next. The last return value is forwarded to the\n       {@link ngModel.NgModelController#$validators `$validators`} collection.\n\nParsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue\n`$viewValue`}.\n\nReturning `undefined` from a parser means a parse error occurred. In that case,\nno {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`\nwill be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}\nis set to `true`. The parse error is stored in `ngModel.$error.parse`.\n\n *\n * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever\n       the model value changes. The functions are called in reverse array order, each passing the value through to the\n       next. The last return value is used as the actual DOM value.\n       Used to format / convert values for display in the control.\n * ```js\n * function formatter(value) {\n *   if (value) {\n *     return value.toUpperCase();\n *   }\n * }\n * ngModel.$formatters.push(formatter);\n * ```\n *\n * @property {Object.<string, function>} $validators A collection of validators that are applied\n *      whenever the model value changes. The key value within the object refers to the name of the\n *      validator while the function refers to the validation operation. The validation operation is\n *      provided with the model value as an argument and must return a true or false value depending\n *      on the response of that validation.\n *\n * ```js\n * ngModel.$validators.validCharacters = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *   return /[0-9]+/.test(value) &&\n *          /[a-z]+/.test(value) &&\n *          /[A-Z]+/.test(value) &&\n *          /\\W+/.test(value);\n * };\n * ```\n *\n * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to\n *      perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided\n *      is expected to return a promise when it is run during the model validation process. Once the promise\n *      is delivered then the validation status will be set to true when fulfilled and false when rejected.\n *      When the asynchronous validators are triggered, each of the validators will run in parallel and the model\n *      value will only be updated once all validators have been fulfilled. As long as an asynchronous validator\n *      is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators\n *      will only run once all synchronous validators have passed.\n *\n * Please note that if $http is used then it is important that the server returns a success HTTP response code\n * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.\n *\n * ```js\n * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {\n *   var value = modelValue || viewValue;\n *\n *   // Lookup user by username\n *   return $http.get('/api/users/' + value).\n *      then(function resolved() {\n *        //username exists, this means validation fails\n *        return $q.reject('exists');\n *      }, function rejected() {\n *        //username does not exist, therefore this validation passes\n *        return true;\n *      });\n * };\n * ```\n *\n * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the\n *     view value has changed. It is called with no arguments, and its return value is ignored.\n *     This can be used in place of additional $watches against the model value.\n *\n * @property {Object} $error An object hash with all failing validator ids as keys.\n * @property {Object} $pending An object hash with all pending validator ids as keys.\n *\n * @property {boolean} $untouched True if control has not lost focus yet.\n * @property {boolean} $touched True if control has lost focus.\n * @property {boolean} $pristine True if user has not interacted with the control yet.\n * @property {boolean} $dirty True if user has already interacted with the control.\n * @property {boolean} $valid True if there is no error.\n * @property {boolean} $invalid True if at least one error on the control.\n * @property {string} $name The name attribute of the control.\n *\n * @description\n *\n * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.\n * The controller contains services for data-binding, validation, CSS updates, and value formatting\n * and parsing. It purposefully does not contain any logic which deals with DOM rendering or\n * listening to DOM events.\n * Such DOM related logic should be provided by other directives which make use of\n * `NgModelController` for data-binding to control elements.\n * Angular provides this DOM logic for most {@link input `input`} elements.\n * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example\n * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.\n *\n * @example\n * ### Custom Control Example\n * This example shows how to use `NgModelController` with a custom control to achieve\n * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)\n * collaborate together to achieve the desired result.\n *\n * `contenteditable` is an HTML5 attribute, which tells the browser to let the element\n * contents be edited in place by the user.\n *\n * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}\n * module to automatically remove \"bad\" content like inline event listener (e.g. `<span onclick=\"...\">`).\n * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks\n * that content using the `$sce` service.\n *\n * <example name=\"NgModelController\" module=\"customControl\" deps=\"angular-sanitize.js\">\n    <file name=\"style.css\">\n      [contenteditable] {\n        border: 1px solid black;\n        background-color: white;\n        min-height: 20px;\n      }\n\n      .ng-invalid {\n        border: 1px solid red;\n      }\n\n    </file>\n    <file name=\"script.js\">\n      angular.module('customControl', ['ngSanitize']).\n        directive('contenteditable', ['$sce', function($sce) {\n          return {\n            restrict: 'A', // only activate on element attribute\n            require: '?ngModel', // get a hold of NgModelController\n            link: function(scope, element, attrs, ngModel) {\n              if (!ngModel) return; // do nothing if no ng-model\n\n              // Specify how UI should be updated\n              ngModel.$render = function() {\n                element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));\n              };\n\n              // Listen for change events to enable binding\n              element.on('blur keyup change', function() {\n                scope.$evalAsync(read);\n              });\n              read(); // initialize\n\n              // Write data to the model\n              function read() {\n                var html = element.html();\n                // When we clear the content editable the browser leaves a <br> behind\n                // If strip-br attribute is provided then we strip this out\n                if ( attrs.stripBr && html == '<br>' ) {\n                  html = '';\n                }\n                ngModel.$setViewValue(html);\n              }\n            }\n          };\n        }]);\n    </file>\n    <file name=\"index.html\">\n      <form name=\"myForm\">\n       <div contenteditable\n            name=\"myWidget\" ng-model=\"userContent\"\n            strip-br=\"true\"\n            required>Change me!</div>\n        <span ng-show=\"myForm.myWidget.$error.required\">Required!</span>\n       <hr>\n       <textarea ng-model=\"userContent\" aria-label=\"Dynamic textarea\"></textarea>\n      </form>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n    it('should data-bind and become invalid', function() {\n      if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {\n        // SafariDriver can't handle contenteditable\n        // and Firefox driver can't clear contenteditables very well\n        return;\n      }\n      var contentEditable = element(by.css('[contenteditable]'));\n      var content = 'Change me!';\n\n      expect(contentEditable.getText()).toEqual(content);\n\n      contentEditable.clear();\n      contentEditable.sendKeys(protractor.Key.BACK_SPACE);\n      expect(contentEditable.getText()).toEqual('');\n      expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);\n    });\n    </file>\n * </example>\n *\n *\n */\nvar NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',\n    function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {\n  this.$viewValue = Number.NaN;\n  this.$modelValue = Number.NaN;\n  this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.\n  this.$validators = {};\n  this.$asyncValidators = {};\n  this.$parsers = [];\n  this.$formatters = [];\n  this.$viewChangeListeners = [];\n  this.$untouched = true;\n  this.$touched = false;\n  this.$pristine = true;\n  this.$dirty = false;\n  this.$valid = true;\n  this.$invalid = false;\n  this.$error = {}; // keep invalid keys here\n  this.$$success = {}; // keep valid keys here\n  this.$pending = undefined; // keep pending keys here\n  this.$name = $interpolate($attr.name || '', false)($scope);\n\n\n  var parsedNgModel = $parse($attr.ngModel),\n      parsedNgModelAssign = parsedNgModel.assign,\n      ngModelGet = parsedNgModel,\n      ngModelSet = parsedNgModelAssign,\n      pendingDebounce = null,\n      parserValid,\n      ctrl = this;\n\n  this.$$setOptions = function(options) {\n    ctrl.$options = options;\n    if (options && options.getterSetter) {\n      var invokeModelGetter = $parse($attr.ngModel + '()'),\n          invokeModelSetter = $parse($attr.ngModel + '($$$p)');\n\n      ngModelGet = function($scope) {\n        var modelValue = parsedNgModel($scope);\n        if (isFunction(modelValue)) {\n          modelValue = invokeModelGetter($scope);\n        }\n        return modelValue;\n      };\n      ngModelSet = function($scope, newValue) {\n        if (isFunction(parsedNgModel($scope))) {\n          invokeModelSetter($scope, {$$$p: ctrl.$modelValue});\n        } else {\n          parsedNgModelAssign($scope, ctrl.$modelValue);\n        }\n      };\n    } else if (!parsedNgModel.assign) {\n      throw ngModelMinErr('nonassign', \"Expression '{0}' is non-assignable. Element: {1}\",\n          $attr.ngModel, startingTag($element));\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$render\n   *\n   * @description\n   * Called when the view needs to be updated. It is expected that the user of the ng-model\n   * directive will implement this method.\n   *\n   * The `$render()` method is invoked in the following situations:\n   *\n   * * `$rollbackViewValue()` is called.  If we are rolling back the view value to the last\n   *   committed value then `$render()` is called to update the input control.\n   * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and\n   *   the `$viewValue` are different from last time.\n   *\n   * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of\n   * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`\n   * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be\n   * invoked if you only change a property on the objects.\n   */\n  this.$render = noop;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$isEmpty\n   *\n   * @description\n   * This is called when we need to determine if the value of an input is empty.\n   *\n   * For instance, the required directive does this to work out if the input has data or not.\n   *\n   * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.\n   *\n   * You can override this for input directives whose concept of being empty is different from the\n   * default. The `checkboxInputType` directive does this because in its case a value of `false`\n   * implies empty.\n   *\n   * @param {*} value The value of the input to check for emptiness.\n   * @returns {boolean} True if `value` is \"empty\".\n   */\n  this.$isEmpty = function(value) {\n    return isUndefined(value) || value === '' || value === null || value !== value;\n  };\n\n  var parentForm = $element.inheritedData('$formController') || nullFormCtrl,\n      currentValidationRunId = 0;\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setValidity\n   *\n   * @description\n   * Change the validity state, and notify the form.\n   *\n   * This method can be called within $parsers/$formatters or a custom validation implementation.\n   * However, in most cases it should be sufficient to use the `ngModel.$validators` and\n   * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.\n   *\n   * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned\n   *        to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`\n   *        (for unfulfilled `$asyncValidators`), so that it is available for data-binding.\n   *        The `validationErrorKey` should be in camelCase and will get converted into dash-case\n   *        for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`\n   *        class and can be bound to as  `{{someForm.someControl.$error.myError}}` .\n   * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),\n   *                          or skipped (null). Pending is used for unfulfilled `$asyncValidators`.\n   *                          Skipped is used by Angular when validators do not run because of parse errors and\n   *                          when `$asyncValidators` do not run because any of the `$validators` failed.\n   */\n  addSetValidityMethod({\n    ctrl: this,\n    $element: $element,\n    set: function(object, property) {\n      object[property] = true;\n    },\n    unset: function(object, property) {\n      delete object[property];\n    },\n    parentForm: parentForm,\n    $animate: $animate\n  });\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setPristine\n   *\n   * @description\n   * Sets the control to its pristine state.\n   *\n   * This method can be called to remove the `ng-dirty` class and set the control to its pristine\n   * state (`ng-pristine` class). A model is considered to be pristine when the control\n   * has not been changed from when first compiled.\n   */\n  this.$setPristine = function() {\n    ctrl.$dirty = false;\n    ctrl.$pristine = true;\n    $animate.removeClass($element, DIRTY_CLASS);\n    $animate.addClass($element, PRISTINE_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setDirty\n   *\n   * @description\n   * Sets the control to its dirty state.\n   *\n   * This method can be called to remove the `ng-pristine` class and set the control to its dirty\n   * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed\n   * from when first compiled.\n   */\n  this.$setDirty = function() {\n    ctrl.$dirty = true;\n    ctrl.$pristine = false;\n    $animate.removeClass($element, PRISTINE_CLASS);\n    $animate.addClass($element, DIRTY_CLASS);\n    parentForm.$setDirty();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setUntouched\n   *\n   * @description\n   * Sets the control to its untouched state.\n   *\n   * This method can be called to remove the `ng-touched` class and set the control to its\n   * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched\n   * by default, however this function can be used to restore that state if the model has\n   * already been touched by the user.\n   */\n  this.$setUntouched = function() {\n    ctrl.$touched = false;\n    ctrl.$untouched = true;\n    $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setTouched\n   *\n   * @description\n   * Sets the control to its touched state.\n   *\n   * This method can be called to remove the `ng-untouched` class and set the control to its\n   * touched state (`ng-touched` class). A model is considered to be touched when the user has\n   * first focused the control element and then shifted focus away from the control (blur event).\n   */\n  this.$setTouched = function() {\n    ctrl.$touched = true;\n    ctrl.$untouched = false;\n    $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$rollbackViewValue\n   *\n   * @description\n   * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,\n   * which may be caused by a pending debounced event or because the input is waiting for a some\n   * future event.\n   *\n   * If you have an input that uses `ng-model-options` to set up debounced events or events such\n   * as blur you can have a situation where there is a period when the `$viewValue`\n   * is out of synch with the ngModel's `$modelValue`.\n   *\n   * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`\n   * programmatically before these debounced/future events have resolved/occurred, because Angular's\n   * dirty checking mechanism is not able to tell whether the model has actually changed or not.\n   *\n   * The `$rollbackViewValue()` method should be called before programmatically changing the model of an\n   * input which may have such events pending. This is important in order to make sure that the\n   * input field will be updated with the new model value and any pending operations are cancelled.\n   *\n   * <example name=\"ng-model-cancel-update\" module=\"cancel-update-example\">\n   *   <file name=\"app.js\">\n   *     angular.module('cancel-update-example', [])\n   *\n   *     .controller('CancelUpdateController', ['$scope', function($scope) {\n   *       $scope.resetWithCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myForm.myInput1.$rollbackViewValue();\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *       $scope.resetWithoutCancel = function(e) {\n   *         if (e.keyCode == 27) {\n   *           $scope.myValue = '';\n   *         }\n   *       };\n   *     }]);\n   *   </file>\n   *   <file name=\"index.html\">\n   *     <div ng-controller=\"CancelUpdateController\">\n   *       <p>Try typing something in each input.  See that the model only updates when you\n   *          blur off the input.\n   *        </p>\n   *        <p>Now see what happens if you start typing then press the Escape key</p>\n   *\n   *       <form name=\"myForm\" ng-model-options=\"{ updateOn: 'blur' }\">\n   *         <p id=\"inputDescription1\">With $rollbackViewValue()</p>\n   *         <input name=\"myInput1\" aria-describedby=\"inputDescription1\" ng-model=\"myValue\"\n   *                ng-keydown=\"resetWithCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *\n   *         <p id=\"inputDescription2\">Without $rollbackViewValue()</p>\n   *         <input name=\"myInput2\" aria-describedby=\"inputDescription2\" ng-model=\"myValue\"\n   *                ng-keydown=\"resetWithoutCancel($event)\"><br/>\n   *         myValue: \"{{ myValue }}\"\n   *       </form>\n   *     </div>\n   *   </file>\n   * </example>\n   */\n  this.$rollbackViewValue = function() {\n    $timeout.cancel(pendingDebounce);\n    ctrl.$viewValue = ctrl.$$lastCommittedViewValue;\n    ctrl.$render();\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$validate\n   *\n   * @description\n   * Runs each of the registered validators (first synchronous validators and then\n   * asynchronous validators).\n   * If the validity changes to invalid, the model will be set to `undefined`,\n   * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.\n   * If the validity changes to valid, it will set the model to the last available valid\n   * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.\n   */\n  this.$validate = function() {\n    // ignore $validate before model is initialized\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      return;\n    }\n\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    // Note: we use the $$rawModelValue as $modelValue might have been\n    // set to undefined during a view -> model update that found validation\n    // errors. We can't parse the view here, since that could change\n    // the model although neither viewValue nor the model on the scope changed\n    var modelValue = ctrl.$$rawModelValue;\n\n    var prevValid = ctrl.$valid;\n    var prevModelValue = ctrl.$modelValue;\n\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n\n    ctrl.$$runValidators(modelValue, viewValue, function(allValid) {\n      // If there was no change in validity, don't update the model\n      // This prevents changing an invalid modelValue to undefined\n      if (!allowInvalid && prevValid !== allValid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n\n        if (ctrl.$modelValue !== prevModelValue) {\n          ctrl.$$writeModelToScope();\n        }\n      }\n    });\n\n  };\n\n  this.$$runValidators = function(modelValue, viewValue, doneCallback) {\n    currentValidationRunId++;\n    var localValidationRunId = currentValidationRunId;\n\n    // check parser error\n    if (!processParseErrors()) {\n      validationDone(false);\n      return;\n    }\n    if (!processSyncValidators()) {\n      validationDone(false);\n      return;\n    }\n    processAsyncValidators();\n\n    function processParseErrors() {\n      var errorKey = ctrl.$$parserName || 'parse';\n      if (parserValid === undefined) {\n        setValidity(errorKey, null);\n      } else {\n        if (!parserValid) {\n          forEach(ctrl.$validators, function(v, name) {\n            setValidity(name, null);\n          });\n          forEach(ctrl.$asyncValidators, function(v, name) {\n            setValidity(name, null);\n          });\n        }\n        // Set the parse error last, to prevent unsetting it, should a $validators key == parserName\n        setValidity(errorKey, parserValid);\n        return parserValid;\n      }\n      return true;\n    }\n\n    function processSyncValidators() {\n      var syncValidatorsValid = true;\n      forEach(ctrl.$validators, function(validator, name) {\n        var result = validator(modelValue, viewValue);\n        syncValidatorsValid = syncValidatorsValid && result;\n        setValidity(name, result);\n      });\n      if (!syncValidatorsValid) {\n        forEach(ctrl.$asyncValidators, function(v, name) {\n          setValidity(name, null);\n        });\n        return false;\n      }\n      return true;\n    }\n\n    function processAsyncValidators() {\n      var validatorPromises = [];\n      var allValid = true;\n      forEach(ctrl.$asyncValidators, function(validator, name) {\n        var promise = validator(modelValue, viewValue);\n        if (!isPromiseLike(promise)) {\n          throw ngModelMinErr(\"$asyncValidators\",\n            \"Expected asynchronous validator to return a promise but got '{0}' instead.\", promise);\n        }\n        setValidity(name, undefined);\n        validatorPromises.push(promise.then(function() {\n          setValidity(name, true);\n        }, function(error) {\n          allValid = false;\n          setValidity(name, false);\n        }));\n      });\n      if (!validatorPromises.length) {\n        validationDone(true);\n      } else {\n        $q.all(validatorPromises).then(function() {\n          validationDone(allValid);\n        }, noop);\n      }\n    }\n\n    function setValidity(name, isValid) {\n      if (localValidationRunId === currentValidationRunId) {\n        ctrl.$setValidity(name, isValid);\n      }\n    }\n\n    function validationDone(allValid) {\n      if (localValidationRunId === currentValidationRunId) {\n\n        doneCallback(allValid);\n      }\n    }\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$commitViewValue\n   *\n   * @description\n   * Commit a pending update to the `$modelValue`.\n   *\n   * Updates may be pending by a debounced event or because the input is waiting for a some future\n   * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`\n   * usually handles calling this in response to input events.\n   */\n  this.$commitViewValue = function() {\n    var viewValue = ctrl.$viewValue;\n\n    $timeout.cancel(pendingDebounce);\n\n    // If the view value has not changed then we should just exit, except in the case where there is\n    // a native validator on the element. In this case the validation state may have changed even though\n    // the viewValue has stayed empty.\n    if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {\n      return;\n    }\n    ctrl.$$lastCommittedViewValue = viewValue;\n\n    // change to dirty\n    if (ctrl.$pristine) {\n      this.$setDirty();\n    }\n    this.$$parseAndValidate();\n  };\n\n  this.$$parseAndValidate = function() {\n    var viewValue = ctrl.$$lastCommittedViewValue;\n    var modelValue = viewValue;\n    parserValid = isUndefined(modelValue) ? undefined : true;\n\n    if (parserValid) {\n      for (var i = 0; i < ctrl.$parsers.length; i++) {\n        modelValue = ctrl.$parsers[i](modelValue);\n        if (isUndefined(modelValue)) {\n          parserValid = false;\n          break;\n        }\n      }\n    }\n    if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {\n      // ctrl.$modelValue has not been touched yet...\n      ctrl.$modelValue = ngModelGet($scope);\n    }\n    var prevModelValue = ctrl.$modelValue;\n    var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;\n    ctrl.$$rawModelValue = modelValue;\n\n    if (allowInvalid) {\n      ctrl.$modelValue = modelValue;\n      writeToModelIfNeeded();\n    }\n\n    // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.\n    // This can happen if e.g. $setViewValue is called from inside a parser\n    ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {\n      if (!allowInvalid) {\n        // Note: Don't check ctrl.$valid here, as we could have\n        // external validators (e.g. calculated on the server),\n        // that just call $setValidity and need the model value\n        // to calculate their validity.\n        ctrl.$modelValue = allValid ? modelValue : undefined;\n        writeToModelIfNeeded();\n      }\n    });\n\n    function writeToModelIfNeeded() {\n      if (ctrl.$modelValue !== prevModelValue) {\n        ctrl.$$writeModelToScope();\n      }\n    }\n  };\n\n  this.$$writeModelToScope = function() {\n    ngModelSet($scope, ctrl.$modelValue);\n    forEach(ctrl.$viewChangeListeners, function(listener) {\n      try {\n        listener();\n      } catch (e) {\n        $exceptionHandler(e);\n      }\n    });\n  };\n\n  /**\n   * @ngdoc method\n   * @name ngModel.NgModelController#$setViewValue\n   *\n   * @description\n   * Update the view value.\n   *\n   * This method should be called when an input directive want to change the view value; typically,\n   * this is done from within a DOM event handler.\n   *\n   * For example {@link ng.directive:input input} calls it when the value of the input changes and\n   * {@link ng.directive:select select} calls it when an option is selected.\n   *\n   * If the new `value` is an object (rather than a string or a number), we should make a copy of the\n   * object before passing it to `$setViewValue`.  This is because `ngModel` does not perform a deep\n   * watch of objects, it only looks for a change of identity. If you only change the property of\n   * the object then ngModel will not realise that the object has changed and will not invoke the\n   * `$parsers` and `$validators` pipelines.\n   *\n   * For this reason, you should not change properties of the copy once it has been passed to\n   * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.\n   *\n   * When this method is called, the new `value` will be staged for committing through the `$parsers`\n   * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged\n   * value sent directly for processing, finally to be applied to `$modelValue` and then the\n   * **expression** specified in the `ng-model` attribute.\n   *\n   * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.\n   *\n   * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`\n   * and the `default` trigger is not listed, all those actions will remain pending until one of the\n   * `updateOn` events is triggered on the DOM element.\n   * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}\n   * directive is used with a custom debounce for this particular event.\n   *\n   * Note that calling this function does not trigger a `$digest`.\n   *\n   * @param {string} value Value from the view.\n   * @param {string} trigger Event that triggered the update.\n   */\n  this.$setViewValue = function(value, trigger) {\n    ctrl.$viewValue = value;\n    if (!ctrl.$options || ctrl.$options.updateOnDefault) {\n      ctrl.$$debounceViewValueCommit(trigger);\n    }\n  };\n\n  this.$$debounceViewValueCommit = function(trigger) {\n    var debounceDelay = 0,\n        options = ctrl.$options,\n        debounce;\n\n    if (options && isDefined(options.debounce)) {\n      debounce = options.debounce;\n      if (isNumber(debounce)) {\n        debounceDelay = debounce;\n      } else if (isNumber(debounce[trigger])) {\n        debounceDelay = debounce[trigger];\n      } else if (isNumber(debounce['default'])) {\n        debounceDelay = debounce['default'];\n      }\n    }\n\n    $timeout.cancel(pendingDebounce);\n    if (debounceDelay) {\n      pendingDebounce = $timeout(function() {\n        ctrl.$commitViewValue();\n      }, debounceDelay);\n    } else if ($rootScope.$$phase) {\n      ctrl.$commitViewValue();\n    } else {\n      $scope.$apply(function() {\n        ctrl.$commitViewValue();\n      });\n    }\n  };\n\n  // model -> value\n  // Note: we cannot use a normal scope.$watch as we want to detect the following:\n  // 1. scope value is 'a'\n  // 2. user enters 'b'\n  // 3. ng-change kicks in and reverts scope value to 'a'\n  //    -> scope value did not change since the last digest as\n  //       ng-change executes in apply phase\n  // 4. view should be changed back to 'a'\n  $scope.$watch(function ngModelWatch() {\n    var modelValue = ngModelGet($scope);\n\n    // if scope model value and ngModel value are out of sync\n    // TODO(perf): why not move this to the action fn?\n    if (modelValue !== ctrl.$modelValue &&\n       // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator\n       (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)\n    ) {\n      ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;\n      parserValid = undefined;\n\n      var formatters = ctrl.$formatters,\n          idx = formatters.length;\n\n      var viewValue = modelValue;\n      while (idx--) {\n        viewValue = formatters[idx](viewValue);\n      }\n      if (ctrl.$viewValue !== viewValue) {\n        ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;\n        ctrl.$render();\n\n        ctrl.$$runValidators(modelValue, viewValue, noop);\n      }\n    }\n\n    return modelValue;\n  });\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngModel\n *\n * @element input\n * @priority 1\n *\n * @description\n * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a\n * property on the scope using {@link ngModel.NgModelController NgModelController},\n * which is created and exposed by this directive.\n *\n * `ngModel` is responsible for:\n *\n * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`\n *   require.\n * - Providing validation behavior (i.e. required, number, email, url).\n * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).\n * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.\n * - Registering the control with its parent {@link ng.directive:form form}.\n *\n * Note: `ngModel` will try to bind to the property given by evaluating the expression on the\n * current scope. If the property doesn't already exist on this scope, it will be created\n * implicitly and added to the scope.\n *\n * For best practices on using `ngModel`, see:\n *\n *  - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)\n *\n * For basic examples, how to use `ngModel`, see:\n *\n *  - {@link ng.directive:input input}\n *    - {@link input[text] text}\n *    - {@link input[checkbox] checkbox}\n *    - {@link input[radio] radio}\n *    - {@link input[number] number}\n *    - {@link input[email] email}\n *    - {@link input[url] url}\n *    - {@link input[date] date}\n *    - {@link input[datetime-local] datetime-local}\n *    - {@link input[time] time}\n *    - {@link input[month] month}\n *    - {@link input[week] week}\n *  - {@link ng.directive:select select}\n *  - {@link ng.directive:textarea textarea}\n *\n * # CSS classes\n * The following CSS classes are added and removed on the associated input/select/textarea element\n * depending on the validity of the model.\n *\n *  - `ng-valid`: the model is valid\n *  - `ng-invalid`: the model is invalid\n *  - `ng-valid-[key]`: for each valid key added by `$setValidity`\n *  - `ng-invalid-[key]`: for each invalid key added by `$setValidity`\n *  - `ng-pristine`: the control hasn't been interacted with yet\n *  - `ng-dirty`: the control has been interacted with\n *  - `ng-touched`: the control has been blurred\n *  - `ng-untouched`: the control hasn't been blurred\n *  - `ng-pending`: any `$asyncValidators` are unfulfilled\n *\n * Keep in mind that ngAnimate can detect each of these classes when added and removed.\n *\n * ## Animation Hooks\n *\n * Animations within models are triggered when any of the associated CSS classes are added and removed\n * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,\n * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.\n * The animations that are triggered within ngModel are similar to how they work in ngClass and\n * animations can be hooked into using CSS transitions, keyframes as well as JS animations.\n *\n * The following example shows a simple way to utilize CSS transitions to style an input element\n * that has been rendered as invalid after it has been validated:\n *\n * <pre>\n * //be sure to include ngAnimate as a module to hook into more\n * //advanced animations\n * .my-input {\n *   transition:0.5s linear all;\n *   background: white;\n * }\n * .my-input.ng-invalid {\n *   background: red;\n *   color:white;\n * }\n * </pre>\n *\n * @example\n * <example deps=\"angular-animate.js\" animations=\"true\" fixBase=\"true\" module=\"inputExample\">\n     <file name=\"index.html\">\n       <script>\n        angular.module('inputExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.val = '1';\n          }]);\n       </script>\n       <style>\n         .my-input {\n           -webkit-transition:all linear 0.5s;\n           transition:all linear 0.5s;\n           background: transparent;\n         }\n         .my-input.ng-invalid {\n           color:white;\n           background: red;\n         }\n       </style>\n       <p id=\"inputDescription\">\n        Update input to see transitions when valid/invalid.\n        Integer is a valid value.\n       </p>\n       <form name=\"testForm\" ng-controller=\"ExampleController\">\n         <input ng-model=\"val\" ng-pattern=\"/^\\d+$/\" name=\"anim\" class=\"my-input\"\n                aria-describedby=\"inputDescription\" />\n       </form>\n     </file>\n * </example>\n *\n * ## Binding to a getter/setter\n *\n * Sometimes it's helpful to bind `ngModel` to a getter/setter function.  A getter/setter is a\n * function that returns a representation of the model when called with zero arguments, and sets\n * the internal state of a model when called with an argument. It's sometimes useful to use this\n * for models that have an internal representation that's different from what the model exposes\n * to the view.\n *\n * <div class=\"alert alert-success\">\n * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more\n * frequently than other parts of your code.\n * </div>\n *\n * You use this behavior by adding `ng-model-options=\"{ getterSetter: true }\"` to an element that\n * has `ng-model` attached to it. You can also add `ng-model-options=\"{ getterSetter: true }\"` to\n * a `<form>`, which will enable this behavior for all `<input>`s within it. See\n * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.\n *\n * The following example shows how to use `ngModel` with a getter/setter:\n *\n * @example\n * <example name=\"ngModel-getter-setter\" module=\"getterSetterExample\">\n     <file name=\"index.html\">\n       <div ng-controller=\"ExampleController\">\n         <form name=\"userForm\">\n           <label>Name:\n             <input type=\"text\" name=\"userName\"\n                    ng-model=\"user.name\"\n                    ng-model-options=\"{ getterSetter: true }\" />\n           </label>\n         </form>\n         <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n       </div>\n     </file>\n     <file name=\"app.js\">\n       angular.module('getterSetterExample', [])\n         .controller('ExampleController', ['$scope', function($scope) {\n           var _name = 'Brian';\n           $scope.user = {\n             name: function(newName) {\n              // Note that newName can be undefined for two reasons:\n              // 1. Because it is called as a getter and thus called with no arguments\n              // 2. Because the property should actually be set to undefined. This happens e.g. if the\n              //    input is invalid\n              return arguments.length ? (_name = newName) : _name;\n             }\n           };\n         }]);\n     </file>\n * </example>\n */\nvar ngModelDirective = ['$rootScope', function($rootScope) {\n  return {\n    restrict: 'A',\n    require: ['ngModel', '^?form', '^?ngModelOptions'],\n    controller: NgModelController,\n    // Prelink needs to run before any input directive\n    // so that we can set the NgModelOptions in NgModelController\n    // before anyone else uses it.\n    priority: 1,\n    compile: function ngModelCompile(element) {\n      // Setup initial state of the control\n      element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);\n\n      return {\n        pre: function ngModelPreLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0],\n              formCtrl = ctrls[1] || nullFormCtrl;\n\n          modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);\n\n          // notify others, especially parent forms\n          formCtrl.$addControl(modelCtrl);\n\n          attr.$observe('name', function(newValue) {\n            if (modelCtrl.$name !== newValue) {\n              formCtrl.$$renameControl(modelCtrl, newValue);\n            }\n          });\n\n          scope.$on('$destroy', function() {\n            formCtrl.$removeControl(modelCtrl);\n          });\n        },\n        post: function ngModelPostLink(scope, element, attr, ctrls) {\n          var modelCtrl = ctrls[0];\n          if (modelCtrl.$options && modelCtrl.$options.updateOn) {\n            element.on(modelCtrl.$options.updateOn, function(ev) {\n              modelCtrl.$$debounceViewValueCommit(ev && ev.type);\n            });\n          }\n\n          element.on('blur', function(ev) {\n            if (modelCtrl.$touched) return;\n\n            if ($rootScope.$$phase) {\n              scope.$evalAsync(modelCtrl.$setTouched);\n            } else {\n              scope.$apply(modelCtrl.$setTouched);\n            }\n          });\n        }\n      };\n    }\n  };\n}];\n\nvar DEFAULT_REGEXP = /(\\s+|^)default(\\s+|$)/;\n\n/**\n * @ngdoc directive\n * @name ngModelOptions\n *\n * @description\n * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of\n * events that will trigger a model update and/or a debouncing delay so that the actual update only\n * takes place when a timer expires; this timer will be reset after another change takes place.\n *\n * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might\n * be different from the value in the actual model. This means that if you update the model you\n * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in\n * order to make sure it is synchronized with the model and that any debounced action is canceled.\n *\n * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}\n * method is by making sure the input is placed inside a form that has a `name` attribute. This is\n * important because `form` controllers are published to the related scope under the name in their\n * `name` attribute.\n *\n * Any pending changes will take place immediately when an enclosing form is submitted via the\n * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`\n * to have access to the updated model.\n *\n * `ngModelOptions` has an effect on the element it's declared on and its descendants.\n *\n * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:\n *   - `updateOn`: string specifying which event should the input be bound to. You can set several\n *     events using an space delimited list. There is a special event called `default` that\n *     matches the default events belonging of the control.\n *   - `debounce`: integer value which contains the debounce model update value in milliseconds. A\n *     value of 0 triggers an immediate update. If an object is supplied instead, you can specify a\n *     custom value for each event. For example:\n *     `ng-model-options=\"{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }\"`\n *   - `allowInvalid`: boolean value which indicates that the model can be set with values that did\n *     not validate correctly instead of the default behavior of setting the model to undefined.\n *   - `getterSetter`: boolean value which determines whether or not to treat functions bound to\n       `ngModel` as getters/setters.\n *   - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for\n *     `<input type=\"date\">`, `<input type=\"time\">`, ... . It understands UTC/GMT and the\n *     continental US time zone abbreviations, but for general use, use a time zone offset, for\n *     example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)\n *     If not specified, the timezone of the browser will be used.\n *\n * @example\n\n  The following example shows how to override immediate updates. Changes on the inputs within the\n  form will update the model only when the control loses focus (blur event). If `escape` key is\n  pressed while the input field is focused, the value is reset to the value in the current model.\n\n  <example name=\"ngModelOptions-directive-blur\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          <label>Name:\n            <input type=\"text\" name=\"userName\"\n                   ng-model=\"user.name\"\n                   ng-model-options=\"{ updateOn: 'blur' }\"\n                   ng-keyup=\"cancel($event)\" />\n          </label><br />\n          <label>Other data:\n            <input type=\"text\" ng-model=\"user.data\" />\n          </label><br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say', data: '' };\n\n          $scope.cancel = function(e) {\n            if (e.keyCode == 27) {\n              $scope.userForm.userName.$rollbackViewValue();\n            }\n          };\n        }]);\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var model = element(by.binding('user.name'));\n      var input = element(by.model('user.name'));\n      var other = element(by.model('user.data'));\n\n      it('should allow custom events', function() {\n        input.sendKeys(' hello');\n        input.click();\n        expect(model.getText()).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say hello');\n      });\n\n      it('should $rollbackViewValue when model changes', function() {\n        input.sendKeys(' hello');\n        expect(input.getAttribute('value')).toEqual('say hello');\n        input.sendKeys(protractor.Key.ESCAPE);\n        expect(input.getAttribute('value')).toEqual('say');\n        other.click();\n        expect(model.getText()).toEqual('say');\n      });\n    </file>\n  </example>\n\n  This one shows how to debounce model changes. Model will be updated only 1 sec after last change.\n  If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.\n\n  <example name=\"ngModelOptions-directive-debounce\" module=\"optionsExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          <label>Name:\n            <input type=\"text\" name=\"userName\"\n                   ng-model=\"user.name\"\n                   ng-model-options=\"{ debounce: 1000 }\" />\n          </label>\n          <button ng-click=\"userForm.userName.$rollbackViewValue(); user.name=''\">Clear</button>\n          <br />\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('optionsExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.user = { name: 'say' };\n        }]);\n    </file>\n  </example>\n\n  This one shows how to bind to getter/setters:\n\n  <example name=\"ngModelOptions-directive-getter-setter\" module=\"getterSetterExample\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <form name=\"userForm\">\n          <label>Name:\n            <input type=\"text\" name=\"userName\"\n                   ng-model=\"user.name\"\n                   ng-model-options=\"{ getterSetter: true }\" />\n          </label>\n        </form>\n        <pre>user.name = <span ng-bind=\"user.name()\"></span></pre>\n      </div>\n    </file>\n    <file name=\"app.js\">\n      angular.module('getterSetterExample', [])\n        .controller('ExampleController', ['$scope', function($scope) {\n          var _name = 'Brian';\n          $scope.user = {\n            name: function(newName) {\n              // Note that newName can be undefined for two reasons:\n              // 1. Because it is called as a getter and thus called with no arguments\n              // 2. Because the property should actually be set to undefined. This happens e.g. if the\n              //    input is invalid\n              return arguments.length ? (_name = newName) : _name;\n            }\n          };\n        }]);\n    </file>\n  </example>\n */\nvar ngModelOptionsDirective = function() {\n  return {\n    restrict: 'A',\n    controller: ['$scope', '$attrs', function($scope, $attrs) {\n      var that = this;\n      this.$options = copy($scope.$eval($attrs.ngModelOptions));\n      // Allow adding/overriding bound events\n      if (this.$options.updateOn !== undefined) {\n        this.$options.updateOnDefault = false;\n        // extract \"default\" pseudo-event from list of events that can trigger a model update\n        this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {\n          that.$options.updateOnDefault = true;\n          return ' ';\n        }));\n      } else {\n        this.$options.updateOnDefault = true;\n      }\n    }]\n  };\n};\n\n\n\n// helper methods\nfunction addSetValidityMethod(context) {\n  var ctrl = context.ctrl,\n      $element = context.$element,\n      classCache = {},\n      set = context.set,\n      unset = context.unset,\n      parentForm = context.parentForm,\n      $animate = context.$animate;\n\n  classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));\n\n  ctrl.$setValidity = setValidity;\n\n  function setValidity(validationErrorKey, state, controller) {\n    if (state === undefined) {\n      createAndSet('$pending', validationErrorKey, controller);\n    } else {\n      unsetAndCleanup('$pending', validationErrorKey, controller);\n    }\n    if (!isBoolean(state)) {\n      unset(ctrl.$error, validationErrorKey, controller);\n      unset(ctrl.$$success, validationErrorKey, controller);\n    } else {\n      if (state) {\n        unset(ctrl.$error, validationErrorKey, controller);\n        set(ctrl.$$success, validationErrorKey, controller);\n      } else {\n        set(ctrl.$error, validationErrorKey, controller);\n        unset(ctrl.$$success, validationErrorKey, controller);\n      }\n    }\n    if (ctrl.$pending) {\n      cachedToggleClass(PENDING_CLASS, true);\n      ctrl.$valid = ctrl.$invalid = undefined;\n      toggleValidationCss('', null);\n    } else {\n      cachedToggleClass(PENDING_CLASS, false);\n      ctrl.$valid = isObjectEmpty(ctrl.$error);\n      ctrl.$invalid = !ctrl.$valid;\n      toggleValidationCss('', ctrl.$valid);\n    }\n\n    // re-read the state as the set/unset methods could have\n    // combined state in ctrl.$error[validationError] (used for forms),\n    // where setting/unsetting only increments/decrements the value,\n    // and does not replace it.\n    var combinedState;\n    if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {\n      combinedState = undefined;\n    } else if (ctrl.$error[validationErrorKey]) {\n      combinedState = false;\n    } else if (ctrl.$$success[validationErrorKey]) {\n      combinedState = true;\n    } else {\n      combinedState = null;\n    }\n\n    toggleValidationCss(validationErrorKey, combinedState);\n    parentForm.$setValidity(validationErrorKey, combinedState, ctrl);\n  }\n\n  function createAndSet(name, value, controller) {\n    if (!ctrl[name]) {\n      ctrl[name] = {};\n    }\n    set(ctrl[name], value, controller);\n  }\n\n  function unsetAndCleanup(name, value, controller) {\n    if (ctrl[name]) {\n      unset(ctrl[name], value, controller);\n    }\n    if (isObjectEmpty(ctrl[name])) {\n      ctrl[name] = undefined;\n    }\n  }\n\n  function cachedToggleClass(className, switchValue) {\n    if (switchValue && !classCache[className]) {\n      $animate.addClass($element, className);\n      classCache[className] = true;\n    } else if (!switchValue && classCache[className]) {\n      $animate.removeClass($element, className);\n      classCache[className] = false;\n    }\n  }\n\n  function toggleValidationCss(validationErrorKey, isValid) {\n    validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';\n\n    cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);\n    cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);\n  }\n}\n\nfunction isObjectEmpty(obj) {\n  if (obj) {\n    for (var prop in obj) {\n      if (obj.hasOwnProperty(prop)) {\n        return false;\n      }\n    }\n  }\n  return true;\n}\n\n/**\n * @ngdoc directive\n * @name ngNonBindable\n * @restrict AC\n * @priority 1000\n *\n * @description\n * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current\n * DOM element. This is useful if the element contains what appears to be Angular directives and\n * bindings but which should be ignored by Angular. This could be the case if you have a site that\n * displays snippets of code, for instance.\n *\n * @element ANY\n *\n * @example\n * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,\n * but the one wrapped in `ngNonBindable` is left alone.\n *\n * @example\n    <example>\n      <file name=\"index.html\">\n        <div>Normal: {{1 + 2}}</div>\n        <div ng-non-bindable>Ignored: {{1 + 2}}</div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n       it('should check ng-non-bindable', function() {\n         expect(element(by.binding('1 + 2')).getText()).toContain('3');\n         expect(element.all(by.css('div')).last().getText()).toMatch(/1 \\+ 2/);\n       });\n      </file>\n    </example>\n */\nvar ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });\n\n/* global jqLiteRemove */\n\nvar ngOptionsMinErr = minErr('ngOptions');\n\n/**\n * @ngdoc directive\n * @name ngOptions\n * @restrict A\n *\n * @description\n *\n * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`\n * elements for the `<select>` element using the array or object obtained by evaluating the\n * `ngOptions` comprehension expression.\n *\n * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a\n * similar result. However, `ngOptions` provides some benefits such as reducing memory and\n * increasing speed by not creating a new scope for each repeated instance, as well as providing\n * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the\n * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound\n *  to a non-string value. This is because an option element can only be bound to string values at\n * present.\n *\n * When an item in the `<select>` menu is selected, the array element or object property\n * represented by the selected option will be bound to the model identified by the `ngModel`\n * directive.\n *\n * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can\n * be nested into the `<select>` element. This element will then represent the `null` or \"not selected\"\n * option. See example below for demonstration.\n *\n * ## Complex Models (objects or collections)\n *\n * **Note:** By default, `ngModel` watches the model by reference, not value. This is important when\n * binding any input directive to a model that is an object or a collection.\n *\n * Since this is a common situation for `ngOptions` the directive additionally watches the model using\n * `$watchCollection` when the select has the `multiple` attribute or when there is a `track by` clause in\n * the options expression. This allows ngOptions to trigger a re-rendering of the options even if the actual\n * object/collection has not changed identity but only a property on the object or an item in the collection\n * changes.\n *\n * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection\n * if the model is an array). This means that changing a property deeper inside the object/collection that the\n * first level will not trigger a re-rendering.\n *\n *\n * ## `select` **`as`**\n *\n * Using `select` **`as`** will bind the result of the `select` expression to the model, but\n * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)\n * or property name (for object data sources) of the value within the collection. If a **`track by`** expression\n * is used, the result of that expression will be set as the value of the `option` and `select` elements.\n *\n *\n * ### `select` **`as`** and **`track by`**\n *\n * <div class=\"alert alert-warning\">\n * Do not use `select` **`as`** and **`track by`** in the same expression. They are not designed to work together.\n * </div>\n *\n * Consider the following example:\n *\n * ```html\n * <select ng-options=\"item.subItem as item.label for item in values track by item.id\" ng-model=\"selected\"></select>\n * ```\n *\n * ```js\n * $scope.values = [{\n *   id: 1,\n *   label: 'aLabel',\n *   subItem: { name: 'aSubItem' }\n * }, {\n *   id: 2,\n *   label: 'bLabel',\n *   subItem: { name: 'bSubItem' }\n * }];\n *\n * $scope.selected = { name: 'aSubItem' };\n * ```\n *\n * With the purpose of preserving the selection, the **`track by`** expression is always applied to the element\n * of the data source (to `item` in this example). To calculate whether an element is selected, we do the\n * following:\n *\n * 1. Apply **`track by`** to the elements in the array. In the example: `[1, 2]`\n * 2. Apply **`track by`** to the already selected value in `ngModel`.\n *    In the example: this is not possible as **`track by`** refers to `item.id`, but the selected\n *    value from `ngModel` is `{name: 'aSubItem'}`, so the **`track by`** expression is applied to\n *    a wrong object, the selected element can't be found, `<select>` is always reset to the \"not\n *    selected\" option.\n *\n *\n * @param {string} ngModel Assignable angular expression to data-bind to.\n * @param {string=} name Property name of the form under which the control is published.\n * @param {string=} required The control is considered valid only if value is entered.\n * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to\n *    the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of\n *    `required` when you want to data-bind to the `required` attribute.\n * @param {comprehension_expression=} ngOptions in one of the following forms:\n *\n *   * for array data sources:\n *     * `label` **`for`** `value` **`in`** `array`\n *     * `select` **`as`** `label` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array`\n *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`\n *     * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`\n *     * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`\n *     * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`\n *        (for including a filter with `track by`)\n *   * for object data sources:\n *     * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`\n *     * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`\n *     * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`group by`** `group`\n *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`\n *     * `select` **`as`** `label` **`disable when`** `disable`\n *         **`for` `(`**`key`**`,`** `value`**`) in`** `object`\n *\n * Where:\n *\n *   * `array` / `object`: an expression which evaluates to an array / object to iterate over.\n *   * `value`: local variable which will refer to each item in the `array` or each property value\n *      of `object` during iteration.\n *   * `key`: local variable which will refer to a property name in `object` during iteration.\n *   * `label`: The result of this expression will be the label for `<option>` element. The\n *     `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).\n *   * `select`: The result of this expression will be bound to the model of the parent `<select>`\n *      element. If not specified, `select` expression will default to `value`.\n *   * `group`: The result of this expression will be used to group options using the `<optgroup>`\n *      DOM element.\n *   * `disable`: The result of this expression will be used to disable the rendered `<option>`\n *      element. Return `true` to disable.\n *   * `trackexpr`: Used when working with an array of objects. The result of this expression will be\n *      used to identify the objects in the array. The `trackexpr` will most likely refer to the\n *     `value` variable (e.g. `value.propertyName`). With this the selection is preserved\n *      even when the options are recreated (e.g. reloaded from the server).\n *\n * @example\n    <example module=\"selectExample\">\n      <file name=\"index.html\">\n        <script>\n        angular.module('selectExample', [])\n          .controller('ExampleController', ['$scope', function($scope) {\n            $scope.colors = [\n              {name:'black', shade:'dark'},\n              {name:'white', shade:'light', notAnOption: true},\n              {name:'red', shade:'dark'},\n              {name:'blue', shade:'dark', notAnOption: true},\n              {name:'yellow', shade:'light', notAnOption: false}\n            ];\n            $scope.myColor = $scope.colors[2]; // red\n          }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          <ul>\n            <li ng-repeat=\"color in colors\">\n              <label>Name: <input ng-model=\"color.name\"></label>\n              <label><input type=\"checkbox\" ng-model=\"color.notAnOption\"> Disabled?</label>\n              <button ng-click=\"colors.splice($index, 1)\" aria-label=\"Remove\">X</button>\n            </li>\n            <li>\n              <button ng-click=\"colors.push({})\">add</button>\n            </li>\n          </ul>\n          <hr/>\n          <label>Color (null not allowed):\n            <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\"></select>\n          </label><br/>\n          <label>Color (null allowed):\n          <span  class=\"nullable\">\n            <select ng-model=\"myColor\" ng-options=\"color.name for color in colors\">\n              <option value=\"\">-- choose color --</option>\n            </select>\n          </span></label><br/>\n\n          <label>Color grouped by shade:\n            <select ng-model=\"myColor\" ng-options=\"color.name group by color.shade for color in colors\">\n            </select>\n          </label><br/>\n\n          <label>Color grouped by shade, with some disabled:\n            <select ng-model=\"myColor\"\n                  ng-options=\"color.name group by color.shade disable when color.notAnOption for color in colors\">\n            </select>\n          </label><br/>\n\n\n\n          Select <button ng-click=\"myColor = { name:'not in list', shade: 'other' }\">bogus</button>.\n          <br/>\n          <hr/>\n          Currently selected: {{ {selected_color:myColor} }}\n          <div style=\"border:solid 1px black; height:20px\"\n               ng-style=\"{'background-color':myColor.name}\">\n          </div>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n         it('should check ng-options', function() {\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');\n           element.all(by.model('myColor')).first().click();\n           element.all(by.css('select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');\n           element(by.css('.nullable select[ng-model=\"myColor\"]')).click();\n           element.all(by.css('.nullable select[ng-model=\"myColor\"] option')).first().click();\n           expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');\n         });\n      </file>\n    </example>\n */\n\n// jshint maxlen: false\n//                     //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999\nvar NG_OPTIONS_REGEXP = /^\\s*([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+group\\s+by\\s+([\\s\\S]+?))?(?:\\s+disable\\s+when\\s+([\\s\\S]+?))?\\s+for\\s+(?:([\\$\\w][\\$\\w]*)|(?:\\(\\s*([\\$\\w][\\$\\w]*)\\s*,\\s*([\\$\\w][\\$\\w]*)\\s*\\)))\\s+in\\s+([\\s\\S]+?)(?:\\s+track\\s+by\\s+([\\s\\S]+?))?$/;\n                        // 1: value expression (valueFn)\n                        // 2: label expression (displayFn)\n                        // 3: group by expression (groupByFn)\n                        // 4: disable when expression (disableWhenFn)\n                        // 5: array item variable name\n                        // 6: object item key variable name\n                        // 7: object item value variable name\n                        // 8: collection expression\n                        // 9: track by expression\n// jshint maxlen: 100\n\n\nvar ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {\n\n  function parseOptionsExpression(optionsExp, selectElement, scope) {\n\n    var match = optionsExp.match(NG_OPTIONS_REGEXP);\n    if (!(match)) {\n      throw ngOptionsMinErr('iexp',\n        \"Expected expression in form of \" +\n        \"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'\" +\n        \" but got '{0}'. Element: {1}\",\n        optionsExp, startingTag(selectElement));\n    }\n\n    // Extract the parts from the ngOptions expression\n\n    // The variable name for the value of the item in the collection\n    var valueName = match[5] || match[7];\n    // The variable name for the key of the item in the collection\n    var keyName = match[6];\n\n    // An expression that generates the viewValue for an option if there is a label expression\n    var selectAs = / as /.test(match[0]) && match[1];\n    // An expression that is used to track the id of each object in the options collection\n    var trackBy = match[9];\n    // An expression that generates the viewValue for an option if there is no label expression\n    var valueFn = $parse(match[2] ? match[1] : valueName);\n    var selectAsFn = selectAs && $parse(selectAs);\n    var viewValueFn = selectAsFn || valueFn;\n    var trackByFn = trackBy && $parse(trackBy);\n\n    // Get the value by which we are going to track the option\n    // if we have a trackFn then use that (passing scope and locals)\n    // otherwise just hash the given viewValue\n    var getTrackByValueFn = trackBy ?\n                              function(value, locals) { return trackByFn(scope, locals); } :\n                              function getHashOfValue(value) { return hashKey(value); };\n    var getTrackByValue = function(value, key) {\n      return getTrackByValueFn(value, getLocals(value, key));\n    };\n\n    var displayFn = $parse(match[2] || match[1]);\n    var groupByFn = $parse(match[3] || '');\n    var disableWhenFn = $parse(match[4] || '');\n    var valuesFn = $parse(match[8]);\n\n    var locals = {};\n    var getLocals = keyName ? function(value, key) {\n      locals[keyName] = key;\n      locals[valueName] = value;\n      return locals;\n    } : function(value) {\n      locals[valueName] = value;\n      return locals;\n    };\n\n\n    function Option(selectValue, viewValue, label, group, disabled) {\n      this.selectValue = selectValue;\n      this.viewValue = viewValue;\n      this.label = label;\n      this.group = group;\n      this.disabled = disabled;\n    }\n\n    function getOptionValuesKeys(optionValues) {\n      var optionValuesKeys;\n\n      if (!keyName && isArrayLike(optionValues)) {\n        optionValuesKeys = optionValues;\n      } else {\n        // if object, extract keys, in enumeration order, unsorted\n        optionValuesKeys = [];\n        for (var itemKey in optionValues) {\n          if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {\n            optionValuesKeys.push(itemKey);\n          }\n        }\n      }\n      return optionValuesKeys;\n    }\n\n    return {\n      trackBy: trackBy,\n      getTrackByValue: getTrackByValue,\n      getWatchables: $parse(valuesFn, function(optionValues) {\n        // Create a collection of things that we would like to watch (watchedArray)\n        // so that they can all be watched using a single $watchCollection\n        // that only runs the handler once if anything changes\n        var watchedArray = [];\n        optionValues = optionValues || [];\n\n        var optionValuesKeys = getOptionValuesKeys(optionValues);\n        var optionValuesLength = optionValuesKeys.length;\n        for (var index = 0; index < optionValuesLength; index++) {\n          var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];\n          var value = optionValues[key];\n\n          var locals = getLocals(optionValues[key], key);\n          var selectValue = getTrackByValueFn(optionValues[key], locals);\n          watchedArray.push(selectValue);\n\n          // Only need to watch the displayFn if there is a specific label expression\n          if (match[2] || match[1]) {\n            var label = displayFn(scope, locals);\n            watchedArray.push(label);\n          }\n\n          // Only need to watch the disableWhenFn if there is a specific disable expression\n          if (match[4]) {\n            var disableWhen = disableWhenFn(scope, locals);\n            watchedArray.push(disableWhen);\n          }\n        }\n        return watchedArray;\n      }),\n\n      getOptions: function() {\n\n        var optionItems = [];\n        var selectValueMap = {};\n\n        // The option values were already computed in the `getWatchables` fn,\n        // which must have been called to trigger `getOptions`\n        var optionValues = valuesFn(scope) || [];\n        var optionValuesKeys = getOptionValuesKeys(optionValues);\n        var optionValuesLength = optionValuesKeys.length;\n\n        for (var index = 0; index < optionValuesLength; index++) {\n          var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];\n          var value = optionValues[key];\n          var locals = getLocals(value, key);\n          var viewValue = viewValueFn(scope, locals);\n          var selectValue = getTrackByValueFn(viewValue, locals);\n          var label = displayFn(scope, locals);\n          var group = groupByFn(scope, locals);\n          var disabled = disableWhenFn(scope, locals);\n          var optionItem = new Option(selectValue, viewValue, label, group, disabled);\n\n          optionItems.push(optionItem);\n          selectValueMap[selectValue] = optionItem;\n        }\n\n        return {\n          items: optionItems,\n          selectValueMap: selectValueMap,\n          getOptionFromViewValue: function(value) {\n            return selectValueMap[getTrackByValue(value)];\n          },\n          getViewValueFromOption: function(option) {\n            // If the viewValue could be an object that may be mutated by the application,\n            // we need to make a copy and not return the reference to the value on the option.\n            return trackBy ? angular.copy(option.viewValue) : option.viewValue;\n          }\n        };\n      }\n    };\n  }\n\n\n  // we can't just jqLite('<option>') since jqLite is not smart enough\n  // to create it in <select> and IE barfs otherwise.\n  var optionTemplate = document.createElement('option'),\n      optGroupTemplate = document.createElement('optgroup');\n\n  return {\n    restrict: 'A',\n    terminal: true,\n    require: ['select', '?ngModel'],\n    link: function(scope, selectElement, attr, ctrls) {\n\n      // if ngModel is not defined, we don't need to do anything\n      var ngModelCtrl = ctrls[1];\n      if (!ngModelCtrl) return;\n\n      var selectCtrl = ctrls[0];\n      var multiple = attr.multiple;\n\n      // The emptyOption allows the application developer to provide their own custom \"empty\"\n      // option when the viewValue does not match any of the option values.\n      var emptyOption;\n      for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {\n        if (children[i].value === '') {\n          emptyOption = children.eq(i);\n          break;\n        }\n      }\n\n      var providedEmptyOption = !!emptyOption;\n\n      var unknownOption = jqLite(optionTemplate.cloneNode(false));\n      unknownOption.val('?');\n\n      var options;\n      var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);\n\n\n      var renderEmptyOption = function() {\n        if (!providedEmptyOption) {\n          selectElement.prepend(emptyOption);\n        }\n        selectElement.val('');\n        emptyOption.prop('selected', true); // needed for IE\n        emptyOption.attr('selected', true);\n      };\n\n      var removeEmptyOption = function() {\n        if (!providedEmptyOption) {\n          emptyOption.remove();\n        }\n      };\n\n\n      var renderUnknownOption = function() {\n        selectElement.prepend(unknownOption);\n        selectElement.val('?');\n        unknownOption.prop('selected', true); // needed for IE\n        unknownOption.attr('selected', true);\n      };\n\n      var removeUnknownOption = function() {\n        unknownOption.remove();\n      };\n\n\n      // Update the controller methods for multiple selectable options\n      if (!multiple) {\n\n        selectCtrl.writeValue = function writeNgOptionsValue(value) {\n          var option = options.getOptionFromViewValue(value);\n\n          if (option && !option.disabled) {\n            if (selectElement[0].value !== option.selectValue) {\n              removeUnknownOption();\n              removeEmptyOption();\n\n              selectElement[0].value = option.selectValue;\n              option.element.selected = true;\n              option.element.setAttribute('selected', 'selected');\n            }\n          } else {\n            if (value === null || providedEmptyOption) {\n              removeUnknownOption();\n              renderEmptyOption();\n            } else {\n              removeEmptyOption();\n              renderUnknownOption();\n            }\n          }\n        };\n\n        selectCtrl.readValue = function readNgOptionsValue() {\n\n          var selectedOption = options.selectValueMap[selectElement.val()];\n\n          if (selectedOption && !selectedOption.disabled) {\n            removeEmptyOption();\n            removeUnknownOption();\n            return options.getViewValueFromOption(selectedOption);\n          }\n          return null;\n        };\n\n        // If we are using `track by` then we must watch the tracked value on the model\n        // since ngModel only watches for object identity change\n        if (ngOptions.trackBy) {\n          scope.$watch(\n            function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },\n            function() { ngModelCtrl.$render(); }\n          );\n        }\n\n      } else {\n\n        ngModelCtrl.$isEmpty = function(value) {\n          return !value || value.length === 0;\n        };\n\n\n        selectCtrl.writeValue = function writeNgOptionsMultiple(value) {\n          options.items.forEach(function(option) {\n            option.element.selected = false;\n          });\n\n          if (value) {\n            value.forEach(function(item) {\n              var option = options.getOptionFromViewValue(item);\n              if (option && !option.disabled) option.element.selected = true;\n            });\n          }\n        };\n\n\n        selectCtrl.readValue = function readNgOptionsMultiple() {\n          var selectedValues = selectElement.val() || [],\n              selections = [];\n\n          forEach(selectedValues, function(value) {\n            var option = options.selectValueMap[value];\n            if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));\n          });\n\n          return selections;\n        };\n\n        // If we are using `track by` then we must watch these tracked values on the model\n        // since ngModel only watches for object identity change\n        if (ngOptions.trackBy) {\n\n          scope.$watchCollection(function() {\n            if (isArray(ngModelCtrl.$viewValue)) {\n              return ngModelCtrl.$viewValue.map(function(value) {\n                return ngOptions.getTrackByValue(value);\n              });\n            }\n          }, function() {\n            ngModelCtrl.$render();\n          });\n\n        }\n      }\n\n\n      if (providedEmptyOption) {\n\n        // we need to remove it before calling selectElement.empty() because otherwise IE will\n        // remove the label from the element. wtf?\n        emptyOption.remove();\n\n        // compile the element since there might be bindings in it\n        $compile(emptyOption)(scope);\n\n        // remove the class, which is added automatically because we recompile the element and it\n        // becomes the compilation root\n        emptyOption.removeClass('ng-scope');\n      } else {\n        emptyOption = jqLite(optionTemplate.cloneNode(false));\n      }\n\n      // We need to do this here to ensure that the options object is defined\n      // when we first hit it in writeNgOptionsValue\n      updateOptions();\n\n      // We will re-render the option elements if the option values or labels change\n      scope.$watchCollection(ngOptions.getWatchables, updateOptions);\n\n      // ------------------------------------------------------------------ //\n\n\n      function updateOptionElement(option, element) {\n        option.element = element;\n        element.disabled = option.disabled;\n        if (option.value !== element.value) element.value = option.selectValue;\n        if (option.label !== element.label) {\n          element.label = option.label;\n          element.textContent = option.label;\n        }\n      }\n\n      function addOrReuseElement(parent, current, type, templateElement) {\n        var element;\n        // Check whether we can reuse the next element\n        if (current && lowercase(current.nodeName) === type) {\n          // The next element is the right type so reuse it\n          element = current;\n        } else {\n          // The next element is not the right type so create a new one\n          element = templateElement.cloneNode(false);\n          if (!current) {\n            // There are no more elements so just append it to the select\n            parent.appendChild(element);\n          } else {\n            // The next element is not a group so insert the new one\n            parent.insertBefore(element, current);\n          }\n        }\n        return element;\n      }\n\n\n      function removeExcessElements(current) {\n        var next;\n        while (current) {\n          next = current.nextSibling;\n          jqLiteRemove(current);\n          current = next;\n        }\n      }\n\n\n      function skipEmptyAndUnknownOptions(current) {\n        var emptyOption_ = emptyOption && emptyOption[0];\n        var unknownOption_ = unknownOption && unknownOption[0];\n\n        if (emptyOption_ || unknownOption_) {\n          while (current &&\n                (current === emptyOption_ ||\n                current === unknownOption_)) {\n            current = current.nextSibling;\n          }\n        }\n        return current;\n      }\n\n\n      function updateOptions() {\n\n        var previousValue = options && selectCtrl.readValue();\n\n        options = ngOptions.getOptions();\n\n        var groupMap = {};\n        var currentElement = selectElement[0].firstChild;\n\n        // Ensure that the empty option is always there if it was explicitly provided\n        if (providedEmptyOption) {\n          selectElement.prepend(emptyOption);\n        }\n\n        currentElement = skipEmptyAndUnknownOptions(currentElement);\n\n        options.items.forEach(function updateOption(option) {\n          var group;\n          var groupElement;\n          var optionElement;\n\n          if (option.group) {\n\n            // This option is to live in a group\n            // See if we have already created this group\n            group = groupMap[option.group];\n\n            if (!group) {\n\n              // We have not already created this group\n              groupElement = addOrReuseElement(selectElement[0],\n                                               currentElement,\n                                               'optgroup',\n                                               optGroupTemplate);\n              // Move to the next element\n              currentElement = groupElement.nextSibling;\n\n              // Update the label on the group element\n              groupElement.label = option.group;\n\n              // Store it for use later\n              group = groupMap[option.group] = {\n                groupElement: groupElement,\n                currentOptionElement: groupElement.firstChild\n              };\n\n            }\n\n            // So now we have a group for this option we add the option to the group\n            optionElement = addOrReuseElement(group.groupElement,\n                                              group.currentOptionElement,\n                                              'option',\n                                              optionTemplate);\n            updateOptionElement(option, optionElement);\n            // Move to the next element\n            group.currentOptionElement = optionElement.nextSibling;\n\n          } else {\n\n            // This option is not in a group\n            optionElement = addOrReuseElement(selectElement[0],\n                                              currentElement,\n                                              'option',\n                                              optionTemplate);\n            updateOptionElement(option, optionElement);\n            // Move to the next element\n            currentElement = optionElement.nextSibling;\n          }\n        });\n\n\n        // Now remove all excess options and group\n        Object.keys(groupMap).forEach(function(key) {\n          removeExcessElements(groupMap[key].currentOptionElement);\n        });\n        removeExcessElements(currentElement);\n\n        ngModelCtrl.$render();\n\n        // Check to see if the value has changed due to the update to the options\n        if (!ngModelCtrl.$isEmpty(previousValue)) {\n          var nextValue = selectCtrl.readValue();\n          if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {\n            ngModelCtrl.$setViewValue(nextValue);\n            ngModelCtrl.$render();\n          }\n        }\n\n      }\n\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngPluralize\n * @restrict EA\n *\n * @description\n * `ngPluralize` is a directive that displays messages according to en-US localization rules.\n * These rules are bundled with angular.js, but can be overridden\n * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive\n * by specifying the mappings between\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * and the strings to be displayed.\n *\n * # Plural categories and explicit number rules\n * There are two\n * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)\n * in Angular's default en-US locale: \"one\" and \"other\".\n *\n * While a plural category may match many numbers (for example, in en-US locale, \"other\" can match\n * any number that is not 1), an explicit number rule can only match one number. For example, the\n * explicit number rule for \"3\" matches the number 3. There are examples of plural categories\n * and explicit number rules throughout the rest of this documentation.\n *\n * # Configuring ngPluralize\n * You configure ngPluralize by providing 2 attributes: `count` and `when`.\n * You can also provide an optional attribute, `offset`.\n *\n * The value of the `count` attribute can be either a string or an {@link guide/expression\n * Angular expression}; these are evaluated on the current scope for its bound value.\n *\n * The `when` attribute specifies the mappings between plural categories and the actual\n * string to be displayed. The value of the attribute should be a JSON object.\n *\n * The following example shows how to configure ngPluralize:\n *\n * ```html\n * <ng-pluralize count=\"personCount\"\n                 when=\"{'0': 'Nobody is viewing.',\n *                      'one': '1 person is viewing.',\n *                      'other': '{} people are viewing.'}\">\n * </ng-pluralize>\n *```\n *\n * In the example, `\"0: Nobody is viewing.\"` is an explicit number rule. If you did not\n * specify this rule, 0 would be matched to the \"other\" category and \"0 people are viewing\"\n * would be shown instead of \"Nobody is viewing\". You can specify an explicit number rule for\n * other numbers, for example 12, so that instead of showing \"12 people are viewing\", you can\n * show \"a dozen people are viewing\".\n *\n * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted\n * into pluralized strings. In the previous example, Angular will replace `{}` with\n * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder\n * for <span ng-non-bindable>{{numberExpression}}</span>.\n *\n * If no rule is defined for a category, then an empty string is displayed and a warning is generated.\n * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.\n *\n * # Configuring ngPluralize with offset\n * The `offset` attribute allows further customization of pluralized text, which can result in\n * a better user experience. For example, instead of the message \"4 people are viewing this document\",\n * you might display \"John, Kate and 2 others are viewing this document\".\n * The offset attribute allows you to offset a number by any desired value.\n * Let's take a look at an example:\n *\n * ```html\n * <ng-pluralize count=\"personCount\" offset=2\n *               when=\"{'0': 'Nobody is viewing.',\n *                      '1': '{{person1}} is viewing.',\n *                      '2': '{{person1}} and {{person2}} are viewing.',\n *                      'one': '{{person1}}, {{person2}} and one other person are viewing.',\n *                      'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n * </ng-pluralize>\n * ```\n *\n * Notice that we are still using two plural categories(one, other), but we added\n * three explicit number rules 0, 1 and 2.\n * When one person, perhaps John, views the document, \"John is viewing\" will be shown.\n * When three people view the document, no explicit number rule is found, so\n * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.\n * In this case, plural category 'one' is matched and \"John, Mary and one other person are viewing\"\n * is shown.\n *\n * Note that when you specify offsets, you must provide explicit number rules for\n * numbers from 0 up to and including the offset. If you use an offset of 3, for example,\n * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for\n * plural categories \"one\" and \"other\".\n *\n * @param {string|expression} count The variable to be bound to.\n * @param {string} when The mapping between plural category to its corresponding strings.\n * @param {number=} offset Offset to deduct from the total number.\n *\n * @example\n    <example module=\"pluralizeExample\">\n      <file name=\"index.html\">\n        <script>\n          angular.module('pluralizeExample', [])\n            .controller('ExampleController', ['$scope', function($scope) {\n              $scope.person1 = 'Igor';\n              $scope.person2 = 'Misko';\n              $scope.personCount = 1;\n            }]);\n        </script>\n        <div ng-controller=\"ExampleController\">\n          <label>Person 1:<input type=\"text\" ng-model=\"person1\" value=\"Igor\" /></label><br/>\n          <label>Person 2:<input type=\"text\" ng-model=\"person2\" value=\"Misko\" /></label><br/>\n          <label>Number of People:<input type=\"text\" ng-model=\"personCount\" value=\"1\" /></label><br/>\n\n          <!--- Example with simple pluralization rules for en locale --->\n          Without Offset:\n          <ng-pluralize count=\"personCount\"\n                        when=\"{'0': 'Nobody is viewing.',\n                               'one': '1 person is viewing.',\n                               'other': '{} people are viewing.'}\">\n          </ng-pluralize><br>\n\n          <!--- Example with offset --->\n          With Offset(2):\n          <ng-pluralize count=\"personCount\" offset=2\n                        when=\"{'0': 'Nobody is viewing.',\n                               '1': '{{person1}} is viewing.',\n                               '2': '{{person1}} and {{person2}} are viewing.',\n                               'one': '{{person1}}, {{person2}} and one other person are viewing.',\n                               'other': '{{person1}}, {{person2}} and {} other people are viewing.'}\">\n          </ng-pluralize>\n        </div>\n      </file>\n      <file name=\"protractor.js\" type=\"protractor\">\n        it('should show correct pluralized string', function() {\n          var withoutOffset = element.all(by.css('ng-pluralize')).get(0);\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var countInput = element(by.model('personCount'));\n\n          expect(withoutOffset.getText()).toEqual('1 person is viewing.');\n          expect(withOffset.getText()).toEqual('Igor is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('0');\n\n          expect(withoutOffset.getText()).toEqual('Nobody is viewing.');\n          expect(withOffset.getText()).toEqual('Nobody is viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('2');\n\n          expect(withoutOffset.getText()).toEqual('2 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('3');\n\n          expect(withoutOffset.getText()).toEqual('3 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');\n\n          countInput.clear();\n          countInput.sendKeys('4');\n\n          expect(withoutOffset.getText()).toEqual('4 people are viewing.');\n          expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');\n        });\n        it('should show data-bound names', function() {\n          var withOffset = element.all(by.css('ng-pluralize')).get(1);\n          var personCount = element(by.model('personCount'));\n          var person1 = element(by.model('person1'));\n          var person2 = element(by.model('person2'));\n          personCount.clear();\n          personCount.sendKeys('4');\n          person1.clear();\n          person1.sendKeys('Di');\n          person2.clear();\n          person2.sendKeys('Vojta');\n          expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');\n        });\n      </file>\n    </example>\n */\nvar ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {\n  var BRACE = /{}/g,\n      IS_WHEN = /^when(Minus)?(.+)$/;\n\n  return {\n    link: function(scope, element, attr) {\n      var numberExp = attr.count,\n          whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs\n          offset = attr.offset || 0,\n          whens = scope.$eval(whenExp) || {},\n          whensExpFns = {},\n          startSymbol = $interpolate.startSymbol(),\n          endSymbol = $interpolate.endSymbol(),\n          braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,\n          watchRemover = angular.noop,\n          lastCount;\n\n      forEach(attr, function(expression, attributeName) {\n        var tmpMatch = IS_WHEN.exec(attributeName);\n        if (tmpMatch) {\n          var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);\n          whens[whenKey] = element.attr(attr.$attr[attributeName]);\n        }\n      });\n      forEach(whens, function(expression, key) {\n        whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));\n\n      });\n\n      scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {\n        var count = parseFloat(newVal);\n        var countIsNaN = isNaN(count);\n\n        if (!countIsNaN && !(count in whens)) {\n          // If an explicit number rule such as 1, 2, 3... is defined, just use it.\n          // Otherwise, check it against pluralization rules in $locale service.\n          count = $locale.pluralCat(count - offset);\n        }\n\n        // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.\n        // In JS `NaN !== NaN`, so we have to exlicitly check.\n        if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {\n          watchRemover();\n          var whenExpFn = whensExpFns[count];\n          if (isUndefined(whenExpFn)) {\n            if (newVal != null) {\n              $log.debug(\"ngPluralize: no rule defined for '\" + count + \"' in \" + whenExp);\n            }\n            watchRemover = noop;\n            updateElementText();\n          } else {\n            watchRemover = scope.$watch(whenExpFn, updateElementText);\n          }\n          lastCount = count;\n        }\n      });\n\n      function updateElementText(newText) {\n        element.text(newText || '');\n      }\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngRepeat\n * @multiElement\n *\n * @description\n * The `ngRepeat` directive instantiates a template once per item from a collection. Each template\n * instance gets its own scope, where the given loop variable is set to the current collection item,\n * and `$index` is set to the item index or key.\n *\n * Special properties are exposed on the local scope of each template instance, including:\n *\n * | Variable  | Type            | Details                                                                     |\n * |-----------|-----------------|-----------------------------------------------------------------------------|\n * | `$index`  | {@type number}  | iterator offset of the repeated element (0..length-1)                       |\n * | `$first`  | {@type boolean} | true if the repeated element is first in the iterator.                      |\n * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |\n * | `$last`   | {@type boolean} | true if the repeated element is last in the iterator.                       |\n * | `$even`   | {@type boolean} | true if the iterator position `$index` is even (otherwise false).           |\n * | `$odd`    | {@type boolean} | true if the iterator position `$index` is odd (otherwise false).            |\n *\n * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.\n * This may be useful when, for instance, nesting ngRepeats.\n *\n *\n * # Iterating over object properties\n *\n * It is possible to get `ngRepeat` to iterate over the properties of an object using the following\n * syntax:\n *\n * ```js\n * <div ng-repeat=\"(key, value) in myObj\"> ... </div>\n * ```\n *\n * You need to be aware that the JavaScript specification does not define the order of keys\n * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive\n * used to sort the keys alphabetically.)\n *\n * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser\n * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing\n * keys in the order in which they were defined, although there are exceptions when keys are deleted\n * and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues\n *\n * If this is not desired, the recommended workaround is to convert your object into an array\n * that is sorted into the order that you prefer before providing it to `ngRepeat`.  You could\n * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)\n * or implement a `$watch` on the object yourself.\n *\n *\n * # Tracking and Duplicates\n *\n * When the contents of the collection change, `ngRepeat` makes the corresponding changes to the DOM:\n *\n * * When an item is added, a new instance of the template is added to the DOM.\n * * When an item is removed, its template instance is removed from the DOM.\n * * When items are reordered, their respective templates are reordered in the DOM.\n *\n * By default, `ngRepeat` does not allow duplicate items in arrays. This is because when\n * there are duplicates, it is not possible to maintain a one-to-one mapping between collection\n * items and DOM elements.\n *\n * If you do need to repeat duplicate items, you can substitute the default tracking behavior\n * with your own using the `track by` expression.\n *\n * For example, you may track items by the index of each item in the collection, using the\n * special scope property `$index`:\n * ```html\n *    <div ng-repeat=\"n in [42, 42, 43, 43] track by $index\">\n *      {{n}}\n *    </div>\n * ```\n *\n * You may use arbitrary expressions in `track by`, including references to custom functions\n * on the scope:\n * ```html\n *    <div ng-repeat=\"n in [42, 42, 43, 43] track by myTrackingFunction(n)\">\n *      {{n}}\n *    </div>\n * ```\n *\n * If you are working with objects that have an identifier property, you can track\n * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`\n * will not have to rebuild the DOM elements for items it has already rendered, even if the\n * JavaScript objects in the collection have been substituted for new ones:\n * ```html\n *    <div ng-repeat=\"model in collection track by model.id\">\n *      {{model.name}}\n *    </div>\n * ```\n *\n * When no `track by` expression is provided, it is equivalent to tracking by the built-in\n * `$id` function, which tracks items by their identity:\n * ```html\n *    <div ng-repeat=\"obj in collection track by $id(obj)\">\n *      {{obj.prop}}\n *    </div>\n * ```\n *\n * <div class=\"alert alert-warning\">\n * **Note:** `track by` must always be the last expression:\n * </div>\n * ```\n * <div ng-repeat=\"model in collection | orderBy: 'id' as filtered_result track by model.id\">\n *     {{model.name}}\n * </div>\n * ```\n *\n * # Special repeat start and end points\n * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending\n * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.\n * The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)\n * up to and including the ending HTML tag where **ng-repeat-end** is placed.\n *\n * The example below makes use of this feature:\n * ```html\n *   <header ng-repeat-start=\"item in items\">\n *     Header {{ item }}\n *   </header>\n *   <div class=\"body\">\n *     Body {{ item }}\n *   </div>\n *   <footer ng-repeat-end>\n *     Footer {{ item }}\n *   </footer>\n * ```\n *\n * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:\n * ```html\n *   <header>\n *     Header A\n *   </header>\n *   <div class=\"body\">\n *     Body A\n *   </div>\n *   <footer>\n *     Footer A\n *   </footer>\n *   <header>\n *     Header B\n *   </header>\n *   <div class=\"body\">\n *     Body B\n *   </div>\n *   <footer>\n *     Footer B\n *   </footer>\n * ```\n *\n * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such\n * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).\n *\n * @animations\n * **.enter** - when a new item is added to the list or when an item is revealed after a filter\n *\n * **.leave** - when an item is removed from the list or when an item is filtered out\n *\n * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered\n *\n * @element ANY\n * @scope\n * @priority 1000\n * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These\n *   formats are currently supported:\n *\n *   * `variable in expression` – where variable is the user defined loop variable and `expression`\n *     is a scope expression giving the collection to enumerate.\n *\n *     For example: `album in artist.albums`.\n *\n *   * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,\n *     and `expression` is the scope expression giving the collection to enumerate.\n *\n *     For example: `(name, age) in {'adam':10, 'amalie':12}`.\n *\n *   * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression\n *     which can be used to associate the objects in the collection with the DOM elements. If no tracking expression\n *     is specified, ng-repeat associates elements by identity. It is an error to have\n *     more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are\n *     mapped to the same DOM element, which is not possible.)\n *\n *     Note that the tracking expression must come last, after any filters, and the alias expression.\n *\n *     For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements\n *     will be associated by item identity in the array.\n *\n *     For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique\n *     `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements\n *     with the corresponding item in the array by identity. Moving the same object in array would move the DOM\n *     element in the same way in the DOM.\n *\n *     For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this\n *     case the object identity does not matter. Two objects are considered equivalent as long as their `id`\n *     property is same.\n *\n *     For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter\n *     to items in conjunction with a tracking expression.\n *\n *   * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the\n *     intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message\n *     when a filter is active on the repeater, but the filtered result set is empty.\n *\n *     For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after\n *     the items have been processed through the filter.\n *\n *     Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end\n *     (and not as operator, inside an expression).\n *\n *     For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .\n *\n * @example\n * This example initializes the scope to a list of names and\n * then uses `ngRepeat` to display every person:\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-init=\"friends = [\n        {name:'John', age:25, gender:'boy'},\n        {name:'Jessie', age:30, gender:'girl'},\n        {name:'Johanna', age:28, gender:'girl'},\n        {name:'Joy', age:15, gender:'girl'},\n        {name:'Mary', age:28, gender:'girl'},\n        {name:'Peter', age:95, gender:'boy'},\n        {name:'Sebastian', age:50, gender:'boy'},\n        {name:'Erika', age:27, gender:'girl'},\n        {name:'Patrick', age:40, gender:'boy'},\n        {name:'Samantha', age:60, gender:'girl'}\n      ]\">\n        I have {{friends.length}} friends. They are:\n        <input type=\"search\" ng-model=\"q\" placeholder=\"filter friends...\" aria-label=\"filter friends\" />\n        <ul class=\"example-animate-container\">\n          <li class=\"animate-repeat\" ng-repeat=\"friend in friends | filter:q as results\">\n            [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.\n          </li>\n          <li class=\"animate-repeat\" ng-if=\"results.length == 0\">\n            <strong>No results found...</strong>\n          </li>\n        </ul>\n      </div>\n    </file>\n    <file name=\"animations.css\">\n      .example-animate-container {\n        background:white;\n        border:1px solid black;\n        list-style:none;\n        margin:0;\n        padding:0 10px;\n      }\n\n      .animate-repeat {\n        line-height:40px;\n        list-style:none;\n        box-sizing:border-box;\n      }\n\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter,\n      .animate-repeat.ng-leave {\n        -webkit-transition:all linear 0.5s;\n        transition:all linear 0.5s;\n      }\n\n      .animate-repeat.ng-leave.ng-leave-active,\n      .animate-repeat.ng-move,\n      .animate-repeat.ng-enter {\n        opacity:0;\n        max-height:0;\n      }\n\n      .animate-repeat.ng-leave,\n      .animate-repeat.ng-move.ng-move-active,\n      .animate-repeat.ng-enter.ng-enter-active {\n        opacity:1;\n        max-height:40px;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var friends = element.all(by.repeater('friend in friends'));\n\n      it('should render initial data set', function() {\n        expect(friends.count()).toBe(10);\n        expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');\n        expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');\n        expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');\n        expect(element(by.binding('friends.length')).getText())\n            .toMatch(\"I have 10 friends. They are:\");\n      });\n\n       it('should update repeater when filter predicate changes', function() {\n         expect(friends.count()).toBe(10);\n\n         element(by.model('q')).sendKeys('ma');\n\n         expect(friends.count()).toBe(2);\n         expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');\n         expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');\n       });\n      </file>\n    </example>\n */\nvar ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {\n  var NG_REMOVED = '$$NG_REMOVED';\n  var ngRepeatMinErr = minErr('ngRepeat');\n\n  var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {\n    // TODO(perf): generate setters to shave off ~40ms or 1-1.5%\n    scope[valueIdentifier] = value;\n    if (keyIdentifier) scope[keyIdentifier] = key;\n    scope.$index = index;\n    scope.$first = (index === 0);\n    scope.$last = (index === (arrayLength - 1));\n    scope.$middle = !(scope.$first || scope.$last);\n    // jshint bitwise: false\n    scope.$odd = !(scope.$even = (index&1) === 0);\n    // jshint bitwise: true\n  };\n\n  var getBlockStart = function(block) {\n    return block.clone[0];\n  };\n\n  var getBlockEnd = function(block) {\n    return block.clone[block.clone.length - 1];\n  };\n\n\n  return {\n    restrict: 'A',\n    multiElement: true,\n    transclude: 'element',\n    priority: 1000,\n    terminal: true,\n    $$tlb: true,\n    compile: function ngRepeatCompile($element, $attr) {\n      var expression = $attr.ngRepeat;\n      var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');\n\n      var match = expression.match(/^\\s*([\\s\\S]+?)\\s+in\\s+([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+track\\s+by\\s+([\\s\\S]+?))?\\s*$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iexp', \"Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.\",\n            expression);\n      }\n\n      var lhs = match[1];\n      var rhs = match[2];\n      var aliasAs = match[3];\n      var trackByExp = match[4];\n\n      match = lhs.match(/^(?:(\\s*[\\$\\w]+)|\\(\\s*([\\$\\w]+)\\s*,\\s*([\\$\\w]+)\\s*\\))$/);\n\n      if (!match) {\n        throw ngRepeatMinErr('iidexp', \"'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.\",\n            lhs);\n      }\n      var valueIdentifier = match[3] || match[1];\n      var keyIdentifier = match[2];\n\n      if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||\n          /^(null|undefined|this|\\$index|\\$first|\\$middle|\\$last|\\$even|\\$odd|\\$parent|\\$root|\\$id)$/.test(aliasAs))) {\n        throw ngRepeatMinErr('badident', \"alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.\",\n          aliasAs);\n      }\n\n      var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;\n      var hashFnLocals = {$id: hashKey};\n\n      if (trackByExp) {\n        trackByExpGetter = $parse(trackByExp);\n      } else {\n        trackByIdArrayFn = function(key, value) {\n          return hashKey(value);\n        };\n        trackByIdObjFn = function(key) {\n          return key;\n        };\n      }\n\n      return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {\n\n        if (trackByExpGetter) {\n          trackByIdExpFn = function(key, value, index) {\n            // assign key, value, and $index to the locals so that they can be used in hash functions\n            if (keyIdentifier) hashFnLocals[keyIdentifier] = key;\n            hashFnLocals[valueIdentifier] = value;\n            hashFnLocals.$index = index;\n            return trackByExpGetter($scope, hashFnLocals);\n          };\n        }\n\n        // Store a list of elements from previous run. This is a hash where key is the item from the\n        // iterator, and the value is objects with following properties.\n        //   - scope: bound scope\n        //   - element: previous element.\n        //   - index: position\n        //\n        // We are using no-proto object so that we don't need to guard against inherited props via\n        // hasOwnProperty.\n        var lastBlockMap = createMap();\n\n        //watch props\n        $scope.$watchCollection(rhs, function ngRepeatAction(collection) {\n          var index, length,\n              previousNode = $element[0],     // node that cloned nodes should be inserted after\n                                              // initialized to the comment node anchor\n              nextNode,\n              // Same as lastBlockMap but it has the current state. It will become the\n              // lastBlockMap on the next iteration.\n              nextBlockMap = createMap(),\n              collectionLength,\n              key, value, // key/value of iteration\n              trackById,\n              trackByIdFn,\n              collectionKeys,\n              block,       // last object information {scope, element, id}\n              nextBlockOrder,\n              elementsToRemove;\n\n          if (aliasAs) {\n            $scope[aliasAs] = collection;\n          }\n\n          if (isArrayLike(collection)) {\n            collectionKeys = collection;\n            trackByIdFn = trackByIdExpFn || trackByIdArrayFn;\n          } else {\n            trackByIdFn = trackByIdExpFn || trackByIdObjFn;\n            // if object, extract keys, in enumeration order, unsorted\n            collectionKeys = [];\n            for (var itemKey in collection) {\n              if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {\n                collectionKeys.push(itemKey);\n              }\n            }\n          }\n\n          collectionLength = collectionKeys.length;\n          nextBlockOrder = new Array(collectionLength);\n\n          // locate existing items\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            trackById = trackByIdFn(key, value, index);\n            if (lastBlockMap[trackById]) {\n              // found previously seen block\n              block = lastBlockMap[trackById];\n              delete lastBlockMap[trackById];\n              nextBlockMap[trackById] = block;\n              nextBlockOrder[index] = block;\n            } else if (nextBlockMap[trackById]) {\n              // if collision detected. restore lastBlockMap and throw an error\n              forEach(nextBlockOrder, function(block) {\n                if (block && block.scope) lastBlockMap[block.id] = block;\n              });\n              throw ngRepeatMinErr('dupes',\n                  \"Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}\",\n                  expression, trackById, value);\n            } else {\n              // new never before seen block\n              nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};\n              nextBlockMap[trackById] = true;\n            }\n          }\n\n          // remove leftover items\n          for (var blockKey in lastBlockMap) {\n            block = lastBlockMap[blockKey];\n            elementsToRemove = getBlockNodes(block.clone);\n            $animate.leave(elementsToRemove);\n            if (elementsToRemove[0].parentNode) {\n              // if the element was not removed yet because of pending animation, mark it as deleted\n              // so that we can ignore it later\n              for (index = 0, length = elementsToRemove.length; index < length; index++) {\n                elementsToRemove[index][NG_REMOVED] = true;\n              }\n            }\n            block.scope.$destroy();\n          }\n\n          // we are not using forEach for perf reasons (trying to avoid #call)\n          for (index = 0; index < collectionLength; index++) {\n            key = (collection === collectionKeys) ? index : collectionKeys[index];\n            value = collection[key];\n            block = nextBlockOrder[index];\n\n            if (block.scope) {\n              // if we have already seen this object, then we need to reuse the\n              // associated scope/element\n\n              nextNode = previousNode;\n\n              // skip nodes that are already pending removal via leave animation\n              do {\n                nextNode = nextNode.nextSibling;\n              } while (nextNode && nextNode[NG_REMOVED]);\n\n              if (getBlockStart(block) != nextNode) {\n                // existing item which got moved\n                $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));\n              }\n              previousNode = getBlockEnd(block);\n              updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n            } else {\n              // new item which we don't know about\n              $transclude(function ngRepeatTransclude(clone, scope) {\n                block.scope = scope;\n                // http://jsperf.com/clone-vs-createcomment\n                var endNode = ngRepeatEndComment.cloneNode(false);\n                clone[clone.length++] = endNode;\n\n                // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?\n                $animate.enter(clone, null, jqLite(previousNode));\n                previousNode = endNode;\n                // Note: We only need the first/last node of the cloned nodes.\n                // However, we need to keep the reference to the jqlite wrapper as it might be changed later\n                // by a directive with templateUrl when its template arrives.\n                block.clone = clone;\n                nextBlockMap[block.id] = block;\n                updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);\n              });\n            }\n          }\n          lastBlockMap = nextBlockMap;\n        });\n      };\n    }\n  };\n}];\n\nvar NG_HIDE_CLASS = 'ng-hide';\nvar NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';\n/**\n * @ngdoc directive\n * @name ngShow\n * @multiElement\n *\n * @description\n * The `ngShow` directive shows or hides the given HTML element based on the expression\n * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding\n * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is visible) -->\n * <div ng-show=\"myValue\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is hidden) -->\n * <div ng-show=\"myValue\" class=\"ng-hide\"></div>\n * ```\n *\n * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope\n * with extra animation classes that can be added.\n *\n * ```css\n * .ng-hide:not(.ng-hide-animate) {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngShow`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass except that\n * you must also include the !important flag to override the display property\n * so that you can perform an animation when the element is hidden during the time of the animation.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   /&#42; this is required as of 1.3x to properly\n *      apply all styling in a show/hide animation &#42;/\n *   transition: 0s linear all;\n * }\n *\n * .my-element.ng-hide-add-active,\n * .my-element.ng-hide-remove-active {\n *   /&#42; the transition is defined in the active class &#42;/\n *   transition: 1s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible\n * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden\n *\n * @element ANY\n * @param {expression} ngShow If the {@link guide/expression expression} is truthy\n *     then the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\" aria-label=\"Toggle ngHide\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-show\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-show\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-show {\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-show.ng-hide-add.ng-hide-add-active,\n      .animate-show.ng-hide-remove.ng-hide-remove-active {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n      }\n\n      .animate-show.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngShowDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngShow, function ngShowWatchAction(value) {\n        // we're adding a temporary, animation-specific class for ng-hide since this way\n        // we can control when the element is actually displayed on screen without having\n        // to have a global/greedy CSS selector that breaks when other animations are run.\n        // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845\n        $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n\n/**\n * @ngdoc directive\n * @name ngHide\n * @multiElement\n *\n * @description\n * The `ngHide` directive shows or hides the given HTML element based on the expression\n * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding\n * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined\n * in AngularJS and sets the display style to none (using an !important flag).\n * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).\n *\n * ```html\n * <!-- when $scope.myValue is truthy (element is hidden) -->\n * <div ng-hide=\"myValue\" class=\"ng-hide\"></div>\n *\n * <!-- when $scope.myValue is falsy (element is visible) -->\n * <div ng-hide=\"myValue\"></div>\n * ```\n *\n * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class\n * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed\n * from the element causing the element not to appear hidden.\n *\n * ## Why is !important used?\n *\n * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector\n * can be easily overridden by heavier selectors. For example, something as simple\n * as changing the display style on a HTML list item would make hidden elements appear visible.\n * This also becomes a bigger issue when dealing with CSS frameworks.\n *\n * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector\n * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the\n * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.\n *\n * ### Overriding `.ng-hide`\n *\n * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change\n * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`\n * class in CSS:\n *\n * ```css\n * .ng-hide {\n *   /&#42; this is just another form of hiding an element &#42;/\n *   display: block!important;\n *   position: absolute;\n *   top: -9999px;\n *   left: -9999px;\n * }\n * ```\n *\n * By default you don't need to override in CSS anything and the animations will work around the display style.\n *\n * ## A note about animations with `ngHide`\n *\n * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression\n * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`\n * CSS class is added and removed for you instead of your own CSS class.\n *\n * ```css\n * //\n * //a working example can be found at the bottom of this page\n * //\n * .my-element.ng-hide-add, .my-element.ng-hide-remove {\n *   transition: 0.5s linear all;\n * }\n *\n * .my-element.ng-hide-add { ... }\n * .my-element.ng-hide-add.ng-hide-add-active { ... }\n * .my-element.ng-hide-remove { ... }\n * .my-element.ng-hide-remove.ng-hide-remove-active { ... }\n * ```\n *\n * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display\n * property to block during animation states--ngAnimate will handle the style toggling automatically for you.\n *\n * @animations\n * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden\n * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible\n *\n * @element ANY\n * @param {expression} ngHide If the {@link guide/expression expression} is truthy then\n *     the element is shown or hidden respectively.\n *\n * @example\n  <example module=\"ngAnimate\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      Click me: <input type=\"checkbox\" ng-model=\"checked\" aria-label=\"Toggle ngShow\"><br/>\n      <div>\n        Show:\n        <div class=\"check-element animate-hide\" ng-show=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-up\"></span> I show up when your checkbox is checked.\n        </div>\n      </div>\n      <div>\n        Hide:\n        <div class=\"check-element animate-hide\" ng-hide=\"checked\">\n          <span class=\"glyphicon glyphicon-thumbs-down\"></span> I hide when your checkbox is checked.\n        </div>\n      </div>\n    </file>\n    <file name=\"glyphicons.css\">\n      @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);\n    </file>\n    <file name=\"animations.css\">\n      .animate-hide {\n        -webkit-transition: all linear 0.5s;\n        transition: all linear 0.5s;\n        line-height: 20px;\n        opacity: 1;\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n\n      .animate-hide.ng-hide {\n        line-height: 0;\n        opacity: 0;\n        padding: 0 10px;\n      }\n\n      .check-element {\n        padding: 10px;\n        border: 1px solid black;\n        background: white;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));\n      var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));\n\n      it('should check ng-show / ng-hide', function() {\n        expect(thumbsUp.isDisplayed()).toBeFalsy();\n        expect(thumbsDown.isDisplayed()).toBeTruthy();\n\n        element(by.model('checked')).click();\n\n        expect(thumbsUp.isDisplayed()).toBeTruthy();\n        expect(thumbsDown.isDisplayed()).toBeFalsy();\n      });\n    </file>\n  </example>\n */\nvar ngHideDirective = ['$animate', function($animate) {\n  return {\n    restrict: 'A',\n    multiElement: true,\n    link: function(scope, element, attr) {\n      scope.$watch(attr.ngHide, function ngHideWatchAction(value) {\n        // The comment inside of the ngShowDirective explains why we add and\n        // remove a temporary class for the show/hide animation\n        $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {\n          tempClasses: NG_HIDE_IN_PROGRESS_CLASS\n        });\n      });\n    }\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name ngStyle\n * @restrict AC\n *\n * @description\n * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.\n *\n * @element ANY\n * @param {expression} ngStyle\n *\n * {@link guide/expression Expression} which evals to an\n * object whose keys are CSS style names and values are corresponding values for those CSS\n * keys.\n *\n * Since some CSS style names are not valid keys for an object, they must be quoted.\n * See the 'background-color' style in the example below.\n *\n * @example\n   <example>\n     <file name=\"index.html\">\n        <input type=\"button\" value=\"set color\" ng-click=\"myStyle={color:'red'}\">\n        <input type=\"button\" value=\"set background\" ng-click=\"myStyle={'background-color':'blue'}\">\n        <input type=\"button\" value=\"clear\" ng-click=\"myStyle={}\">\n        <br/>\n        <span ng-style=\"myStyle\">Sample Text</span>\n        <pre>myStyle={{myStyle}}</pre>\n     </file>\n     <file name=\"style.css\">\n       span {\n         color: black;\n       }\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n       var colorSpan = element(by.css('span'));\n\n       it('should check ng-style', function() {\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n         element(by.css('input[value=\\'set color\\']')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');\n         element(by.css('input[value=clear]')).click();\n         expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');\n       });\n     </file>\n   </example>\n */\nvar ngStyleDirective = ngDirective(function(scope, element, attr) {\n  scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {\n    if (oldStyles && (newStyles !== oldStyles)) {\n      forEach(oldStyles, function(val, style) { element.css(style, '');});\n    }\n    if (newStyles) element.css(newStyles);\n  }, true);\n});\n\n/**\n * @ngdoc directive\n * @name ngSwitch\n * @restrict EA\n *\n * @description\n * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.\n * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location\n * as specified in the template.\n *\n * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it\n * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element\n * matches the value obtained from the evaluated expression. In other words, you define a container element\n * (where you place the directive), place an expression on the **`on=\"...\"` attribute**\n * (or the **`ng-switch=\"...\"` attribute**), define any inner elements inside of the directive and place\n * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on\n * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default\n * attribute is displayed.\n *\n * <div class=\"alert alert-info\">\n * Be aware that the attribute values to match against cannot be expressions. They are interpreted\n * as literal string values to match against.\n * For example, **`ng-switch-when=\"someVal\"`** will match against the string `\"someVal\"` not against the\n * value of the expression `$scope.someVal`.\n * </div>\n\n * @animations\n * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container\n * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM\n *\n * @usage\n *\n * ```\n * <ANY ng-switch=\"expression\">\n *   <ANY ng-switch-when=\"matchValue1\">...</ANY>\n *   <ANY ng-switch-when=\"matchValue2\">...</ANY>\n *   <ANY ng-switch-default>...</ANY>\n * </ANY>\n * ```\n *\n *\n * @scope\n * @priority 1200\n * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.\n * On child elements add:\n *\n * * `ngSwitchWhen`: the case statement to match against. If match then this\n *   case will be displayed. If the same match appears multiple times, all the\n *   elements will be displayed.\n * * `ngSwitchDefault`: the default case when no other case match. If there\n *   are multiple default cases, all of them will be displayed when no other\n *   case match.\n *\n *\n * @example\n  <example module=\"switchExample\" deps=\"angular-animate.js\" animations=\"true\">\n    <file name=\"index.html\">\n      <div ng-controller=\"ExampleController\">\n        <select ng-model=\"selection\" ng-options=\"item for item in items\">\n        </select>\n        <code>selection={{selection}}</code>\n        <hr/>\n        <div class=\"animate-switch-container\"\n          ng-switch on=\"selection\">\n            <div class=\"animate-switch\" ng-switch-when=\"settings\">Settings Div</div>\n            <div class=\"animate-switch\" ng-switch-when=\"home\">Home Span</div>\n            <div class=\"animate-switch\" ng-switch-default>default</div>\n        </div>\n      </div>\n    </file>\n    <file name=\"script.js\">\n      angular.module('switchExample', ['ngAnimate'])\n        .controller('ExampleController', ['$scope', function($scope) {\n          $scope.items = ['settings', 'home', 'other'];\n          $scope.selection = $scope.items[0];\n        }]);\n    </file>\n    <file name=\"animations.css\">\n      .animate-switch-container {\n        position:relative;\n        background:white;\n        border:1px solid black;\n        height:40px;\n        overflow:hidden;\n      }\n\n      .animate-switch {\n        padding:10px;\n      }\n\n      .animate-switch.ng-animate {\n        -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n        transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;\n\n        position:absolute;\n        top:0;\n        left:0;\n        right:0;\n        bottom:0;\n      }\n\n      .animate-switch.ng-leave.ng-leave-active,\n      .animate-switch.ng-enter {\n        top:-50px;\n      }\n      .animate-switch.ng-leave,\n      .animate-switch.ng-enter.ng-enter-active {\n        top:0;\n      }\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      var switchElem = element(by.css('[ng-switch]'));\n      var select = element(by.model('selection'));\n\n      it('should start in settings', function() {\n        expect(switchElem.getText()).toMatch(/Settings Div/);\n      });\n      it('should change to home', function() {\n        select.all(by.css('option')).get(1).click();\n        expect(switchElem.getText()).toMatch(/Home Span/);\n      });\n      it('should select default', function() {\n        select.all(by.css('option')).get(2).click();\n        expect(switchElem.getText()).toMatch(/default/);\n      });\n    </file>\n  </example>\n */\nvar ngSwitchDirective = ['$animate', function($animate) {\n  return {\n    require: 'ngSwitch',\n\n    // asks for $scope to fool the BC controller module\n    controller: ['$scope', function ngSwitchController() {\n     this.cases = {};\n    }],\n    link: function(scope, element, attr, ngSwitchController) {\n      var watchExpr = attr.ngSwitch || attr.on,\n          selectedTranscludes = [],\n          selectedElements = [],\n          previousLeaveAnimations = [],\n          selectedScopes = [];\n\n      var spliceFactory = function(array, index) {\n          return function() { array.splice(index, 1); };\n      };\n\n      scope.$watch(watchExpr, function ngSwitchWatchAction(value) {\n        var i, ii;\n        for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {\n          $animate.cancel(previousLeaveAnimations[i]);\n        }\n        previousLeaveAnimations.length = 0;\n\n        for (i = 0, ii = selectedScopes.length; i < ii; ++i) {\n          var selected = getBlockNodes(selectedElements[i].clone);\n          selectedScopes[i].$destroy();\n          var promise = previousLeaveAnimations[i] = $animate.leave(selected);\n          promise.then(spliceFactory(previousLeaveAnimations, i));\n        }\n\n        selectedElements.length = 0;\n        selectedScopes.length = 0;\n\n        if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {\n          forEach(selectedTranscludes, function(selectedTransclude) {\n            selectedTransclude.transclude(function(caseElement, selectedScope) {\n              selectedScopes.push(selectedScope);\n              var anchor = selectedTransclude.element;\n              caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');\n              var block = { clone: caseElement };\n\n              selectedElements.push(block);\n              $animate.enter(caseElement, anchor.parent(), anchor);\n            });\n          });\n        }\n      });\n    }\n  };\n}];\n\nvar ngSwitchWhenDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attrs, ctrl, $transclude) {\n    ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);\n    ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });\n  }\n});\n\nvar ngSwitchDefaultDirective = ngDirective({\n  transclude: 'element',\n  priority: 1200,\n  require: '^ngSwitch',\n  multiElement: true,\n  link: function(scope, element, attr, ctrl, $transclude) {\n    ctrl.cases['?'] = (ctrl.cases['?'] || []);\n    ctrl.cases['?'].push({ transclude: $transclude, element: element });\n   }\n});\n\n/**\n * @ngdoc directive\n * @name ngTransclude\n * @restrict EAC\n *\n * @description\n * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.\n *\n * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.\n *\n * @element ANY\n *\n * @example\n   <example module=\"transcludeExample\">\n     <file name=\"index.html\">\n       <script>\n         angular.module('transcludeExample', [])\n          .directive('pane', function(){\n             return {\n               restrict: 'E',\n               transclude: true,\n               scope: { title:'@' },\n               template: '<div style=\"border: 1px solid black;\">' +\n                           '<div style=\"background-color: gray\">{{title}}</div>' +\n                           '<ng-transclude></ng-transclude>' +\n                         '</div>'\n             };\n         })\n         .controller('ExampleController', ['$scope', function($scope) {\n           $scope.title = 'Lorem Ipsum';\n           $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';\n         }]);\n       </script>\n       <div ng-controller=\"ExampleController\">\n         <input ng-model=\"title\" aria-label=\"title\"> <br/>\n         <textarea ng-model=\"text\" aria-label=\"text\"></textarea> <br/>\n         <pane title=\"{{title}}\">{{text}}</pane>\n       </div>\n     </file>\n     <file name=\"protractor.js\" type=\"protractor\">\n        it('should have transcluded', function() {\n          var titleElement = element(by.model('title'));\n          titleElement.clear();\n          titleElement.sendKeys('TITLE');\n          var textElement = element(by.model('text'));\n          textElement.clear();\n          textElement.sendKeys('TEXT');\n          expect(element(by.binding('title')).getText()).toEqual('TITLE');\n          expect(element(by.binding('text')).getText()).toEqual('TEXT');\n        });\n     </file>\n   </example>\n *\n */\nvar ngTranscludeDirective = ngDirective({\n  restrict: 'EAC',\n  link: function($scope, $element, $attrs, controller, $transclude) {\n    if (!$transclude) {\n      throw minErr('ngTransclude')('orphan',\n       'Illegal use of ngTransclude directive in the template! ' +\n       'No parent directive that requires a transclusion found. ' +\n       'Element: {0}',\n       startingTag($element));\n    }\n\n    $transclude(function(clone) {\n      $element.empty();\n      $element.append(clone);\n    });\n  }\n});\n\n/**\n * @ngdoc directive\n * @name script\n * @restrict E\n *\n * @description\n * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the\n * template can be used by {@link ng.directive:ngInclude `ngInclude`},\n * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the\n * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be\n * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.\n *\n * @param {string} type Must be set to `'text/ng-template'`.\n * @param {string} id Cache name of the template.\n *\n * @example\n  <example>\n    <file name=\"index.html\">\n      <script type=\"text/ng-template\" id=\"/tpl.html\">\n        Content of the template.\n      </script>\n\n      <a ng-click=\"currentTpl='/tpl.html'\" id=\"tpl-link\">Load inlined template</a>\n      <div id=\"tpl-content\" ng-include src=\"currentTpl\"></div>\n    </file>\n    <file name=\"protractor.js\" type=\"protractor\">\n      it('should load template defined inside script tag', function() {\n        element(by.css('#tpl-link')).click();\n        expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);\n      });\n    </file>\n  </example>\n */\nvar scriptDirective = ['$templateCache', function($templateCache) {\n  return {\n    restrict: 'E',\n    terminal: true,\n    compile: function(element, attr) {\n      if (attr.type == 'text/ng-template') {\n        var templateUrl = attr.id,\n            text = element[0].text;\n\n        $templateCache.put(templateUrl, text);\n      }\n    }\n  };\n}];\n\nvar noopNgModelController = { $setViewValue: noop, $render: noop };\n\n/**\n * @ngdoc type\n * @name  select.SelectController\n * @description\n * The controller for the `<select>` directive. This provides support for reading\n * and writing the selected value(s) of the control and also coordinates dynamically\n * added `<option>` elements, perhaps by an `ngRepeat` directive.\n */\nvar SelectController =\n        ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {\n\n  var self = this,\n      optionsMap = new HashMap();\n\n  // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors\n  self.ngModelCtrl = noopNgModelController;\n\n  // The \"unknown\" option is one that is prepended to the list if the viewValue\n  // does not match any of the options. When it is rendered the value of the unknown\n  // option is '? XXX ?' where XXX is the hashKey of the value that is not known.\n  //\n  // We can't just jqLite('<option>') since jqLite is not smart enough\n  // to create it in <select> and IE barfs otherwise.\n  self.unknownOption = jqLite(document.createElement('option'));\n  self.renderUnknownOption = function(val) {\n    var unknownVal = '? ' + hashKey(val) + ' ?';\n    self.unknownOption.val(unknownVal);\n    $element.prepend(self.unknownOption);\n    $element.val(unknownVal);\n  };\n\n  $scope.$on('$destroy', function() {\n    // disable unknown option so that we don't do work when the whole select is being destroyed\n    self.renderUnknownOption = noop;\n  });\n\n  self.removeUnknownOption = function() {\n    if (self.unknownOption.parent()) self.unknownOption.remove();\n  };\n\n\n  // Read the value of the select control, the implementation of this changes depending\n  // upon whether the select can have multiple values and whether ngOptions is at work.\n  self.readValue = function readSingleValue() {\n    self.removeUnknownOption();\n    return $element.val();\n  };\n\n\n  // Write the value to the select control, the implementation of this changes depending\n  // upon whether the select can have multiple values and whether ngOptions is at work.\n  self.writeValue = function writeSingleValue(value) {\n    if (self.hasOption(value)) {\n      self.removeUnknownOption();\n      $element.val(value);\n      if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy\n    } else {\n      if (value == null && self.emptyOption) {\n        self.removeUnknownOption();\n        $element.val('');\n      } else {\n        self.renderUnknownOption(value);\n      }\n    }\n  };\n\n\n  // Tell the select control that an option, with the given value, has been added\n  self.addOption = function(value, element) {\n    assertNotHasOwnProperty(value, '\"option value\"');\n    if (value === '') {\n      self.emptyOption = element;\n    }\n    var count = optionsMap.get(value) || 0;\n    optionsMap.put(value, count + 1);\n  };\n\n  // Tell the select control that an option, with the given value, has been removed\n  self.removeOption = function(value) {\n    var count = optionsMap.get(value);\n    if (count) {\n      if (count === 1) {\n        optionsMap.remove(value);\n        if (value === '') {\n          self.emptyOption = undefined;\n        }\n      } else {\n        optionsMap.put(value, count - 1);\n      }\n    }\n  };\n\n  // Check whether the select control has an option matching the given value\n  self.hasOption = function(value) {\n    return !!optionsMap.get(value);\n  };\n}];\n\n/**\n * @ngdoc directive\n * @name select\n * @restrict E\n *\n * @description\n * HTML `SELECT` element with angular data-binding.\n *\n * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions\n * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits such as reducing\n * memory and increasing speed by not creating a new scope for each repeated instance, as well as providing\n * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the\n * comprehension expression.\n *\n * When an item in the `<select>` menu is selected, the array element or object property\n * represented by the selected option will be bound to the model identified by the `ngModel`\n * directive.\n *\n * If the viewValue contains a value that doesn't match any of the options then the control\n * will automatically add an \"unknown\" option, which it then removes when this is resolved.\n *\n * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can\n * be nested into the `<select>` element. This element will then represent the `null` or \"not selected\"\n * option. See example below for demonstration.\n *\n * <div class=\"alert alert-info\">\n * The value of a `select` directive used without `ngOptions` is always a string.\n * When the model needs to be bound to a non-string value, you must either explictly convert it\n * using a directive (see example below) or use `ngOptions` to specify the set of options.\n * This is because an option element can only be bound to string values at present.\n * </div>\n *\n * ### Example (binding `select` to a non-string value)\n *\n * <example name=\"select-with-non-string-options\" module=\"nonStringSelect\">\n *   <file name=\"index.html\">\n *     <select ng-model=\"model.id\" convert-to-number>\n *       <option value=\"0\">Zero</option>\n *       <option value=\"1\">One</option>\n *       <option value=\"2\">Two</option>\n *     </select>\n *     {{ model }}\n *   </file>\n *   <file name=\"app.js\">\n *     angular.module('nonStringSelect', [])\n *       .run(function($rootScope) {\n *         $rootScope.model = { id: 2 };\n *       })\n *       .directive('convertToNumber', function() {\n *         return {\n *           require: 'ngModel',\n *           link: function(scope, element, attrs, ngModel) {\n *             ngModel.$parsers.push(function(val) {\n *               return parseInt(val, 10);\n *             });\n *             ngModel.$formatters.push(function(val) {\n *               return '' + val;\n *             });\n *           }\n *         };\n *       });\n *   </file>\n *   <file name=\"protractor.js\" type=\"protractor\">\n *     it('should initialize to model', function() {\n *       var select = element(by.css('select'));\n *       expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');\n *     });\n *   </file>\n * </example>\n *\n */\nvar selectDirective = function() {\n\n  return {\n    restrict: 'E',\n    require: ['select', '?ngModel'],\n    controller: SelectController,\n    link: function(scope, element, attr, ctrls) {\n\n      // if ngModel is not defined, we don't need to do anything\n      var ngModelCtrl = ctrls[1];\n      if (!ngModelCtrl) return;\n\n      var selectCtrl = ctrls[0];\n\n      selectCtrl.ngModelCtrl = ngModelCtrl;\n\n      // We delegate rendering to the `writeValue` method, which can be changed\n      // if the select can have multiple selected values or if the options are being\n      // generated by `ngOptions`\n      ngModelCtrl.$render = function() {\n        selectCtrl.writeValue(ngModelCtrl.$viewValue);\n      };\n\n      // When the selected item(s) changes we delegate getting the value of the select control\n      // to the `readValue` method, which can be changed if the select can have multiple\n      // selected values or if the options are being generated by `ngOptions`\n      element.on('change', function() {\n        scope.$apply(function() {\n          ngModelCtrl.$setViewValue(selectCtrl.readValue());\n        });\n      });\n\n      // If the select allows multiple values then we need to modify how we read and write\n      // values from and to the control; also what it means for the value to be empty and\n      // we have to add an extra watch since ngModel doesn't work well with arrays - it\n      // doesn't trigger rendering if only an item in the array changes.\n      if (attr.multiple) {\n\n        // Read value now needs to check each option to see if it is selected\n        selectCtrl.readValue = function readMultipleValue() {\n          var array = [];\n          forEach(element.find('option'), function(option) {\n            if (option.selected) {\n              array.push(option.value);\n            }\n          });\n          return array;\n        };\n\n        // Write value now needs to set the selected property of each matching option\n        selectCtrl.writeValue = function writeMultipleValue(value) {\n          var items = new HashMap(value);\n          forEach(element.find('option'), function(option) {\n            option.selected = isDefined(items.get(option.value));\n          });\n        };\n\n        // we have to do it on each watch since ngModel watches reference, but\n        // we need to work of an array, so we need to see if anything was inserted/removed\n        var lastView, lastViewRef = NaN;\n        scope.$watch(function selectMultipleWatch() {\n          if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {\n            lastView = shallowCopy(ngModelCtrl.$viewValue);\n            ngModelCtrl.$render();\n          }\n          lastViewRef = ngModelCtrl.$viewValue;\n        });\n\n        // If we are a multiple select then value is now a collection\n        // so the meaning of $isEmpty changes\n        ngModelCtrl.$isEmpty = function(value) {\n          return !value || value.length === 0;\n        };\n\n      }\n    }\n  };\n};\n\n\n// The option directive is purely designed to communicate the existence (or lack of)\n// of dynamically created (and destroyed) option elements to their containing select\n// directive via its controller.\nvar optionDirective = ['$interpolate', function($interpolate) {\n\n  function chromeHack(optionElement) {\n    // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459\n    // Adding an <option selected=\"selected\"> element to a <select required=\"required\"> should\n    // automatically select the new element\n    if (optionElement[0].hasAttribute('selected')) {\n      optionElement[0].selected = true;\n    }\n  }\n\n  return {\n    restrict: 'E',\n    priority: 100,\n    compile: function(element, attr) {\n\n      // If the value attribute is not defined then we fall back to the\n      // text content of the option element, which may be interpolated\n      if (isUndefined(attr.value)) {\n        var interpolateFn = $interpolate(element.text(), true);\n        if (!interpolateFn) {\n          attr.$set('value', element.text());\n        }\n      }\n\n      return function(scope, element, attr) {\n\n        // This is an optimization over using ^^ since we don't want to have to search\n        // all the way to the root of the DOM for every single option element\n        var selectCtrlName = '$selectController',\n            parent = element.parent(),\n            selectCtrl = parent.data(selectCtrlName) ||\n              parent.parent().data(selectCtrlName); // in case we are in optgroup\n\n        // Only update trigger option updates if this is an option within a `select`\n        // that also has `ngModel` attached\n        if (selectCtrl && selectCtrl.ngModelCtrl) {\n\n          if (interpolateFn) {\n            scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {\n              attr.$set('value', newVal);\n              if (oldVal !== newVal) {\n                selectCtrl.removeOption(oldVal);\n              }\n              selectCtrl.addOption(newVal, element);\n              selectCtrl.ngModelCtrl.$render();\n              chromeHack(element);\n            });\n          } else {\n            selectCtrl.addOption(attr.value, element);\n            selectCtrl.ngModelCtrl.$render();\n            chromeHack(element);\n          }\n\n          element.on('$destroy', function() {\n            selectCtrl.removeOption(attr.value);\n            selectCtrl.ngModelCtrl.$render();\n          });\n        }\n      };\n    }\n  };\n}];\n\nvar styleDirective = valueFn({\n  restrict: 'E',\n  terminal: false\n});\n\nvar requiredDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n      attr.required = true; // force truthy in case we are on non input element\n\n      ctrl.$validators.required = function(modelValue, viewValue) {\n        return !attr.required || !ctrl.$isEmpty(viewValue);\n      };\n\n      attr.$observe('required', function() {\n        ctrl.$validate();\n      });\n    }\n  };\n};\n\n\nvar patternDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var regexp, patternExp = attr.ngPattern || attr.pattern;\n      attr.$observe('pattern', function(regex) {\n        if (isString(regex) && regex.length > 0) {\n          regex = new RegExp('^' + regex + '$');\n        }\n\n        if (regex && !regex.test) {\n          throw minErr('ngPattern')('noregexp',\n            'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,\n            regex, startingTag(elm));\n        }\n\n        regexp = regex || undefined;\n        ctrl.$validate();\n      });\n\n      ctrl.$validators.pattern = function(value) {\n        return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);\n      };\n    }\n  };\n};\n\n\nvar maxlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var maxlength = -1;\n      attr.$observe('maxlength', function(value) {\n        var intVal = toInt(value);\n        maxlength = isNaN(intVal) ? -1 : intVal;\n        ctrl.$validate();\n      });\n      ctrl.$validators.maxlength = function(modelValue, viewValue) {\n        return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);\n      };\n    }\n  };\n};\n\nvar minlengthDirective = function() {\n  return {\n    restrict: 'A',\n    require: '?ngModel',\n    link: function(scope, elm, attr, ctrl) {\n      if (!ctrl) return;\n\n      var minlength = 0;\n      attr.$observe('minlength', function(value) {\n        minlength = toInt(value) || 0;\n        ctrl.$validate();\n      });\n      ctrl.$validators.minlength = function(modelValue, viewValue) {\n        return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;\n      };\n    }\n  };\n};\n\nif (window.angular.bootstrap) {\n  //AngularJS is already loaded, so we can return here...\n  console.log('WARNING: Tried to load angular more than once.');\n  return;\n}\n\n//try to bind to jquery now so that one can write jqLite(document).ready()\n//but we will rebind on bootstrap again.\nbindJQuery();\n\npublishExternalAPI(angular);\n\nangular.module(\"ngLocale\", [], [\"$provide\", function($provide) {\nvar PLURAL_CATEGORY = {ZERO: \"zero\", ONE: \"one\", TWO: \"two\", FEW: \"few\", MANY: \"many\", OTHER: \"other\"};\nfunction getDecimals(n) {\n  n = n + '';\n  var i = n.indexOf('.');\n  return (i == -1) ? 0 : n.length - i - 1;\n}\n\nfunction getVF(n, opt_precision) {\n  var v = opt_precision;\n\n  if (undefined === v) {\n    v = Math.min(getDecimals(n), 3);\n  }\n\n  var base = Math.pow(10, v);\n  var f = ((n * base) | 0) % base;\n  return {v: v, f: f};\n}\n\n$provide.value(\"$locale\", {\n  \"DATETIME_FORMATS\": {\n    \"AMPMS\": [\n      \"AM\",\n      \"PM\"\n    ],\n    \"DAY\": [\n      \"Sunday\",\n      \"Monday\",\n      \"Tuesday\",\n      \"Wednesday\",\n      \"Thursday\",\n      \"Friday\",\n      \"Saturday\"\n    ],\n    \"ERANAMES\": [\n      \"Before Christ\",\n      \"Anno Domini\"\n    ],\n    \"ERAS\": [\n      \"BC\",\n      \"AD\"\n    ],\n    \"FIRSTDAYOFWEEK\": 6,\n    \"MONTH\": [\n      \"January\",\n      \"February\",\n      \"March\",\n      \"April\",\n      \"May\",\n      \"June\",\n      \"July\",\n      \"August\",\n      \"September\",\n      \"October\",\n      \"November\",\n      \"December\"\n    ],\n    \"SHORTDAY\": [\n      \"Sun\",\n      \"Mon\",\n      \"Tue\",\n      \"Wed\",\n      \"Thu\",\n      \"Fri\",\n      \"Sat\"\n    ],\n    \"SHORTMONTH\": [\n      \"Jan\",\n      \"Feb\",\n      \"Mar\",\n      \"Apr\",\n      \"May\",\n      \"Jun\",\n      \"Jul\",\n      \"Aug\",\n      \"Sep\",\n      \"Oct\",\n      \"Nov\",\n      \"Dec\"\n    ],\n    \"WEEKENDRANGE\": [\n      5,\n      6\n    ],\n    \"fullDate\": \"EEEE, MMMM d, y\",\n    \"longDate\": \"MMMM d, y\",\n    \"medium\": \"MMM d, y h:mm:ss a\",\n    \"mediumDate\": \"MMM d, y\",\n    \"mediumTime\": \"h:mm:ss a\",\n    \"short\": \"M/d/yy h:mm a\",\n    \"shortDate\": \"M/d/yy\",\n    \"shortTime\": \"h:mm a\"\n  },\n  \"NUMBER_FORMATS\": {\n    \"CURRENCY_SYM\": \"$\",\n    \"DECIMAL_SEP\": \".\",\n    \"GROUP_SEP\": \",\",\n    \"PATTERNS\": [\n      {\n        \"gSize\": 3,\n        \"lgSize\": 3,\n        \"maxFrac\": 3,\n        \"minFrac\": 0,\n        \"minInt\": 1,\n        \"negPre\": \"-\",\n        \"negSuf\": \"\",\n        \"posPre\": \"\",\n        \"posSuf\": \"\"\n      },\n      {\n        \"gSize\": 3,\n        \"lgSize\": 3,\n        \"maxFrac\": 2,\n        \"minFrac\": 2,\n        \"minInt\": 1,\n        \"negPre\": \"-\\u00a4\",\n        \"negSuf\": \"\",\n        \"posPre\": \"\\u00a4\",\n        \"posSuf\": \"\"\n      }\n    ]\n  },\n  \"id\": \"en-us\",\n  \"pluralCat\": function(n, opt_precision) {  var i = n | 0;  var vf = getVF(n, opt_precision);  if (i == 1 && vf.v == 0) {    return PLURAL_CATEGORY.ONE;  }  return PLURAL_CATEGORY.OTHER;}\n});\n}]);\n\n  jqLite(document).ready(function() {\n    angularInit(document, bootstrap);\n  });\n\n})(window, document);\n\n!window.angular.$$csp().noInlineStyle && window.angular.element(document.head).prepend('<style type=\"text/css\">@charset \"UTF-8\";[ng\\\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide:not(.ng-hide-animate){display:none !important;}ng\\\\:form{display:block;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');"
  },
  {
    "path": "examples/server/php/public/vendor/dist/satellizer.js",
    "content": "(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n    typeof define === 'function' && define.amd ? define(factory) :\n    (global.satellizer = factory());\n}(this, function () { 'use strict';\n\n    var Config = (function () {\n        function Config() {\n            this.baseUrl = '/';\n            this.loginUrl = '/auth/login';\n            this.signupUrl = '/auth/signup';\n            this.unlinkUrl = '/auth/unlink/';\n            this.tokenName = 'token';\n            this.tokenPrefix = 'satellizer';\n            this.tokenHeader = 'Authorization';\n            this.tokenType = 'Bearer';\n            this.storageType = 'localStorage';\n            this.tokenRoot = null;\n            this.withCredentials = false;\n            this.providers = {\n                facebook: {\n                    name: 'facebook',\n                    url: '/auth/facebook',\n                    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ',',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 580, height: 400 }\n                },\n                google: {\n                    name: 'google',\n                    url: '/auth/google',\n                    authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    optionalUrlParams: ['display', 'state'],\n                    scope: ['profile', 'email'],\n                    scopePrefix: 'openid',\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 452, height: 633 },\n                    state: function () { encodeURIComponent(Math.random().toString(36).substr(2)); }\n                },\n                github: {\n                    name: 'github',\n                    url: '/auth/github',\n                    authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['scope'],\n                    scope: ['user:email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1020, height: 618 }\n                },\n                instagram: {\n                    name: 'instagram',\n                    url: '/auth/instagram',\n                    authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['basic'],\n                    scopeDelimiter: '+',\n                    oauthType: '2.0'\n                },\n                linkedin: {\n                    name: 'linkedin',\n                    url: '/auth/linkedin',\n                    authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['state'],\n                    scope: ['r_emailaddress'],\n                    scopeDelimiter: ' ',\n                    state: 'STATE',\n                    oauthType: '2.0',\n                    popupOptions: { width: 527, height: 582 }\n                },\n                twitter: {\n                    name: 'twitter',\n                    url: '/auth/twitter',\n                    authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n                    redirectUri: window.location.origin,\n                    oauthType: '1.0',\n                    popupOptions: { width: 495, height: 645 }\n                },\n                twitch: {\n                    name: 'twitch',\n                    url: '/auth/twitch',\n                    authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['user_read'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                live: {\n                    name: 'live',\n                    url: '/auth/live',\n                    authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['wl.emails'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                yahoo: {\n                    name: 'yahoo',\n                    url: '/auth/yahoo',\n                    authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n                    redirectUri: window.location.origin,\n                    scope: [],\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 559, height: 519 }\n                },\n                bitbucket: {\n                    name: 'bitbucket',\n                    url: '/auth/bitbucket',\n                    authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1028, height: 529 }\n                }\n            };\n            this.httpInterceptor = function () { return true; };\n        }\n        Object.defineProperty(Config, \"getConstant\", {\n            get: function () {\n                return new Config();\n            },\n            enumerable: true,\n            configurable: true\n        });\n        return Config;\n    }());\n    ;\n\n    var AuthProvider = (function () {\n        function AuthProvider(SatellizerConfig) {\n            this.SatellizerConfig = SatellizerConfig;\n        }\n        Object.defineProperty(AuthProvider.prototype, \"baseUrl\", {\n            get: function () { return this.SatellizerConfig.baseUrl; },\n            set: function (value) { this.SatellizerConfig.baseUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"loginUrl\", {\n            get: function () { return this.SatellizerConfig.loginUrl; },\n            set: function (value) { this.SatellizerConfig.loginUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"signupUrl\", {\n            get: function () { return this.SatellizerConfig.signupUrl; },\n            set: function (value) { this.SatellizerConfig.signupUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"unlinkUrl\", {\n            get: function () { return this.SatellizerConfig.unlinkUrl; },\n            set: function (value) { this.SatellizerConfig.unlinkUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenRoot\", {\n            get: function () { return this.SatellizerConfig.tokenRoot; },\n            set: function (value) { this.SatellizerConfig.tokenRoot = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenName\", {\n            get: function () { return this.SatellizerConfig.tokenName; },\n            set: function (value) { this.SatellizerConfig.tokenName = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenPrefix\", {\n            get: function () { return this.SatellizerConfig.tokenPrefix; },\n            set: function (value) { this.SatellizerConfig.tokenPrefix = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenHeader\", {\n            get: function () { return this.SatellizerConfig.tokenHeader; },\n            set: function (value) { this.SatellizerConfig.tokenHeader = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenType\", {\n            get: function () { return this.SatellizerConfig.tokenType; },\n            set: function (value) { this.SatellizerConfig.tokenType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"withCredentials\", {\n            get: function () { return this.SatellizerConfig.withCredentials; },\n            set: function (value) { this.SatellizerConfig.withCredentials = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"storageType\", {\n            get: function () { return this.SatellizerConfig.storageType; },\n            set: function (value) { this.SatellizerConfig.storageType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"httpInterceptor\", {\n            get: function () { return this.SatellizerConfig.httpInterceptor; },\n            set: function (value) {\n                if (typeof value === 'function') {\n                    this.SatellizerConfig.httpInterceptor = value;\n                }\n                else {\n                    this.SatellizerConfig.httpInterceptor = function () { return value; };\n                }\n            },\n            enumerable: true,\n            configurable: true\n        });\n        AuthProvider.prototype.facebook = function (options) {\n            angular.extend(this.SatellizerConfig.providers.facebook, options);\n        };\n        AuthProvider.prototype.google = function (options) {\n            angular.extend(this.SatellizerConfig.providers.google, options);\n        };\n        AuthProvider.prototype.github = function (options) {\n            angular.extend(this.SatellizerConfig.providers.github, options);\n        };\n        AuthProvider.prototype.instagram = function (options) {\n            angular.extend(this.SatellizerConfig.providers.instagram, options);\n        };\n        AuthProvider.prototype.linkedin = function (options) {\n            angular.extend(this.SatellizerConfig.providers.linkedin, options);\n        };\n        AuthProvider.prototype.twitter = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitter, options);\n        };\n        AuthProvider.prototype.twitch = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitch, options);\n        };\n        AuthProvider.prototype.live = function (options) {\n            angular.extend(this.SatellizerConfig.providers.live, options);\n        };\n        AuthProvider.prototype.yahoo = function (options) {\n            angular.extend(this.SatellizerConfig.providers.yahoo, options);\n        };\n        AuthProvider.prototype.bitbucket = function (options) {\n            angular.extend(this.SatellizerConfig.providers.bitbucket, options);\n        };\n        AuthProvider.prototype.oauth1 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '1.0'\n            });\n        };\n        AuthProvider.prototype.oauth2 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '2.0'\n            });\n        };\n        AuthProvider.prototype.$get = function (SatellizerShared, SatellizerLocal, SatellizerOAuth) {\n            return {\n                login: function (user, options) { return SatellizerLocal.login(user, options); },\n                signup: function (user, options) { return SatellizerLocal.signup(user, options); },\n                logout: function () { return SatellizerShared.logout(); },\n                authenticate: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                link: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                unlink: function (name, options) { return SatellizerOAuth.unlink(name, options); },\n                isAuthenticated: function () { return SatellizerShared.isAuthenticated(); },\n                getPayload: function () { return SatellizerShared.getPayload(); },\n                getToken: function () { return SatellizerShared.getToken(); },\n                setToken: function (token) { return SatellizerShared.setToken({ access_token: token }); },\n                removeToken: function () { return SatellizerShared.removeToken(); },\n                setStorageType: function (type) { return SatellizerShared.setStorageType(type); }\n            };\n        };\n        AuthProvider.$inject = ['SatellizerConfig'];\n        return AuthProvider;\n    }());\n\n    function joinUrl(baseUrl, url) {\n        if (/^(?:[a-z]+:)?\\/\\//i.test(url)) {\n            return url;\n        }\n        var joined = [baseUrl, url].join('/');\n        var normalize = function (str) {\n            return str\n                .replace(/[\\/]+/g, '/')\n                .replace(/\\/\\?/g, '?')\n                .replace(/\\/\\#/g, '#')\n                .replace(/\\:\\//g, '://');\n        };\n        return normalize(joined);\n    }\n    function getFullUrlPath(location) {\n        var isHttps = location.protocol === 'https:';\n        return location.protocol + '//' + location.hostname +\n            ':' + (location.port || (isHttps ? '443' : '80')) +\n            (/^\\//.test(location.pathname) ? location.pathname : '/' + location.pathname);\n    }\n    function parseQueryString(str) {\n        var obj = {};\n        var key;\n        var value;\n        angular.forEach((str || '').split('&'), function (keyValue) {\n            if (keyValue) {\n                value = keyValue.split('=');\n                key = decodeURIComponent(value[0]);\n                obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;\n            }\n        });\n        return obj;\n    }\n    function decodeBase64(str) {\n        var buffer;\n        if (typeof module !== 'undefined' && module.exports) {\n            try {\n                buffer = require('buffer').Buffer;\n            }\n            catch (err) {\n            }\n        }\n        var fromCharCode = String.fromCharCode;\n        var re_btou = new RegExp([\n            '[\\xC0-\\xDF][\\x80-\\xBF]',\n            '[\\xE0-\\xEF][\\x80-\\xBF]{2}',\n            '[\\xF0-\\xF7][\\x80-\\xBF]{3}'\n        ].join('|'), 'g');\n        var cb_btou = function (cccc) {\n            switch (cccc.length) {\n                case 4:\n                    var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n                        | ((0x3f & cccc.charCodeAt(1)) << 12)\n                        | ((0x3f & cccc.charCodeAt(2)) << 6)\n                        | (0x3f & cccc.charCodeAt(3));\n                    var offset = cp - 0x10000;\n                    return (fromCharCode((offset >>> 10) + 0xD800)\n                        + fromCharCode((offset & 0x3FF) + 0xDC00));\n                case 3:\n                    return fromCharCode(((0x0f & cccc.charCodeAt(0)) << 12)\n                        | ((0x3f & cccc.charCodeAt(1)) << 6)\n                        | (0x3f & cccc.charCodeAt(2)));\n                default:\n                    return fromCharCode(((0x1f & cccc.charCodeAt(0)) << 6)\n                        | (0x3f & cccc.charCodeAt(1)));\n            }\n        };\n        var btou = function (b) {\n            return b.replace(re_btou, cb_btou);\n        };\n        var _decode = buffer ? function (a) {\n            return (a.constructor === buffer.constructor\n                ? a : new buffer(a, 'base64')).toString();\n        }\n            : function (a) {\n                return btou(atob(a));\n            };\n        return _decode(String(str).replace(/[-_]/g, function (m0) {\n            return m0 === '-' ? '+' : '/';\n        })\n            .replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n    }\n\n    var Shared = (function () {\n        function Shared($q, $window, $log, SatellizerConfig, SatellizerStorage) {\n            this.$q = $q;\n            this.$window = $window;\n            this.$log = $log;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerStorage = SatellizerStorage;\n            var _a = this.SatellizerConfig, tokenName = _a.tokenName, tokenPrefix = _a.tokenPrefix;\n            this.prefixedTokenName = tokenPrefix ? [tokenPrefix, tokenName].join('_') : tokenName;\n        }\n        Shared.prototype.getToken = function () {\n            return this.SatellizerStorage.get(this.prefixedTokenName);\n        };\n        Shared.prototype.getPayload = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token && token.split('.').length === 3) {\n                try {\n                    var base64Url = token.split('.')[1];\n                    var base64 = base64Url.replace('-', '+').replace('_', '/');\n                    return JSON.parse(decodeBase64(base64));\n                }\n                catch (e) {\n                }\n            }\n        };\n        Shared.prototype.setToken = function (response) {\n            if (!response) {\n                return this.$log.warn('Can\\'t set token without passing a value');\n            }\n            var token;\n            var accessToken = response && response.access_token;\n            if (accessToken) {\n                if (angular.isObject(accessToken) && angular.isObject(accessToken.data)) {\n                    response = accessToken;\n                }\n                else if (angular.isString(accessToken)) {\n                    token = accessToken;\n                }\n            }\n            if (!token && response) {\n                var tokenRootData = this.SatellizerConfig.tokenRoot && this.SatellizerConfig.tokenRoot.split('.').reduce(function (o, x) { return o[x]; }, response.data);\n                token = tokenRootData ? tokenRootData[this.SatellizerConfig.tokenName] : response.data && response.data[this.SatellizerConfig.tokenName];\n            }\n            if (!token) {\n                var tokenPath = this.SatellizerConfig.tokenRoot ? this.SatellizerConfig.tokenRoot + '.' + this.SatellizerConfig.tokenName : this.SatellizerConfig.tokenName;\n                return this.$log.warn('Expecting a token named \"' + tokenPath);\n            }\n            this.SatellizerStorage.set(this.prefixedTokenName, token);\n        };\n        Shared.prototype.removeToken = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n        };\n        Shared.prototype.isAuthenticated = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token) {\n                if (token.split('.').length === 3) {\n                    try {\n                        var base64Url = token.split('.')[1];\n                        var base64 = base64Url.replace('-', '+').replace('_', '/');\n                        var exp = JSON.parse(this.$window.atob(base64)).exp;\n                        if (exp) {\n                            return (Math.round(new Date().getTime() / 1000) >= exp) ? false : true;\n                        }\n                    }\n                    catch (e) {\n                        return true; // Pass: Non-JWT token that looks like JWT\n                    }\n                }\n                return true; // Pass: All other tokens\n            }\n            return false; // Fail: No token at all\n        };\n        Shared.prototype.logout = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n            return this.$q.when();\n        };\n        Shared.prototype.setStorageType = function (type) {\n            this.SatellizerConfig.storageType = type;\n        };\n        Shared.$inject = ['$q', '$window', '$log', 'SatellizerConfig', 'SatellizerStorage'];\n        return Shared;\n    }());\n\n    var Local = (function () {\n        function Local($http, SatellizerConfig, SatellizerShared) {\n            this.$http = $http;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n        }\n        Local.prototype.login = function (user, options) {\n            var _this = this;\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.loginUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options).then(function (response) {\n                _this.SatellizerShared.setToken(response);\n                return response;\n            });\n        };\n        Local.prototype.signup = function (user, options) {\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.signupUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options);\n        };\n        Local.$inject = ['$http', 'SatellizerConfig', 'SatellizerShared'];\n        return Local;\n    }());\n\n    var Popup = (function () {\n        function Popup($interval, $window) {\n            this.$interval = $interval;\n            this.$window = $window;\n            this.popup = null;\n            this.url = 'about:blank'; // TODO remove\n            this.defaults = {\n                redirectUri: null\n            };\n        }\n        Popup.prototype.stringifyOptions = function (options) {\n            var parts = [];\n            angular.forEach(options, function (value, key) {\n                parts.push(key + '=' + value);\n            });\n            return parts.join(',');\n        };\n        Popup.prototype.open = function (url, name, popupOptions) {\n            this.url = url; // TODO remove\n            var width = popupOptions.width || 500;\n            var height = popupOptions.height || 500;\n            var options = this.stringifyOptions({\n                width: width,\n                height: height,\n                top: this.$window.screenY + ((this.$window.outerHeight - height) / 2.5),\n                left: this.$window.screenX + ((this.$window.outerWidth - width) / 2)\n            });\n            var popupName = this.$window['cordova'] || this.$window.navigator.userAgent.indexOf('CriOS') > -1 ? '_blank' : name;\n            this.popup = window.open(this.url, popupName, options);\n            if (this.popup && this.popup.focus) {\n                this.popup.focus();\n            }\n            //\n            // if (this.$window['cordova']) {\n            //   return this.eventListener(this.defaults.redirectUri); // TODO pass redirect uri\n            // } else {\n            //   return this.polling(redirectUri);\n            // }\n        };\n        Popup.prototype.polling = function (redirectUri) {\n            var _this = this;\n            return new Promise(function (resolve, reject) {\n                var redirectUriParser = document.createElement('a');\n                redirectUriParser.href = redirectUri;\n                var redirectUriPath = getFullUrlPath(redirectUriParser);\n                var polling = _this.$interval(function () {\n                    if (!_this.popup || _this.popup.closed || _this.popup.closed === undefined) {\n                        _this.$interval.cancel(polling);\n                        reject(new Error('The popup window was closed'));\n                    }\n                    try {\n                        var popupWindowPath = getFullUrlPath(_this.popup.location);\n                        if (popupWindowPath === redirectUriPath) {\n                            if (_this.popup.location.search || _this.popup.location.hash) {\n                                var query = parseQueryString(_this.popup.location.search.substring(1).replace(/\\/$/, ''));\n                                var hash = parseQueryString(_this.popup.location.hash.substring(1).replace(/[\\/$]/, ''));\n                                var params = Object.assign({}, query, hash);\n                                if (params.error) {\n                                    reject(new Error(params.error));\n                                }\n                                else {\n                                    resolve(params);\n                                }\n                            }\n                            else {\n                                reject(new Error('OAuth redirect has occurred but no query or hash parameters were found. ' +\n                                    'They were either not set during the redirect, or were removed—typically by a ' +\n                                    'routing library—before Satellizer could read it.'));\n                            }\n                            _this.$interval.cancel(polling);\n                            _this.popup.close();\n                        }\n                    }\n                    catch (error) {\n                    }\n                }, 500);\n            });\n        };\n        Popup.prototype.eventListener = function (redirectUri) {\n            var _this = this;\n            return new Promise(function (resolve, reject) {\n                _this.popup.addEventListener('loadstart', function (event) {\n                    if (!event.url.includes(redirectUri)) {\n                        return;\n                    }\n                    var parser = document.createElement('a');\n                    parser.href = event.url;\n                    if (parser.search || parser.hash) {\n                        var query = parseQueryString(parser.search.substring(1).replace(/\\/$/, ''));\n                        var hash = parseQueryString(parser.hash.substring(1).replace(/[\\/$]/, ''));\n                        var params = Object.assign({}, query, hash);\n                        if (params.error) {\n                            reject(new Error(params.error));\n                        }\n                        else {\n                            resolve(params);\n                        }\n                        _this.popup.close();\n                    }\n                });\n                _this.popup.addEventListener('loaderror', function () {\n                    reject(new Error('Authorization failed'));\n                });\n            });\n        };\n        Popup.$inject = ['$interval', '$window'];\n        return Popup;\n    }());\n\n    var OAuth = (function () {\n        function OAuth($http, SatellizerConfig, SatellizerShared, SatellizerOAuth1, SatellizerOAuth2) {\n            this.$http = $http;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerOAuth1 = SatellizerOAuth1;\n            this.SatellizerOAuth2 = SatellizerOAuth2;\n        }\n        OAuth.prototype.authenticate = function (name, userData) {\n            var _this = this;\n            return new Promise(function (resolve, reject) {\n                var provider = _this.SatellizerConfig.providers[name];\n                var initialize = provider.oauthType === '1.0' ? _this.SatellizerOAuth1.init(provider, userData) : _this.SatellizerOAuth2.init(provider, userData);\n                return initialize.then(function (response) {\n                    if (provider.url) {\n                        _this.SatellizerShared.setToken(response);\n                    }\n                    resolve(response);\n                }).catch(function (error) {\n                    reject(error);\n                });\n            });\n        };\n        OAuth.prototype.unlink = function (provider, httpOptions) {\n            if (httpOptions === void 0) { httpOptions = {}; }\n            httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);\n            httpOptions.data = { provider: provider } || httpOptions.data;\n            httpOptions.method = httpOptions.method || 'POST';\n            httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(httpOptions);\n        };\n        OAuth.$inject = ['$http', 'SatellizerConfig', 'SatellizerShared', 'SatellizerOAuth1', 'SatellizerOAuth2'];\n        return OAuth;\n    }());\n\n    var OAuth2 = (function () {\n        function OAuth2($http, $window, $timeout, SatellizerConfig, SatellizerPopup, SatellizerStorage) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.defaults = {\n                name: null,\n                url: null,\n                clientId: null,\n                authorizationEndpoint: null,\n                redirectUri: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                state: null,\n                requiredUrlParams: null,\n                defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n                responseType: 'code',\n                responseParams: {\n                    code: 'code',\n                    clientId: 'clientId',\n                    redirectUri: 'redirectUri'\n                },\n                oauthType: '2.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        OAuth2.camelCase = function (name) {\n            return name.replace(/([\\:\\-\\_]+(.))/g, function (_, separator, letter, offset) {\n                return offset ? letter.toUpperCase() : letter;\n            });\n        };\n        OAuth2.prototype.init = function (options, userData) {\n            var _this = this;\n            return new Promise(function (resolve, reject) {\n                Object.assign(_this.defaults, options);\n                _this.$timeout(function () {\n                    var url = [_this.defaults.authorizationEndpoint, _this.buildQueryString()].join('?');\n                    var stateName = _this.defaults.name + '_state';\n                    var _a = _this.defaults, name = _a.name, state = _a.state, popupOptions = _a.popupOptions, redirectUri = _a.redirectUri, responseType = _a.responseType;\n                    if (typeof state === 'function') {\n                        _this.SatellizerStorage.set(stateName, state());\n                    }\n                    else if (typeof state === 'string') {\n                        _this.SatellizerStorage.set(stateName, state);\n                    }\n                    _this.SatellizerPopup.open(url, name, popupOptions);\n                    _this.SatellizerPopup.polling(redirectUri).then(function (oauth) {\n                        if (responseType === 'token' || !url) {\n                            return resolve(oauth);\n                        }\n                        if (oauth.state && oauth.state !== _this.SatellizerStorage.get(stateName)) {\n                            return reject(new Error('The value returned in the state parameter does not match the state value from your original ' +\n                                'authorization code request.'));\n                        }\n                        resolve(_this.exchangeForToken(oauth, userData));\n                    })\n                        .catch(function (error) { return reject(error); });\n                });\n            });\n        };\n        OAuth2.prototype.exchangeForToken = function (oauthData, userData) {\n            var _this = this;\n            var payload = Object.assign({}, userData);\n            angular.forEach(this.defaults.responseParams, function (value, key) {\n                switch (key) {\n                    case 'code':\n                        payload[value] = oauthData.code;\n                        break;\n                    case 'clientId':\n                        payload[value] = _this.defaults.clientId;\n                        break;\n                    case 'redirectUri':\n                        payload[value] = _this.defaults.redirectUri;\n                        break;\n                    default:\n                        payload[value] = oauthData[key];\n                }\n            });\n            if (oauthData.state) {\n                payload.state = oauthData.state;\n            }\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ?\n                joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) :\n                this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth2.prototype.buildQueryString = function () {\n            var _this = this;\n            var keyValuePairs = [];\n            var urlParamsCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];\n            angular.forEach(urlParamsCategories, function (paramsCategory) {\n                angular.forEach(_this.defaults[paramsCategory], function (paramName) {\n                    var camelizedName = OAuth2.camelCase(paramName);\n                    var paramValue = angular.isFunction(_this.defaults[paramName]) ? _this.defaults[paramName]() : _this.defaults[camelizedName];\n                    if (paramName === 'redirect_uri' && !paramValue) {\n                        return;\n                    }\n                    if (paramName === 'state') {\n                        var stateName = _this.defaults.name + '_state';\n                        paramValue = encodeURIComponent(_this.SatellizerStorage.get(stateName));\n                    }\n                    if (paramName === 'scope' && Array.isArray(paramValue)) {\n                        paramValue = paramValue.join(_this.defaults.scopeDelimiter);\n                        if (_this.defaults.scopePrefix) {\n                            paramValue = [_this.defaults.scopePrefix, paramValue].join(_this.defaults.scopeDelimiter);\n                        }\n                    }\n                    keyValuePairs.push([paramName, paramValue]);\n                });\n            });\n            return keyValuePairs.map(function (pair) { return pair.join('='); }).join('&');\n        };\n        OAuth2.$inject = ['$http', '$window', '$timeout', 'SatellizerConfig', 'SatellizerPopup', 'SatellizerStorage'];\n        return OAuth2;\n    }());\n\n    var OAuth1 = (function () {\n        function OAuth1($http, $window, SatellizerConfig, SatellizerPopup) {\n            this.$http = $http;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.defaults = {\n                name: null,\n                url: null,\n                authorizationEndpoint: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                redirectUri: null,\n                requiredUrlParams: null,\n                defaultUrlParams: null,\n                oauthType: '1.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        ;\n        OAuth1.prototype.init = function (options, userData) {\n            var _this = this;\n            Object.assign(this.defaults, options);\n            if (!this.$window['cordova']) {\n                this.SatellizerPopup.open('about:blank', options.name, options.popupOptions);\n            }\n            return this.getRequestToken().then(function (response) {\n                return _this.openPopup(options, response).then(function (popupResponse) {\n                    return _this.exchangeForToken(popupResponse, userData);\n                });\n            });\n        };\n        OAuth1.prototype.openPopup = function (options, response) {\n            var popupUrl = [options.authorizationEndpoint, this.buildQueryString(response.data)].join('?');\n            if (this.$window['cordova']) {\n                this.SatellizerPopup.open(popupUrl, options.name, options.popupOptions);\n                return this.SatellizerPopup.eventListener(this.defaults.redirectUri);\n            }\n            else {\n                this.SatellizerPopup.popup.location = popupUrl;\n                return this.SatellizerPopup.polling(this.defaults.redirectUri);\n            }\n        };\n        OAuth1.prototype.getRequestToken = function () {\n            var url = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(url, this.defaults);\n        };\n        OAuth1.prototype.exchangeForToken = function (oauthData, userData) {\n            var payload = Object.assign({}, userData, oauthData);\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth1.prototype.buildQueryString = function (obj) {\n            var str = [];\n            angular.forEach(obj, function (value, key) {\n                str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n            });\n            return str.join('&');\n        };\n        OAuth1.$inject = ['$http', '$window', 'SatellizerConfig', 'SatellizerPopup'];\n        return OAuth1;\n    }());\n\n    var Storage = (function () {\n        function Storage($window, SatellizerConfig) {\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.memoryStore = {};\n            this.storageType = SatellizerConfig.storageType;\n        }\n        Storage.prototype.get = function (key) {\n            try {\n                return this.$window[this.storageType].getItem(key);\n            }\n            catch (e) {\n                return this.memoryStore[key];\n            }\n        };\n        Storage.prototype.set = function (key, value) {\n            try {\n                this.$window[this.storageType].setItem(key, value);\n            }\n            catch (e) {\n                this.memoryStore[key] = value;\n            }\n        };\n        Storage.prototype.remove = function (key) {\n            try {\n                this.$window[this.storageType].removeItem(key);\n            }\n            catch (e) {\n                delete this.memoryStore[key];\n            }\n        };\n        Storage.$inject = ['$window', 'SatellizerConfig'];\n        return Storage;\n    }());\n\n    var Interceptor = (function () {\n        function Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            var _this = this;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerStorage = SatellizerStorage;\n            this.request = function (request) {\n                if (request.skipAuthorization) {\n                    return request;\n                }\n                if (_this.SatellizerShared.isAuthenticated() && _this.SatellizerConfig.httpInterceptor()) {\n                    var tokenName = _this.SatellizerConfig.tokenPrefix ?\n                        [_this.SatellizerConfig.tokenPrefix, _this.SatellizerConfig.tokenName].join('_') : _this.SatellizerConfig.tokenName;\n                    var token = _this.SatellizerStorage.get(tokenName);\n                    if (_this.SatellizerConfig.tokenHeader && _this.SatellizerConfig.tokenType) {\n                        token = _this.SatellizerConfig.tokenType + ' ' + token;\n                    }\n                    request.headers[_this.SatellizerConfig.tokenHeader] = token;\n                }\n                return request;\n            };\n        }\n        Interceptor.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n        return Interceptor;\n    }());\n\n    var HttpProviderConfig = (function () {\n        function HttpProviderConfig($httpProvider) {\n            this.$httpProvider = $httpProvider;\n            $httpProvider.interceptors.push('SatellizerInterceptor');\n        }\n        HttpProviderConfig.$inject = ['$httpProvider'];\n        return HttpProviderConfig;\n    }());\n\n    angular.module('satellizer', [])\n        .provider('$auth', ['SatellizerConfig', function (SatellizerConfig) { return new AuthProvider(SatellizerConfig); }])\n        .constant('SatellizerConfig', Config.getConstant)\n        .service('SatellizerShared', Shared)\n        .service('SatellizerLocal', Local)\n        .service('SatellizerPopup', Popup)\n        .service('SatellizerOAuth', OAuth)\n        .service('SatellizerOAuth2', OAuth2)\n        .service('SatellizerOAuth1', OAuth1)\n        .service('SatellizerStorage', Storage)\n        .service('SatellizerInterceptor', Interceptor)\n        .config(function ($httpProvider) { return new HttpProviderConfig($httpProvider); });\n    var ng1 = 'satellizer';\n\n    return ng1;\n\n}));"
  },
  {
    "path": "examples/server/php/public/vendor/satellizer.js",
    "content": "/**\n * Satellizer 0.15.5\n * (c) 2016 Sahat Yalkabov \n * License: MIT \n */\n\n(function (global, factory) {\n    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n    typeof define === 'function' && define.amd ? define(factory) :\n    (global.satellizer = factory());\n}(this, function () { 'use strict';\n\n    var Config = (function () {\n        function Config() {\n            this.baseUrl = '/';\n            this.loginUrl = '/auth/login';\n            this.signupUrl = '/auth/signup';\n            this.unlinkUrl = '/auth/unlink/';\n            this.tokenName = 'token';\n            this.tokenPrefix = 'satellizer';\n            this.tokenHeader = 'Authorization';\n            this.tokenType = 'Bearer';\n            this.storageType = 'localStorage';\n            this.tokenRoot = null;\n            this.withCredentials = false;\n            this.providers = {\n                facebook: {\n                    name: 'facebook',\n                    url: '/auth/facebook',\n                    authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ',',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 580, height: 400 }\n                },\n                google: {\n                    name: 'google',\n                    url: '/auth/google',\n                    authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    optionalUrlParams: ['display', 'state'],\n                    scope: ['profile', 'email'],\n                    scopePrefix: 'openid',\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 452, height: 633 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                },\n                github: {\n                    name: 'github',\n                    url: '/auth/github',\n                    authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['scope'],\n                    scope: ['user:email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1020, height: 618 }\n                },\n                instagram: {\n                    name: 'instagram',\n                    url: '/auth/instagram',\n                    authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['basic'],\n                    scopeDelimiter: '+',\n                    oauthType: '2.0'\n                },\n                linkedin: {\n                    name: 'linkedin',\n                    url: '/auth/linkedin',\n                    authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['state'],\n                    scope: ['r_emailaddress'],\n                    scopeDelimiter: ' ',\n                    state: 'STATE',\n                    oauthType: '2.0',\n                    popupOptions: { width: 527, height: 582 }\n                },\n                twitter: {\n                    name: 'twitter',\n                    url: '/auth/twitter',\n                    authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n                    redirectUri: window.location.origin,\n                    oauthType: '1.0',\n                    popupOptions: { width: 495, height: 645 }\n                },\n                twitch: {\n                    name: 'twitch',\n                    url: '/auth/twitch',\n                    authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['scope'],\n                    scope: ['user_read'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                live: {\n                    name: 'live',\n                    url: '/auth/live',\n                    authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n                    redirectUri: window.location.origin,\n                    requiredUrlParams: ['display', 'scope'],\n                    scope: ['wl.emails'],\n                    scopeDelimiter: ' ',\n                    display: 'popup',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 560 }\n                },\n                yahoo: {\n                    name: 'yahoo',\n                    url: '/auth/yahoo',\n                    authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n                    redirectUri: window.location.origin,\n                    scope: [],\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 559, height: 519 }\n                },\n                bitbucket: {\n                    name: 'bitbucket',\n                    url: '/auth/bitbucket',\n                    authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n                    redirectUri: window.location.origin + '/',\n                    requiredUrlParams: ['scope'],\n                    scope: ['email'],\n                    scopeDelimiter: ' ',\n                    oauthType: '2.0',\n                    popupOptions: { width: 1028, height: 529 }\n                },\n                spotify: {\n                    name: 'spotify',\n                    url: '/auth/spotify',\n                    authorizationEndpoint: 'https://accounts.spotify.com/authorize',\n                    redirectUri: window.location.origin,\n                    optionalUrlParams: ['state'],\n                    requiredUrlParams: ['scope'],\n                    scope: ['user-read-email'],\n                    scopePrefix: '',\n                    scopeDelimiter: ',',\n                    oauthType: '2.0',\n                    popupOptions: { width: 500, height: 530 },\n                    state: function () { return encodeURIComponent(Math.random().toString(36).substr(2)); }\n                }\n            };\n            this.httpInterceptor = function () { return true; };\n        }\n        Object.defineProperty(Config, \"getConstant\", {\n            get: function () {\n                return new Config();\n            },\n            enumerable: true,\n            configurable: true\n        });\n        return Config;\n    }());\n    ;\n\n    var AuthProvider = (function () {\n        function AuthProvider(SatellizerConfig) {\n            this.SatellizerConfig = SatellizerConfig;\n        }\n        Object.defineProperty(AuthProvider.prototype, \"baseUrl\", {\n            get: function () { return this.SatellizerConfig.baseUrl; },\n            set: function (value) { this.SatellizerConfig.baseUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"loginUrl\", {\n            get: function () { return this.SatellizerConfig.loginUrl; },\n            set: function (value) { this.SatellizerConfig.loginUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"signupUrl\", {\n            get: function () { return this.SatellizerConfig.signupUrl; },\n            set: function (value) { this.SatellizerConfig.signupUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"unlinkUrl\", {\n            get: function () { return this.SatellizerConfig.unlinkUrl; },\n            set: function (value) { this.SatellizerConfig.unlinkUrl = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenRoot\", {\n            get: function () { return this.SatellizerConfig.tokenRoot; },\n            set: function (value) { this.SatellizerConfig.tokenRoot = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenName\", {\n            get: function () { return this.SatellizerConfig.tokenName; },\n            set: function (value) { this.SatellizerConfig.tokenName = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenPrefix\", {\n            get: function () { return this.SatellizerConfig.tokenPrefix; },\n            set: function (value) { this.SatellizerConfig.tokenPrefix = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenHeader\", {\n            get: function () { return this.SatellizerConfig.tokenHeader; },\n            set: function (value) { this.SatellizerConfig.tokenHeader = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"tokenType\", {\n            get: function () { return this.SatellizerConfig.tokenType; },\n            set: function (value) { this.SatellizerConfig.tokenType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"withCredentials\", {\n            get: function () { return this.SatellizerConfig.withCredentials; },\n            set: function (value) { this.SatellizerConfig.withCredentials = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"storageType\", {\n            get: function () { return this.SatellizerConfig.storageType; },\n            set: function (value) { this.SatellizerConfig.storageType = value; },\n            enumerable: true,\n            configurable: true\n        });\n        Object.defineProperty(AuthProvider.prototype, \"httpInterceptor\", {\n            get: function () { return this.SatellizerConfig.httpInterceptor; },\n            set: function (value) {\n                if (typeof value === 'function') {\n                    this.SatellizerConfig.httpInterceptor = value;\n                }\n                else {\n                    this.SatellizerConfig.httpInterceptor = function () { return value; };\n                }\n            },\n            enumerable: true,\n            configurable: true\n        });\n        AuthProvider.prototype.facebook = function (options) {\n            angular.extend(this.SatellizerConfig.providers.facebook, options);\n        };\n        AuthProvider.prototype.google = function (options) {\n            angular.extend(this.SatellizerConfig.providers.google, options);\n        };\n        AuthProvider.prototype.github = function (options) {\n            angular.extend(this.SatellizerConfig.providers.github, options);\n        };\n        AuthProvider.prototype.instagram = function (options) {\n            angular.extend(this.SatellizerConfig.providers.instagram, options);\n        };\n        AuthProvider.prototype.linkedin = function (options) {\n            angular.extend(this.SatellizerConfig.providers.linkedin, options);\n        };\n        AuthProvider.prototype.twitter = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitter, options);\n        };\n        AuthProvider.prototype.twitch = function (options) {\n            angular.extend(this.SatellizerConfig.providers.twitch, options);\n        };\n        AuthProvider.prototype.live = function (options) {\n            angular.extend(this.SatellizerConfig.providers.live, options);\n        };\n        AuthProvider.prototype.yahoo = function (options) {\n            angular.extend(this.SatellizerConfig.providers.yahoo, options);\n        };\n        AuthProvider.prototype.bitbucket = function (options) {\n            angular.extend(this.SatellizerConfig.providers.bitbucket, options);\n        };\n        AuthProvider.prototype.spotify = function (options) {\n            angular.extend(this.SatellizerConfig.providers.spotify, options);\n        };\n        AuthProvider.prototype.oauth1 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '1.0'\n            });\n        };\n        AuthProvider.prototype.oauth2 = function (options) {\n            this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n                oauthType: '2.0'\n            });\n        };\n        AuthProvider.prototype.$get = function (SatellizerShared, SatellizerLocal, SatellizerOAuth) {\n            return {\n                login: function (user, options) { return SatellizerLocal.login(user, options); },\n                signup: function (user, options) { return SatellizerLocal.signup(user, options); },\n                logout: function () { return SatellizerShared.logout(); },\n                authenticate: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                link: function (name, data) { return SatellizerOAuth.authenticate(name, data); },\n                unlink: function (name, options) { return SatellizerOAuth.unlink(name, options); },\n                isAuthenticated: function () { return SatellizerShared.isAuthenticated(); },\n                getPayload: function () { return SatellizerShared.getPayload(); },\n                getToken: function () { return SatellizerShared.getToken(); },\n                setToken: function (token) { return SatellizerShared.setToken({ access_token: token }); },\n                removeToken: function () { return SatellizerShared.removeToken(); },\n                setStorageType: function (type) { return SatellizerShared.setStorageType(type); }\n            };\n        };\n        AuthProvider.$inject = ['SatellizerConfig'];\n        return AuthProvider;\n    }());\n    AuthProvider.prototype.$get.$inject = ['SatellizerShared', 'SatellizerLocal', 'SatellizerOAuth'];\n\n    function joinUrl(baseUrl, url) {\n        if (/^(?:[a-z]+:)?\\/\\//i.test(url)) {\n            return url;\n        }\n        var joined = [baseUrl, url].join('/');\n        var normalize = function (str) {\n            return str\n                .replace(/[\\/]+/g, '/')\n                .replace(/\\/\\?/g, '?')\n                .replace(/\\/\\#/g, '#')\n                .replace(/\\:\\//g, '://');\n        };\n        return normalize(joined);\n    }\n    function getFullUrlPath(location) {\n        var isHttps = location.protocol === 'https:';\n        return location.protocol + '//' + location.hostname +\n            ':' + (location.port || (isHttps ? '443' : '80')) +\n            (/^\\//.test(location.pathname) ? location.pathname : '/' + location.pathname);\n    }\n    function parseQueryString(str) {\n        var obj = {};\n        var key;\n        var value;\n        angular.forEach((str || '').split('&'), function (keyValue) {\n            if (keyValue) {\n                value = keyValue.split('=');\n                key = decodeURIComponent(value[0]);\n                obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;\n            }\n        });\n        return obj;\n    }\n    function decodeBase64(str) {\n        var buffer;\n        if (typeof module !== 'undefined' && module.exports) {\n            try {\n                buffer = require('buffer').Buffer;\n            }\n            catch (err) {\n            }\n        }\n        var fromCharCode = String.fromCharCode;\n        var re_btou = new RegExp([\n            '[\\xC0-\\xDF][\\x80-\\xBF]',\n            '[\\xE0-\\xEF][\\x80-\\xBF]{2}',\n            '[\\xF0-\\xF7][\\x80-\\xBF]{3}'\n        ].join('|'), 'g');\n        var cb_btou = function (cccc) {\n            switch (cccc.length) {\n                case 4:\n                    var cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n                        | ((0x3f & cccc.charCodeAt(1)) << 12)\n                        | ((0x3f & cccc.charCodeAt(2)) << 6)\n                        | (0x3f & cccc.charCodeAt(3));\n                    var offset = cp - 0x10000;\n                    return (fromCharCode((offset >>> 10) + 0xD800)\n                        + fromCharCode((offset & 0x3FF) + 0xDC00));\n                case 3:\n                    return fromCharCode(((0x0f & cccc.charCodeAt(0)) << 12)\n                        | ((0x3f & cccc.charCodeAt(1)) << 6)\n                        | (0x3f & cccc.charCodeAt(2)));\n                default:\n                    return fromCharCode(((0x1f & cccc.charCodeAt(0)) << 6)\n                        | (0x3f & cccc.charCodeAt(1)));\n            }\n        };\n        var btou = function (b) {\n            return b.replace(re_btou, cb_btou);\n        };\n        var _decode = buffer ? function (a) {\n            return (a.constructor === buffer.constructor\n                ? a : new buffer(a, 'base64')).toString();\n        }\n            : function (a) {\n                return btou(atob(a));\n            };\n        return _decode(String(str).replace(/[-_]/g, function (m0) {\n            return m0 === '-' ? '+' : '/';\n        })\n            .replace(/[^A-Za-z0-9\\+\\/]/g, ''));\n    }\n\n    var Shared = (function () {\n        function Shared($q, $window, SatellizerConfig, SatellizerStorage) {\n            this.$q = $q;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerStorage = SatellizerStorage;\n            var _a = this.SatellizerConfig, tokenName = _a.tokenName, tokenPrefix = _a.tokenPrefix;\n            this.prefixedTokenName = tokenPrefix ? [tokenPrefix, tokenName].join('_') : tokenName;\n        }\n        Shared.prototype.getToken = function () {\n            return this.SatellizerStorage.get(this.prefixedTokenName);\n        };\n        Shared.prototype.getPayload = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token && token.split('.').length === 3) {\n                try {\n                    var base64Url = token.split('.')[1];\n                    var base64 = base64Url.replace('-', '+').replace('_', '/');\n                    return JSON.parse(decodeBase64(base64));\n                }\n                catch (e) {\n                }\n            }\n        };\n        Shared.prototype.setToken = function (response) {\n            var tokenRoot = this.SatellizerConfig.tokenRoot;\n            var tokenName = this.SatellizerConfig.tokenName;\n            var accessToken = response && response.access_token;\n            var token;\n            if (accessToken) {\n                if (angular.isObject(accessToken) && angular.isObject(accessToken.data)) {\n                    response = accessToken;\n                }\n                else if (angular.isString(accessToken)) {\n                    token = accessToken;\n                }\n            }\n            if (!token && response) {\n                var tokenRootData = tokenRoot && tokenRoot.split('.').reduce(function (o, x) { return o[x]; }, response.data);\n                token = tokenRootData ? tokenRootData[tokenName] : response.data && response.data[tokenName];\n            }\n            if (token) {\n                this.SatellizerStorage.set(this.prefixedTokenName, token);\n            }\n        };\n        Shared.prototype.removeToken = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n        };\n        Shared.prototype.isAuthenticated = function () {\n            var token = this.SatellizerStorage.get(this.prefixedTokenName);\n            if (token) {\n                if (token.split('.').length === 3) {\n                    try {\n                        var base64Url = token.split('.')[1];\n                        var base64 = base64Url.replace('-', '+').replace('_', '/');\n                        var exp = JSON.parse(this.$window.atob(base64)).exp;\n                        if (typeof exp === 'number') {\n                            return Math.round(new Date().getTime() / 1000) < exp;\n                        }\n                    }\n                    catch (e) {\n                        return true; // Pass: Non-JWT token that looks like JWT\n                    }\n                }\n                return true; // Pass: All other tokens\n            }\n            return false; // Fail: No token at all\n        };\n        Shared.prototype.logout = function () {\n            this.SatellizerStorage.remove(this.prefixedTokenName);\n            return this.$q.when();\n        };\n        Shared.prototype.setStorageType = function (type) {\n            this.SatellizerConfig.storageType = type;\n        };\n        Shared.$inject = ['$q', '$window', 'SatellizerConfig', 'SatellizerStorage'];\n        return Shared;\n    }());\n\n    var Local = (function () {\n        function Local($http, SatellizerConfig, SatellizerShared) {\n            this.$http = $http;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n        }\n        Local.prototype.login = function (user, options) {\n            var _this = this;\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.loginUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options).then(function (response) {\n                _this.SatellizerShared.setToken(response);\n                return response;\n            });\n        };\n        Local.prototype.signup = function (user, options) {\n            if (options === void 0) { options = {}; }\n            options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.signupUrl);\n            options.data = user || options.data;\n            options.method = options.method || 'POST';\n            options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(options);\n        };\n        Local.$inject = ['$http', 'SatellizerConfig', 'SatellizerShared'];\n        return Local;\n    }());\n\n    var Popup = (function () {\n        function Popup($interval, $window, $q) {\n            this.$interval = $interval;\n            this.$window = $window;\n            this.$q = $q;\n            this.popup = null;\n            this.defaults = {\n                redirectUri: null\n            };\n        }\n        Popup.prototype.stringifyOptions = function (options) {\n            var parts = [];\n            angular.forEach(options, function (value, key) {\n                parts.push(key + '=' + value);\n            });\n            return parts.join(',');\n        };\n        Popup.prototype.open = function (url, name, popupOptions, redirectUri, dontPoll) {\n            var width = popupOptions.width || 500;\n            var height = popupOptions.height || 500;\n            var options = this.stringifyOptions({\n                width: width,\n                height: height,\n                top: this.$window.screenY + ((this.$window.outerHeight - height) / 2.5),\n                left: this.$window.screenX + ((this.$window.outerWidth - width) / 2)\n            });\n            var popupName = this.$window['cordova'] || this.$window.navigator.userAgent.indexOf('CriOS') > -1 ? '_blank' : name;\n            this.popup = this.$window.open(url, popupName, options);\n            if (this.popup && this.popup.focus) {\n                this.popup.focus();\n            }\n            if (dontPoll) {\n                return;\n            }\n            if (this.$window['cordova']) {\n                return this.eventListener(redirectUri);\n            }\n            else {\n                if (url === 'about:blank') {\n                    this.popup.location = url;\n                }\n                return this.polling(redirectUri);\n            }\n        };\n        Popup.prototype.polling = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var redirectUriParser = document.createElement('a');\n                redirectUriParser.href = redirectUri;\n                var redirectUriPath = getFullUrlPath(redirectUriParser);\n                var polling = _this.$interval(function () {\n                    if (!_this.popup || _this.popup.closed || _this.popup.closed === undefined) {\n                        _this.$interval.cancel(polling);\n                        reject(new Error('The popup window was closed'));\n                    }\n                    try {\n                        var popupWindowPath = getFullUrlPath(_this.popup.location);\n                        if (popupWindowPath === redirectUriPath) {\n                            if (_this.popup.location.search || _this.popup.location.hash) {\n                                var query = parseQueryString(_this.popup.location.search.substring(1).replace(/\\/$/, ''));\n                                var hash = parseQueryString(_this.popup.location.hash.substring(1).replace(/[\\/$]/, ''));\n                                var params = angular.extend({}, query, hash);\n                                if (params.error) {\n                                    reject(new Error(params.error));\n                                }\n                                else {\n                                    resolve(params);\n                                }\n                            }\n                            else {\n                                reject(new Error('OAuth redirect has occurred but no query or hash parameters were found. ' +\n                                    'They were either not set during the redirect, or were removed—typically by a ' +\n                                    'routing library—before Satellizer could read it.'));\n                            }\n                            _this.$interval.cancel(polling);\n                            _this.popup.close();\n                        }\n                    }\n                    catch (error) {\n                    }\n                }, 500);\n            });\n        };\n        Popup.prototype.eventListener = function (redirectUri) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                _this.popup.addEventListener('loadstart', function (event) {\n                    if (event.url.indexOf(redirectUri) !== 0) {\n                        return;\n                    }\n                    var parser = document.createElement('a');\n                    parser.href = event.url;\n                    if (parser.search || parser.hash) {\n                        var query = parseQueryString(parser.search.substring(1).replace(/\\/$/, ''));\n                        var hash = parseQueryString(parser.hash.substring(1).replace(/[\\/$]/, ''));\n                        var params = angular.extend({}, query, hash);\n                        if (params.error) {\n                            reject(new Error(params.error));\n                        }\n                        else {\n                            resolve(params);\n                        }\n                        _this.popup.close();\n                    }\n                });\n                _this.popup.addEventListener('loaderror', function () {\n                    reject(new Error('Authorization failed'));\n                });\n                _this.popup.addEventListener('exit', function () {\n                    reject(new Error('The popup window was closed'));\n                });\n            });\n        };\n        Popup.$inject = ['$interval', '$window', '$q'];\n        return Popup;\n    }());\n\n    var OAuth1 = (function () {\n        function OAuth1($http, $window, SatellizerConfig, SatellizerPopup) {\n            this.$http = $http;\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.defaults = {\n                name: null,\n                url: null,\n                authorizationEndpoint: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                redirectUri: null,\n                requiredUrlParams: null,\n                defaultUrlParams: null,\n                oauthType: '1.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        ;\n        OAuth1.prototype.init = function (options, userData) {\n            var _this = this;\n            angular.extend(this.defaults, options);\n            var name = options.name, popupOptions = options.popupOptions;\n            var redirectUri = this.defaults.redirectUri;\n            // Should open an empty popup and wait until request token is received\n            if (!this.$window['cordova']) {\n                this.SatellizerPopup.open('about:blank', name, popupOptions, redirectUri, true);\n            }\n            return this.getRequestToken().then(function (response) {\n                return _this.openPopup(options, response).then(function (popupResponse) {\n                    return _this.exchangeForToken(popupResponse, userData);\n                });\n            });\n        };\n        OAuth1.prototype.openPopup = function (options, response) {\n            var url = [options.authorizationEndpoint, this.buildQueryString(response.data)].join('?');\n            var redirectUri = this.defaults.redirectUri;\n            if (this.$window['cordova']) {\n                return this.SatellizerPopup.open(url, options.name, options.popupOptions, redirectUri);\n            }\n            else {\n                this.SatellizerPopup.popup.location = url;\n                return this.SatellizerPopup.polling(redirectUri);\n            }\n        };\n        OAuth1.prototype.getRequestToken = function () {\n            var url = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(url, this.defaults);\n        };\n        OAuth1.prototype.exchangeForToken = function (oauthData, userData) {\n            var payload = angular.extend({}, userData, oauthData);\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth1.prototype.buildQueryString = function (obj) {\n            var str = [];\n            angular.forEach(obj, function (value, key) {\n                str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n            });\n            return str.join('&');\n        };\n        OAuth1.$inject = ['$http', '$window', 'SatellizerConfig', 'SatellizerPopup'];\n        return OAuth1;\n    }());\n\n    var OAuth2 = (function () {\n        function OAuth2($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.defaults = {\n                name: null,\n                url: null,\n                clientId: null,\n                authorizationEndpoint: null,\n                redirectUri: null,\n                scope: null,\n                scopePrefix: null,\n                scopeDelimiter: null,\n                state: null,\n                requiredUrlParams: null,\n                defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n                responseType: 'code',\n                responseParams: {\n                    code: 'code',\n                    clientId: 'clientId',\n                    redirectUri: 'redirectUri'\n                },\n                oauthType: '2.0',\n                popupOptions: { width: null, height: null }\n            };\n        }\n        OAuth2.camelCase = function (name) {\n            return name.replace(/([\\:\\-\\_]+(.))/g, function (_, separator, letter, offset) {\n                return offset ? letter.toUpperCase() : letter;\n            });\n        };\n        OAuth2.prototype.init = function (options, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                angular.extend(_this.defaults, options);\n                var stateName = _this.defaults.name + '_state';\n                var _a = _this.defaults, name = _a.name, state = _a.state, popupOptions = _a.popupOptions, redirectUri = _a.redirectUri, responseType = _a.responseType;\n                if (typeof state === 'function') {\n                    _this.SatellizerStorage.set(stateName, state());\n                }\n                else if (typeof state === 'string') {\n                    _this.SatellizerStorage.set(stateName, state);\n                }\n                var url = [_this.defaults.authorizationEndpoint, _this.buildQueryString()].join('?');\n                _this.SatellizerPopup.open(url, name, popupOptions, redirectUri).then(function (oauth) {\n                    if (responseType === 'token' || !url) {\n                        return resolve(oauth);\n                    }\n                    if (oauth.state && oauth.state !== _this.SatellizerStorage.get(stateName)) {\n                        return reject(new Error('The value returned in the state parameter does not match the state value from your original ' +\n                            'authorization code request.'));\n                    }\n                    resolve(_this.exchangeForToken(oauth, userData));\n                }).catch(function (error) { return reject(error); });\n            });\n        };\n        OAuth2.prototype.exchangeForToken = function (oauthData, userData) {\n            var _this = this;\n            var payload = angular.extend({}, userData);\n            angular.forEach(this.defaults.responseParams, function (value, key) {\n                switch (key) {\n                    case 'code':\n                        payload[value] = oauthData.code;\n                        break;\n                    case 'clientId':\n                        payload[value] = _this.defaults.clientId;\n                        break;\n                    case 'redirectUri':\n                        payload[value] = _this.defaults.redirectUri;\n                        break;\n                    default:\n                        payload[value] = oauthData[key];\n                }\n            });\n            if (oauthData.state) {\n                payload.state = oauthData.state;\n            }\n            var exchangeForTokenUrl = this.SatellizerConfig.baseUrl ?\n                joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) :\n                this.defaults.url;\n            return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n        };\n        OAuth2.prototype.buildQueryString = function () {\n            var _this = this;\n            var keyValuePairs = [];\n            var urlParamsCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];\n            angular.forEach(urlParamsCategories, function (paramsCategory) {\n                angular.forEach(_this.defaults[paramsCategory], function (paramName) {\n                    var camelizedName = OAuth2.camelCase(paramName);\n                    var paramValue = angular.isFunction(_this.defaults[paramName]) ? _this.defaults[paramName]() : _this.defaults[camelizedName];\n                    if (paramName === 'redirect_uri' && !paramValue) {\n                        return;\n                    }\n                    if (paramName === 'state') {\n                        var stateName = _this.defaults.name + '_state';\n                        paramValue = encodeURIComponent(_this.SatellizerStorage.get(stateName));\n                    }\n                    if (paramName === 'scope' && Array.isArray(paramValue)) {\n                        paramValue = paramValue.join(_this.defaults.scopeDelimiter);\n                        if (_this.defaults.scopePrefix) {\n                            paramValue = [_this.defaults.scopePrefix, paramValue].join(_this.defaults.scopeDelimiter);\n                        }\n                    }\n                    keyValuePairs.push([paramName, paramValue]);\n                });\n            });\n            return keyValuePairs.map(function (pair) { return pair.join('='); }).join('&');\n        };\n        OAuth2.$inject = ['$http', '$window', '$timeout', '$q', 'SatellizerConfig', 'SatellizerPopup', 'SatellizerStorage'];\n        return OAuth2;\n    }());\n\n    var OAuth = (function () {\n        function OAuth($http, $window, $timeout, $q, SatellizerConfig, SatellizerPopup, SatellizerStorage, SatellizerShared, SatellizerOAuth1, SatellizerOAuth2) {\n            this.$http = $http;\n            this.$window = $window;\n            this.$timeout = $timeout;\n            this.$q = $q;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerPopup = SatellizerPopup;\n            this.SatellizerStorage = SatellizerStorage;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerOAuth1 = SatellizerOAuth1;\n            this.SatellizerOAuth2 = SatellizerOAuth2;\n        }\n        OAuth.prototype.authenticate = function (name, userData) {\n            var _this = this;\n            return this.$q(function (resolve, reject) {\n                var provider = _this.SatellizerConfig.providers[name];\n                var oauth = null;\n                switch (provider.oauthType) {\n                    case '1.0':\n                        oauth = new OAuth1(_this.$http, _this.$window, _this.SatellizerConfig, _this.SatellizerPopup);\n                        break;\n                    case '2.0':\n                        oauth = new OAuth2(_this.$http, _this.$window, _this.$timeout, _this.$q, _this.SatellizerConfig, _this.SatellizerPopup, _this.SatellizerStorage);\n                        break;\n                    default:\n                        return reject(new Error('Invalid OAuth Type'));\n                }\n                return oauth.init(provider, userData).then(function (response) {\n                    if (provider.url) {\n                        _this.SatellizerShared.setToken(response);\n                    }\n                    resolve(response);\n                }).catch(function (error) {\n                    reject(error);\n                });\n            });\n        };\n        OAuth.prototype.unlink = function (provider, httpOptions) {\n            if (httpOptions === void 0) { httpOptions = {}; }\n            httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);\n            httpOptions.data = { provider: provider } || httpOptions.data;\n            httpOptions.method = httpOptions.method || 'POST';\n            httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;\n            return this.$http(httpOptions);\n        };\n        OAuth.$inject = [\n            '$http',\n            '$window',\n            '$timeout',\n            '$q',\n            'SatellizerConfig',\n            'SatellizerPopup',\n            'SatellizerStorage',\n            'SatellizerShared',\n            'SatellizerOAuth1',\n            'SatellizerOAuth2'\n        ];\n        return OAuth;\n    }());\n\n    var Storage = (function () {\n        function Storage($window, SatellizerConfig) {\n            this.$window = $window;\n            this.SatellizerConfig = SatellizerConfig;\n            this.memoryStore = {};\n        }\n        Storage.prototype.get = function (key) {\n            try {\n                return this.$window[this.SatellizerConfig.storageType].getItem(key);\n            }\n            catch (e) {\n                return this.memoryStore[key];\n            }\n        };\n        Storage.prototype.set = function (key, value) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].setItem(key, value);\n            }\n            catch (e) {\n                this.memoryStore[key] = value;\n            }\n        };\n        Storage.prototype.remove = function (key) {\n            try {\n                this.$window[this.SatellizerConfig.storageType].removeItem(key);\n            }\n            catch (e) {\n                delete this.memoryStore[key];\n            }\n        };\n        Storage.$inject = ['$window', 'SatellizerConfig'];\n        return Storage;\n    }());\n\n    var Interceptor = (function () {\n        function Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            var _this = this;\n            this.SatellizerConfig = SatellizerConfig;\n            this.SatellizerShared = SatellizerShared;\n            this.SatellizerStorage = SatellizerStorage;\n            this.request = function (config) {\n                if (config['skipAuthorization']) {\n                    return config;\n                }\n                if (_this.SatellizerShared.isAuthenticated() && _this.SatellizerConfig.httpInterceptor()) {\n                    var tokenName = _this.SatellizerConfig.tokenPrefix ?\n                        [_this.SatellizerConfig.tokenPrefix, _this.SatellizerConfig.tokenName].join('_') : _this.SatellizerConfig.tokenName;\n                    var token = _this.SatellizerStorage.get(tokenName);\n                    if (_this.SatellizerConfig.tokenHeader && _this.SatellizerConfig.tokenType) {\n                        token = _this.SatellizerConfig.tokenType + ' ' + token;\n                    }\n                    config.headers[_this.SatellizerConfig.tokenHeader] = token;\n                }\n                return config;\n            };\n        }\n        Interceptor.Factory = function (SatellizerConfig, SatellizerShared, SatellizerStorage) {\n            return new Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage);\n        };\n        Interceptor.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n        return Interceptor;\n    }());\n    Interceptor.Factory.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n\n    var HttpProviderConfig = (function () {\n        function HttpProviderConfig($httpProvider) {\n            this.$httpProvider = $httpProvider;\n            $httpProvider.interceptors.push(Interceptor.Factory);\n        }\n        HttpProviderConfig.$inject = ['$httpProvider'];\n        return HttpProviderConfig;\n    }());\n\n    angular.module('satellizer', [])\n        .provider('$auth', ['SatellizerConfig', function (SatellizerConfig) { return new AuthProvider(SatellizerConfig); }])\n        .constant('SatellizerConfig', Config.getConstant)\n        .service('SatellizerShared', Shared)\n        .service('SatellizerLocal', Local)\n        .service('SatellizerPopup', Popup)\n        .service('SatellizerOAuth', OAuth)\n        .service('SatellizerOAuth2', OAuth2)\n        .service('SatellizerOAuth1', OAuth1)\n        .service('SatellizerStorage', Storage)\n        .service('SatellizerInterceptor', Interceptor)\n        .config(['$httpProvider', function ($httpProvider) { return new HttpProviderConfig($httpProvider); }]);\n    var ng1 = 'satellizer';\n\n    return ng1;\n\n}));\n//# sourceMappingURL=satellizer.js.map\n"
  },
  {
    "path": "examples/server/php/resources/assets/less/app.less",
    "content": "\n"
  },
  {
    "path": "examples/server/php/resources/lang/en/pagination.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Pagination Language Lines\n\t|--------------------------------------------------------------------------\n\t|\n\t| The following language lines are used by the paginator library to build\n\t| the simple pagination links. You are free to change them to anything\n\t| you want to customize your views to better match your application.\n\t|\n\t*/\n\n\t'previous' => '&laquo; Previous',\n\t'next'     => 'Next &raquo;',\n\n];\n"
  },
  {
    "path": "examples/server/php/resources/lang/en/passwords.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Password Reminder Language Lines\n\t|--------------------------------------------------------------------------\n\t|\n\t| The following language lines are the default lines which match reasons\n\t| that are given by the password broker for a password update attempt\n\t| has failed, such as for an invalid token or invalid new password.\n\t|\n\t*/\n\n\t\"password\" => \"Passwords must be at least six characters and match the confirmation.\",\n\t\"user\" => \"We can't find a user with that e-mail address.\",\n\t\"token\" => \"This password reset token is invalid.\",\n\t\"sent\" => \"We have e-mailed your password reset link!\",\n\t\"reset\" => \"Your password has been reset!\",\n\n];\n"
  },
  {
    "path": "examples/server/php/resources/lang/en/validation.php",
    "content": "<?php\n\nreturn [\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Validation Language Lines\n\t|--------------------------------------------------------------------------\n\t|\n\t| The following language lines contain the default error messages used by\n\t| the validator class. Some of these rules have multiple versions such\n\t| as the size rules. Feel free to tweak each of these messages here.\n\t|\n\t*/\n\n\t\"accepted\"             => \"The :attribute must be accepted.\",\n\t\"active_url\"           => \"The :attribute is not a valid URL.\",\n\t\"after\"                => \"The :attribute must be a date after :date.\",\n\t\"alpha\"                => \"The :attribute may only contain letters.\",\n\t\"alpha_dash\"           => \"The :attribute may only contain letters, numbers, and dashes.\",\n\t\"alpha_num\"            => \"The :attribute may only contain letters and numbers.\",\n\t\"array\"                => \"The :attribute must be an array.\",\n\t\"before\"               => \"The :attribute must be a date before :date.\",\n\t\"between\"              => [\n\t\t\"numeric\" => \"The :attribute must be between :min and :max.\",\n\t\t\"file\"    => \"The :attribute must be between :min and :max kilobytes.\",\n\t\t\"string\"  => \"The :attribute must be between :min and :max characters.\",\n\t\t\"array\"   => \"The :attribute must have between :min and :max items.\",\n\t],\n\t\"boolean\"              => \"The :attribute field must be true or false.\",\n\t\"confirmed\"            => \"The :attribute confirmation does not match.\",\n\t\"date\"                 => \"The :attribute is not a valid date.\",\n\t\"date_format\"          => \"The :attribute does not match the format :format.\",\n\t\"different\"            => \"The :attribute and :other must be different.\",\n\t\"digits\"               => \"The :attribute must be :digits digits.\",\n\t\"digits_between\"       => \"The :attribute must be between :min and :max digits.\",\n\t\"email\"                => \"The :attribute must be a valid email address.\",\n\t\"filled\"               => \"The :attribute field is required.\",\n\t\"exists\"               => \"The selected :attribute is invalid.\",\n\t\"image\"                => \"The :attribute must be an image.\",\n\t\"in\"                   => \"The selected :attribute is invalid.\",\n\t\"integer\"              => \"The :attribute must be an integer.\",\n\t\"ip\"                   => \"The :attribute must be a valid IP address.\",\n\t\"max\"                  => [\n\t\t\"numeric\" => \"The :attribute may not be greater than :max.\",\n\t\t\"file\"    => \"The :attribute may not be greater than :max kilobytes.\",\n\t\t\"string\"  => \"The :attribute may not be greater than :max characters.\",\n\t\t\"array\"   => \"The :attribute may not have more than :max items.\",\n\t],\n\t\"mimes\"                => \"The :attribute must be a file of type: :values.\",\n\t\"min\"                  => [\n\t\t\"numeric\" => \"The :attribute must be at least :min.\",\n\t\t\"file\"    => \"The :attribute must be at least :min kilobytes.\",\n\t\t\"string\"  => \"The :attribute must be at least :min characters.\",\n\t\t\"array\"   => \"The :attribute must have at least :min items.\",\n\t],\n\t\"not_in\"               => \"The selected :attribute is invalid.\",\n\t\"numeric\"              => \"The :attribute must be a number.\",\n\t\"regex\"                => \"The :attribute format is invalid.\",\n\t\"required\"             => \"The :attribute field is required.\",\n\t\"required_if\"          => \"The :attribute field is required when :other is :value.\",\n\t\"required_with\"        => \"The :attribute field is required when :values is present.\",\n\t\"required_with_all\"    => \"The :attribute field is required when :values is present.\",\n\t\"required_without\"     => \"The :attribute field is required when :values is not present.\",\n\t\"required_without_all\" => \"The :attribute field is required when none of :values are present.\",\n\t\"same\"                 => \"The :attribute and :other must match.\",\n\t\"size\"                 => [\n\t\t\"numeric\" => \"The :attribute must be :size.\",\n\t\t\"file\"    => \"The :attribute must be :size kilobytes.\",\n\t\t\"string\"  => \"The :attribute must be :size characters.\",\n\t\t\"array\"   => \"The :attribute must contain :size items.\",\n\t],\n\t\"unique\"               => \"The :attribute has already been taken.\",\n\t\"url\"                  => \"The :attribute format is invalid.\",\n\t\"timezone\"             => \"The :attribute must be a valid zone.\",\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Custom Validation Language Lines\n\t|--------------------------------------------------------------------------\n\t|\n\t| Here you may specify custom validation messages for attributes using the\n\t| convention \"attribute.rule\" to name the lines. This makes it quick to\n\t| specify a specific custom language line for a given attribute rule.\n\t|\n\t*/\n\n\t'custom' => [\n\t\t'attribute-name' => [\n\t\t\t'rule-name' => 'custom-message',\n\t\t],\n\t],\n\n\t/*\n\t|--------------------------------------------------------------------------\n\t| Custom Validation Attributes\n\t|--------------------------------------------------------------------------\n\t|\n\t| The following language lines are used to swap attribute place-holders\n\t| with something more reader friendly such as E-Mail Address instead\n\t| of \"email\". This simply helps us make messages a little cleaner.\n\t|\n\t*/\n\n\t'attributes' => [],\n\n];\n"
  },
  {
    "path": "examples/server/php/resources/views/errors/503.blade.php",
    "content": "<html>\n\t<head>\n\t\t<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>\n\n\t\t<style>\n\t\t\tbody {\n\t\t\t\tmargin: 0;\n\t\t\t\tpadding: 0;\n\t\t\t\twidth: 100%;\n\t\t\t\theight: 100%;\n\t\t\t\tcolor: #B0BEC5;\n\t\t\t\tdisplay: table;\n\t\t\t\tfont-weight: 100;\n\t\t\t\tfont-family: 'Lato';\n\t\t\t}\n\n\t\t\t.container {\n\t\t\t\ttext-align: center;\n\t\t\t\tdisplay: table-cell;\n\t\t\t\tvertical-align: middle;\n\t\t\t}\n\n\t\t\t.content {\n\t\t\t\ttext-align: center;\n\t\t\t\tdisplay: inline-block;\n\t\t\t}\n\n\t\t\t.title {\n\t\t\t\tfont-size: 72px;\n\t\t\t\tmargin-bottom: 40px;\n\t\t\t}\n\t\t</style>\n\t</head>\n\t<body>\n\t\t<div class=\"container\">\n\t\t\t<div class=\"content\">\n\t\t\t\t<div class=\"title\">Be right back.</div>\n\t\t\t</div>\n\t\t</div>\n\t</body>\n</html>\n"
  },
  {
    "path": "examples/server/php/resources/views/vendor/.gitkeep",
    "content": ""
  },
  {
    "path": "examples/server/php/resources/views/welcome.blade.php",
    "content": "<html>\n\t<head>\n\t\t<title>Laravel</title>\n\t\t\n\t\t<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>\n\n\t\t<style>\n\t\t\tbody {\n\t\t\t\tmargin: 0;\n\t\t\t\tpadding: 0;\n\t\t\t\twidth: 100%;\n\t\t\t\theight: 100%;\n\t\t\t\tcolor: #B0BEC5;\n\t\t\t\tdisplay: table;\n\t\t\t\tfont-weight: 100;\n\t\t\t\tfont-family: 'Lato';\n\t\t\t}\n\n\t\t\t.container {\n\t\t\t\ttext-align: center;\n\t\t\t\tdisplay: table-cell;\n\t\t\t\tvertical-align: middle;\n\t\t\t}\n\n\t\t\t.content {\n\t\t\t\ttext-align: center;\n\t\t\t\tdisplay: inline-block;\n\t\t\t}\n\n\t\t\t.title {\n\t\t\t\tfont-size: 96px;\n\t\t\t\tmargin-bottom: 40px;\n\t\t\t}\n\n\t\t\t.quote {\n\t\t\t\tfont-size: 24px;\n\t\t\t}\n\t\t</style>\n\t</head>\n\t<body>\n\t\t<div class=\"container\">\n\t\t\t<div class=\"content\">\n\t\t\t\t<div class=\"title\">Laravel 5</div>\n\t\t\t\t<div class=\"quote\">{{ Inspiring::quote() }}</div>\n\t\t\t</div>\n\t\t</div>\n\t</body>\n</html>\n"
  },
  {
    "path": "examples/server/php/server.php",
    "content": "<?php\n/**\n * Laravel - A PHP Framework For Web Artisans\n *\n * @package  Laravel\n * @author   Taylor Otwell <taylorotwell@gmail.com>\n */\n\n$uri = urldecode(\n\tparse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)\n);\n\n// This file allows us to emulate Apache's \"mod_rewrite\" functionality from the\n// built-in PHP web server. This provides a convenient way to test a Laravel\n// application without having installed a \"real\" web server software here.\nif ($uri !== '/' && file_exists(__DIR__.'/public'.$uri))\n{\n\treturn false;\n}\n\nrequire_once __DIR__.'/public/index.php';\n"
  },
  {
    "path": "examples/server/php/storage/app/.gitignore",
    "content": "*\n!.gitignore"
  },
  {
    "path": "examples/server/php/storage/framework/.gitignore",
    "content": "config.php\nroutes.php\ncompiled.php\nservices.json\nevents.scanned.php\nroutes.scanned.php\n"
  },
  {
    "path": "examples/server/php/storage/framework/cache/.gitignore",
    "content": "*\n!.gitignore"
  },
  {
    "path": "examples/server/php/storage/framework/sessions/.gitignore",
    "content": "*\n!.gitignore\n"
  },
  {
    "path": "examples/server/php/storage/framework/views/.gitignore",
    "content": "*\n!.gitignore\n"
  },
  {
    "path": "examples/server/php/storage/logs/.gitkeep",
    "content": ""
  },
  {
    "path": "examples/server/php/tests/ExampleTest.php",
    "content": "<?php\n\nclass ExampleTest extends TestCase {\n\n\t/**\n\t * A basic functional test example.\n\t *\n\t * @return void\n\t */\n\tpublic function testBasicExample()\n\t{\n\t\t$response = $this->call('GET', '/');\n\n\t\t$this->assertEquals(200, $response->getStatusCode());\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/php/tests/TestCase.php",
    "content": "<?php\n\nclass TestCase extends Illuminate\\Foundation\\Testing\\TestCase {\n\n\t/**\n\t * Creates the application.\n\t *\n\t * @return \\Illuminate\\Foundation\\Application\n\t */\n\tpublic function createApplication()\n\t{\n\t\t$app = require __DIR__.'/../bootstrap/app.php';\n\n\t\t$app->make('Illuminate\\Contracts\\Console\\Kernel')->bootstrap();\n\n\t\treturn $app;\n\t}\n\n}\n"
  },
  {
    "path": "examples/server/python/app.py",
    "content": "from datetime import datetime, timedelta\nimport os\nimport jwt\nimport json\nimport requests\nimport base64\nfrom functools import wraps\nfrom urlparse import parse_qs, parse_qsl\nfrom urllib import urlencode\nfrom flask import Flask, g, send_file, request, redirect, url_for, jsonify\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom werkzeug.security import generate_password_hash, check_password_hash\nfrom requests_oauthlib import OAuth1\nfrom jwt import DecodeError, ExpiredSignature\n\n# Configuration\n\ncurrent_path = os.path.dirname(__file__)\nclient_path = os.path.abspath(os.path.join(current_path, '..', '..', 'client'))\n\napp = Flask(__name__, static_url_path='', static_folder=client_path)\napp.config.from_object('config')\n\ndb = SQLAlchemy(app)\n\n\nclass User(db.Model):\n    id = db.Column(db.Integer, primary_key=True)\n    email = db.Column(db.String(120), unique=True)\n    password = db.Column(db.String(120))\n    display_name = db.Column(db.String(120))\n    facebook = db.Column(db.String(120))\n    github = db.Column(db.String(120))\n    google = db.Column(db.String(120))\n    linkedin = db.Column(db.String(120))\n    twitter = db.Column(db.String(120))\n    bitbucket = db.Column(db.String(120))\n\n    def __init__(self, email=None, password=None, display_name=None,\n                 facebook=None, github=None, google=None, linkedin=None,\n                 twitter=None, bitbucket=None):\n        if email:\n            self.email = email.lower()\n        if password:\n            self.set_password(password)\n        if display_name:\n            self.display_name = display_name\n        if facebook:\n            self.facebook = facebook\n        if google:\n            self.google = google\n        if linkedin:\n            self.linkedin = linkedin\n        if twitter:\n            self.twitter = twitter\n        if bitbucket:\n            self.bitbucket = bitbucket\n\n    def set_password(self, password):\n        self.password = generate_password_hash(password)\n\n    def check_password(self, password):\n        return check_password_hash(self.password, password)\n\n    def to_json(self):\n        return dict(id=self.id, email=self.email, displayName=self.display_name,\n                    facebook=self.facebook, google=self.google,\n                    linkedin=self.linkedin, twitter=self.twitter,\n                    bitbucket=self.bitbucket)\n\n\ndb.create_all()\n\n\ndef create_token(user):\n    payload = {\n        'sub': user.id,\n        'iat': datetime.utcnow(),\n        'exp': datetime.utcnow() + timedelta(days=14)\n    }\n    token = jwt.encode(payload, app.config['TOKEN_SECRET'])\n    return token.decode('unicode_escape')\n\n\ndef parse_token(req):\n    token = req.headers.get('Authorization').split()[1]\n    return jwt.decode(token, app.config['TOKEN_SECRET'])\n\n\ndef login_required(f):\n    @wraps(f)\n    def decorated_function(*args, **kwargs):\n        if not request.headers.get('Authorization'):\n            response = jsonify(message='Missing authorization header')\n            response.status_code = 401\n            return response\n\n        try:\n            payload = parse_token(request)\n        except DecodeError:\n            response = jsonify(message='Token is invalid')\n            response.status_code = 401\n            return response\n        except ExpiredSignature:\n            response = jsonify(message='Token has expired')\n            response.status_code = 401\n            return response\n\n        g.user_id = payload['sub']\n\n        return f(*args, **kwargs)\n\n    return decorated_function\n\n\n# Routes\n\n@app.route('/')\ndef index():\n    return send_file(os.path.join(client_path, 'index.html'))\n\n\n@app.route('/api/me')\n@login_required\ndef me():\n    user = User.query.filter_by(id=g.user_id).first()\n    return jsonify(user.to_json())\n\n\n@app.route('/auth/login', methods=['POST'])\ndef login():\n    user = User.query.filter_by(email=request.json['email']).first()\n    if not user or not user.check_password(request.json['password']):\n        response = jsonify(message='Wrong Email or Password')\n        response.status_code = 401\n        return response\n    token = create_token(user)\n    return jsonify(token=token)\n\n\n@app.route('/auth/signup', methods=['POST'])\ndef signup():\n    user = User(email=request.json['email'], password=request.json['password'])\n    db.session.add(user)\n    db.session.commit()\n    token = create_token(user)\n    return jsonify(token=token)\n\n\n@app.route('/auth/facebook', methods=['POST'])\ndef facebook():\n    access_token_url = 'https://graph.facebook.com/v2.3/oauth/access_token'\n    graph_api_url = 'https://graph.facebook.com/v2.3/me'\n\n    params = {\n        'client_id': request.json['clientId'],\n        'redirect_uri': request.json['redirectUri'],\n        'client_secret': app.config['FACEBOOK_SECRET'],\n        'code': request.json['code']\n    }\n\n    # Step 1. Exchange authorization code for access token.\n    r = requests.get(access_token_url, params=params)\n    access_token = dict(parse_qsl(r.text))\n\n    # Step 2. Retrieve information about the current user.\n    r = requests.get(graph_api_url, params=access_token)\n    profile = json.loads(r.text)\n\n    # Step 3. (optional) Link accounts.\n    if request.headers.get('Authorization'):\n        user = User.query.filter_by(facebook=profile['id']).first()\n        if user:\n            response = jsonify(message='There is already a Facebook account that belongs to you')\n            response.status_code = 409\n            return response\n\n        payload = parse_token(request)\n\n        user = User.query.filter_by(id=payload['sub']).first()\n        if not user:\n            response = jsonify(message='User not found')\n            response.status_code = 400\n            return response\n\n        user.facebook = profile['id']\n        user.display_name = user.display_name or profile['name']\n        db.session.commit()\n        token = create_token(user)\n        return jsonify(token=token)\n\n    # Step 4. Create a new account or return an existing one.\n    user = User.query.filter_by(facebook=profile['id']).first()\n    if user:\n        token = create_token(user)\n        return jsonify(token=token)\n\n    u = User(facebook=profile['id'], display_name=profile['name'])\n    db.session.add(u)\n    db.session.commit()\n    token = create_token(u)\n    return jsonify(token=token)\n\n@app.route('/auth/github', methods=['POST'])\ndef github():\n    access_token_url = 'https://github.com/login/oauth/access_token'\n    users_api_url = 'https://api.github.com/user'\n\n    params = {\n        'client_id': request.json['clientId'],\n        'redirect_uri': request.json['redirectUri'],\n        'client_secret': app.config['GITHUB_SECRET'],\n        'code': request.json['code']\n    }\n\n    # Step 1. Exchange authorization code for access token.\n    r = requests.get(access_token_url, params=params)\n    access_token = dict(parse_qsl(r.text))\n    headers = {'User-Agent': 'Satellizer'}\n\n    # Step 2. Retrieve information about the current user.\n    r = requests.get(users_api_url, params=access_token, headers=headers)\n    profile = json.loads(r.text)\n\n    # Step 3. (optional) Link accounts.\n    if request.headers.get('Authorization'):\n        user = User.query.filter_by(github=profile['id']).first()\n        if user:\n            response = jsonify(message='There is already a GitHub account that belongs to you')\n            response.status_code = 409\n            return response\n\n        payload = parse_token(request)\n\n        user = User.query.filter_by(id=payload['sub']).first()\n        if not user:\n            response = jsonify(message='User not found')\n            response.status_code = 400\n            return response\n\n        user.github = profile['id']\n        user.display_name = display_name or profile['name']\n        db.session.commit()\n        token = create_token(user)\n        return jsonify(token=token)\n\n    # Step 4. Create a new account or return an existing one.\n    user = User.query.filter_by(github=profile['id']).first()\n    if user:\n        token = create_token(user)\n        return jsonify(token=token)\n\n    u = User(github=profile['id'], display_name=profile['name'])\n    db.session.add(u)\n    db.session.commit()\n    token = create_token(u)\n    return jsonify(token=token)\n\n\n\n@app.route('/auth/google', methods=['POST'])\ndef google():\n    access_token_url = 'https://accounts.google.com/o/oauth2/token'\n    people_api_url = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'\n\n    payload = dict(client_id=request.json['clientId'],\n                   redirect_uri=request.json['redirectUri'],\n                   client_secret=app.config['GOOGLE_SECRET'],\n                   code=request.json['code'],\n                   grant_type='authorization_code')\n\n    # Step 1. Exchange authorization code for access token.\n    r = requests.post(access_token_url, data=payload)\n    token = json.loads(r.text)\n    headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}\n\n    # Step 2. Retrieve information about the current user.\n    r = requests.get(people_api_url, headers=headers)\n    profile = json.loads(r.text)\n\n    # Step 3. (optional) Link accounts.\n    if request.headers.get('Authorization'):\n        user = User.query.filter_by(google=profile['sub']).first()\n        if user:\n            response = jsonify(message='There is already a Google account that belongs to you')\n            response.status_code = 409\n            return response\n\n        payload = parse_token(request)\n\n        user = User.query.filter_by(id=payload['sub']).first()\n        if not user:\n            response = jsonify(message='User not found')\n            response.status_code = 400\n            return response\n        user.google = profile['sub']\n        user.display_name = user.display_name or profile['name']\n        db.session.commit()\n        token = create_token(user)\n        return jsonify(token=token)\n\n    # Step 4. Create a new account or return an existing one.\n\n    user = User.query.filter_by(google=profile['sub']).first()\n    if user:\n        token = create_token(user)\n        return jsonify(token=token)\n    u = User(google=profile['sub'],\n             display_name=profile['name'])\n    db.session.add(u)\n    db.session.commit()\n    token = create_token(u)\n    return jsonify(token=token)\n\n\n@app.route('/auth/linkedin', methods=['POST'])\ndef linkedin():\n    access_token_url = 'https://www.linkedin.com/uas/oauth2/accessToken'\n    people_api_url = 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)'\n\n    payload = dict(client_id=request.json['clientId'],\n                   redirect_uri=request.json['redirectUri'],\n                   client_secret=app.config['LINKEDIN_SECRET'],\n                   code=request.json['code'],\n                   grant_type='authorization_code')\n\n    # Step 1. Exchange authorization code for access token.\n    r = requests.post(access_token_url, data=payload)\n    access_token = json.loads(r.text)\n    params = dict(oauth2_access_token=access_token['access_token'],\n                  format='json')\n\n    # Step 2. Retrieve information about the current user.\n    r = requests.get(people_api_url, params=params)\n    profile = json.loads(r.text)\n    \n    # Step 3. (optional) Link accounts.\n    if request.headers.get('Authorization'):\n        user = User.query.filter_by(linkedin=profile['id']).first()\n        if user:\n            response = jsonify(message='There is already a LinkedIn account that belongs to you')\n            response.status_code = 409\n            return response\n\n        payload = parse_token(request)\n\n        user = User.query.filter_by(id=payload['sub']).first()\n        if not user:\n            response = jsonify(message='User not found')\n            response.status_code = 400\n            return response\n        user.linkedin = profile['id']\n        user.display_name = user.display_name or (profile['firstName'] + ' ' + profile['lastName'])\n        db.session.commit()\n        token = create_token(user)\n        return jsonify(token=token)\n\n    # Step 4. Create a new account or return an existing one.\n\n    user = User.query.filter_by(linkedin=profile['id']).first()\n    if user:\n        token = create_token(user)\n        return jsonify(token=token)\n    u = User(linkedin=profile['id'],\n             display_name=profile['firstName'] + ' ' + profile['lastName'])\n    db.session.add(u)\n    db.session.commit()\n    token = create_token(u)\n    return jsonify(token=token)\n\n\n@app.route('/auth/twitter', methods=['POST'])\ndef twitter():\n    request_token_url = 'https://api.twitter.com/oauth/request_token'\n    access_token_url = 'https://api.twitter.com/oauth/access_token'\n\n    if request.json.get('oauth_token') and request.json.get('oauth_verifier'):\n        auth = OAuth1(app.config['TWITTER_CONSUMER_KEY'],\n                      client_secret=app.config['TWITTER_CONSUMER_SECRET'],\n                      resource_owner_key=request.json.get('oauth_token'),\n                      verifier=request.json.get('oauth_verifier'))\n        r = requests.post(access_token_url, auth=auth)\n        profile = dict(parse_qsl(r.text))\n\n        user = User.query.filter_by(twitter=profile['user_id']).first()\n        if user:\n            token = create_token(user)\n            return jsonify(token=token)\n        u = User(twitter=profile['user_id'],\n                 display_name=profile['screen_name'])\n        db.session.add(u)\n        db.session.commit()\n        token = create_token(u)\n        return jsonify(token=token)\n    else:\n        oauth = OAuth1(app.config['TWITTER_CONSUMER_KEY'],\n                       client_secret=app.config['TWITTER_CONSUMER_SECRET'],\n                       callback_uri=app.config['TWITTER_CALLBACK_URL'])\n        r = requests.post(request_token_url, auth=oauth)\n        oauth_token = dict(parse_qsl(r.text))\n        return jsonify(oauth_token)\n\n\n@app.route('/auth/bitbucket', methods=['POST'])\ndef bitbucket():\n    access_token_url = 'https://bitbucket.org/site/oauth2/access_token'\n    users_api_url = 'https://api.bitbucket.org/2.0/user'\n    auth_encoded = base64.b64encode(\n        \"{0}:{1}\".format(request.json['clientId'],\n                         app.config['BITBUCKET_SECRET']))\n\n    headers = {'Authorization': 'Basic {0}'.format(auth_encoded)}\n    payload = dict(redirect_uri=request.json['redirectUri'],\n                   code=request.json['code'],\n                   grant_type='authorization_code')\n\n    # Step 1. Exchange authorization code for access token.\n    r = requests.post(access_token_url, data=payload, headers=headers)\n    token = json.loads(r.text)\n    params = {'access_token': token['access_token']}\n\n    # Step 2. Retrieve information about the current user.\n    r = requests.get(users_api_url, params=params)\n    profile = json.loads(r.text)\n\n    # Step 3. (optional) Link accounts.\n    if request.headers.get('Authorization'):\n        user = User.query.filter_by(bitbucket=profile['uuid']).first()\n        if user:\n            response = jsonify(message='There is already a Bitbucket account that belongs to you')\n            response.status_code = 409\n            return response\n\n        payload = parse_token(request)\n\n        user = User.query.filter_by(id=payload['sub']).first()\n        if not user:\n            response = jsonify(message='User not found')\n            response.status_code = 400\n            return response\n\n        user.bitbucket = profile['uuid']\n        user.display_name = user.display_name or profile['display_name']\n        db.session.commit()\n        token = create_token(user)\n        return jsonify(token=token)\n\n    # Step 4. Create a new account or return an existing one.\n    user = User.query.filter_by(bitbucket=profile['uuid']).first()\n    if user:\n        token = create_token(user)\n        return jsonify(token=token)\n\n    u = User(bitbucket=profile['uuid'], display_name=profile['display_name'])\n    db.session.add(u)\n    db.session.commit()\n    token = create_token(u)\n    return jsonify(token=token)\n\n\nif __name__ == '__main__':\n    app.run(port=3000)\n"
  },
  {
    "path": "examples/server/python/config.py",
    "content": "import os\n\nDEBUG = True\n\nTOKEN_SECRET = os.environ.get('SECRET_KEY') or 'JWT Token Secret String'\nFACEBOOK_SECRET = os.environ.get('FACEBOOK_SECRET') or 'Facebook Client Secret'\nGITHUB_SECRET = os.environ.get('GITHUB_SECRET') or 'GitHub Client Secret'\nFOURSQUARE_SECRET = os.environ.get('FOURSQUARE_SECRET') or 'Foursquare Client Secret'\nGOOGLE_SECRET = os.environ.get('GOOGLE_SECRET') or 'Google Client Secret'\nLINKEDIN_SECRET = os.environ.get('LINKEDIN_SECRET') or 'LinkedIn Client Secret'\nTWITTER_CONSUMER_KEY = os.environ.get('TWITTER_CONSUMER_KEY') or 'Twitter Consumer Secret'\nTWITTER_CONSUMER_SECRET = os.environ.get('TWITTER_CONSUMER_SECRET') or 'Twitter Consumer Secret'\nTWITTER_CALLBACK_URL = os.environ.get('TWITTER_CALLBACK_URL') or 'Twitter Redirect URI'\nBITBUCKET_SECRET = os.environ.get('BITBUCKET_SECRET') or 'Bitbucket Client Secret'\nSQLALCHEMY_DATABASE_URI = os.environ.get('SQLALCHEMY_DATABASE_URI') or 'sqlite:///app.db'"
  },
  {
    "path": "examples/server/python/requirements.txt",
    "content": "Flask==0.10.1\nFlask-SQLAlchemy==1.0\nJinja2==2.7.3\nMarkupSafe==0.23\nSQLAlchemy==0.9.7\nWerkzeug==0.9.6\nitsdangerous==0.24\nPyJWT==0.2.1\nrequests==2.3.0\nrequests-oauthlib==0.4.1\n"
  },
  {
    "path": "examples/server/ruby/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files for more about ignoring files.\n#\n# If you find yourself ignoring temporary files generated by your text editor\n# or operating system, you probably want to add a global ignore instead:\n#   git config --global core.excludesfile '~/.gitignore_global'\n\n# Ignore bundler config.\n/.bundle\n\n# Ignore the default SQLite database.\n/db/*.sqlite3\n/db/*.sqlite3-journal\n\n# Ignore all logfiles and tempfiles.\n/log/*\n!/log/.keep\n/tmp\n"
  },
  {
    "path": "examples/server/ruby/Gemfile",
    "content": "source 'https://rubygems.org'\n\n\n# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'\ngem 'rails', '4.2.0'\n# Use sqlite3 as the database for Active Record\ngem 'sqlite3'\n\ngem 'jwt'\ngem 'twitter_oauth'\ngem 'httpclient'\ngem 'responders', '~> 2.0'\ngem 'active_model_serializers', '~> 0.8.2'\ngem 'bcrypt', '~> 3.1.7'\ngem 'sinatra'\n\ngem 'thin', group: :development\n\ngroup :development, :test do\n  # Call 'byebug' anywhere in the code to stop execution and get a debugger console\n  gem 'byebug'\n\n  # Access an IRB console on exception pages or by using <%= console %> in views\n  gem 'web-console', '~> 2.0'\n\n  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring\n  gem 'spring'\nend\n\n"
  },
  {
    "path": "examples/server/ruby/README.rdoc",
    "content": "== README\n\nThis README would normally document whatever steps are necessary to get the\napplication up and running.\n\nThings you may want to cover:\n\n* Ruby version\n\n* System dependencies\n\n* Configuration\n\n* Database creation\n\n* Database initialization\n\n* How to run the test suite\n\n* Services (job queues, cache servers, search engines, etc.)\n\n* Deployment instructions\n\n* ...\n\n\nPlease feel free to use a different markup language if you do not plan to run\n<tt>rake doc:app</tt>.\n"
  },
  {
    "path": "examples/server/ruby/Rakefile",
    "content": "# Add your own tasks in files placed in lib/tasks ending in .rake,\n# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.\n\nrequire File.expand_path('../config/application', __FILE__)\n\nRails.application.load_tasks\n"
  },
  {
    "path": "examples/server/ruby/app/assets/images/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/app/assets/javascripts/application.js",
    "content": "// This is a manifest file that'll be compiled into application.js, which will include all the files\n// listed below.\n//\n// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,\n// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.\n//\n// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the\n// compiled file.\n//\n// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details\n// about supported directives.\n//\n//= require jquery\n//= require jquery_ujs\n//= require turbolinks\n//= require_tree .\n"
  },
  {
    "path": "examples/server/ruby/app/assets/stylesheets/application.css",
    "content": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below.\n *\n * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,\n * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.\n *\n * You're free to add application-wide styles to this file and they'll appear at the bottom of the\n * compiled file so the styles you add here take precedence over styles defined in any styles\n * defined in the other CSS/SCSS files in this directory. It is generally better to create a new\n * file per style scope.\n *\n *= require_tree .\n *= require_self\n */\n"
  },
  {
    "path": "examples/server/ruby/app/controllers/api_controller.rb",
    "content": "class APIController < ApplicationController\n  before_filter :set_current_user, :authenticate_user!\n\n  def show\n    render json: current_user\n  end\n\n  def update\n    current_user.update api_params\n\n    head :no_content\n  end\n\n  private\n\n  def api_params\n    params.require(:api).permit(:email, :displayName)\n  end\nend"
  },
  {
    "path": "examples/server/ruby/app/controllers/application_controller.rb",
    "content": "class ApplicationController < ActionController::Base\n  # Prevent CSRF attacks by raising an exception.\n  # For APIs, you may want to use :null_session instead.\n  protect_from_forgery with: :null_session\n\n  private\n\n  def authenticate_user!\n    unauthorized! unless current_user\n  end\n  \n  def unauthorized!\n    head :unauthorized\n  end\n\n  def current_user\n    @current_user\n  end\n\n  def set_current_user\n    token = request.headers['Authorization'].to_s.split(' ').last\n    return unless token\n\n    payload = Token.new(token)\n\n    @current_user = User.find(payload.user_id) if payload.valid?\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/app/controllers/auth_controller.rb",
    "content": "class AuthController < ApplicationController\n\n  def render_data(data, status)\n    render json: data, status: status, callback: params[:callback]\n  end\n\n  def render_error(message, status = :unprocessable_entity)\n    render_data({ error: message }, status)\n  end\n\n  def render_success(data, status = :ok)\n    if data.is_a? String\n      render_data({ message: data }, status)\n    else\n      render_data(data, status)\n    end\n  end\n\n  def signup\n    @user = User.create auth_params\n    render json: { token: Token.encode(@user.id) }\n  end\n\n  def login\n    @user = User.find_by email: params[:email] if params[:email].present?\n\n    if @user && @user.authenticate(params[:password])\n      render json: { token: Token.encode(@user.id) }\n    else\n      render json: { message: 'Invalid credentials' }, status: :unauthorized\n    end\n  end\n\n  def authenticate\n    @oauth = \"Oauth::#{params['provider'].titleize}\".constantize.new(params)     \n    if @oauth.authorized?\n      @user = User.from_auth(@oauth.formatted_user_data, current_user)\n      if @user\n        render_success(token: Token.encode(@user.id), id: @user.id)\n      else\n        render_error \"This #{params[:provider]} account is used already\"\n      end\n    else\n      render_error(\"There was an error with #{params['provider']}. please try again.\")\n    end\n  end\n\n  # Twitter don't support auth2 protocol yet, so it has it's own implementation for now\n  def twitter\n    if params[:oauth_token].blank?\n      render_success({ oauth_token: twitter_oauth.request_token })\n    else\n      render_success({ token: twitter_oauth.access_token })\n    end\n  end\n\n  def twitter_step_2\n    if twitter_oauth.authorized?\n      if User.from_auth(twitter_oauth.formatted_account_info, current_user)\n        render_success(\"connected twitter to profile successfuly\")\n      else\n        render_error \"This twitter account is used already\"\n      end\n    else\n      render_error(\"There was an error with twitter. please try again.\")\n    end\n  end\n\n  private\n  \n    def twitter_oauth\n      @oauth ||= Oauth::Twitter.new(params)\n    end\n\n    def auth_params\n      params.require(:auth).permit(:email, :password, :displayName)\n    end\n\nend\n"
  },
  {
    "path": "examples/server/ruby/app/controllers/concerns/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/app/helpers/application_helper.rb",
    "content": "module ApplicationHelper\nend\n"
  },
  {
    "path": "examples/server/ruby/app/mailers/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/app/models/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/app/models/authorization.rb",
    "content": "# == Schema Information\n#\n# Table name: authorizations\n#\n#  id         :integer          not null, primary key\n#  provider   :string\n#  uid        :string\n#  token      :string\n#  user_id    :integer\n#  created_at :datetime\n#  updated_at :datetime\n#  secret     :string\n#\n# Indexes\n#\n#  index_authorizations_on_user_id  (user_id)\n#\n\nclass Authorization < ActiveRecord::Base\n  belongs_to :user\n  validates_presence_of :user_id, :uid, :provider\n  validates_uniqueness_of :uid, scope: :provider\n\n  scope :facebook, lambda { find_by(provider: 'facebook') }\n  # after_create :fetch_details\n\n  def fetch_details\n    self.send(\"fetch_details_from_#{self.provider.downcase}\")\n  end\n\n  def fetch_details_from_facebook\n    graph = Koala::Facebook::API.new(self.token)\n    profile = graph.get_object(\"me\")\n    user = self.user\n    user.update_attributes(first_name: profile['first_name'], last_name: profile['last_name'],\n                            address: profile[\"location\"][\"name\"])\n    \n    user.save\n  end\n\n  def fetch_details_from_linkedin\n  end\n\n  def fetch_details_from_google_oauth2\n  end\n\n  def fetch_details_from_github\n  end\n\nend\n"
  },
  {
    "path": "examples/server/ruby/app/models/concerns/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/app/models/oauth/base.rb",
    "content": "module Oauth\n  class Base\n    attr_reader :provider, :data, :access_token, :uid\n\n    def initialize params\n      @provider = self.class.name.split('::').last.downcase\n      prepare_params params\n      puts \"PARAMS - #{@params}\"\n      @client = HTTPClient.new\n      @access_token = params[:access_token].presence || get_access_token\n      puts \"ACCESS TOKEN IS - #{@access_token}\"\n      get_data if @access_token.present?\n    end\n\n    def get_access_token\n      response = @client.post(self.class::ACCESS_TOKEN_URL, @params)\n      puts \"ACCESS TOKEN RESPONSE - #{response.body}\"\n      JSON.parse(response.body)[\"access_token\"]\n    end\n\n    def prepare_params params\n      @params = {\n        code:          params[:code],\n        redirect_uri:  params[:redirectUri],\n        client_id:     ENV[\"#{@provider.upcase}_KEY\"],\n        client_secret: ENV[\"#{@provider.upcase}_SECRET\"],\n        grant_type:    'authorization_code'\n      }\n    end\n\n    def authorized?\n      @access_token.present?\n    end\n\n  end\n\nend"
  },
  {
    "path": "examples/server/ruby/app/models/oauth/facebook.rb",
    "content": "module Oauth\n  class Facebook < Oauth::Base\n    ACCESS_TOKEN_URL = 'https://graph.facebook.com/v2.5/oauth/access_token'\n    DATA_URL = 'https://graph.facebook.com/v2.5/me'\n\n    def get_data\n      response = @client.get(DATA_URL, access_token: @access_token, fields: 'first_name, last_name, email, gender, about, link, website, picture')\n      @data = JSON.parse(response.body).with_indifferent_access\n      @data['image_url'] = @data['picture']['data']['url'] if @data['picture'].present?\n      @uid = @data[:id] ||= @data[:sub]\n      @data\n    end\n\n    def formatted_user_data\n      {\n        facebook_profile: @data['link'],\n        first_name:       @data['first_name'],\n        last_name:        @data['last_name'],\n        image_url:        @data['image_url'],\n        provider:        'facebook',\n        gender:           @data['gender'],\n        token:            @access_token,\n        email:            @data['email'],\n        uid:              @data['id']\n      }\n    end\n\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/app/models/oauth/foursquare.rb",
    "content": "module Oauth\n  class Foursquare < Oauth::Base\n    ACCESS_TOKEN_URL = 'https://foursquare.com/oauth2/access_token'\n    USER_URL = 'https://api.foursquare.com/v2/users/self'\n\n    def get_data\n      response = @client.get(USER_URL, oauth_token: @access_token, v: 20140806)\n      @data = JSON.parse(response.body)['response']['user']\n      @uid = @data[\"id\"]\n      @data\n    end\n\n    def formatted_user_data\n      {\n        provider:       'foursquare',\n        token:          @access_token,\n        uid:            @data['id'],\n        first_name:     @data['firstName'],\n        last_name:      @data['lastName'],\n        email:          @data['contact']['email'],\n        image_url:      \"#{@data['photo']['prefix']}256x256#{@data['photo']['suffix']}\",\n        foursquare_profile: \"https://foursquare.com/user/#{@data['id']}\"\n      }\n    end\n\n  end\nend\n\n\n"
  },
  {
    "path": "examples/server/ruby/app/models/oauth/github.rb",
    "content": "module Oauth\n  class Github < Oauth::Base\n    ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token'\n    DATA_URL = 'https://api.github.com/user'\n    EMAIL_URL = 'https://api.github.com/user/emails'\n\n    def get_access_token\n      response = @client.post(ACCESS_TOKEN_URL, @params)\n      response.body.split('=')[1].split('&')[0]\n    end\n\n    def get_data\n      response = @client.get(DATA_URL, access_token: @access_token)\n      @data = JSON.parse(response.body).with_indifferent_access\n      @data[\"email\"] = get_email if email_is_in_scopes(response.headers)\n      @uid = @data[:id] ||= @data[:sub]\n      @data\n    end\n\n    def formatted_user_data\n      {\n        provider:       'github',\n        token:          @access_token,\n        uid:            @data['id'],\n        first_name:     @data['login'],\n        email:          @data['email'],\n        image_url:      @data['avatar_url'],\n        github_profile: @data['html_url']\n      }\n    end\n\n    def email_is_in_scopes headers\n      headers.include?(\"X-OAuth-Scopes\") && headers[\"X-OAuth-Scopes\"].split(',').include?(\"user:email\")\n    end\n\n    def get_email\n      JSON.parse(@client.get(EMAIL_URL, access_token: @access_token).body)[0][\"email\"]\n    end\n\n  end\nend"
  },
  {
    "path": "examples/server/ruby/app/models/oauth/google.rb",
    "content": "module Oauth\n  class Google < Oauth::Base\n    ACCESS_TOKEN_URL = 'https://accounts.google.com/o/oauth2/token'\n    DATA_URL = 'https://www.googleapis.com/plus/v1/people/me/openIdConnect'\n\n    def get_names\n      names = data[:name].try(:split).to_a\n      [data[:given_name] || names.first, data[:family_name] || names.last]\n    end\n\n    def get_data\n      response = @client.get(DATA_URL, access_token: @access_token)\n      @data = JSON.parse(response.body).with_indifferent_access\n      @uid = @data[:id] ||= @data[:sub]\n      @data\n    end\n\n    def formatted_user_data\n      {\n        provider:       'google',\n        token:          @access_token,\n        uid:            @data['id'],\n        first_name:     @data['given_name'],\n        last_name:      @data['family_name'],\n        email:          @data['email'],\n        image_url:      @data['picture'].gsub(\"?sz=50\", \"\"),\n        google_profile: @data['profile']\n      }\n    end    \n\n  end\nend"
  },
  {
    "path": "examples/server/ruby/app/models/oauth/linkedin.rb",
    "content": "module Oauth\n  class Linkedin < Oauth::Base\n    ACCESS_TOKEN_URL = 'https://www.linkedin.com/uas/oauth2/accessToken'\n    DATA_URL = 'https://api.linkedin.com/v1/people/~:(id,email-address,first-name,last-name,picture-url,summary,location,picture-urls::(original),public-profile-url)?format=json'\n\n    def get_data\n      response = @client.get(DATA_URL, oauth2_access_token: @access_token)\n      @data = JSON.parse(response.body).with_indifferent_access\n      @uid = @data[:id] ||= @data[:sub]\n      @data\n    end\n\n    def formatted_user_data\n      {\n        provider:        'linkedin',\n        token:            @access_token,\n        linkedin_profile: @data['publicProfileUrl'],\n        email:            @data['emailAddress'],\n        image_url:        @data['pictureUrl'],\n        first_name:       @data['firstName'],\n        last_name:        @data['lastName'],\n        about:            @data['summary'],\n        uid:              @data['id']\n      }\n    end\n\n  end\nend"
  },
  {
    "path": "examples/server/ruby/app/models/oauth/twitter.rb",
    "content": "module Oauth\n  class Twitter\n    attr_reader :access_token, :formatted_account_info, :twitter_account\n\n    def initialize params\n      @client = TwitterOAuth::Client.new( consumer_key: ENV['TWITTER_KEY'], consumer_secret: ENV['TWITTER_SECRET'])\n      @params = params\n      \n      if params[:oauth_token] && params[:oauth_verifier]\n        get_access_token \n      elsif params[:twitter_token]\n        get_account\n        format_account_info \n      end\n    end\n\n    def request_token\n      if @request_token.blank?\n        @token = @client.request_token(oauth_callback: \"#{ENV['ANGULAR_SITE_URL']}\")\n        $redis.set(@token.token, @token.secret)\n        @request_token = @token.token\n      else\n        @request_token\n      end\n    end\n\n    def get_access_token\n      @access_token = @client.authorize(\n        @params[:oauth_token], $redis.get(@params[:oauth_token]),\n        oauth_verifier: @params[:oauth_verifier]\n      )\n      $redis.set(@access_token.token, @access_token.secret)\n      @access_token = @access_token.token\n    end\n\n    def get_account\n      @twitter_account = TwitterOAuth::Client.new(\n        consumer_key: ENV['TWITTER_KEY'], \n        consumer_secret: ENV['TWITTER_SECRET'],\n        token: @params[:twitter_token],    \n        secret: $redis.get(@params[:twitter_token])\n      )\n    end\n\n    def authorized?\n      @authorized ||= @twitter_account.authorized?\n    end\n\n    def format_account_info\n      twitter_profile = @twitter_account.info\n      begin\n        website = twitter_profile[\"entities\"][\"url\"][\"urls\"][0][\"expanded_url\"]\n      rescue\n      end\n      @formatted_account_info = {\n        provider:        'twitter', \n        uid:             twitter_profile[\"id\"],\n        name:            twitter_profile[\"name\"],\n        description:     twitter_profile[\"description\"],\n        website:         website,\n        token:           @params[:twitter_token],\n        secret:          $redis.get(@params[:twitter_token]),\n        image_url:       twitter_profile[\"profile_background_image_url\"],\n        twitter_profile: \"http://www.twitter.com/#{twitter_profile['screen_name']}\"\n      }\n    end\n\n  end\nend"
  },
  {
    "path": "examples/server/ruby/app/models/token.rb",
    "content": "class Token\n  JWT_SECRET = Rails.application.secrets.jwt_secret\n  JWT_ALGORITHM = Rails.application.secrets.jwt_algorithm\n\n  attr_reader :user_id, :payload\n\n  def initialize token\n    @payload = JWT.decode(token, JWT_SECRET, JWT_ALGORITHM).first.with_indifferent_access\n    @user_id = @payload[:user_id]\n  end\n\n  def valid?\n    user_id.presence && Time.now < Time.at(@payload[:exp].to_i)\n  end\n\n  def self.encode user_id\n    JWT.encode({ user_id: user_id, exp: (DateTime.now + 30).to_i }, JWT_SECRET, JWT_ALGORITHM)\n  end\n\nend\n"
  },
  {
    "path": "examples/server/ruby/app/models/user.rb",
    "content": "class User < ActiveRecord::Base\n  has_secure_password\n\n  def self.for_oauth oauth\n    oauth.get_data\n    data = oauth.data\n\n    user = find_by(oauth.provider => data[:id]) || find_or_create_by(email: data[:email]) do |u|\n      u.password =  SecureRandom.hex\n    end\n\n    user.update(\n      display_name: oauth.get_names.join(' '),\n      email: data[:email],\n      oauth.provider => data[:id]\n    )\n\n    user\n  end\n\n  def self.from_auth(params, current_user)\n    params = params.smash.with_indifferent_access\n    authorization = Authorization.find_or_initialize_by(provider: params[:provider], uid: params[:uid])\n    if authorization.persisted?\n      if current_user\n        if current_user.id == authorization.user.id\n          user = current_user\n        else\n          return false\n        end\n      else\n        user = authorization.user\n      end\n    else\n      if current_user\n        user = current_user\n      elsif params[:email].present?\n        user = User.find_or_initialize_by(email: params[:email])\n      else\n        user = User.new\n      end\n    end\n    authorization.secret = params[:secret]\n    authorization.token  = params[:token]\n    fallback_name        = params[:name].split(\" \") if params[:name]\n    fallback_first_name  = fallback_name.try(:first)\n    fallback_last_name   = fallback_name.try(:last)\n    user.first_name    ||= (params[:first_name] || fallback_first_name)\n    user.last_name     ||= (params[:last_name]  || fallback_last_name)\n\n    if user.image_url.blank?\n      user.image = Image.new(name: user.full_name, remote_file_url: params[:image_url])\n    end\n\n    user.password = Devise.friendly_token[0,10] if user.encrypted_password.blank?\n\n    if user.email.blank?\n      user.save(validate: false)\n    else\n      user.save\n    end\n    authorization.user_id ||= user.id\n    authorization.save\n    user\n  end\n\n\n  def displayName= name\n    self.display_name = name\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/app/serializers/user_serializer.rb",
    "content": "class UserSerializer < ActiveModel::Serializer\n  self.root = false\n\n  attributes :id, :displayName, :email\n\n  def displayName\n    object.display_name\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/app/views/layouts/application.html.erb",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>SatellizerBackend</title>\n  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>\n  <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>\n  <%= csrf_meta_tags %>\n</head>\n<body>\n\n<%= yield %>\n\n</body>\n</html>\n"
  },
  {
    "path": "examples/server/ruby/bin/bundle",
    "content": "#!/usr/bin/env ruby\nENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)\nload Gem.bin_path('bundler', 'bundle')\n"
  },
  {
    "path": "examples/server/ruby/bin/rails",
    "content": "#!/usr/bin/env ruby\nbegin\n  load File.expand_path('../spring', __FILE__)\nrescue LoadError => e\n  raise unless e.message.include?('spring')\nend\nAPP_PATH = File.expand_path('../../config/application', __FILE__)\nrequire_relative '../config/boot'\nrequire 'rails/commands'\n"
  },
  {
    "path": "examples/server/ruby/bin/rake",
    "content": "#!/usr/bin/env ruby\nbegin\n  load File.expand_path('../spring', __FILE__)\nrescue LoadError => e\n  raise unless e.message.include?('spring')\nend\nrequire_relative '../config/boot'\nrequire 'rake'\nRake.application.run\n"
  },
  {
    "path": "examples/server/ruby/bin/setup",
    "content": "#!/usr/bin/env ruby\nrequire 'pathname'\n\n# path to your application root.\nAPP_ROOT = Pathname.new File.expand_path('../../',  __FILE__)\n\nDir.chdir APP_ROOT do\n  # This script is a starting point to setup your application.\n  # Add necessary setup steps to this file:\n\n  puts \"== Installing dependencies ==\"\n  system \"gem install bundler --conservative\"\n  system \"bundle check || bundle install\"\n\n  # puts \"\\n== Copying sample files ==\"\n  # unless File.exist?(\"config/database.yml\")\n  #   system \"cp config/database.yml.sample config/database.yml\"\n  # end\n\n  puts \"\\n== Preparing database ==\"\n  system \"bin/rake db:setup\"\n\n  puts \"\\n== Removing old logs and tempfiles ==\"\n  system \"rm -f log/*\"\n  system \"rm -rf tmp/cache\"\n\n  puts \"\\n== Restarting application server ==\"\n  system \"touch tmp/restart.txt\"\nend\n"
  },
  {
    "path": "examples/server/ruby/bin/spring",
    "content": "#!/usr/bin/env ruby\n\n# This file loads spring without using Bundler, in order to be fast.\n# It gets overwritten when you run the `spring binstub` command.\n\nunless defined?(Spring)\n  require 'rubygems'\n  require 'bundler'\n\n  if (match = Bundler.default_lockfile.read.match(/^GEM$.*?^    (?:  )*spring \\((.*?)\\)$.*?^$/m))\n    Gem.paths = { 'GEM_PATH' => [Bundler.bundle_path.to_s, *Gem.path].uniq }\n    gem 'spring', match[1]\n    require 'spring/binstub'\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/config/application.rb",
    "content": "require File.expand_path('../boot', __FILE__)\n\nrequire 'rails/all'\n\n# Require the gems listed in Gemfile, including any gems\n# you've limited to :test, :development, or :production.\nBundler.require(*Rails.groups)\n\nmodule SatellizerBackend\n  class Application < Rails::Application\n    # Settings in config/environments/* take precedence over those specified here.\n    # Application configuration should go into files in config/initializers\n    # -- all .rb files in that directory are automatically loaded.\n\n    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.\n    # Run \"rake -D time\" for a list of tasks for finding time zone names. Default is UTC.\n    # config.time_zone = 'Central Time (US & Canada)'\n\n    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.\n    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]\n    # config.i18n.default_locale = :de\n\n    # Do not swallow errors in after_commit/after_rollback callbacks.\n    config.active_record.raise_in_transactional_callbacks = true\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/config/boot.rb",
    "content": "ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)\n\nrequire 'bundler/setup' # Set up gems listed in the Gemfile.\n"
  },
  {
    "path": "examples/server/ruby/config/database.yml",
    "content": "# SQLite version 3.x\n#   gem install sqlite3\n#\n#   Ensure the SQLite 3 gem is defined in your Gemfile\n#   gem 'sqlite3'\n#\ndefault: &default\n  adapter: sqlite3\n  pool: 5\n  timeout: 5000\n\ndevelopment:\n  <<: *default\n  database: db/development.sqlite3\n\n# Warning: The database defined as \"test\" will be erased and\n# re-generated from your development database when you run \"rake\".\n# Do not set this db to the same as development or production.\ntest:\n  <<: *default\n  database: db/test.sqlite3\n\nproduction:\n  <<: *default\n  database: db/production.sqlite3\n"
  },
  {
    "path": "examples/server/ruby/config/environment.rb",
    "content": "# Load the Rails application.\nrequire File.expand_path('../application', __FILE__)\n\n# Initialize the Rails application.\nRails.application.initialize!\n"
  },
  {
    "path": "examples/server/ruby/config/environments/development.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # In the development environment your application's code is reloaded on\n  # every request. This slows down response time but is perfect for development\n  # since you don't have to restart the web server when you make code changes.\n  config.cache_classes = false\n\n  # Do not eager load code on boot.\n  config.eager_load = false\n\n  # Show full error reports and disable caching.\n  config.consider_all_requests_local       = true\n  config.action_controller.perform_caching = false\n\n  # Don't care if the mailer can't send.\n  config.action_mailer.raise_delivery_errors = false\n\n  # Print deprecation notices to the Rails logger.\n  config.active_support.deprecation = :log\n\n  # Raise an error on page load if there are pending migrations.\n  config.active_record.migration_error = :page_load\n\n  # Debug mode disables concatenation and preprocessing of assets.\n  # This option may cause significant delays in view rendering with a large\n  # number of complex assets.\n  config.assets.debug = true\n\n  # Asset digests allow you to set far-future HTTP expiration dates on all assets,\n  # yet still be able to expire them through the digest params.\n  config.assets.digest = true\n\n  # Adds additional error checking when serving assets at runtime.\n  # Checks for improperly declared sprockets dependencies.\n  # Raises helpful error messages.\n  config.assets.raise_runtime_errors = true\n\n  # Raises error for missing translations\n  # config.action_view.raise_on_missing_translations = true\nend\n"
  },
  {
    "path": "examples/server/ruby/config/environments/production.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # Code is not reloaded between requests.\n  config.cache_classes = true\n\n  # Eager load code on boot. This eager loads most of Rails and\n  # your application in memory, allowing both threaded web servers\n  # and those relying on copy on write to perform better.\n  # Rake tasks automatically ignore this option for performance.\n  config.eager_load = true\n\n  # Full error reports are disabled and caching is turned on.\n  config.consider_all_requests_local       = false\n  config.action_controller.perform_caching = true\n\n  # Enable Rack::Cache to put a simple HTTP cache in front of your application\n  # Add `rack-cache` to your Gemfile before enabling this.\n  # For large-scale production use, consider using a caching reverse proxy like\n  # NGINX, varnish or squid.\n  # config.action_dispatch.rack_cache = true\n\n  # Disable serving static files from the `/public` folder by default since\n  # Apache or NGINX already handles this.\n  config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?\n\n  # Compress JavaScripts and CSS.\n  config.assets.js_compressor = :uglifier\n  # config.assets.css_compressor = :sass\n\n  # Do not fallback to assets pipeline if a precompiled asset is missed.\n  config.assets.compile = false\n\n  # Asset digests allow you to set far-future HTTP expiration dates on all assets,\n  # yet still be able to expire them through the digest params.\n  config.assets.digest = true\n\n  # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb\n\n  # Specifies the header that your server uses for sending files.\n  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache\n  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX\n\n  # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.\n  # config.force_ssl = true\n\n  # Use the lowest log level to ensure availability of diagnostic information\n  # when problems arise.\n  config.log_level = :debug\n\n  # Prepend all log lines with the following tags.\n  # config.log_tags = [ :subdomain, :uuid ]\n\n  # Use a different logger for distributed setups.\n  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)\n\n  # Use a different cache store in production.\n  # config.cache_store = :mem_cache_store\n\n  # Enable serving of images, stylesheets, and JavaScripts from an asset server.\n  # config.action_controller.asset_host = 'http://assets.example.com'\n\n  # Ignore bad email addresses and do not raise email delivery errors.\n  # Set this to true and configure the email server for immediate delivery to raise delivery errors.\n  # config.action_mailer.raise_delivery_errors = false\n\n  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to\n  # the I18n.default_locale when a translation cannot be found).\n  config.i18n.fallbacks = true\n\n  # Send deprecation notices to registered listeners.\n  config.active_support.deprecation = :notify\n\n  # Use default logging formatter so that PID and timestamp are not suppressed.\n  config.log_formatter = ::Logger::Formatter.new\n\n  # Do not dump schema after migrations.\n  config.active_record.dump_schema_after_migration = false\nend\n"
  },
  {
    "path": "examples/server/ruby/config/environments/test.rb",
    "content": "Rails.application.configure do\n  # Settings specified here will take precedence over those in config/application.rb.\n\n  # The test environment is used exclusively to run your application's\n  # test suite. You never need to work with it otherwise. Remember that\n  # your test database is \"scratch space\" for the test suite and is wiped\n  # and recreated between test runs. Don't rely on the data there!\n  config.cache_classes = true\n\n  # Do not eager load code on boot. This avoids loading your whole application\n  # just for the purpose of running a single test. If you are using a tool that\n  # preloads Rails for running tests, you may have to set it to true.\n  config.eager_load = false\n\n  # Configure static file server for tests with Cache-Control for performance.\n  config.serve_static_files   = true\n  config.static_cache_control = 'public, max-age=3600'\n\n  # Show full error reports and disable caching.\n  config.consider_all_requests_local       = true\n  config.action_controller.perform_caching = false\n\n  # Raise exceptions instead of rendering exception templates.\n  config.action_dispatch.show_exceptions = false\n\n  # Disable request forgery protection in test environment.\n  config.action_controller.allow_forgery_protection = false\n\n  # Tell Action Mailer not to deliver emails to the real world.\n  # The :test delivery method accumulates sent emails in the\n  # ActionMailer::Base.deliveries array.\n  config.action_mailer.delivery_method = :test\n\n  # Randomize the order test cases are executed.\n  config.active_support.test_order = :random\n\n  # Print deprecation notices to the stderr.\n  config.active_support.deprecation = :stderr\n\n  # Raises error for missing translations\n  # config.action_view.raise_on_missing_translations = true\nend\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/assets.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Version of your assets, change this if you want to expire all your assets.\nRails.application.config.assets.version = '1.0'\n\n# Add additional assets to the asset load path\n# Rails.application.config.assets.paths << Emoji.images_path\n\n# Precompile additional assets.\n# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.\n# Rails.application.config.assets.precompile += %w( search.js )\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/backtrace_silencers.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.\n# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }\n\n# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.\n# Rails.backtrace_cleaner.remove_silencers!\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/cookies_serializer.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\nRails.application.config.action_dispatch.cookies_serializer = :json\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/filter_parameter_logging.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Configure sensitive parameters which will be filtered from the log file.\nRails.application.config.filter_parameters += [:password]\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/hash.rb",
    "content": "class Hash\n  def except(*blacklist)\n    reject {|key, value| blacklist.include?(key) }\n  end\n\n  def only(*whitelist)\n    reject {|key, value| !whitelist.include?(key) }\n  end\n\n  def smash(prefix = nil)\n    inject({}) do |acc, (k, v)|\n      Hash === v ? acc.merge(v.smash(k)) : acc.merge(k => v)\n    end\n  end\n\nend"
  },
  {
    "path": "examples/server/ruby/config/initializers/inflections.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Add new inflection rules using the following format. Inflections\n# are locale specific, and you may define rules for as many different\n# locales as you wish. All of these examples are active by default:\n# ActiveSupport::Inflector.inflections(:en) do |inflect|\n#   inflect.plural /^(ox)$/i, '\\1en'\n#   inflect.singular /^(ox)en/i, '\\1'\n#   inflect.irregular 'person', 'people'\n#   inflect.uncountable %w( fish sheep )\n# end\n\n# These inflection rules are supported but not enabled by default:\nActiveSupport::Inflector.inflections(:en) do |inflect|\n  inflect.acronym 'API'\n  inflect.acronym 'OAuth'\nend\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/mime_types.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Add new mime types for use in respond_to blocks:\n# Mime::Type.register \"text/richtext\", :rtf\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/session_store.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\nRails.application.config.session_store :cookie_store, key: '_satellizer-backend_session'\n"
  },
  {
    "path": "examples/server/ruby/config/initializers/wrap_parameters.rb",
    "content": "# Be sure to restart your server when you modify this file.\n\n# This file contains settings for ActionController::ParamsWrapper which\n# is enabled by default.\n\n# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.\nActiveSupport.on_load(:action_controller) do\n  wrap_parameters format: [:json] if respond_to?(:wrap_parameters)\nend\n\n# To enable root element in JSON for ActiveRecord objects.\n# ActiveSupport.on_load(:active_record) do\n#  self.include_root_in_json = true\n# end\n"
  },
  {
    "path": "examples/server/ruby/config/locales/en.yml",
    "content": "# Files in the config/locales directory are used for internationalization\n# and are automatically loaded by Rails. If you want to use locales other\n# than English, add the necessary files in this directory.\n#\n# To use the locales, use `I18n.t`:\n#\n#     I18n.t 'hello'\n#\n# In views, this is aliased to just `t`:\n#\n#     <%= t('hello') %>\n#\n# To use a different locale, set it with `I18n.locale`:\n#\n#     I18n.locale = :es\n#\n# This would use the information in config/locales/es.yml.\n#\n# To learn more, please read the Rails Internationalization guide\n# available at http://guides.rubyonrails.org/i18n.html.\n\nen:\n  hello: \"Hello world\"\n"
  },
  {
    "path": "examples/server/ruby/config/routes.rb",
    "content": "Rails.application.routes.draw do\n  post :login, to: 'auth#login'\n  post :signup, to: 'auth#signup'\n  post '/:provider',      to: 'auth#authenticate'\n  post '/twitter',        to: 'auth#twitter'\n  post '/twitter_step_2', to: 'auth#twitter_step_2'\n\n  get '/me', to: 'api#show'\n  put '/me', to: 'api#update'\nend\n"
  },
  {
    "path": "examples/server/ruby/config/secrets.yml",
    "content": "# Be sure to restart your server when you modify this file.\n\n# Your secret key is used for verifying the integrity of signed cookies.\n# If you change this key, all old signed cookies will become invalid!\n\n# Make sure the secret is at least 30 characters and all random,\n# no regular words or you'll be exposed to dictionary attacks.\n# You can use `rake secret` to generate a secure secret key.\n\n# Make sure the secrets in this file are kept private\n# if you're sharing your code publicly.\n\ndevelopment:\n  facebook_oauth_secret: 'Facebook oauth secret'\n  google_oauth_secret: 'Google oauth secret'\n  jwt_secret: supersecurestringyallwontevenknow\n  jwt_algorithm: HS512\n  secret_key_base: d8eb3cc59969ad8e2d30de8f6d7d2412c995b0add2ade3114bf03003e68b318528c8851290f600a2d89c07d4d0b5c86dc93fa0070c991f57347c9cc237e8ed9a\n\ntest:\n  secret_key_base: 21743e96f802207adb46e1098aad2460839b6736c830ec9821ca014b4b16f5efc2ffe80b7de879e5d9eb0e18ef379c952cf4beb7a185bf7fc6973d492936d936\n\n# Do not keep production secrets in the repository,\n# instead read values from the environment.\nproduction:\n  facebook_oauth_secret: <%= ENV['FACEBOOK_SECRET'] %>\n  google_oauth_secret: <%= ENV['GOOGLE_SECRET'] %>\n  jwt_secret: <%= ENV['TOKEN_SECRET'] %>\n  jwt_algorithm: HS512\n  secret_key_base: <%= ENV[\"SECRET_KEY_BASE\"] %>\n"
  },
  {
    "path": "examples/server/ruby/config.ru",
    "content": "# This file is used by Rack-based servers to start the application.\n\nrequire ::File.expand_path('../config/environment', __FILE__)\nrequire './sinatra_static.rb'\n\n# Hack this up, so we wouldn't need to duplicate client code\nmap \"/api\" do\n  run Rails.application\nend\n\nmap '/auth' do\n  run Rails.application\nend\n\n# Use sinatra to serve static files, because it can be configured\nmap \"/\" do\n  run SinatraStatic\nend\n"
  },
  {
    "path": "examples/server/ruby/db/migrate/20150331192120_create_users.rb",
    "content": "class CreateUsers < ActiveRecord::Migration\n  def change\n    create_table :users do |t|\n      t.string :email, null: false, default: ''\n      t.string :password_digest, null: false, default: ''\n      t.string :display_name\n      t.string :facebook\n      t.string :google\n\n      t.timestamps null: false\n    end\n    add_index :users, :email, unique: true\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/db/migrate/20160703114821_create_authorizations.rb",
    "content": "class CreateAuthorizations < ActiveRecord::Migration\n  def change\n    create_table :authorizations do |t|\n      t.string :provider\n      t.string :uid\n      t.string :token\n      t.integer :user_id\n      t.string :secret\n\n      t.timestamps\n    end\n    add_index :authorizations, :user_id\n  end\nend\n"
  },
  {
    "path": "examples/server/ruby/db/schema.rb",
    "content": "# encoding: UTF-8\n# This file is auto-generated from the current state of the database. Instead\n# of editing this file, please use the migrations feature of Active Record to\n# incrementally modify your database, and then regenerate this schema definition.\n#\n# Note that this schema.rb definition is the authoritative source for your\n# database schema. If you need to create the application database on another\n# system, you should be using db:schema:load, not running all the migrations\n# from scratch. The latter is a flawed and unsustainable approach (the more migrations\n# you'll amass, the slower it'll run and the greater likelihood for issues).\n#\n# It's strongly recommended that you check this file into your version control system.\n\nActiveRecord::Schema.define(version: 20150331192120) do\n\n  create_table \"users\", force: :cascade do |t|\n    t.string   \"email\",           default: \"\", null: false\n    t.string   \"password_digest\", default: \"\", null: false\n    t.string   \"display_name\"\n    t.string   \"facebook\"\n    t.string   \"google\"\n    t.datetime \"created_at\",                   null: false\n    t.datetime \"updated_at\",                   null: false\n  end\n\n  add_index \"users\", [\"email\"], name: \"index_users_on_email\", unique: true\n\nend\n"
  },
  {
    "path": "examples/server/ruby/db/seeds.rb",
    "content": "# This file should contain all the record creation needed to seed the database with its default values.\n# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).\n#\n# Examples:\n#\n#   cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])\n#   Mayor.create(name: 'Emanuel', city: cities.first)\n"
  },
  {
    "path": "examples/server/ruby/log/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/public/404.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The page you were looking for doesn't exist (404)</title>\n  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n    margin: 0;\n  }\n\n  div.dialog {\n    width: 95%;\n    max-width: 33em;\n    margin: 4em auto 0;\n  }\n\n  div.dialog > div {\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 12% 0;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  div.dialog > p {\n    margin: 0 0 1em;\n    padding: 1em;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/404.html -->\n  <div class=\"dialog\">\n    <div>\n      <h1>The page you were looking for doesn't exist.</h1>\n      <p>You may have mistyped the address or the page may have moved.</p>\n    </div>\n    <p>If you are the application owner check the logs for more information.</p>\n  </div>\n</body>\n</html>\n"
  },
  {
    "path": "examples/server/ruby/public/422.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The change you wanted was rejected (422)</title>\n  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n    margin: 0;\n  }\n\n  div.dialog {\n    width: 95%;\n    max-width: 33em;\n    margin: 4em auto 0;\n  }\n\n  div.dialog > div {\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 12% 0;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  div.dialog > p {\n    margin: 0 0 1em;\n    padding: 1em;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/422.html -->\n  <div class=\"dialog\">\n    <div>\n      <h1>The change you wanted was rejected.</h1>\n      <p>Maybe you tried to change something you didn't have access to.</p>\n    </div>\n    <p>If you are the application owner check the logs for more information.</p>\n  </div>\n</body>\n</html>\n"
  },
  {
    "path": "examples/server/ruby/public/500.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n  <title>We're sorry, but something went wrong (500)</title>\n  <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n  <style>\n  body {\n    background-color: #EFEFEF;\n    color: #2E2F30;\n    text-align: center;\n    font-family: arial, sans-serif;\n    margin: 0;\n  }\n\n  div.dialog {\n    width: 95%;\n    max-width: 33em;\n    margin: 4em auto 0;\n  }\n\n  div.dialog > div {\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #BBB;\n    border-top: #B00100 solid 4px;\n    border-top-left-radius: 9px;\n    border-top-right-radius: 9px;\n    background-color: white;\n    padding: 7px 12% 0;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n\n  h1 {\n    font-size: 100%;\n    color: #730E15;\n    line-height: 1.5em;\n  }\n\n  div.dialog > p {\n    margin: 0 0 1em;\n    padding: 1em;\n    background-color: #F7F7F7;\n    border: 1px solid #CCC;\n    border-right-color: #999;\n    border-left-color: #999;\n    border-bottom-color: #999;\n    border-bottom-left-radius: 4px;\n    border-bottom-right-radius: 4px;\n    border-top-color: #DADADA;\n    color: #666;\n    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);\n  }\n  </style>\n</head>\n\n<body>\n  <!-- This file lives in public/500.html -->\n  <div class=\"dialog\">\n    <div>\n      <h1>We're sorry, but something went wrong.</h1>\n    </div>\n    <p>If you are the application owner check the logs for more information.</p>\n  </div>\n</body>\n</html>\n"
  },
  {
    "path": "examples/server/ruby/public/index.html",
    "content": "<!DOCTYPE html>\n<html ng-app=\"MyApp\">\n<head>\n  <meta charset=\"utf-8\">\n  <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n  <title>Satellizer</title>\n  <link href=\"favicon.png\" rel=\"shortcut icon\">\n  <link href=\"//fonts.googleapis.com/css?family=Roboto|Montserrat:400,700|Open+Sans:400,300,600\" rel=\"stylesheet\">\n  <link href=\"//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\" rel=\"stylesheet\">\n  <link href=\"//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css\" rel=\"stylesheet\">\n  <link href=\"//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css\" rel=\"stylesheet\">\n  <link href=\"//cdn.jsdelivr.net/animatecss/3.2.0/animate.css\" rel=\"stylesheet\">\n  <link href=\"stylesheets/styles.css\" rel=\"stylesheet\">\n</head>\n<body>\n<div ng-controller=\"NavbarCtrl\" class=\"navbar navbar-default navbar-static-top\">\n  <div class=\"navbar-header\">\n    <a class=\"navbar-brand\" href=\"/\"><i class=\"ion-ios7-pulse-strong\"></i> Satellizer</a>\n  </div>\n  <ul class=\"nav navbar-nav\">\n    <li><a href=\"/#/\">Home</a></li>\n    <li ng-if=\"isAuthenticated()\"><a href=\"/#/profile\">Profile</a></li>\n  </ul>\n  <ul ng-if=\"!isAuthenticated()\" class=\"nav navbar-nav pull-right\">\n    <li><a href=\"/#/login\">Login</a></li>\n    <li><a href=\"/#/signup\">Sign up</a></li>\n  </ul>\n  <ul ng-if=\"isAuthenticated()\" class=\"nav navbar-nav pull-right\">\n    <li><a href=\"/#/logout\">Logout</a></li>\n  </ul>\n</div>\n\n<div ui-view class=\"fadeZoom\"></div>\n\n<!-- Third-party Libraries -->\n<script src=\"vendor/angular.js\"></script>\n<script src=\"vendor/angular-messages.js\"></script>\n<script src=\"vendor/angular-resource.js\"></script>\n<script src=\"vendor/angular-animate.js\"></script>\n<script src=\"vendor/angular-ui-router.js\"></script>\n<script src=\"vendor/angular-strap.js\"></script>\n<script src=\"vendor/angular-strap.tpl.js\"></script>\n<script src=\"vendor/satellizer.js\"></script>\n\n<!-- Application Code -->\n<script src=\"app.js\"></script>\n<script src=\"directives/passwordStrength.js\"></script>\n<script src=\"directives/passwordMatch.js\"></script>\n<script src=\"controllers/login.js\"></script>\n<script src=\"controllers/signup.js\"></script>\n<script src=\"controllers/logout.js\"></script>\n<script src=\"controllers/profile.js\"></script>\n<script src=\"controllers/navbar.js\"></script>\n<script src=\"services/account.js\"></script>\n</body>\n</html>\n"
  },
  {
    "path": "examples/server/ruby/public/robots.txt",
    "content": "# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file\n#\n# To ban all spiders from the entire site uncomment the next two lines:\n# User-agent: *\n# Disallow: /\n"
  },
  {
    "path": "examples/server/ruby/sinatra_static.rb",
    "content": "require \"sinatra/base\"\n\nclass SinatraStatic < Sinatra::Base\n  client_folder = File.expand_path('../../../client', __FILE__)\n  set :public_folder, client_folder\n\n  get \"/\" do\n    send_file File.join(client_folder, 'index.html')\n  end\nend"
  },
  {
    "path": "examples/server/ruby/test/controllers/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/test/fixtures/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/test/fixtures/users.yml",
    "content": "# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\none:\n  email: MyString\n  first_name: MyString\n  last_name: MyString\n  facebook: MyString\n  foursquare: MyString\n  github: MyString\n  google: MyString\n  linkedin: MyString\n  twitter: MyString\n\ntwo:\n  email: MyString\n  first_name: MyString\n  last_name: MyString\n  facebook: MyString\n  foursquare: MyString\n  github: MyString\n  google: MyString\n  linkedin: MyString\n  twitter: MyString\n"
  },
  {
    "path": "examples/server/ruby/test/helpers/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/test/integration/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/test/mailers/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/test/models/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/test/models/user_test.rb",
    "content": "require 'test_helper'\n\nclass UserTest < ActiveSupport::TestCase\n  # test \"the truth\" do\n  #   assert true\n  # end\nend\n"
  },
  {
    "path": "examples/server/ruby/test/test_helper.rb",
    "content": "ENV['RAILS_ENV'] ||= 'test'\nrequire File.expand_path('../../config/environment', __FILE__)\nrequire 'rails/test_help'\n\nclass ActiveSupport::TestCase\n  # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order.\n  fixtures :all\n\n  # Add more helper methods to be used by all tests here...\nend\n"
  },
  {
    "path": "examples/server/ruby/vendor/assets/javascripts/.keep",
    "content": ""
  },
  {
    "path": "examples/server/ruby/vendor/assets/stylesheets/.keep",
    "content": ""
  },
  {
    "path": "karma.conf.js",
    "content": "module.exports = function (config) {\n  config.set({\n    files: [\n      'examples/client/vendor/angular.js',\n      'examples/client/vendor/angular-mocks.js',\n      'node_modules/babel-polyfill/dist/polyfill.js',\n      'test/*.spec.ts'\n    ],\n\n    browsers: ['PhantomJS'],\n\n    frameworks: ['jasmine'],\n\n    plugins: [\n      'karma-phantomjs-launcher',\n      'karma-jasmine',\n      'karma-coverage',\n      'karma-webpack'\n    ],\n\n    singleRun: true,\n\n    autoWatch: false,\n\n    reporters: ['dots'],\n\n    preprocessors: {\n      'test/*.spec.ts': ['webpack']\n    },\n\n    webpack: {\n      resolve: {\n        extensions: ['', '.ts', '.js']\n      },\n      module: {\n        loaders: [\n          { test: /\\.ts$/, loader: 'ts' }\n        ]\n      }\n    },\n\n    webpackMiddleware: {\n      noInfo: true\n    }\n  });\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"satellizer\",\n  \"description\": \"Token-based AngularJS Authentication\",\n  \"version\": \"0.15.5\",\n  \"main\": \"dist/satellizer.js\",\n  \"scripts\": {\n    \"start\": \"supervisor ./examples/server/node/server.js\",\n    \"test\": \"karma start\",\n    \"build\": \"npm run clean && tsc && rollup -c && uglifyjs dist/satellizer.js -o dist/satellizer.min.js && npm run copy\",\n    \"clean\": \"rimraf build dist\",\n    \"copy\": \"npm-run-all copy:*\",\n    \"copy:angular\": \"cp dist/satellizer.js examples/client/vendor\",\n    \"copy:ionic\": \"cp -R dist examples/ionic/www/lib/satellizer\",\n    \"copy:php\": \"cp -R examples/client/ examples/server/php/public/\",\n    \"bump\": \"npm version patch\",\n    \"postversion\": \"npm test && npm run build && git add -A dist && git commit -m 'Release'\",\n    \"publish-please\": \"publish-please\",\n    \"prepublish\": \"publish-please guard\"\n  },\n  \"author\": {\n    \"name\": \"Sahat Yalkabov\",\n    \"email\": \"sahat@me.com\",\n    \"url\": \"http://sahatyalkabov.com\"\n  },\n  \"homepage\": \"https://github.com/sahat/satellizer\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"https://github.com/sahat/satellizer.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/sahat/satellizer/issues\"\n  },\n  \"license\": \"MIT\",\n  \"devDependencies\": {\n    \"angular-mocks\": \"^1.5.8\",\n    \"babel-core\": \"^6.14.0\",\n    \"babel-eslint\": \"^7.0.0\",\n    \"babel-loader\": \"^6.2.5\",\n    \"babel-polyfill\": \"^6.13.0\",\n    \"babel-preset-es2015\": \"^6.14.0\",\n    \"babel-preset-es2015-rollup\": \"^1.2.0\",\n    \"jasmine-core\": \"^2.4.1\",\n    \"karma\": \"^1.2.0\",\n    \"karma-coverage\": \"^1.1.1\",\n    \"karma-jasmine\": \"^1.0.2\",\n    \"karma-phantomjs-launcher\": \"^1.0.1\",\n    \"karma-source-map-support\": \"^1.1.0\",\n    \"karma-sourcemap-loader\": \"^0.3.7\",\n    \"karma-typescript-preprocessor\": \"^0.3.0\",\n    \"karma-webpack\": \"^1.8.0\",\n    \"npm-run-all\": \"^3.0.0\",\n    \"phantomjs-prebuilt\": \"^2.1.12\",\n    \"publish-please\": \"^2.2.0\",\n    \"rollup\": \"^0.36.0\",\n    \"rollup-plugin-babel\": \"^2.6.1\",\n    \"rollup-plugin-node-resolve\": \"^2.0.0\",\n    \"rollup-plugin-typescript\": \"^0.8.1\",\n    \"rollup-plugin-uglify\": \"^1.0.1\",\n    \"supervisor\": \"^0.11.0\",\n    \"ts-loader\": \"^0.9.4\",\n    \"ts-node\": \"^1.3.0\",\n    \"tslint\": \"~3.15.1\",\n    \"tslint-loader\": \"^2.1.5\",\n    \"typescript\": \"^2.0.3\",\n    \"uglify-js\": \"^2.7.3\",\n    \"webpack\": \"^1.13.2\"\n  },\n  \"tags\": [\n    \"authentication\",\n    \"login\",\n    \"token\",\n    \"jwt\",\n    \"angularjs\",\n    \"angular\",\n    \"auth\",\n    \"facebook\",\n    \"google\",\n    \"linkedin\",\n    \"twitter\",\n    \"foursquare\",\n    \"github\",\n    \"yahoo\",\n    \"oauth\",\n    \"oauth 1.0\",\n    \"oauth 2.0\",\n    \"oauth2\",\n    \"oauth1\",\n    \"sign-in\",\n    \"social\",\n    \"twitch\"\n  ]\n}\n"
  },
  {
    "path": "rollup.config.js",
    "content": "import typescript from 'rollup-plugin-typescript';\nconst version = require('./package.json').version;\n\nexport default {\n  entry: 'src/ng1.ts',\n  dest: 'dist/satellizer.js',\n  sourceMap: 'dist/satellizer.map',\n  banner: '/**\\n * Satellizer ' + version + '\\n * (c) 2016 Sahat Yalkabov \\n * License: MIT \\n */\\n',\n  format: 'umd',\n  moduleName: 'satellizer',\n  plugins: [\n    typescript()\n  ]\n}\n"
  },
  {
    "path": "src/authProvider.ts",
    "content": "import Config from './config';\nimport { IOAuth1Options } from './oauth1';\nimport { IOAuth2Options } from './oauth2';\n\nexport default class AuthProvider {\n  static $inject = ['SatellizerConfig'];\n\n  constructor(private SatellizerConfig: Config) {}\n\n  get baseUrl(): string { return this.SatellizerConfig.baseUrl; }\n  set baseUrl(value) { this.SatellizerConfig.baseUrl = value; }\n\n  get loginUrl(): string { return this.SatellizerConfig.loginUrl; }\n  set loginUrl(value) { this.SatellizerConfig.loginUrl = value; }\n\n  get signupUrl(): string { return this.SatellizerConfig.signupUrl; }\n  set signupUrl(value) { this.SatellizerConfig.signupUrl = value; }\n\n  get unlinkUrl(): string { return this.SatellizerConfig.unlinkUrl; }\n  set unlinkUrl(value) { this.SatellizerConfig.unlinkUrl = value; }\n\n  get tokenRoot(): string { return this.SatellizerConfig.tokenRoot; }\n  set tokenRoot(value) { this.SatellizerConfig.tokenRoot = value; }\n\n  get tokenName(): string { return this.SatellizerConfig.tokenName; }\n  set tokenName(value) { this.SatellizerConfig.tokenName = value; }\n\n  get tokenPrefix(): string { return this.SatellizerConfig.tokenPrefix; }\n  set tokenPrefix(value) { this.SatellizerConfig.tokenPrefix = value; }\n\n  get tokenHeader(): string { return this.SatellizerConfig.tokenHeader; }\n  set tokenHeader(value) { this.SatellizerConfig.tokenHeader = value; }\n\n  get tokenType(): string { return this.SatellizerConfig.tokenType; }\n  set tokenType(value) { this.SatellizerConfig.tokenType = value; }\n\n  get withCredentials(): boolean { return this.SatellizerConfig.withCredentials; }\n  set withCredentials(value) { this.SatellizerConfig.withCredentials = value; }\n\n  get storageType(): string { return this.SatellizerConfig.storageType; }\n  set storageType(value) { this.SatellizerConfig.storageType = value; }\n\n  get httpInterceptor(): boolean { return this.SatellizerConfig.httpInterceptor; }\n  set httpInterceptor(value) {\n    if (typeof value === 'function') {\n      this.SatellizerConfig.httpInterceptor = value;\n    } else {\n      this.SatellizerConfig.httpInterceptor = () => value;\n    }\n  }\n\n  facebook(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.facebook, options);\n  }\n\n  google(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.google, options);\n  }\n\n  github(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.github, options);\n  }\n\n  instagram(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.instagram, options);\n  }\n\n  linkedin(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.linkedin, options);\n  }\n\n  twitter(options: IOAuth1Options): void {\n    angular.extend(this.SatellizerConfig.providers.twitter, options);\n  }\n\n  twitch(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.twitch, options);\n  }\n\n  live(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.live, options);\n  }\n\n  yahoo(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.yahoo, options);\n  }\n\n  bitbucket(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.bitbucket, options);\n  }\n\n  spotify(options: IOAuth2Options): void {\n    angular.extend(this.SatellizerConfig.providers.spotify, options);\n  }\n\n  oauth1(options: IOAuth1Options): void {\n    this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n      oauthType: '1.0'\n    });\n  }\n\n  oauth2(options: IOAuth2Options): void {\n    this.SatellizerConfig.providers[options.name] = angular.extend(options, {\n      oauthType: '2.0'\n    });\n  }\n\n  $get(SatellizerShared, SatellizerLocal, SatellizerOAuth): any {\n    return {\n      login: (user, options) => SatellizerLocal.login(user, options),\n      signup: (user, options) => SatellizerLocal.signup(user, options),\n      logout: () => SatellizerShared.logout(),\n      authenticate: (name, data) => SatellizerOAuth.authenticate(name, data),\n      link: (name, data) => SatellizerOAuth.authenticate(name, data),\n      unlink: (name, options) => SatellizerOAuth.unlink(name, options),\n      isAuthenticated: () => SatellizerShared.isAuthenticated(),\n      getPayload: () => SatellizerShared.getPayload(),\n      getToken: () => SatellizerShared.getToken(),\n      setToken: (token) => SatellizerShared.setToken({ access_token: token }),\n      removeToken: () => SatellizerShared.removeToken(),\n      setStorageType: (type) => SatellizerShared.setStorageType(type)\n    };\n  }\n}\n\nAuthProvider.prototype.$get.$inject = ['SatellizerShared', 'SatellizerLocal', 'SatellizerOAuth'];\n"
  },
  {
    "path": "src/config.ts",
    "content": "export default class Config {\n  static get getConstant() {\n    return new Config();\n  }\n\n  baseUrl = '/';\n  loginUrl = '/auth/login';\n  signupUrl = '/auth/signup';\n  unlinkUrl = '/auth/unlink/';\n  tokenName = 'token';\n  tokenPrefix = 'satellizer';\n  tokenHeader = 'Authorization';\n  tokenType = 'Bearer';\n  storageType = 'localStorage';\n  tokenRoot = null;\n  withCredentials = false;\n  providers = {\n    facebook: {\n      name: 'facebook',\n      url: '/auth/facebook',\n      authorizationEndpoint: 'https://www.facebook.com/v2.5/dialog/oauth',\n      redirectUri: window.location.origin + '/',\n      requiredUrlParams: ['display', 'scope'],\n      scope: ['email'],\n      scopeDelimiter: ',',\n      display: 'popup',\n      oauthType: '2.0',\n      popupOptions: { width: 580, height: 400 }\n    },\n    google: {\n      name: 'google',\n      url: '/auth/google',\n      authorizationEndpoint: 'https://accounts.google.com/o/oauth2/auth',\n      redirectUri: window.location.origin,\n      requiredUrlParams: ['scope'],\n      optionalUrlParams: ['display', 'state'],\n      scope: ['profile', 'email'],\n      scopePrefix: 'openid',\n      scopeDelimiter: ' ',\n      display: 'popup',\n      oauthType: '2.0',\n      popupOptions: { width: 452, height: 633 },\n      state: () => encodeURIComponent(Math.random().toString(36).substr(2))\n    },\n    github: {\n      name: 'github',\n      url: '/auth/github',\n      authorizationEndpoint: 'https://github.com/login/oauth/authorize',\n      redirectUri: window.location.origin,\n      optionalUrlParams: ['scope'],\n      scope: ['user:email'],\n      scopeDelimiter: ' ',\n      oauthType: '2.0',\n      popupOptions: { width: 1020, height: 618 }\n    },\n    instagram: {\n      name: 'instagram',\n      url: '/auth/instagram',\n      authorizationEndpoint: 'https://api.instagram.com/oauth/authorize',\n      redirectUri: window.location.origin,\n      requiredUrlParams: ['scope'],\n      scope: ['basic'],\n      scopeDelimiter: '+',\n      oauthType: '2.0'\n    },\n    linkedin: {\n      name: 'linkedin',\n      url: '/auth/linkedin',\n      authorizationEndpoint: 'https://www.linkedin.com/uas/oauth2/authorization',\n      redirectUri: window.location.origin,\n      requiredUrlParams: ['state'],\n      scope: ['r_emailaddress'],\n      scopeDelimiter: ' ',\n      state: 'STATE',\n      oauthType: '2.0',\n      popupOptions: { width: 527, height: 582 }\n    },\n    twitter: {\n      name: 'twitter',\n      url: '/auth/twitter',\n      authorizationEndpoint: 'https://api.twitter.com/oauth/authenticate',\n      redirectUri: window.location.origin,\n      oauthType: '1.0',\n      popupOptions: { width: 495, height: 645 }\n    },\n    twitch: {\n      name: 'twitch',\n      url: '/auth/twitch',\n      authorizationEndpoint: 'https://api.twitch.tv/kraken/oauth2/authorize',\n      redirectUri: window.location.origin,\n      requiredUrlParams: ['scope'],\n      scope: ['user_read'],\n      scopeDelimiter: ' ',\n      display: 'popup',\n      oauthType: '2.0',\n      popupOptions: { width: 500, height: 560 }\n    },\n    live: {\n      name: 'live',\n      url: '/auth/live',\n      authorizationEndpoint: 'https://login.live.com/oauth20_authorize.srf',\n      redirectUri: window.location.origin,\n      requiredUrlParams: ['display', 'scope'],\n      scope: ['wl.emails'],\n      scopeDelimiter: ' ',\n      display: 'popup',\n      oauthType: '2.0',\n      popupOptions: { width: 500, height: 560 }\n    },\n    yahoo: {\n      name: 'yahoo',\n      url: '/auth/yahoo',\n      authorizationEndpoint: 'https://api.login.yahoo.com/oauth2/request_auth',\n      redirectUri: window.location.origin,\n      scope: [],\n      scopeDelimiter: ',',\n      oauthType: '2.0',\n      popupOptions: { width: 559, height: 519 }\n    },\n    bitbucket: {\n      name: 'bitbucket',\n      url: '/auth/bitbucket',\n      authorizationEndpoint: 'https://bitbucket.org/site/oauth2/authorize',\n      redirectUri: window.location.origin + '/',\n      requiredUrlParams: ['scope'],\n      scope: ['email'],\n      scopeDelimiter: ' ',\n      oauthType: '2.0',\n      popupOptions: { width: 1028, height: 529 }\n    },\n    spotify: {\n      name: 'spotify',\n      url: '/auth/spotify',\n      authorizationEndpoint: 'https://accounts.spotify.com/authorize',\n      redirectUri: window.location.origin,\n      optionalUrlParams: ['state'],\n      requiredUrlParams: ['scope'],\n      scope: ['user-read-email'],\n      scopePrefix: '',\n      scopeDelimiter: ',',\n      oauthType: '2.0',\n      popupOptions: { width: 500, height: 530 },\n      state: () => encodeURIComponent(Math.random().toString(36).substr(2))\n    }\n  };\n  httpInterceptor: any = (): boolean => true;\n};\n"
  },
  {
    "path": "src/httpProviderConfig.ts",
    "content": "import Interceptor from './interceptor';\n\nexport default class HttpProviderConfig {\n  static $inject = ['$httpProvider'];\n\n  constructor(private $httpProvider: angular.IHttpProvider) {\n    $httpProvider.interceptors.push(Interceptor.Factory);\n  }\n}\n"
  },
  {
    "path": "src/interceptor.ts",
    "content": "import Config from './config';\nimport Shared from './shared';\nimport Storage from './storage';\n\nexport default class Interceptor implements angular.IHttpInterceptor {\n\n  static $inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];\n\n  static Factory(SatellizerConfig: Config, SatellizerShared: Shared, SatellizerStorage: Storage): Interceptor {\n    return new Interceptor(SatellizerConfig, SatellizerShared, SatellizerStorage);\n  }\n\n  constructor(private SatellizerConfig: Config,\n              private SatellizerShared: Shared,\n              private SatellizerStorage: Storage) {\n  }\n\n  request = (config: angular.IRequestConfig): angular.IRequestConfig => {\n    if (config['skipAuthorization']) {\n      return config;\n    }\n\n    if (this.SatellizerShared.isAuthenticated() && this.SatellizerConfig.httpInterceptor()) {\n      const tokenName = this.SatellizerConfig.tokenPrefix ?\n        [this.SatellizerConfig.tokenPrefix, this.SatellizerConfig.tokenName].join('_') : this.SatellizerConfig.tokenName;\n      let token = this.SatellizerStorage.get(tokenName);\n\n      if (this.SatellizerConfig.tokenHeader && this.SatellizerConfig.tokenType) {\n        token = this.SatellizerConfig.tokenType + ' ' + token;\n      }\n\n      config.headers[this.SatellizerConfig.tokenHeader] = token;\n    }\n\n    return config;\n  };\n}\n\nInterceptor.Factory.$inject = ['SatellizerConfig', 'SatellizerShared', 'SatellizerStorage'];"
  },
  {
    "path": "src/local.ts",
    "content": "import { joinUrl } from './utils';\nimport Config from './config';\nimport Shared from './shared';\n\nclass Local {\n  static $inject = ['$http', 'SatellizerConfig', 'SatellizerShared'];\n\n\n  constructor(private $http: angular.IHttpService,\n              private SatellizerConfig: Config,\n              private SatellizerShared: Shared) {}\n\n  login(user: string|Object, options: any = {}): angular.IHttpPromise<any> {\n    options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.loginUrl);\n    options.data = user || options.data;\n    options.method = options.method || 'POST';\n    options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n\n    return this.$http(options).then((response) => {\n      this.SatellizerShared.setToken(response);\n      return response;\n    });\n  }\n\n  signup(user: string|Object, options: any = {}): angular.IHttpPromise<any> {\n    options.url = options.url ? options.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.signupUrl);\n    options.data = user || options.data;\n    options.method = options.method || 'POST';\n    options.withCredentials = options.withCredentials || this.SatellizerConfig.withCredentials;\n\n    return this.$http(options);\n  }\n}\n\nexport default Local;\n"
  },
  {
    "path": "src/ng1.ts",
    "content": "import Config from './config';\nimport AuthProvider from './authProvider';\nimport Shared from './shared';\nimport Local from './local';\nimport Popup from './popup';\nimport OAuth from './oauth';\nimport OAuth2 from './oauth2';\nimport OAuth1 from './oauth1';\nimport Storage from './storage';\nimport Interceptor from './interceptor';\nimport HttpProviderConfig from './httpProviderConfig';\n\nangular.module('satellizer', [])\n  .provider('$auth', ['SatellizerConfig', (SatellizerConfig) => new AuthProvider(SatellizerConfig)])\n  .constant('SatellizerConfig', Config.getConstant)\n  .service('SatellizerShared', Shared)\n  .service('SatellizerLocal', Local)\n  .service('SatellizerPopup', Popup)\n  .service('SatellizerOAuth', OAuth)\n  .service('SatellizerOAuth2', OAuth2)\n  .service('SatellizerOAuth1', OAuth1)\n  .service('SatellizerStorage', Storage)\n  .service('SatellizerInterceptor', Interceptor)\n  .config(['$httpProvider', ($httpProvider) => new HttpProviderConfig($httpProvider)]);\n\nexport default 'satellizer';\n\n"
  },
  {
    "path": "src/oauth.ts",
    "content": "import { joinUrl } from './utils';\nimport Config from './config';\nimport Popup from './popup';\nimport Storage from './storage';\nimport Shared from './shared';\nimport OAuth1 from './oauth1';\nimport OAuth2 from './oauth2';\n\nexport default class OAuth {\n  static $inject = [\n    '$http',\n    '$window',\n    '$timeout',\n    '$q',\n    'SatellizerConfig',\n    'SatellizerPopup',\n    'SatellizerStorage',\n    'SatellizerShared',\n    'SatellizerOAuth1',\n    'SatellizerOAuth2'\n  ];\n\n  constructor(private $http: angular.IHttpService,\n              private $window: angular.IWindowService,\n              private $timeout: angular.ITimeoutService,\n              private $q: angular.IQService,\n              private SatellizerConfig: Config,\n              private SatellizerPopup: Popup,\n              private SatellizerStorage: Storage,\n              private SatellizerShared: Shared,\n              private SatellizerOAuth1: OAuth1,\n              private SatellizerOAuth2: OAuth2) {}\n\n  authenticate(name: string, userData?: any): angular.IPromise<any> {\n    return this.$q((resolve, reject) => {\n      const provider = this.SatellizerConfig.providers[name];\n\n      let oauth = null;\n\n      switch (provider.oauthType) {\n        case '1.0':\n          oauth = new OAuth1(this.$http, this.$window, this.SatellizerConfig, this.SatellizerPopup);\n          break;\n        case '2.0':\n          oauth = new OAuth2(this.$http, this.$window, this.$timeout, this.$q, this.SatellizerConfig, this.SatellizerPopup, this.SatellizerStorage);\n          break;\n        default:\n          return reject(new Error('Invalid OAuth Type'));\n      }\n\n      return oauth.init(provider, userData).then((response) => {\n        if (provider.url) {\n          this.SatellizerShared.setToken(response);\n        }\n        resolve(response);\n      }).catch((error) => {\n        reject(error);\n      });\n    });\n  }\n\n  unlink(provider: string, httpOptions: any = {}): angular.IHttpPromise<any> {\n    httpOptions.url = httpOptions.url ? httpOptions.url : joinUrl(this.SatellizerConfig.baseUrl, this.SatellizerConfig.unlinkUrl);\n    httpOptions.data = { provider: provider } || httpOptions.data;\n    httpOptions.method = httpOptions.method || 'POST';\n    httpOptions.withCredentials = httpOptions.withCredentials || this.SatellizerConfig.withCredentials;\n\n    return this.$http(httpOptions);\n  }\n}\n"
  },
  {
    "path": "src/oauth1.ts",
    "content": "import { joinUrl } from './utils';\nimport Config from './config';\nimport Popup from './popup';\nimport { IOAuth1Options } from './oauth1';\n\nexport interface IOAuth1 {\n  init(options: any, data: any): angular.IPromise<any>;\n  getRequestToken(): angular.IHttpPromise<any>;\n  openPopup(options: IOAuth1Options, response: angular.IHttpPromiseCallbackArg<any>): angular.IPromise<any>;\n  exchangeForToken(oauthData: any, userData: any): angular.IHttpPromise<any>;\n  buildQueryString(obj: any): string;\n}\n\nexport interface IOAuth1Options {\n  name: string;\n  url: string;\n  authorizationEndpoint: string;\n  redirectUri: string;\n  scope: string[];\n  scopePrefix: string;\n  scopeDelimiter: string;\n  requiredUrlParams: string[];\n  defaultUrlParams: string[];\n  oauthType: string;\n  popupOptions: { width: number, height: number };\n}\n\nexport default class OAuth1 implements IOAuth1 {\n  static $inject = ['$http', '$window', 'SatellizerConfig', 'SatellizerPopup'];\n\n  private defaults: IOAuth1Options;\n\n  constructor(private $http: angular.IHttpService,\n              private $window: angular.IWindowService,\n              private SatellizerConfig: Config,\n              private SatellizerPopup: Popup) {\n\n    this.defaults = {\n      name: null,\n      url: null,\n      authorizationEndpoint: null,\n      scope: null,\n      scopePrefix: null,\n      scopeDelimiter: null,\n      redirectUri: null,\n      requiredUrlParams: null,\n      defaultUrlParams: null,\n      oauthType: '1.0',\n      popupOptions: { width: null, height: null }\n    };\n  };\n\n  init(options: IOAuth1Options, userData: any): angular.IHttpPromise<any> {\n    angular.extend(this.defaults, options);\n    const { name, popupOptions } = options;\n    const { redirectUri } = this.defaults;\n\n    // Should open an empty popup and wait until request token is received\n    if (!this.$window['cordova']) {\n      this.SatellizerPopup.open('about:blank', name, popupOptions, redirectUri, true);\n    }\n\n    return this.getRequestToken().then((response) => {\n      return this.openPopup(options, response).then((popupResponse) => {\n        return this.exchangeForToken(popupResponse, userData);\n      });\n    });\n  }\n\n  openPopup(options: IOAuth1Options, response: angular.IHttpPromiseCallbackArg<any>): angular.IPromise<any> {\n    const url = [options.authorizationEndpoint, this.buildQueryString(response.data)].join('?');\n    const { redirectUri } = this.defaults;\n\n    if (this.$window['cordova']) {\n      return this.SatellizerPopup.open(url, options.name, options.popupOptions, redirectUri);\n    } else {\n      this.SatellizerPopup.popup.location = url;\n      return this.SatellizerPopup.polling(redirectUri);\n    }\n  }\n\n  getRequestToken(): angular.IHttpPromise<any> {\n    const url = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n    return this.$http.post(url, this.defaults);\n  }\n\n  exchangeForToken(oauthData, userData): angular.IHttpPromise<any> {\n    const payload = angular.extend({}, userData, oauthData);\n    const exchangeForTokenUrl = this.SatellizerConfig.baseUrl ? joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) : this.defaults.url;\n    return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n  }\n\n  buildQueryString(obj): string {\n    const str = [];\n    angular.forEach(obj, function (value, key) {\n      str.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));\n    });\n    return str.join('&');\n  }\n}\n"
  },
  {
    "path": "src/oauth2.ts",
    "content": "import { joinUrl } from './utils';\nimport Config from './config';\nimport Popup from './popup';\nimport Storage from './storage';\n\nexport interface IOAuth2Options {\n  name: string;\n  url: string;\n  clientId: string;\n  authorizationEndpoint: string;\n  redirectUri: string;\n  scope: string[];\n  scopePrefix: string;\n  scopeDelimiter: string;\n  state?: string|(() => string);\n  requiredUrlParams: string[];\n  defaultUrlParams: string[];\n  responseType: string;\n  responseParams: {\n    code: string,\n    clientId: string,\n    redirectUri: string\n  };\n  oauthType: string;\n  popupOptions: { width: number, height: number };\n}\n\nexport default class OAuth2 {\n  static $inject = ['$http', '$window', '$timeout', '$q', 'SatellizerConfig', 'SatellizerPopup', 'SatellizerStorage'];\n\n  static camelCase(name): string {\n    return name.replace(/([\\:\\-\\_]+(.))/g, (_, separator, letter, offset) => {\n      return offset ? letter.toUpperCase() : letter;\n    });\n  }\n\n  public defaults: IOAuth2Options;\n\n  constructor(private $http: angular.IHttpService,\n              private $window: angular.IWindowService,\n              private $timeout: angular.ITimeoutService,\n              private $q: angular.IQService,\n              private SatellizerConfig: Config,\n              private SatellizerPopup: Popup,\n              private SatellizerStorage: Storage) {\n\n    this.defaults = {\n      name: null,\n      url: null,\n      clientId: null,\n      authorizationEndpoint: null,\n      redirectUri: null,\n      scope: null,\n      scopePrefix: null,\n      scopeDelimiter: null,\n      state: null,\n      requiredUrlParams: null,\n      defaultUrlParams: ['response_type', 'client_id', 'redirect_uri'],\n      responseType: 'code',\n      responseParams: {\n        code: 'code',\n        clientId: 'clientId',\n        redirectUri: 'redirectUri'\n      },\n      oauthType: '2.0',\n      popupOptions: { width: null, height: null }\n    };\n  }\n\n  init(options: IOAuth2Options, userData: any): angular.IPromise<any> {\n    return this.$q((resolve, reject) => {\n      angular.extend(this.defaults, options);\n\n      const stateName = this.defaults.name + '_state';\n      const { name, state, popupOptions, redirectUri, responseType } = this.defaults;\n\n      if (typeof state === 'function') {\n        this.SatellizerStorage.set(stateName, state());\n      } else if (typeof state === 'string') {\n        this.SatellizerStorage.set(stateName, state);\n      }\n\n      const url = [this.defaults.authorizationEndpoint, this.buildQueryString()].join('?');\n\n      this.SatellizerPopup.open(url, name, popupOptions, redirectUri).then((oauth: any): void|angular.IPromise<any>|angular.IHttpPromise<any> => {\n        if (responseType === 'token' || !this.defaults.url) {\n          return resolve(oauth);\n        }\n\n        if (oauth.state && oauth.state !== this.SatellizerStorage.get(stateName)) {\n          return reject(new Error(\n            'The value returned in the state parameter does not match the state value from your original ' +\n            'authorization code request.'\n          ));\n        }\n\n        resolve(this.exchangeForToken(oauth, userData));\n      }).catch(error => reject(error));\n    });\n  }\n\n  exchangeForToken(oauthData: { code?, state? }, userData: any): angular.IHttpPromise<any> {\n    const payload = angular.extend({}, userData);\n\n    angular.forEach(this.defaults.responseParams, (value, key) => {\n      switch (key) {\n        case 'code':\n          payload[value] = oauthData.code;\n          break;\n        case 'clientId':\n          payload[value] = this.defaults.clientId;\n          break;\n        case 'redirectUri':\n          payload[value] = this.defaults.redirectUri;\n          break;\n        default:\n          payload[value] = oauthData[key];\n      }\n    });\n\n    if (oauthData.state) {\n      payload.state = oauthData.state;\n    }\n\n    let exchangeForTokenUrl = this.SatellizerConfig.baseUrl ?\n      joinUrl(this.SatellizerConfig.baseUrl, this.defaults.url) :\n      this.defaults.url;\n\n    return this.$http.post(exchangeForTokenUrl, payload, { withCredentials: this.SatellizerConfig.withCredentials });\n  }\n\n  buildQueryString(): string {\n    const keyValuePairs = [];\n    const urlParamsCategories = ['defaultUrlParams', 'requiredUrlParams', 'optionalUrlParams'];\n\n    angular.forEach(urlParamsCategories, (paramsCategory) => {\n      angular.forEach(this.defaults[paramsCategory], (paramName) => {\n        const camelizedName = OAuth2.camelCase(paramName);\n        let paramValue = angular.isFunction(this.defaults[paramName]) ? this.defaults[paramName]() : this.defaults[camelizedName];\n\n        if (paramName === 'redirect_uri' && !paramValue) {\n          return;\n        }\n        if (paramName === 'state') {\n          const stateName = this.defaults.name + '_state';\n          paramValue = encodeURIComponent(this.SatellizerStorage.get(stateName));\n        }\n        if (paramName === 'scope' && Array.isArray(paramValue)) {\n          paramValue = paramValue.join(this.defaults.scopeDelimiter);\n          if (this.defaults.scopePrefix) {\n            paramValue = [this.defaults.scopePrefix, paramValue].join(this.defaults.scopeDelimiter);\n          }\n        }\n\n        keyValuePairs.push([paramName, paramValue]);\n      });\n    });\n\n    return keyValuePairs.map(pair => pair.join('=')).join('&');\n  }\n}\n"
  },
  {
    "path": "src/popup.ts",
    "content": "import { parseQueryString, getFullUrlPath } from './utils';\n\nexport interface IPopup {\n  open(url: string, name: string, popupOptions: { width: number, height: number }, redirectUri: string): void;\n  stringifyOptions (options: any): string;\n  polling(redirectUri: string): angular.IPromise<any>;\n  eventListener(redirectUri: string): angular.IPromise<any>;\n}\n\nexport default class Popup implements IPopup {\n  static $inject = ['$interval', '$window', '$q'];\n\n  public popup: any;\n  private url: string;\n  private defaults: { redirectUri: string };\n\n  constructor(private $interval: angular.IIntervalService,\n              private $window: angular.IWindowService,\n              private $q: angular.IQService) {\n    this.popup = null;\n    this.defaults = {\n      redirectUri: null\n    };\n  }\n\n  stringifyOptions (options: any): string {\n    const parts = [];\n    angular.forEach(options, function (value, key) {\n      parts.push(key + '=' + value);\n    });\n    return parts.join(',');\n  }\n\n  open(url: string,\n       name: string,\n       popupOptions: { width: number, height: number },\n       redirectUri: string,\n       dontPoll?: boolean): angular.IPromise<any> {\n    const width = popupOptions.width || 500;\n    const height = popupOptions.height || 500;\n\n    const options = this.stringifyOptions({\n      width: width,\n      height: height,\n      top: this.$window.screenY + ((this.$window.outerHeight - height) / 2.5),\n      left: this.$window.screenX + ((this.$window.outerWidth - width) / 2)\n    });\n\n    const popupName = this.$window['cordova'] || this.$window.navigator.userAgent.indexOf('CriOS') > -1 ? '_blank' : name;\n\n    this.popup = this.$window.open(url, popupName, options);\n\n    if (this.popup && this.popup.focus) {\n      this.popup.focus();\n    }\n\n    if (dontPoll) {\n      return;\n    }\n\n    if (this.$window['cordova']) {\n      return this.eventListener(redirectUri);\n    } else {\n      if (url === 'about:blank') {\n        this.popup.location = url;\n      }\n      return this.polling(redirectUri);\n    }\n\n  }\n\n  polling(redirectUri: string): angular.IPromise<any> {\n    return this.$q((resolve, reject) => {\n      const redirectUriParser = document.createElement('a');\n      redirectUriParser.href = redirectUri;\n      const redirectUriPath = getFullUrlPath(redirectUriParser);\n\n      const polling = this.$interval(() => {\n        if (!this.popup || this.popup.closed || this.popup.closed === undefined) {\n          this.$interval.cancel(polling);\n          reject(new Error('The popup window was closed'));\n        }\n\n        try {\n          const popupWindowPath = getFullUrlPath(this.popup.location);\n\n          if (popupWindowPath === redirectUriPath) {\n            if (this.popup.location.search || this.popup.location.hash) {\n              const query = parseQueryString(this.popup.location.search.substring(1).replace(/\\/$/, ''));\n              const hash = parseQueryString(this.popup.location.hash.substring(1).replace(/[\\/$]/, ''));\n              const params = angular.extend({}, query, hash);\n\n              if (params.error) {\n                reject(new Error(params.error));\n              } else {\n                resolve(params);\n              }\n            } else {\n              reject(new Error(\n                'OAuth redirect has occurred but no query or hash parameters were found. ' +\n                'They were either not set during the redirect, or were removed—typically by a ' +\n                'routing library—before Satellizer could read it.'\n              ));\n            }\n\n            this.$interval.cancel(polling);\n            this.popup.close();\n          }\n        } catch (error) {\n          // Ignore DOMException: Blocked a frame with origin from accessing a cross-origin frame.\n          // A hack to get around same-origin security policy errors in IE.\n        }\n      }, 500);\n    });\n  }\n\n  eventListener(redirectUri): angular.IPromise<any> {\n    return this.$q((resolve, reject) => {\n      this.popup.addEventListener('loadstart', (event) => {\n        if (event.url.indexOf(redirectUri) !== 0) {\n          return;\n        }\n\n        const parser = document.createElement('a');\n        parser.href = event.url;\n\n        if (parser.search || parser.hash) {\n          const query = parseQueryString(parser.search.substring(1).replace(/\\/$/, ''));\n          const hash = parseQueryString(parser.hash.substring(1).replace(/[\\/$]/, ''));\n          const params = angular.extend({}, query, hash);\n\n          if (params.error) {\n            reject(new Error(params.error));\n          } else {\n            resolve(params);\n          }\n\n          this.popup.close();\n        }\n      });\n\n      this.popup.addEventListener('loaderror', () => {\n        reject(new Error('Authorization failed'));\n      });\n\n      this.popup.addEventListener('exit', () => {\n        reject(new Error('The popup window was closed'));\n      });\n    });\n  }\n}\n"
  },
  {
    "path": "src/shared.ts",
    "content": "import Config from './config';\nimport Storage from './storage';\nimport { decodeBase64 } from './utils';\n\nclass Shared {\n  static $inject = ['$q', '$window', 'SatellizerConfig', 'SatellizerStorage'];\n  \n  private prefixedTokenName: string;\n\n  constructor(private $q: angular.IQService,\n              private $window: angular.IWindowService,\n              private SatellizerConfig: Config,\n              private SatellizerStorage: Storage) {\n    const { tokenName, tokenPrefix } = this.SatellizerConfig;\n    this.prefixedTokenName = tokenPrefix ? [tokenPrefix, tokenName].join('_') : tokenName;\n  }\n\n  getToken(): string {\n    return this.SatellizerStorage.get(this.prefixedTokenName);\n  }\n\n  getPayload(): any {\n    const token = this.SatellizerStorage.get(this.prefixedTokenName);\n\n    if (token && token.split('.').length === 3) {\n      try {\n        const base64Url = token.split('.')[1];\n        const base64 = base64Url.replace('-', '+').replace('_', '/');\n        return JSON.parse(decodeBase64(base64));\n      } catch (e) {\n        // no-op\n      }\n    }\n  }\n\n  setToken(response): void {\n    const tokenRoot = this.SatellizerConfig.tokenRoot;\n    const tokenName = this.SatellizerConfig.tokenName;\n    const accessToken = response && response.access_token;\n\n    let token;\n\n    if (accessToken) {\n      if (angular.isObject(accessToken) && angular.isObject(accessToken.data)) {\n        response = accessToken;\n      } else if (angular.isString(accessToken)) {\n        token = accessToken;\n      }\n    }\n\n    if (!token && response) {\n      const tokenRootData = tokenRoot && tokenRoot.split('.').reduce((o, x) => o[x], response.data);\n      token = tokenRootData ? tokenRootData[tokenName] : response.data && response.data[tokenName];\n    }\n\n    if (token) {\n      this.SatellizerStorage.set(this.prefixedTokenName, token);\n    }\n  }\n\n  removeToken(): void {\n    this.SatellizerStorage.remove(this.prefixedTokenName);\n  }\n\n  isAuthenticated(): boolean {\n    const token = this.SatellizerStorage.get(this.prefixedTokenName);\n\n    if (token) {  // Token is present\n      if (token.split('.').length === 3) {  // Token with a valid JWT format XXX.YYY.ZZZ\n        try { // Could be a valid JWT or an access token with the same format\n          const base64Url = token.split('.')[1];\n          const base64 = base64Url.replace('-', '+').replace('_', '/');\n          const exp = JSON.parse(this.$window.atob(base64)).exp;\n          if (typeof exp === 'number') {  // JWT with an optonal expiration claims\n            return Math.round(new Date().getTime() / 1000) < exp;\n          }\n        } catch (e) {\n          return true;  // Pass: Non-JWT token that looks like JWT\n        }\n      }\n      return true;  // Pass: All other tokens\n    }\n    return false; // Fail: No token at all\n  }\n\n  logout(): angular.IPromise<void> {\n    this.SatellizerStorage.remove(this.prefixedTokenName);\n    return this.$q.when();\n  }\n\n  setStorageType(type): void {\n    this.SatellizerConfig.storageType = type;\n  }\n}\n\nexport default Shared;\n"
  },
  {
    "path": "src/storage.ts",
    "content": "import Config from './config';\n\nexport default class Storage {\n  static $inject = ['$window', 'SatellizerConfig'];\n\n  private memoryStore: any;\n  private storageType: string;\n\n  constructor(private $window: angular.IHttpService,\n              private SatellizerConfig: Config) {\n    this.memoryStore = {};\n  }\n\n  get(key: string): string {\n    try {\n      return this.$window[this.SatellizerConfig.storageType].getItem(key);\n    } catch (e) {\n      return this.memoryStore[key];\n    }\n  }\n\n  set(key: string, value: string): void {\n    try {\n      this.$window[this.SatellizerConfig.storageType].setItem(key, value);\n    } catch (e) {\n      this.memoryStore[key] = value;\n    }\n  }\n\n  remove(key: string): void {\n    try {\n      this.$window[this.SatellizerConfig.storageType].removeItem(key);\n    } catch (e) {\n      delete this.memoryStore[key];\n    }\n  }\n}\n"
  },
  {
    "path": "src/utils.ts",
    "content": "export function joinUrl (baseUrl, url) {\n  if (/^(?:[a-z]+:)?\\/\\//i.test(url)) {\n    return url;\n  }\n  let joined = [baseUrl, url].join('/');\n  let normalize = function (str) {\n    return str\n      .replace(/[\\/]+/g, '/')\n      .replace(/\\/\\?/g, '?')\n      .replace(/\\/\\#/g, '#')\n      .replace(/\\:\\//g, '://');\n  };\n  return normalize(joined);\n}\n\nexport function getFullUrlPath (location) {\n  const isHttps = location.protocol === 'https:';\n  return location.protocol + '//' + location.hostname +\n    ':' + (location.port || (isHttps ? '443' : '80')) +\n    (/^\\//.test(location.pathname) ? location.pathname : '/' + location.pathname);\n}\n\nexport function parseQueryString (str) {\n  let obj = {};\n  let key;\n  let value;\n  angular.forEach((str || '').split('&'), (keyValue) => {\n    if (keyValue) {\n      value = keyValue.split('=');\n      key = decodeURIComponent(value[0]);\n      obj[key] = angular.isDefined(value[1]) ? decodeURIComponent(value[1]) : true;\n    }\n  });\n  return obj;\n}\n\nexport function decodeBase64 (str) {\n  let buffer;\n  if (typeof module !== 'undefined' && module.exports) {\n    try {\n      buffer = require('buffer').Buffer;\n    } catch (err) {\n      // noop\n    }\n  }\n\n  let fromCharCode = String.fromCharCode;\n\n  let re_btou = new RegExp([\n    '[\\xC0-\\xDF][\\x80-\\xBF]',\n    '[\\xE0-\\xEF][\\x80-\\xBF]{2}',\n    '[\\xF0-\\xF7][\\x80-\\xBF]{3}'\n  ].join('|'), 'g');\n\n  let cb_btou = function (cccc) {\n    switch (cccc.length) {\n      case 4:\n        let cp = ((0x07 & cccc.charCodeAt(0)) << 18)\n          | ((0x3f & cccc.charCodeAt(1)) << 12)\n          | ((0x3f & cccc.charCodeAt(2)) << 6)\n          | (0x3f & cccc.charCodeAt(3));\n        let offset = cp - 0x10000;\n        return (fromCharCode((offset >>> 10) + 0xD800)\n        + fromCharCode((offset & 0x3FF) + 0xDC00));\n      case 3:\n        return fromCharCode(\n          ((0x0f & cccc.charCodeAt(0)) << 12)\n          | ((0x3f & cccc.charCodeAt(1)) << 6)\n          | (0x3f & cccc.charCodeAt(2))\n        );\n      default:\n        return fromCharCode(\n          ((0x1f & cccc.charCodeAt(0)) << 6)\n          | (0x3f & cccc.charCodeAt(1))\n        );\n    }\n  };\n\n  let btou = function (b) {\n    return b.replace(re_btou, cb_btou);\n  };\n\n  let _decode = buffer ? function (a) {\n    return (a.constructor === buffer.constructor\n      ? a : new buffer(a, 'base64')).toString();\n  }\n    : function (a) {\n    return btou(atob(a));\n  };\n\n  return _decode(\n    String(str).replace(/[-_]/g, function (m0) {\n      return m0 === '-' ? '+' : '/';\n    })\n      .replace(/[^A-Za-z0-9\\+\\/]/g, '')\n  );\n}\n"
  },
  {
    "path": "test/annotations.spec.ts",
    "content": "import satellizer from './../src/ng1';\n\ndescribe('angular annotations', () => {\n\n  beforeEach(angular.mock.module(satellizer));\n\n  beforeEach(() => {\n    angular.mock.inject.strictDi(true);\n  });\n\n  it('should create the injector without errors', angular.mock.inject(['$auth', ($auth) => {\n    expect($auth).toBeTruthy();\n  }]));\n\n});"
  },
  {
    "path": "test/authProvider.spec.ts",
    "content": "import Config from '../src/config';\nimport Storage from '../src/storage';\nimport Shared from '../src/shared';\nimport Popup from '../src/popup';\nimport OAuth1 from '../src/oauth1';\nimport OAuth2 from '../src/oauth2';\nimport OAuth from '../src/oauth';\nimport Local from '../src/local';\nimport AuthProvider from '../src/authProvider';\n\nlet window;\nlet http;\nlet httpBackend;\nlet config;\nlet authProvider;\nlet storage;\nlet shared;\nlet popup;\nlet oauth1;\nlet oauth2;\nlet oauth;\nlet local;\nlet auth;\nconst token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7Il9pZCI6IjUzZTU3ZDZiY2MzNmMxNTgwNzU4NDJkZCIsImVtYWlsIjoiZm9vQGJhci5jb20iLCJfX3YiOjB9LCJpYXQiOjE0MDc1NDg3ODI5NzMsImV4cCI6MTQwODE1MzU4Mjk3M30.1Ak6mij5kfkSi6d_wtPOx4yK7pS7ZFSiwbkL7AJbnYs';\n\ndescribe('AuthProvider', () => {\n\n  beforeEach(() => {\n    config = new Config();\n    authProvider = new AuthProvider(config);\n  });\n\n  beforeEach(angular.mock.inject(($q, $http, $window, $interval, $timeout, $httpBackend) => {\n    window = $window;\n    http = $http;\n    httpBackend = $httpBackend;\n    storage = new Storage($window, config);\n    shared = new Shared($q, $window, config, storage);\n    popup = new Popup($interval, $window, $q);\n    oauth1 = new OAuth1($http, $window, config, popup);\n    oauth2 = new OAuth2($http, $window, $timeout, $q, config, popup, storage);\n    oauth = new OAuth($http, $window, $timeout, $q, config, popup, storage, shared, oauth1, oauth2);\n    local = new Local($http, config, shared);\n    auth = authProvider.$get(shared, local, oauth);\n  }));\n\n  it('should set baseUrl', () => {\n    authProvider.baseUrl = '/api/v2/';\n    expect(authProvider.baseUrl).toEqual('/api/v2/');\n  });\n\n  it('should set loginUrl', () => {\n    authProvider.loginUrl = '/api/sign_in';\n    expect(authProvider.loginUrl).toEqual('/api/sign_in');\n  });\n\n  it('should set signupUrl', () => {\n    authProvider.signupUrl = '/api/register';\n    expect(authProvider.signupUrl).toEqual('/api/register');\n  });\n\n  it('should set unlinkUrl', () => {\n    authProvider.unlinkUrl = '/disconnect';\n    expect(authProvider.unlinkUrl).toEqual('/disconnect');\n  });\n\n  it('should set tokenRoot', () => {\n    authProvider.tokenRoot = 'deep.nested.object';\n    expect(authProvider.tokenRoot).toEqual('deep.nested.object');\n  });\n\n  it('should set tokenName', () => {\n    authProvider.tokenName = 'access_token';\n    expect(authProvider.tokenName).toEqual('access_token');\n  });\n\n  it('should set tokenPrefix', () => {\n    authProvider.tokenPrefix = 'myApp';\n    expect(authProvider.tokenPrefix).toEqual('myApp');\n  });\n\n  it('should set tokenHeader', () => {\n    authProvider.tokenHeader = 'x-auth-token';\n    expect(authProvider.tokenHeader).toEqual('x-auth-token');\n  });\n\n  it('should set tokenType', () => {\n    authProvider.tokenType = 'TOKEN';\n    expect(authProvider.tokenType).toEqual('TOKEN');\n  });\n\n  it('should set withCredentials', () => {\n    authProvider.withCredentials = false;\n    expect(authProvider.withCredentials).toEqual(false);\n  });\n\n  it('should set storageType', () => {\n    authProvider.storageType = 'sessionStorage';\n    expect(authProvider.storageType).toEqual('sessionStorage');\n  });\n\n  it('should set httpInterceptor as a boolean', () => {\n    authProvider.httpInterceptor = false;\n    expect(authProvider.httpInterceptor()).toEqual(false);\n  });\n\n  it('should set httpInterceptor as a function', () => {\n    authProvider.httpInterceptor = (request) => {\n      return request.uri.indexOf('/api/') === 0;\n    };\n    expect(authProvider.httpInterceptor({ uri: '/somewhere/else' })).toEqual(false);\n  });\n\n  it('should set facebook with new params', () => {\n    authProvider.facebook({ clientId: '1234' });\n    expect(config.providers.facebook.clientId).toBe('1234');\n  });\n\n  it('should set google with new params', () => {\n    authProvider.google({ state: 'secret' });\n    expect(config.providers.google.state).toBe('secret');\n  });\n\n  it('should set github with new params', () => {\n    authProvider.github({ clientId: '1234' });\n    expect(config.providers.github.clientId).toBe('1234');\n  });\n\n  it('should set linkedin with new params', () => {\n    authProvider.linkedin({ state: 'secret' });\n    expect(config.providers.linkedin.state).toBe('secret');\n  });\n\n  it('should set twitter with new params', () => {\n    authProvider.twitter({ url: '/api/twitter' });\n    expect(config.providers.twitter.url).toBe('/api/twitter');\n  });\n\n  it('should create new OAuth 2.0 provider', () => {\n    authProvider.oauth2({ name: 'instagram', url: '/auth/instagram' });\n    expect(config.providers.instagram.name).toBe('instagram');\n    expect(config.providers.instagram.url).toBe('/auth/instagram');\n  });\n\n  it('should create new OAuth 1.0 provider', () => {\n    authProvider.oauth1({ name: 'goodreads', url: '/auth/goodreads' });\n    expect(config.providers.goodreads.url).toBe('/auth/goodreads');\n  });\n\n  describe('$auth service', () => {\n\n    it('should be defined', () => {\n      expect(auth).toBeDefined();\n    });\n\n    describe('authenticate()', () => {\n\n      it('should be defined', () => {\n        expect(auth.authenticate).toBeDefined();\n      });\n\n      it('should authenticate', () => {\n        spyOn(oauth, 'authenticate');\n        auth.authenticate('facebook');\n        expect(oauth.authenticate).toHaveBeenCalled();\n      });\n\n    });\n\n    describe('isAuthenticated()', () => {\n\n      it('should be defined', () => {\n        expect(auth.isAuthenticated).toBeDefined();\n      });\n\n      it('should check if user is authenticated', () => {\n        const storageType = config.storageType;\n        const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n        window[storageType][tokenName] = token;\n        expect(auth.isAuthenticated()).toBe(true);\n      });\n\n    });\n\n    describe('getToken()', () => {\n\n      it('should be defined', () => {\n        expect(auth.getToken).toBeDefined();\n      });\n\n      it('should get token', () => {\n        const storageType = config.storageType;\n        const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n        window[storageType][tokenName] = token;\n        expect(auth.getToken()).toEqual(window[storageType][tokenName]);\n      });\n\n    });\n\n    describe('setToken()', () => {\n\n      it('should be defined', () => {\n        expect(auth.setToken).toBeDefined();\n      });\n\n      it('should set token', () => {\n        const response = {\n          data: {\n            token: token\n          }\n        };\n        auth.setToken(response);\n        expect(token).toEqual(auth.getToken());\n      });\n\n    });\n\n    describe('removeToken()', () => {\n\n      it('should be defined', () => {\n        expect(auth.removeToken).toBeDefined();\n      });\n\n      it('should remove token', () => {\n        const storageType = config.storageType;\n        const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n        window[storageType][tokenName] = token;\n        auth.removeToken();\n        expect(window.localStorage[tokenName]).toBeUndefined();\n      });\n\n    });\n\n    describe('getPayload()', () => {\n\n      it('should be defined', () => {\n        expect(auth.getPayload).toBeDefined();\n      });\n\n      it('should get a JWT payload', () => {\n        const storageType = config.storageType;\n        const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n        window[storageType][tokenName] = token;\n        const payload = auth.getPayload();\n        expect(payload).toBeDefined();\n        expect(angular.isObject(payload)).toBe(true);\n      });\n\n    });\n\n    describe('link()', () => {\n\n      it('should be defined', () => {\n        expect(auth.link).toBeDefined();\n      });\n\n      it('should link third-party provider', () => {\n        spyOn(oauth, 'authenticate');\n        auth.link('facebook');\n        expect(oauth.authenticate).toHaveBeenCalled();\n      });\n\n    });\n\n    describe('unlink()', () => {\n\n      it('should be defined', () => {\n        expect(auth.unlink).toBeDefined();\n      });\n\n      it('should unlink third-party provider', () => {\n        let result = null;\n\n        httpBackend.expectPOST('/auth/unlink/').respond(200);\n\n        auth.unlink('facebook').then((response) => {\n          result = response.status;\n        });\n\n        httpBackend.flush();\n\n        expect(result).toBe(200);\n      });\n\n    });\n\n    describe('logout()', () => {\n\n      it('should be defined', () => {\n        expect(auth.logout).toBeDefined();\n      });\n\n      it('should log out a user', () => {\n        const storageType = config.storageType;\n        const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n        auth.logout();\n        expect([storageType][tokenName]).toBeUndefined();\n      });\n\n    });\n\n    describe('login()', () => {\n\n      it('should be defined', () => {\n        expect(auth.login).toBeDefined();\n      });\n\n      it('should be able to call login', function () {\n        spyOn(local, 'login');\n        const user = { email: 'foo@bar.com', password: '1234' };\n        auth.login(user);\n        expect(local.login).toHaveBeenCalled();\n      });\n\n      describe('signup()', () => {\n\n        it('should be able to call signup', () => {\n          spyOn(local, 'signup');\n          const user = { email: 'foo@bar.com', password: '1234' };\n          auth.signup(user);\n          expect(local.signup).toHaveBeenCalled();\n        });\n\n      });\n\n      describe('setStorageType()', () => {\n\n        it('should be defined', () => {\n          expect(auth.setStorageType).toBeDefined();\n        });\n\n        it('should set storage type', () => {\n          auth.setStorageType('sessionStorage');\n          expect(config.storageType).toBe('sessionStorage');\n        });\n\n      });\n\n    });\n\n  });\n\n});\n"
  },
  {
    "path": "test/local.spec.ts",
    "content": "import Local from '../src/local';\nimport Shared from '../src/shared';\nimport Storage from '../src/storage';\nimport Config from '../src/config';\n\nlet httpBackend;\nlet location;\nlet window;\nlet config;\nlet storage;\nlet shared;\nlet local;\n\ndescribe('Local', () => {\n\n  beforeEach(angular.mock.inject(($q, $http, $window, $httpBackend, $location) => {\n    httpBackend = $httpBackend;\n    location = $location;\n    window = $window;\n    config = new Config();\n    storage = new Storage($window, config);\n    shared = new Shared($q, $window, config, storage);\n    local = new Local($http, config, shared);\n  }));\n\n  afterEach(() => {\n    window.localStorage.clear();\n    window.sessionStorage.clear();\n    httpBackend.verifyNoOutstandingExpectation();\n    httpBackend.verifyNoOutstandingRequest();\n  });\n\n  describe('login()', () => {\n\n    it('should be defined', () => {\n      expect(local.login).toBeDefined();\n    });\n\n    it('should return a user object on successful login', () => {\n      let result = null;\n      const user = { email: 'john@email.com', password: 'password' };\n      const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7Il9pZCI6IjUzZjYxZTEwNmZjNjFhNmMxM2I1Mjc4ZCIsImVtYWlsIjoic2FoYXQ_QG1lLmNvbSIsIl9fdiI6MH0sImlhdCI6MTQwODgyMTA5MTY3NiwiZXhwIjoxNDA5NDI1ODkxNjc2fQ.0l-ql-ZVjHiILMcMegNb3bNqapt3TZwjHy_ieduioiQ';\n\n      httpBackend.expectPOST(config.loginUrl).respond({ token: token });\n\n      local.login(user).then((response) => {\n        result = response.data.token;\n      });\n\n      httpBackend.flush();\n\n      expect(shared.isAuthenticated()).toBe(true);\n      expect(result).toEqual(token);\n    });\n\n    it('should fail login with incorrect credentials', () => {\n      let result = null;\n      const user = { email: 'foo@bar.com', password: 'invalid' };\n\n      httpBackend.expectPOST(config.loginUrl).respond(401, 'Wrong email or password');\n\n      local.login(user).catch((response) => {\n        result = response.data;\n      });\n\n      httpBackend.flush();\n\n      expect(shared.isAuthenticated()).toBe(false);\n      expect(result).toEqual('Wrong email or password');\n    });\n\n  });\n\n  describe('signup()', () => {\n\n    it('should have a signup function', () => {\n      expect(local.signup).toBeDefined();\n      expect(angular.isFunction(local.signup)).toBe(true);\n    });\n\n    it('should create a new user', () => {\n      let result = null;\n      const user = { email: 'john@email.com', password: '1234' };\n      const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7Il9pZCI6IjUzZjYxZTEwNmZjNjFhNmMxM2I1Mjc4ZCIsImVtYWlsIjoic2FoYXQ_QG1lLmNvbSIsIl9fdiI6MH0sImlhdCI6MTQwODgyMTA5MTY3NiwiZXhwIjoxNDA5NDI1ODkxNjc2fQ.0l-ql-ZVjHiILMcMegNb3bNqapt3TZwjHy_ieduioiQ';\n\n      httpBackend.expectPOST(config.signupUrl).respond({ token: token });\n\n      local.signup(user).then((response) => {\n        result = response.data.token;\n      });\n\n      httpBackend.flush();\n\n      expect(result).toEqual(token);\n    });\n\n    it('should be able to handle signup errors', () => {\n      let result = null;\n      const user = { email: 'foo@bar.com', password: '1234' };\n\n      httpBackend.expectPOST(config.signupUrl).respond(400);\n\n      local.signup(user).catch(() => {\n        result = false;\n      });\n\n      httpBackend.flush();\n\n      expect(result).toBe(false);\n    });\n\n  });\n\n});\n"
  },
  {
    "path": "test/oauth.spec.ts",
    "content": "import OAuth from '../src/oauth';\nimport OAuth1 from '../src/oauth1';\nimport OAuth2 from '../src/oauth2';\nimport Config from '../src/config';\nimport Shared from '../src/shared';\nimport Storage from '../src/storage';\nimport Popup from '../src/popup';\n\nlet httpBackend;\nlet config;\nlet storage;\nlet shared;\nlet popup;\nlet oauth;\nlet oauth1;\nlet oauth2;\n\ndescribe('OAuth', () => {\n\n  beforeEach(angular.mock.inject(($q, $http, $window, $interval, $httpBackend, $timeout) => {\n    httpBackend = $httpBackend;\n    config = new Config();\n    storage = new Storage($window, config);\n    shared = new Shared($q, $window, config, storage);\n    popup = new Popup($interval, $window, $q);\n    oauth1 = new OAuth1($http, $window, config, popup);\n    oauth2 = new OAuth2($http, $window, $timeout, $q, config, popup, storage);\n    oauth = new OAuth($http, $window, $timeout, $q, config, popup, storage, shared, oauth1, oauth2);\n  }));\n\n  afterEach(() => {\n    httpBackend.verifyNoOutstandingExpectation();\n    httpBackend.verifyNoOutstandingRequest();\n  });\n\n  describe('unlink()', () => {\n\n    it('should be defined', () => {\n      expect(oauth.unlink).toBeDefined();\n    });\n\n    it('should unlink a provider successfully', () => {\n      let result = null;\n\n      httpBackend.expectPOST(config.unlinkUrl).respond(200);\n\n      oauth.unlink('google').then((response) => {\n        result = response.status;\n      });\n\n      httpBackend.flush();\n\n      expect(result).toBe(200);\n    });\n\n    it('should unlink a provider and get an error', () => {\n      let result = null;\n\n      httpBackend.expectPOST(config.unlinkUrl).respond(400);\n\n      oauth.unlink('facebook').catch((response) => {\n        result = response.status;\n      });\n\n      httpBackend.flush();\n\n      expect(result).toEqual(400);\n    });\n\n  });\n\n});\n"
  },
  {
    "path": "test/oauth1.spec.ts",
    "content": "import OAuth1 from '../src/oauth1';\nimport Config from '../src/config';\nimport Shared from '../src/shared';\nimport Storage from '../src/storage';\nimport Popup from '../src/popup';\n\nlet httpBackend;\nlet config;\nlet storage;\nlet shared;\nlet popup;\nlet oauth1;\n\ndescribe('OAuth1', () => {\n\n  beforeEach(angular.mock.inject(($q, $http, $window, $interval, $httpBackend) => {\n    httpBackend = $httpBackend;\n    config = new Config();\n    storage = new Storage($window, config);\n    shared = new Shared($q, $window, config, storage);\n    popup = new Popup($interval, $window, $q);\n    oauth1 = new OAuth1($http, $window, config, popup);\n  }));\n\n  afterEach(() => {\n    httpBackend.verifyNoOutstandingExpectation();\n    httpBackend.verifyNoOutstandingRequest();\n  });\n\n  describe('init()', () => {\n\n    it('should be defined', () => {\n      expect(oauth1.init).toBeDefined();\n    });\n\n    it('should work with a web browser', () => {\n      let result = null;\n\n      httpBackend.expectPOST('/auth/twitter').respond(200);\n\n      oauth1.init(config.providers.twitter).then((response) => {\n        result = response;\n      });\n\n      httpBackend.flush();\n    });\n\n  });\n\n  describe('getRequestToken()', () => {\n\n    it('should be defined', () => {\n      expect(oauth1.getRequestToken).toBeDefined();\n    });\n\n    it('should get request token to initiate oauth 1.0 flow', () => {\n      let result = null;\n\n      Object.assign(oauth1.defaults, config.providers.twitter);\n\n      httpBackend.expectPOST('/auth/twitter').respond(200, { request_token: 'qwerty' });\n\n      oauth1.getRequestToken().then((response) => {\n        result = response.data.request_token;\n      });\n\n      httpBackend.flush();\n\n      expect(result).toBe('qwerty');\n    });\n\n  });\n\n  describe('exchangeForToken()', () => {\n\n    it('should be defined', () => {\n      expect(oauth1.exchangeForToken).toBeDefined();\n    });\n\n    it('should exchange oauth_token and oauth_verifier for JWT token', () => {\n      Object.assign(oauth1.defaults, config.providers.twitter);\n\n      let result = null;\n      const oauthData = {\n        oauth_token: 'foo',\n        oauth_verifier: 'bar'\n      };\n\n      httpBackend.expectPOST('/auth/twitter').respond(200, { token: 'jwt token' });\n\n      oauth1.exchangeForToken(oauthData).then((response) => {\n        result = response.data.token;\n      });\n\n      httpBackend.flush();\n\n      expect(result).toBe('jwt token');\n    });\n\n  });\n\n  describe('buildQueryString()', () => {\n\n    it('should be defined', () => {\n      expect(oauth1.buildQueryString).toBeDefined();\n    });\n\n    it('should build a query', () => {\n      const querystring = oauth1.buildQueryString({ code: 'test1', client_id: 'test2', redirect_uri: 'test3' });\n      expect(querystring).toBe('code=test1&client_id=test2&redirect_uri=test3');\n    });\n\n  });\n\n});\n\n"
  },
  {
    "path": "test/oauth2.spec.ts",
    "content": "import OAuth2 from '../src/oauth2';\nimport Config from '../src/config';\nimport Shared from '../src/shared';\nimport Storage from '../src/storage';\nimport Popup from '../src/popup';\n\nlet q;\nlet window;\nlet http;\nlet timeout;\nlet httpBackend;\nlet config;\nlet storage;\nlet shared;\nlet popup;\nlet oauth2;\n\ndescribe('OAuth2', () => {\n\n  beforeEach(angular.mock.inject(($q, $http, $window, $interval, $timeout, $httpBackend) => {\n    q = $q;\n    http = $http;\n    window = $window;\n    timeout = $timeout;\n    httpBackend = $httpBackend;\n    config = new Config();\n    storage = new Storage($window, config);\n    shared = new Shared($q, $window, config, storage);\n    popup = new Popup($interval, $window, $q);\n    oauth2 = new OAuth2($http, $window, $timeout, $q, config, popup, storage);\n  }));\n\n  afterEach(() => {\n    httpBackend.verifyNoOutstandingExpectation();\n    httpBackend.verifyNoOutstandingRequest();\n  });\n\n  describe('init()', () => {\n\n    it('should be defined', () => {\n      expect(oauth2.init).toBeDefined();\n    });\n\n    it('should open a popup window', () => {\n      spyOn(window, 'open');\n      oauth2.init(config.providers.github);\n\n      expect(window.open).toHaveBeenCalled();\n    });\n\n    it('should propagate promise rejections', () => {\n      let result = null;\n      const p = Promise.reject(new Error('The popup window was closed'));\n      spyOn(popup, 'polling').and.returnValue(p);\n\n      oauth2.init(config.providers.github).catch((err) => {\n        result = err.message;\n        expect(result).toEqual('The popup window was closed');\n      });\n\n      expect(popup.polling).toHaveBeenCalled();\n    });\n\n  });\n\n  describe('exchangeForToken()', () => {\n\n    it('should be defined', () => {\n      expect(oauth2.exchangeForToken).toBeDefined();\n    });\n\n    it('should exchange code for token', () => {\n      let result = null;\n\n      httpBackend.expectPOST('/').respond(200, { token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9' });\n\n      oauth2.exchangeForToken({ code: '1234567890' }).then((response) => {\n        result = response.data.token;\n      });\n\n      httpBackend.flush();\n\n      expect('eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9');\n    });\n\n    it('should exchange code for token with custom responseParams', () => {\n      let result = null;\n      const deferred = q.defer();\n      spyOn(http, 'post').and.returnValue(deferred.promise);\n\n      oauth2.defaults.clientId = 'asdf1234';\n      oauth2.defaults.redirectUri = 'http://localhost/callback';\n      oauth2.defaults.responseParams = {\n        code: 'code',\n        clientId: 'client_id',\n        redirectUri: 'redirect_uri'\n      };\n\n      oauth2.exchangeForToken({ code: '1234567890' }).then((response) => {\n        result = response.data.token;\n      });\n\n      expect(http.post).toHaveBeenCalledWith(\n        '/',\n        { code: '1234567890', client_id: 'asdf1234', redirect_uri: 'http://localhost/callback' },\n        { withCredentials: false }\n      );\n    });\n\n  });\n\n  xdescribe('buildQueryString()', () => {\n    it('should be defined', () => {\n      expect(oauth2.buildQueryString).toBeDefined();\n    });\n\n    it('should URI-encode state value', () => {\n      oauth2.open({ defaultUrlParams: ['state'], state: 'foo+bar' }).then(() => {\n        expect(oauth2.buildQueryString()).toContain('state=foo%2Bbar');\n      });\n\n      timeout.flush();\n      timeout.verifyNoPendingTasks();\n    });\n\n    it('should use scopePrefix if provided', () => {\n      oauth2.open(config.providers.google)\n        .then(() => {\n          expect(oauth2.buildQueryString()).toContain('scope=openid profile email');\n        });\n      timeout.flush();\n      timeout.verifyNoPendingTasks();\n    });\n\n    it('should remove redirect_uri if param redirectUrl is null', () => {\n      const tempProvider = angular.copy(config.providers.google);\n      tempProvider.redirectUri = null;\n      oauth2.open(tempProvider)\n        .then(() => {\n          expect(oauth2.buildQueryString()).not.toContain('redirect_uri=');\n        });\n      this.$timeout.flush();\n      this.$timeout.verifyNoPendingTasks();\n    });\n\n  });\n\n  describe('camelCase()', () => {\n\n    it('should be defined', () => {\n      expect(OAuth2.camelCase).toBeDefined();\n    });\n\n    it('should return camelized string', () => {\n      expect(OAuth2.camelCase('redirect_uri')).toEqual('redirectUri');\n    });\n\n  });\n\n});\n\n"
  },
  {
    "path": "test/popup.spec.ts",
    "content": "import Popup from '../src/popup';\n\nlet interval;\nlet window;\nlet popup;\n\ndescribe('Popup', () => {\n\n  beforeEach(angular.mock.inject(($interval, $window, $q) => {\n    interval = $interval;\n    window = $window;\n    popup = new Popup($interval, $window, $q);\n  }));\n\n  it('should be defined', () => {\n    expect(popup).toBeDefined();\n  });\n\n  it('should stringify popup options', () => {\n    const options = { width: 481, height: 269 };\n    const stringOptions = popup.stringifyOptions(options);\n    expect(stringOptions).toBe('width=481,height=269');\n  });\n\n  it('should open a new popup', () => {\n    spyOn(window, 'open');\n    popup.open('about:blank', 'test', { width: 500, height: 500 }, 'http://localhost/redirect', true);\n    interval.flush(1000);\n    expect(window.open).toHaveBeenCalled();\n  });\n\n  it('should poll popup', () => {\n    const open = popup.polling();\n    interval.flush(300);\n    expect(angular.isObject(open)).toBe(true);\n  });\n\n  it('should handle the case when popup redirect has occured', () => {\n    popup.popup = {\n      location: {\n        host: document.location.host,\n        search: '?code=foo_query',\n        hash: '#code=foo_hash'\n      }\n    };\n    const open = popup.polling();\n    interval.flush(300);\n    expect(angular.isObject(open)).toBe(true);\n  });\n\n  it('should handle the case when popup redirect has occured but no parameters are set', () => {\n    popup.popup = {\n      location: {\n        host: document.location.host\n      }\n    };\n    const open = popup.polling();\n    let error = null;\n    open.catch((err) => {\n      error = err;\n    });\n    interval.flush(300);\n    expect(error).toBeDefined();\n  });\n\n  it('should handle the case when popup is closed', () => {\n    const open = popup.polling();\n    let error = null;\n    open.catch((err) => {\n      error = err;\n    });\n    interval.flush(300);\n    expect(error).toBeDefined();\n  });\n});\n\n"
  },
  {
    "path": "test/shared.spec.ts",
    "content": "import Shared from '../src/shared';\nimport Storage from '../src/storage';\nimport Config from '../src/config';\n\nlet window;\nlet config;\nlet storage;\nlet shared;\n\ndescribe('Shared', () => {\n\n  beforeEach(angular.mock.inject(($q, $window) => {\n    window = $window;\n    config = new Config();\n    storage = new Storage($window, config);\n    shared = new Shared($q, $window, config, storage);\n  }));\n\n  afterEach(() => {\n    window.localStorage.clear();\n    window.sessionStorage.clear();\n  });\n\n  describe('logout()', () => {\n\n    it('should be defined', () => {\n      expect(shared.logout).toBeDefined();\n    });\n\n    it('should log out a user', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9';\n      shared.logout();\n      expect(window[storageType][tokenName]).toBeFalsy();\n    });\n\n  });\n\n  describe('getToken()', () => {\n\n    it('should be defined', () => {\n      expect(shared.getToken).toBeDefined();\n    });\n\n    it('should get a token from Local Storage', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9';\n      expect(shared.getToken()).toEqual(window[storageType][tokenName]);\n    });\n\n  });\n\n  describe('getPayload()', () => {\n\n    it('should be defined', () => {\n      expect(shared.getPayload).toBeDefined();\n    });\n\n    it('should get a JWT payload', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEyMzQ1Njc4OTAsIm5hbWUiOiJKb2huIERvZSJ9.kRkUHzvZMWXjgB4zkO3d6P1imkdp0ogebLuxnTCiYUU';\n      const payload = shared.getPayload();\n      expect(angular.isObject(payload)).toBe(true);\n      expect(payload.name).toEqual('John Doe');\n    });\n\n    it('should get a JWT payload with non-english characters', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOjEyMzQ1Njc4OTAsIm5hbWUiOiJSb2LDqXJ0w6AgVGjDqcO0In0.sgREDWs78UYxIMDfa9cwYqvDgco3i_Ap4MUwmprZWN0';\n      const payload = shared.getPayload();\n      expect(angular.isObject(payload)).toBe(true);\n      expect(payload.name).toEqual('Robértà Théô');\n    });\n\n    it('should return undefined if not a valid JWT', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa';\n      const payload = shared.getPayload();\n      expect(payload).toBeUndefined();\n    });\n\n    it('should return undefined if token looks like JWT but is not valid', function () {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'f0af717251950dbd4.d73154fdf0a474a5c5119ada.d999683f5b450c460726aa';\n      const payload = shared.getPayload();\n      expect(payload).toBeUndefined();\n    });\n\n  });\n\n  describe('isAuthenticated()', () => {\n\n    it('should be defined', () => {\n      expect(shared.isAuthenticated).toBeDefined();\n      expect(angular.isFunction(shared.isAuthenticated)).toBe(true);\n    });\n\n    it('should handle expired token', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNDQ1NDEzODU5LCJleHAiOjE0NDU0MTM4NjR9.FWflFgVTYu4riXLDzOAx9xy1x-qYyzwi09oN_pmoLcg';\n      expect(shared.isAuthenticated()).toBe(false);\n    });\n\n    it('should work with non-JWT token', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'foo.bar.baz';\n      expect(shared.isAuthenticated()).toBe(true);\n    });\n\n  });\n\n  describe('setToken()', () => {\n\n    it('should gracefully return without a response param', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      shared.setToken();\n      expect(window[storageType][tokenName]).toBeUndefined();\n    });\n\n    it('should set the token when tokenRoot is provided', () => {\n      const token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsb…YzMn0.YATZN37JENCQWeNAoN4M7KxJl7OAIJL4ka_fSM_gYkE';\n      const response = {\n        data: {\n          foo: {\n            bar: {\n              token: token\n            }\n          }\n        }\n      };\n      config.tokenRoot = 'foo.bar';\n      shared.setToken(response);\n      expect(token).toEqual(shared.getToken());\n    });\n\n    it('should set string access_token', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      const response = { access_token: 'test' };\n      shared.setToken(response);\n      expect(window[storageType][tokenName]).toBe('test');\n    });\n\n    it('should set object access_token', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      const response = {\n        access_token: {\n          data: {\n            token: 'access_token_object_test'\n          }\n        }\n      };\n      shared.setToken(response);\n      expect(window[storageType][tokenName]).toBe('access_token_object_test');\n    });\n\n    it('should gracefully return if no token is passed in', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      delete window[storageType][tokenName];\n      const response = {\n        access_token: {\n          data: {}\n        }\n      };\n      shared.setToken(response);\n      expect(window[storageType][tokenName]).toBeUndefined();\n    });\n\n  });\n\n  describe('removeToken()', () => {\n\n    it('should be defined', () => {\n      expect(shared.removeToken).toBeDefined();\n    });\n\n    it('should remove a token', () => {\n      const storageType = config.storageType;\n      const tokenName = [config.tokenPrefix, config.tokenName].join('_');\n      window[storageType][tokenName] = 'f0af717251950dbd4d73154fdf0a474a5c5119adad999683f5b450c460726aa';\n      shared.removeToken();\n      expect(window[storageType][tokenName]).toBeUndefined();\n    });\n\n  });\n\n  describe('setStorageType()', () => {\n\n    it('should be defined', () => {\n      expect(shared.setStorageType).toBeDefined();\n    });\n\n    it('should be able to set storage type to session storage', () => {\n      shared.setStorageType('sessionStorage');\n      expect(config.storageType).toBe('sessionStorage');\n    });\n\n  });\n\n});\n"
  },
  {
    "path": "test/storage.spec.ts",
    "content": "import Config from '../src/config';\nimport Storage from '../src/storage';\n\nlet config;\nlet storage;\n\ndescribe('Storage', () => {\n\n  beforeEach(angular.mock.inject(($q) => {\n    config = new Config();\n    storage = new Storage($q, config);\n  }));\n\n  it('should save token to local storage', () => {\n    storage.set('token', 'foo');\n    expect(storage.get('token')).toEqual('foo');\n  });\n\n  it('should remove token to local storage', () => {\n    storage.remove('token');\n    expect(storage.get('token')).toBeUndefined();\n  });\n\n  it('should save token to session storage', () => {\n    config.storageType = 'sessionStorage';\n    storage.set('token', 'foo');\n    expect(storage.get('token')).toEqual('foo');\n  });\n\n  it('should remove token to session storage', () => {\n    config.storageType = 'sessionStorage';\n    storage.remove('token');\n    expect(storage.get('token')).toBeUndefined();\n  });\n\n});\n"
  },
  {
    "path": "test/utils.spec.ts",
    "content": "import { joinUrl, getFullUrlPath, parseQueryString } from '../src/utils';\n\ndescribe('Utils', function () {\n\n  describe('parseQueryString()', () => {\n\n    it('should be defined', () => {\n      expect(parseQueryString).toBeDefined();\n    });\n\n    it('should parse a query string', () => {\n      const querystring = 'hello=world&foo=bar';\n      expect(parseQueryString(querystring)).toEqual({ hello: 'world', foo: 'bar' });\n    });\n\n  });\n\n  describe('joinUrl()', () => {\n\n    it('should be defined', () => {\n      expect(joinUrl).toBeDefined();\n    });\n\n    it('should merge baseUrl with relative url', () => {\n      const baseUrl = 'http://localhost:3000';\n      const urlPath = '/auth/facebook';\n      expect(joinUrl(baseUrl, urlPath)).toEqual('http://localhost:3000/auth/facebook');\n    });\n\n  });\n\n  describe('getFullUrlPath()', () => {\n\n    it('should be defined', () => {\n      expect(getFullUrlPath).toBeDefined();\n    });\n\n    it('should normalize full url from window.location', () => {\n      const url1 = getFullUrlPath({\n        hash: '#/',\n        host: 'localhost:3000',\n        hostname: 'localhost',\n        href: 'http://localhost:3000/#/',\n        origin: 'http://localhost:3000',\n        pathname: '/',\n        port: '3000',\n        protocol: 'http:',\n        search: ''\n      });\n      const url2 = getFullUrlPath({\n        protocol: 'http:',\n        hostname: 'google.com',\n        port: '',\n        pathname: '/test'\n      });\n      const url3 = getFullUrlPath({\n        protocol: 'https:',\n        hostname: 'google.com',\n        port: '',\n        pathname: '/test'\n      });\n      expect(url1).toEqual('http://localhost:3000/');\n      expect(url2).toEqual('http://google.com:80/test');\n      expect(url3).toEqual('https://google.com:443/test');\n    });\n\n    it('should normalize full url from createElement(\"a\")', function () {\n      const urlElement = document.createElement('a');\n\n      urlElement.href = 'http://d4507eb5.ngrok.io/#/';\n      const url1 = getFullUrlPath(urlElement);\n\n      urlElement.href = 'https://google.com/test';\n      const url2 = getFullUrlPath(urlElement);\n\n      urlElement.href = 'http://localhost:3000/';\n      const url3 = getFullUrlPath(urlElement);\n\n      expect(url1).toEqual('http://d4507eb5.ngrok.io:80/');\n      expect(url2).toEqual('https://google.com:443/test');\n      expect(url3).toEqual('http://localhost:3000/');\n    });\n\n  });\n\n});\n\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"declaration\": true,\n    \"sourceMap\": true,\n    \"noImplicitAny\": false,\n    \"noResolve\": true,\n    \"target\": \"es5\",\n    \"module\": \"commonjs\",\n    \"moduleResolution\": \"node\",\n    \"outDir\": \"build\"\n  },\n  \"exclude\": [\n    \"examples\",\n    \"node_modules\"\n  ]\n}\n"
  },
  {
    "path": "tslint.json",
    "content": "{\n  \"extends\": \"tslint:latest\",\n  \"rules\": {\n    \"member-access\": false,\n    \"no-namespace\": false,\n    \"no-reference\": false,\n    \"object-literal-sort-keys\": false,\n    \"quotemark\": false,\n    \"no-constructor-vars\": false,\n    \"no-trailing-whitespace\": false,\n    \"max-line-length\": false,\n    \"trailing-comma\": false,\n    \"no-string-literal\": false,\n    \"variable-name\": false,\n    \"no-bitwise\": false\n  }\n}\n"
  },
  {
    "path": "typings/globals/angular/index.d.ts",
    "content": "// Generated by typings\n// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/592a11f956f63a1028b76638f6aa47c8950ea705/angularjs/angular.d.ts\ndeclare var angular: angular.IAngularStatic;\n\n// Support for painless dependency injection\ninterface Function {\n    $inject?: string[];\n}\n\n// Collapse angular into ng\nimport ng = angular;\n// Support AMD require\ndeclare module 'angular' {\n    export = angular;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// ng module (angular.js)\n///////////////////////////////////////////////////////////////////////////////\ndeclare namespace angular {\n\n    // not directly implemented, but ensures that constructed class implements $get\n    interface IServiceProviderClass {\n        new (...args: any[]): IServiceProvider;\n    }\n\n    interface IServiceProviderFactory {\n        (...args: any[]): IServiceProvider;\n    }\n\n    // All service providers extend this interface\n    interface IServiceProvider {\n        $get: any;\n    }\n\n    interface IAngularBootstrapConfig {\n        strictDi?: boolean;\n        debugInfoEnabled?: boolean;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // AngularStatic\n    // see http://docs.angularjs.org/api\n    ///////////////////////////////////////////////////////////////////////////\n    interface IAngularStatic {\n        bind(context: any, fn: Function, ...args: any[]): Function;\n\n        /**\n         * Use this function to manually start up angular application.\n         *\n         * @param element DOM element which is the root of angular application.\n         * @param modules An array of modules to load into the application.\n         *     Each item in the array should be the name of a predefined module or a (DI annotated)\n         *     function that will be invoked by the injector as a config block.\n         * @param config an object for defining configuration options for the application. The following keys are supported:\n         *     - `strictDi`: disable automatic function annotation for the application. This is meant to assist in finding bugs which break minified code.\n         */\n        bootstrap(element: string|Element|JQuery|Document, modules?: (string|Function|any[])[], config?: IAngularBootstrapConfig): auto.IInjectorService;\n\n        /**\n         * Creates a deep copy of source, which should be an object or an array.\n         *\n         * - If no destination is supplied, a copy of the object or array is created.\n         * - If a destination is provided, all of its elements (for array) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.\n         * - If source is not an object or array (inc. null and undefined), source is returned.\n         * - If source is identical to 'destination' an exception will be thrown.\n         *\n         * @param source The source that will be used to make a copy. Can be any type, including primitives, null, and undefined.\n         * @param destination Destination into which the source is copied. If provided, must be of the same type as source.\n         */\n        copy<T>(source: T, destination?: T): T;\n\n        /**\n         * Wraps a raw DOM element or HTML string as a jQuery element.\n         *\n         * If jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to Angular's built-in subset of jQuery, called \"jQuery lite\" or \"jqLite.\"\n         */\n        element: JQueryStatic;\n        equals(value1: any, value2: any): boolean;\n        extend(destination: any, ...sources: any[]): any;\n\n        /**\n         * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.\n         *\n         * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.\n         *\n         * @param obj Object to iterate over.\n         * @param iterator Iterator function.\n         * @param context Object to become context (this) for the iterator function.\n         */\n        forEach<T>(obj: T[], iterator: (value: T, key: number) => any, context?: any): any;\n        /**\n         * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.\n         *\n         * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.\n         *\n         * @param obj Object to iterate over.\n         * @param iterator Iterator function.\n         * @param context Object to become context (this) for the iterator function.\n         */\n        forEach<T>(obj: { [index: string]: T; }, iterator: (value: T, key: string) => any, context?: any): any;\n        /**\n         * Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key), where value is the value of an object property or an array element and key is the object property key or array element index. Specifying a context for the function is optional.\n         *\n         * It is worth noting that .forEach does not iterate over inherited properties because it filters using the hasOwnProperty method.\n         *\n         * @param obj Object to iterate over.\n         * @param iterator Iterator function.\n         * @param context Object to become context (this) for the iterator function.\n         */\n        forEach(obj: any, iterator: (value: any, key: any) => any, context?: any): any;\n\n        fromJson(json: string): any;\n        identity<T>(arg?: T): T;\n        injector(modules?: any[], strictDi?: boolean): auto.IInjectorService;\n        isArray(value: any): boolean;\n        isDate(value: any): boolean;\n        isDefined(value: any): boolean;\n        isElement(value: any): boolean;\n        isFunction(value: any): boolean;\n        isNumber(value: any): boolean;\n        isObject(value: any): boolean;\n        isString(value: any): boolean;\n        isUndefined(value: any): boolean;\n        lowercase(str: string): string;\n\n        /**\n         * Deeply extends the destination object dst by copying own enumerable properties from the src object(s) to dst. You can specify multiple src objects. If you want to preserve original objects, you can do so by passing an empty object as the target: var object = angular.merge({}, object1, object2).\n         *\n         * Unlike extend(), merge() recursively descends into object properties of source objects, performing a deep copy.\n         *\n         * @param dst Destination object.\n         * @param src Source object(s).\n         */\n        merge(dst: any, ...src: any[]): any;\n\n        /**\n         * The angular.module is a global place for creating, registering and retrieving Angular modules. All modules (angular core or 3rd party) that should be available to an application must be registered using this mechanism.\n         *\n         * When passed two or more arguments, a new module is created. If passed only one argument, an existing module (the name passed as the first argument to module) is retrieved.\n         *\n         * @param name The name of the module to create or retrieve.\n         * @param requires The names of modules this module depends on. If specified then new module is being created. If unspecified then the module is being retrieved for further configuration.\n         * @param configFn Optional configuration function for the module.\n         */\n        module(\n            name: string,\n            requires?: string[],\n            configFn?: Function): IModule;\n\n        noop(...args: any[]): void;\n        reloadWithDebugInfo(): void;\n        toJson(obj: any, pretty?: boolean): string;\n        uppercase(str: string): string;\n        version: {\n            full: string;\n            major: number;\n            minor: number;\n            dot: number;\n            codeName: string;\n        };\n\n        /**\n         * If window.name contains prefix NG_DEFER_BOOTSTRAP! when angular.bootstrap is called, the bootstrap process will be paused until angular.resumeBootstrap() is called.\n         * @param extraModules An optional array of modules that should be added to the original list of modules that the app was about to be bootstrapped with.\n         */\n        resumeBootstrap?(extraModules?: string[]): ng.auto.IInjectorService;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // Module\n    // see http://docs.angularjs.org/api/angular.Module\n    ///////////////////////////////////////////////////////////////////////////\n    interface IModule {\n        /**\n         * Use this method to register a component.\n         *\n         * @param name The name of the component.\n         * @param options A definition object passed into the component.\n         */\n        component(name: string, options: IComponentOptions): IModule;\n        /**\n         * Use this method to register work which needs to be performed on module loading.\n         *\n         * @param configFn Execute this function on module load. Useful for service configuration.\n         */\n        config(configFn: Function): IModule;\n        /**\n         * Use this method to register work which needs to be performed on module loading.\n         *\n         * @param inlineAnnotatedFunction Execute this function on module load. Useful for service configuration.\n         */\n        config(inlineAnnotatedFunction: any[]): IModule;\n        config(object: Object): IModule;\n        /**\n         * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.\n         *\n         * @param name The name of the constant.\n         * @param value The constant value.\n         */\n        constant<T>(name: string, value: T): IModule;\n        constant(object: Object): IModule;\n        /**\n         * The $controller service is used by Angular to create new controllers.\n         *\n         * This provider allows controller registration via the register method.\n         *\n         * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.\n         * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).\n         */\n        controller(name: string, controllerConstructor: Function): IModule;\n        /**\n         * The $controller service is used by Angular to create new controllers.\n         *\n         * This provider allows controller registration via the register method.\n         *\n         * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.\n         * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).\n         */\n        controller(name: string, inlineAnnotatedConstructor: any[]): IModule;\n        controller(object: Object): IModule;\n        /**\n         * Register a new directive with the compiler.\n         *\n         * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)\n         * @param directiveFactory An injectable directive factory function.\n         */\n        directive(name: string, directiveFactory: IDirectiveFactory): IModule;\n        /**\n         * Register a new directive with the compiler.\n         *\n         * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)\n         * @param directiveFactory An injectable directive factory function.\n         */\n        directive(name: string, inlineAnnotatedFunction: any[]): IModule;\n        directive(object: Object): IModule;\n        /**\n         * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.\n         *\n         * @param name The name of the instance.\n         * @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).\n         */\n        factory(name: string, $getFn: Function): IModule;\n        /**\n         * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.\n         *\n         * @param name The name of the instance.\n         * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).\n         */\n        factory(name: string, inlineAnnotatedFunction: any[]): IModule;\n        factory(object: Object): IModule;\n        filter(name: string, filterFactoryFunction: Function): IModule;\n        filter(name: string, inlineAnnotatedFunction: any[]): IModule;\n        filter(object: Object): IModule;\n        provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule;\n        provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule;\n        provider(name: string, inlineAnnotatedConstructor: any[]): IModule;\n        provider(name: string, providerObject: IServiceProvider): IModule;\n        provider(object: Object): IModule;\n        /**\n         * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.\n         */\n        run(initializationFunction: Function): IModule;\n        /**\n         * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.\n         */\n        run(inlineAnnotatedFunction: any[]): IModule;\n        /**\n         * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function.\n         *\n         * @param name The name of the instance.\n         * @param serviceConstructor An injectable class (constructor function) that will be instantiated.\n         */\n        service(name: string, serviceConstructor: Function): IModule;\n        /**\n         * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function.\n         *\n         * @param name The name of the instance.\n         * @param inlineAnnotatedConstructor An injectable class (constructor function) that will be instantiated.\n         */\n        service(name: string, inlineAnnotatedConstructor: any[]): IModule;\n        service(object: Object): IModule;\n        /**\n         * Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service.\n\n           Value services are similar to constant services, except that they cannot be injected into a module configuration function (see config) but they can be overridden by an Angular decorator.\n         *\n         * @param name The name of the instance.\n         * @param value The value.\n         */\n        value<T>(name: string, value: T): IModule;\n        value(object: Object): IModule;\n\n        /**\n         * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.\n         * @param name The name of the service to decorate\n         * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.\n         */\n        decorator(name:string, decoratorConstructor: Function): IModule;\n        decorator(name:string, inlineAnnotatedConstructor: any[]): IModule;\n\n        // Properties\n        name: string;\n        requires: string[];\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // Attributes\n    // see http://docs.angularjs.org/api/ng.$compile.directive.Attributes\n    ///////////////////////////////////////////////////////////////////////////\n    interface IAttributes {\n        /**\n         * this is necessary to be able to access the scoped attributes. it's not very elegant\n         * because you have to use attrs['foo'] instead of attrs.foo but I don't know of a better way\n         * this should really be limited to return string but it creates this problem: http://stackoverflow.com/q/17201854/165656\n         */\n        [name: string]: any;\n\n        /**\n         * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with x- or data-) to its normalized, camelCase form.\n         *\n         * Also there is special case for Moz prefix starting with upper case letter.\n         *\n         * For further information check out the guide on @see https://docs.angularjs.org/guide/directive#matching-directives\n         */\n        $normalize(name: string): string;\n\n        /**\n         * Adds the CSS class value specified by the classVal parameter to the\n         * element. If animations are enabled then an animation will be triggered\n         * for the class addition.\n         */\n        $addClass(classVal: string): void;\n\n        /**\n         * Removes the CSS class value specified by the classVal parameter from the\n         * element. If animations are enabled then an animation will be triggered for\n         * the class removal.\n         */\n        $removeClass(classVal: string): void;\n\n        /**\n         * Adds and removes the appropriate CSS class values to the element based on the difference between\n         * the new and old CSS class values (specified as newClasses and oldClasses).\n         */\n        $updateClass(newClasses: string, oldClasses: string): void;\n\n        /**\n         * Set DOM element attribute value.\n         */\n        $set(key: string, value: any): void;\n\n        /**\n         * Observes an interpolated attribute.\n         * The observer function will be invoked once during the next $digest\n         * following compilation. The observer is then invoked whenever the\n         * interpolated value changes.\n         */\n        $observe<T>(name: string, fn: (value?: T) => any): Function;\n\n        /**\n         * A map of DOM element attribute names to the normalized name. This is needed\n         * to do reverse lookup from normalized name back to actual name.\n         */\n        $attr: Object;\n    }\n\n    /**\n     * form.FormController - type in module ng\n     * see https://docs.angularjs.org/api/ng/type/form.FormController\n     */\n    interface IFormController {\n\n        /**\n         * Indexer which should return ng.INgModelController for most properties but cannot because of \"All named properties must be assignable to string indexer type\" constraint - see https://github.com/Microsoft/TypeScript/issues/272\n         */\n        [name: string]: any;\n\n        $pristine: boolean;\n        $dirty: boolean;\n        $valid: boolean;\n        $invalid: boolean;\n        $submitted: boolean;\n        $error: any;\n        $pending: any;\n        $addControl(control: INgModelController | IFormController): void;\n        $removeControl(control: INgModelController | IFormController): void;\n        $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void;\n        $setDirty(): void;\n        $setPristine(): void;\n        $commitViewValue(): void;\n        $rollbackViewValue(): void;\n        $setSubmitted(): void;\n        $setUntouched(): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // NgModelController\n    // see http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController\n    ///////////////////////////////////////////////////////////////////////////\n    interface INgModelController {\n        $render(): void;\n        $setValidity(validationErrorKey: string, isValid: boolean): void;\n        // Documentation states viewValue and modelValue to be a string but other\n        // types do work and it's common to use them.\n        $setViewValue(value: any, trigger?: string): void;\n        $setPristine(): void;\n        $setDirty(): void;\n        $validate(): void;\n        $setTouched(): void;\n        $setUntouched(): void;\n        $rollbackViewValue(): void;\n        $commitViewValue(): void;\n        $isEmpty(value: any): boolean;\n\n        $viewValue: any;\n\n        $modelValue: any;\n\n        $parsers: IModelParser[];\n        $formatters: IModelFormatter[];\n        $viewChangeListeners: IModelViewChangeListener[];\n        $error: any;\n        $name: string;\n\n        $touched: boolean;\n        $untouched: boolean;\n\n        $validators: IModelValidators;\n        $asyncValidators: IAsyncModelValidators;\n\n        $pending: any;\n        $pristine: boolean;\n        $dirty: boolean;\n        $valid: boolean;\n        $invalid: boolean;\n    }\n\n    //Allows tuning how model updates are done.\n    //https://docs.angularjs.org/api/ng/directive/ngModelOptions\n    interface INgModelOptions {\n        updateOn?: string;\n        debounce?: any;\n        allowInvalid?: boolean;\n        getterSetter?: boolean;\n        timezone?: string;\n    }\n\n    interface IModelValidators {\n        /**\n         * viewValue is any because it can be an object that is called in the view like $viewValue.name:$viewValue.subName\n         */\n        [index: string]: (modelValue: any, viewValue: any) => boolean;\n    }\n\n    interface IAsyncModelValidators {\n        [index: string]: (modelValue: any, viewValue: any) => IPromise<any>;\n    }\n\n    interface IModelParser {\n        (value: any): any;\n    }\n\n    interface IModelFormatter {\n        (value: any): any;\n    }\n\n    interface IModelViewChangeListener {\n        (): void;\n    }\n\n    /**\n     * $rootScope - $rootScopeProvider - service in module ng\n     * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope\n     */\n    interface IRootScopeService {\n        [index: string]: any;\n\n        $apply(): any;\n        $apply(exp: string): any;\n        $apply(exp: (scope: IScope) => any): any;\n\n        $applyAsync(): any;\n        $applyAsync(exp: string): any;\n        $applyAsync(exp: (scope: IScope) => any): any;\n\n        /**\n         * Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.\n         *\n         * The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled.\n         *\n         * Any exception emitted from the listeners will be passed onto the $exceptionHandler service.\n         *\n         * @param name Event name to broadcast.\n         * @param args Optional one or more arguments which will be passed onto the event listeners.\n         */\n        $broadcast(name: string, ...args: any[]): IAngularEvent;\n        $destroy(): void;\n        $digest(): void;\n        /**\n         * Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.\n         *\n         * The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.\n         *\n         * Any exception emitted from the listeners will be passed onto the $exceptionHandler service.\n         *\n         * @param name Event name to emit.\n         * @param args Optional one or more arguments which will be passed onto the event listeners.\n         */\n        $emit(name: string, ...args: any[]): IAngularEvent;\n\n        $eval(): any;\n        $eval(expression: string, locals?: Object): any;\n        $eval(expression: (scope: IScope) => any, locals?: Object): any;\n\n        $evalAsync(): void;\n        $evalAsync(expression: string): void;\n        $evalAsync(expression: (scope: IScope) => any): void;\n\n        // Defaults to false by the implementation checking strategy\n        $new(isolate?: boolean, parent?: IScope): IScope;\n\n        /**\n         * Listens on events of a given type. See $emit for discussion of event life cycle.\n         *\n         * The event listener function format is: function(event, args...).\n         *\n         * @param name Event name to listen on.\n         * @param listener Function to call when the event is emitted.\n         */\n        $on(name: string, listener: (event: IAngularEvent, ...args: any[]) => any): () => void;\n\n        $watch(watchExpression: string, listener?: string, objectEquality?: boolean): () => void;\n        $watch<T>(watchExpression: string, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void;\n        $watch(watchExpression: (scope: IScope) => any, listener?: string, objectEquality?: boolean): () => void;\n        $watch<T>(watchExpression: (scope: IScope) => T, listener?: (newValue: T, oldValue: T, scope: IScope) => any, objectEquality?: boolean): () => void;\n\n        $watchCollection<T>(watchExpression: string, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void;\n        $watchCollection<T>(watchExpression: (scope: IScope) => T, listener: (newValue: T, oldValue: T, scope: IScope) => any): () => void;\n\n        $watchGroup(watchExpressions: any[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void;\n        $watchGroup(watchExpressions: { (scope: IScope): any }[], listener: (newValue: any, oldValue: any, scope: IScope) => any): () => void;\n\n        $parent: IScope;\n        $root: IRootScopeService;\n        $id: number;\n\n        // Hidden members\n        $$isolateBindings: any;\n        $$phase: any;\n    }\n\n    interface IScope extends IRootScopeService { }\n\n    /**\n     * $scope for ngRepeat directive.\n     * see https://docs.angularjs.org/api/ng/directive/ngRepeat\n     */\n    interface IRepeatScope extends IScope {\n\n        /**\n         * iterator offset of the repeated element (0..length-1).\n         */\n        $index: number;\n\n        /**\n         * true if the repeated element is first in the iterator.\n         */\n        $first: boolean;\n\n        /**\n         * true if the repeated element is between the first and last in the iterator.\n         */\n        $middle: boolean;\n\n        /**\n         * true if the repeated element is last in the iterator.\n         */\n        $last: boolean;\n\n        /**\n         * true if the iterator position $index is even (otherwise false).\n         */\n        $even: boolean;\n\n        /**\n         * true if the iterator position $index is odd (otherwise false).\n         */\n        $odd: boolean;\n\n    }\n\n    interface IAngularEvent {\n        /**\n         * the scope on which the event was $emit-ed or $broadcast-ed.\n         */\n        targetScope: IScope;\n        /**\n         * the scope that is currently handling the event. Once the event propagates through the scope hierarchy, this property is set to null.\n         */\n        currentScope: IScope;\n        /**\n         * name of the event.\n         */\n        name: string;\n        /**\n         * calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed).\n         */\n        stopPropagation?: Function;\n        /**\n         * calling preventDefault sets defaultPrevented flag to true.\n         */\n        preventDefault: Function;\n        /**\n         * true if preventDefault was called.\n         */\n        defaultPrevented: boolean;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // WindowService\n    // see http://docs.angularjs.org/api/ng.$window\n    ///////////////////////////////////////////////////////////////////////////\n    interface IWindowService extends Window {\n        [key: string]: any;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // TimeoutService\n    // see http://docs.angularjs.org/api/ng.$timeout\n    ///////////////////////////////////////////////////////////////////////////\n    interface ITimeoutService {\n        (delay?: number, invokeApply?: boolean): IPromise<void>;\n        <T>(fn: (...args: any[]) => T, delay?: number, invokeApply?: boolean, ...args: any[]): IPromise<T>;\n        cancel(promise?: IPromise<any>): boolean;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // IntervalService\n    // see http://docs.angularjs.org/api/ng.$interval\n    ///////////////////////////////////////////////////////////////////////////\n    interface IIntervalService {\n        (func: Function, delay: number, count?: number, invokeApply?: boolean, ...args: any[]): IPromise<any>;\n        cancel(promise: IPromise<any>): boolean;\n    }\n\n    /**\n     * $filter - $filterProvider - service in module ng\n     *\n     * Filters are used for formatting data displayed to the user.\n     *\n     * see https://docs.angularjs.org/api/ng/service/$filter\n     */\n    interface IFilterService {\n        (name: 'filter'): IFilterFilter;\n        (name: 'currency'): IFilterCurrency;\n        (name: 'number'): IFilterNumber;\n        (name: 'date'): IFilterDate;\n        (name: 'json'): IFilterJson;\n        (name: 'lowercase'): IFilterLowercase;\n        (name: 'uppercase'): IFilterUppercase;\n        (name: 'limitTo'): IFilterLimitTo;\n        (name: 'orderBy'): IFilterOrderBy;\n        /**\n         * Usage:\n         * $filter(name);\n         *\n         * @param name Name of the filter function to retrieve\n         */\n        <T>(name: string): T;\n    }\n\n    interface IFilterFilter {\n        <T>(array: T[], expression: string | IFilterFilterPatternObject | IFilterFilterPredicateFunc<T>, comparator?: IFilterFilterComparatorFunc<T>|boolean): T[];\n    }\n\n    interface IFilterFilterPatternObject {\n        [name: string]: any;\n    }\n\n    interface IFilterFilterPredicateFunc<T> {\n        (value: T, index: number, array: T[]): boolean;\n    }\n\n    interface IFilterFilterComparatorFunc<T> {\n        (actual: T, expected: T): boolean;\n    }\n\n    interface IFilterCurrency {\n        /**\n         * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.\n         * @param amount Input to filter.\n         * @param symbol Currency symbol or identifier to be displayed.\n         * @param fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale\n         * @return Formatted number\n         */\n        (amount: number, symbol?: string, fractionSize?: number): string;\n    }\n\n    interface IFilterNumber {\n        /**\n         * Formats a number as text.\n         * @param number Number to format.\n         * @param fractionSize Number of decimal places to round the number to. If this is not provided then the fraction size is computed from the current locale's number formatting pattern. In the case of the default locale, it will be 3.\n         * @return Number rounded to decimalPlaces and places a “,” after each third digit.\n         */\n        (value: number|string, fractionSize?: number|string): string;\n    }\n\n    interface IFilterDate {\n        /**\n         * Formats date to a string based on the requested format.\n         *\n         * @param date Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.\n         * @param format Formatting rules (see Description). If not specified, mediumDate is used.\n         * @param timezone Timezone to be used for formatting. It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used.\n         * @return Formatted string or the input if input is not recognized as date/millis.\n         */\n        (date: Date | number | string, format?: string, timezone?: string): string;\n    }\n\n    interface IFilterJson {\n        /**\n         * Allows you to convert a JavaScript object into JSON string.\n         * @param object Any JavaScript object (including arrays and primitive types) to filter.\n         * @param spacing The number of spaces to use per indentation, defaults to 2.\n         * @return JSON string.\n         */\n        (object: any, spacing?: number): string;\n    }\n\n    interface IFilterLowercase {\n        /**\n         * Converts string to lowercase.\n         */\n        (value: string): string;\n    }\n\n    interface IFilterUppercase {\n        /**\n         * Converts string to uppercase.\n         */\n        (value: string): string;\n    }\n\n    interface IFilterLimitTo {\n        /**\n         * Creates a new array containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit.\n         * @param input Source array to be limited.\n         * @param limit The length of the returned array. If the limit number is positive, limit number of items from the beginning of the source array/string are copied. If the number is negative, limit number of items from the end of the source array are copied. The limit will be trimmed if it exceeds array.length. If limit is undefined, the input will be returned unchanged.\n         * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0.\n         * @return A new sub-array of length limit or less if input array had less than limit elements.\n         */\n        <T>(input: T[], limit: string|number, begin?: string|number): T[];\n        /**\n         * Creates a new string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source string or number, as specified by the value and sign (positive or negative) of limit. If a number is used as input, it is converted to a string.\n         * @param input Source string or number to be limited.\n         * @param limit The length of the returned string. If the limit number is positive, limit number of items from the beginning of the source string are copied. If the number is negative, limit number of items from the end of the source string are copied. The limit will be trimmed if it exceeds input.length. If limit is undefined, the input will be returned unchanged.\n         * @param begin Index at which to begin limitation. As a negative index, begin indicates an offset from the end of input. Defaults to 0.\n         * @return A new substring of length limit or less if input had less than limit elements.\n         */\n        (input: string|number, limit: string|number, begin?: string|number): string;\n    }\n\n    interface IFilterOrderBy {\n        /**\n         * Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers. Note: if you notice numbers are not being sorted as expected, make sure they are actually being saved as numbers and not strings.\n         * @param array The array to sort.\n         * @param expression A predicate to be used by the comparator to determine the order of elements.\n         * @param reverse Reverse the order of the array.\n         * @return Reverse the order of the array.\n         */\n        <T>(array: T[], expression: string|((value: T) => any)|(((value: T) => any)|string)[], reverse?: boolean): T[];\n    }\n\n    /**\n     * $filterProvider - $filter - provider in module ng\n     *\n     * Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To achieve this a filter definition consists of a factory function which is annotated with dependencies and is responsible for creating a filter function.\n     *\n     * see https://docs.angularjs.org/api/ng/provider/$filterProvider\n     */\n    interface IFilterProvider extends IServiceProvider {\n        /**\n         * register(name);\n         *\n         * @param name Name of the filter function, or an object map of filters where the keys are the filter names and the values are the filter factories. Note: Filter names must be valid angular Expressions identifiers, such as uppercase or orderBy. Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace your filters, then you can use capitalization (myappSubsectionFilterx) or underscores (myapp_subsection_filterx).\n         */\n        register(name: string | {}): IServiceProvider;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // LocaleService\n    // see http://docs.angularjs.org/api/ng.$locale\n    ///////////////////////////////////////////////////////////////////////////\n    interface ILocaleService {\n        id: string;\n\n        // These are not documented\n        // Check angular's i18n files for exemples\n        NUMBER_FORMATS: ILocaleNumberFormatDescriptor;\n        DATETIME_FORMATS: ILocaleDateTimeFormatDescriptor;\n        pluralCat: (num: any) => string;\n    }\n\n    interface ILocaleNumberFormatDescriptor {\n        DECIMAL_SEP: string;\n        GROUP_SEP: string;\n        PATTERNS: ILocaleNumberPatternDescriptor[];\n        CURRENCY_SYM: string;\n    }\n\n    interface ILocaleNumberPatternDescriptor {\n        minInt: number;\n        minFrac: number;\n        maxFrac: number;\n        posPre: string;\n        posSuf: string;\n        negPre: string;\n        negSuf: string;\n        gSize: number;\n        lgSize: number;\n    }\n\n    interface ILocaleDateTimeFormatDescriptor {\n        MONTH: string[];\n        SHORTMONTH: string[];\n        DAY: string[];\n        SHORTDAY: string[];\n        AMPMS: string[];\n        medium: string;\n        short: string;\n        fullDate: string;\n        longDate: string;\n        mediumDate: string;\n        shortDate: string;\n        mediumTime: string;\n        shortTime: string;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // LogService\n    // see http://docs.angularjs.org/api/ng.$log\n    // see http://docs.angularjs.org/api/ng.$logProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface ILogService {\n        debug: ILogCall;\n        error: ILogCall;\n        info: ILogCall;\n        log: ILogCall;\n        warn: ILogCall;\n    }\n\n    interface ILogProvider extends IServiceProvider {\n        debugEnabled(): boolean;\n        debugEnabled(enabled: boolean): ILogProvider;\n    }\n\n    // We define this as separate interface so we can reopen it later for\n    // the ngMock module.\n    interface ILogCall {\n        (...args: any[]): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // ParseService\n    // see http://docs.angularjs.org/api/ng.$parse\n    // see http://docs.angularjs.org/api/ng.$parseProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface IParseService {\n        (expression: string): ICompiledExpression;\n    }\n\n    interface IParseProvider {\n        logPromiseWarnings(): boolean;\n        logPromiseWarnings(value: boolean): IParseProvider;\n\n        unwrapPromises(): boolean;\n        unwrapPromises(value: boolean): IParseProvider;\n\n        /**\n         * Configure $parse service to add literal values that will be present as literal at expressions.\n         *\n         * @param literalName Token for the literal value. The literal name value must be a valid literal name.\n         * @param literalValue Value for this literal. All literal values must be primitives or `undefined`.\n         **/\n        addLiteral(literalName: string, literalValue: any): void;\n\n        /**\n         * Allows defining the set of characters that are allowed in Angular expressions. The function identifierStart will get called to know if a given character is a valid character to be the first character for an identifier. The function identifierContinue will get called to know if a given character is a valid character to be a follow-up identifier character. The functions identifierStart and identifierContinue will receive as arguments the single character to be identifier and the character code point. These arguments will be string and numeric. Keep in mind that the string parameter can be two characters long depending on the character representation. It is expected for the function to return true or false, whether that character is allowed or not.\n         * Since this function will be called extensivelly, keep the implementation of these functions fast, as the performance of these functions have a direct impact on the expressions parsing speed.\n         *\n         * @param identifierStart The function that will decide whether the given character is a valid identifier start character.\n         * @param identifierContinue The function that will decide whether the given character is a valid identifier continue character.\n         **/\n        setIdentifierFns(identifierStart?: (character: string, codePoint: number) => boolean,\n            identifierContinue?: (character: string, codePoint: number) => boolean): void;\n    }\n\n    interface ICompiledExpression {\n        (context: any, locals?: any): any;\n\n        literal: boolean;\n        constant: boolean;\n\n        // If value is not provided, undefined is gonna be used since the implementation\n        // does not check the parameter. Let's force a value for consistency. If consumer\n        // whants to undefine it, pass the undefined value explicitly.\n        assign(context: any, value: any): any;\n    }\n\n    /**\n     * $location - $locationProvider - service in module ng\n     * see https://docs.angularjs.org/api/ng/service/$location\n     */\n    interface ILocationService {\n        absUrl(): string;\n        hash(): string;\n        hash(newHash: string): ILocationService;\n        host(): string;\n\n        /**\n         * Return path of current url\n         */\n        path(): string;\n\n        /**\n         * Change path when called with parameter and return $location.\n         * Note: Path should always begin with forward slash (/), this method will add the forward slash if it is missing.\n         *\n         * @param path New path\n         */\n        path(path: string): ILocationService;\n\n        port(): number;\n        protocol(): string;\n        replace(): ILocationService;\n\n        /**\n         * Return search part (as object) of current url\n         */\n        search(): any;\n\n        /**\n         * Change search part when called with parameter and return $location.\n         *\n         * @param search When called with a single argument the method acts as a setter, setting the search component of $location to the specified value.\n         *\n         * If the argument is a hash object containing an array of values, these values will be encoded as duplicate search parameters in the url.\n         */\n        search(search: any): ILocationService;\n\n        /**\n         * Change search part when called with parameter and return $location.\n         *\n         * @param search New search params\n         * @param paramValue If search is a string or a Number, then paramValue will override only a single search property. If paramValue is null, the property specified via the first argument will be deleted. If paramValue is an array, it will override the property of the search component of $location specified via the first argument. If paramValue is true, the property specified via the first argument will be added with no value nor trailing equal sign.\n         */\n        search(search: string, paramValue: string|number|string[]|boolean): ILocationService;\n\n        state(): any;\n        state(state: any): ILocationService;\n        url(): string;\n        url(url: string): ILocationService;\n    }\n\n    interface ILocationProvider extends IServiceProvider {\n        hashPrefix(): string;\n        hashPrefix(prefix: string): ILocationProvider;\n        html5Mode(): boolean;\n\n        // Documentation states that parameter is string, but\n        // implementation tests it as boolean, which makes more sense\n        // since this is a toggler\n        html5Mode(active: boolean): ILocationProvider;\n        html5Mode(mode: { enabled?: boolean; requireBase?: boolean; rewriteLinks?: boolean; }): ILocationProvider;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // DocumentService\n    // see http://docs.angularjs.org/api/ng.$document\n    ///////////////////////////////////////////////////////////////////////////\n    interface IDocumentService extends JQuery {}\n\n    ///////////////////////////////////////////////////////////////////////////\n    // ExceptionHandlerService\n    // see http://docs.angularjs.org/api/ng.$exceptionHandler\n    ///////////////////////////////////////////////////////////////////////////\n    interface IExceptionHandlerService {\n        (exception: Error, cause?: string): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // RootElementService\n    // see http://docs.angularjs.org/api/ng.$rootElement\n    ///////////////////////////////////////////////////////////////////////////\n    interface IRootElementService extends JQuery {}\n\n    interface IQResolveReject<T> {\n        (): void;\n        (value: T): void;\n    }\n    /**\n     * $q - service in module ng\n     * A promise/deferred implementation inspired by Kris Kowal's Q.\n     * See http://docs.angularjs.org/api/ng/service/$q\n     */\n    interface IQService {\n        new <T>(resolver: (resolve: IQResolveReject<T>) => any): IPromise<T>;\n        new <T>(resolver: (resolve: IQResolveReject<T>, reject: IQResolveReject<any>) => any): IPromise<T>;\n        <T>(resolver: (resolve: IQResolveReject<T>) => any): IPromise<T>;\n        <T>(resolver: (resolve: IQResolveReject<T>, reject: IQResolveReject<any>) => any): IPromise<T>;\n\n        /**\n         * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.\n         *\n         * Returns a single promise that will be resolved with an array of values, each value corresponding to the promise at the same index in the promises array. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.\n         *\n         * @param promises An array of promises.\n         */\n        all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>, T5 | IPromise<T5>, T6 | IPromise<T6>, T7 | IPromise<T7>, T8 | IPromise<T8>, T9 | IPromise<T9>, T10 | IPromise<T10>]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;\n        all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>, T5 | IPromise<T5>, T6 | IPromise<T6>, T7 | IPromise<T7>, T8 | IPromise<T8>, T9 | IPromise<T9>]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;\n        all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>, T5 | IPromise<T5>, T6 | IPromise<T6>, T7 | IPromise<T7>, T8 | IPromise<T8>]): IPromise<[T1, T2, T3, T4, T5, T6, T7, T8]>;\n        all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>, T5 | IPromise<T5>, T6 | IPromise<T6>, T7 | IPromise<T7>]): IPromise<[T1, T2, T3, T4, T5, T6, T7]>;\n        all<T1, T2, T3, T4, T5, T6>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>, T5 | IPromise<T5>, T6 | IPromise<T6>]): IPromise<[T1, T2, T3, T4, T5, T6]>;\n        all<T1, T2, T3, T4, T5>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>, T5 | IPromise<T5>]): IPromise<[T1, T2, T3, T4, T5]>;\n        all<T1, T2, T3, T4>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>, T4 | IPromise <T4>]): IPromise<[T1, T2, T3, T4]>;\n        all<T1, T2, T3>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>, T3 | IPromise<T3>]): IPromise<[T1, T2, T3]>;\n        all<T1, T2>(values: [T1 | IPromise<T1>, T2 | IPromise<T2>]): IPromise<[T1, T2]>;\n        all<TAll>(promises: IPromise<TAll>[]): IPromise<TAll[]>;\n        /**\n         * Combines multiple promises into a single promise that is resolved when all of the input promises are resolved.\n         *\n         * Returns a single promise that will be resolved with a hash of values, each value corresponding to the promise at the same key in the promises hash. If any of the promises is resolved with a rejection, this resulting promise will be rejected with the same rejection value.\n         *\n         * @param promises A hash of promises.\n         */\n        all(promises: { [id: string]: IPromise<any>; }): IPromise<{ [id: string]: any; }>;\n        all<T extends {}>(promises: { [id: string]: IPromise<any>; }): IPromise<T>;\n        /**\n         * Creates a Deferred object which represents a task which will finish in the future.\n         */\n        defer<T>(): IDeferred<T>;\n        /**\n         * Creates a promise that is resolved as rejected with the specified reason. This api should be used to forward rejection in a chain of promises. If you are dealing with the last promise in a promise chain, you don't need to worry about it.\n         *\n         * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of reject as the throw keyword in JavaScript. This also means that if you \"catch\" an error via a promise error callback and you want to forward the error to the promise derived from the current promise, you have to \"rethrow\" the error by returning a rejection constructed via reject.\n         *\n         * @param reason Constant, message, exception or an object representing the rejection reason.\n         */\n        reject(reason?: any): IPromise<any>;\n        /**\n         * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.\n         *\n         * @param value Value or a promise\n         */\n        resolve<T>(value: IPromise<T>|T): IPromise<T>;\n        /**\n         * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.\n         */\n        resolve(): IPromise<void>;\n        /**\n         * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.\n         *\n         * @param value Value or a promise\n         */\n        when<T>(value: IPromise<T>|T): IPromise<T>;\n        /**\n         * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise. This is useful when you are dealing with an object that might or might not be a promise, or if the promise comes from a source that can't be trusted.\n         */\n        when(): IPromise<void>;\n    }\n\n    interface IPromise<T> {\n        /**\n         * Regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.\n         * The successCallBack may return IPromise<void> for when a $q.reject() needs to be returned\n         * This method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback. It also notifies via the return value of the notifyCallback method. The promise can not be resolved or rejected from the notifyCallback method.\n         */\n        then<TResult>(successCallback: (promiseValue: T) => IPromise<TResult>|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise<TResult>;\n\n        /**\n         * Shorthand for promise.then(null, errorCallback)\n         */\n        catch<TResult>(onRejected: (reason: any) => IPromise<TResult>|TResult): IPromise<TResult>;\n\n        /**\n         * Allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful to release resources or do some clean-up that needs to be done whether the promise was rejected or resolved. See the full specification for more information.\n         *\n         * Because finally is a reserved word in JavaScript and reserved keywords are not supported as property names by ES3, you'll need to invoke the method like promise['finally'](callback) to make your code IE8 and Android 2.x compatible.\n         */\n        finally(finallyCallback: () => any): IPromise<T>;\n    }\n\n    interface IDeferred<T> {\n        resolve(value?: T|IPromise<T>): void;\n        reject(reason?: any): void;\n        notify(state?: any): void;\n        promise: IPromise<T>;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // AnchorScrollService\n    // see http://docs.angularjs.org/api/ng.$anchorScroll\n    ///////////////////////////////////////////////////////////////////////////\n    interface IAnchorScrollService {\n        (): void;\n        (hash: string): void;\n        yOffset: any;\n    }\n\n    interface IAnchorScrollProvider extends IServiceProvider {\n        disableAutoScrolling(): void;\n    }\n\n    /**\n     * $cacheFactory - service in module ng\n     *\n     * Factory that constructs Cache objects and gives access to them.\n     *\n     * see https://docs.angularjs.org/api/ng/service/$cacheFactory\n     */\n    interface ICacheFactoryService {\n        /**\n         * Factory that constructs Cache objects and gives access to them.\n         *\n         * @param cacheId Name or id of the newly created cache.\n         * @param optionsMap Options object that specifies the cache behavior. Properties:\n         *\n         * capacity — turns the cache into LRU cache.\n         */\n        (cacheId: string, optionsMap?: { capacity?: number; }): ICacheObject;\n\n        /**\n         * Get information about all the caches that have been created.\n         * @returns key-value map of cacheId to the result of calling cache#info\n         */\n        info(): any;\n\n        /**\n         * Get access to a cache object by the cacheId used when it was created.\n         *\n         * @param cacheId Name or id of a cache to access.\n         */\n        get(cacheId: string): ICacheObject;\n    }\n\n    /**\n     * $cacheFactory.Cache - type in module ng\n     *\n     * A cache object used to store and retrieve data, primarily used by $http and the script directive to cache templates and other data.\n     *\n     * see https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache\n     */\n    interface ICacheObject {\n        /**\n         * Retrieve information regarding a particular Cache.\n         */\n        info(): {\n            /**\n             * the id of the cache instance\n             */\n            id: string;\n\n            /**\n             * the number of entries kept in the cache instance\n             */\n            size: number;\n\n            //...: any additional properties from the options object when creating the cache.\n        };\n\n        /**\n         * Inserts a named entry into the Cache object to be retrieved later, and incrementing the size of the cache if the key was not already present in the cache. If behaving like an LRU cache, it will also remove stale entries from the set.\n         *\n         * It will not insert undefined values into the cache.\n         *\n         * @param key the key under which the cached data is stored.\n         * @param value the value to store alongside the key. If it is undefined, the key will not be stored.\n         */\n        put<T>(key: string, value?: T): T;\n\n        /**\n         * Retrieves named data stored in the Cache object.\n         *\n         * @param key the key of the data to be retrieved\n         */\n        get<T>(key: string): T;\n\n        /**\n         * Removes an entry from the Cache object.\n         *\n         * @param key the key of the entry to be removed\n         */\n        remove(key: string): void;\n\n        /**\n         * Clears the cache object of any entries.\n         */\n        removeAll(): void;\n\n        /**\n         * Destroys the Cache object entirely, removing it from the $cacheFactory set.\n         */\n        destroy(): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // CompileService\n    // see http://docs.angularjs.org/api/ng.$compile\n    // see http://docs.angularjs.org/api/ng.$compileProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface ICompileService {\n        (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;\n        (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;\n        (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;\n    }\n\n    interface ICompileProvider extends IServiceProvider {\n        directive(name: string, directiveFactory: Function): ICompileProvider;\n        directive(directivesMap: Object, directiveFactory: Function): ICompileProvider;\n        directive(name: string, inlineAnnotatedFunction: any[]): ICompileProvider;\n        directive(directivesMap: Object, inlineAnnotatedFunction: any[]): ICompileProvider;\n\n        // Undocumented, but it is there...\n        directive(directivesMap: any): ICompileProvider;\n\n        component(name: string, options: IComponentOptions): ICompileProvider;\n\n        aHrefSanitizationWhitelist(): RegExp;\n        aHrefSanitizationWhitelist(regexp: RegExp): ICompileProvider;\n\n        imgSrcSanitizationWhitelist(): RegExp;\n        imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider;\n\n        debugInfoEnabled(enabled?: boolean): any;\n    }\n\n    interface ICloneAttachFunction {\n        // Let's hint but not force cloneAttachFn's signature\n        (clonedElement?: JQuery, scope?: IScope): any;\n    }\n\n    // This corresponds to the \"publicLinkFn\" returned by $compile.\n    interface ITemplateLinkingFunction {\n        (scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery;\n    }\n\n    // This corresponds to $transclude (and also the transclude function passed to link).\n    interface ITranscludeFunction {\n        // If the scope is provided, then the cloneAttachFn must be as well.\n        (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery;\n        // If one argument is provided, then it's assumed to be the cloneAttachFn.\n        (cloneAttachFn?: ICloneAttachFunction): JQuery;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // ControllerService\n    // see http://docs.angularjs.org/api/ng.$controller\n    // see http://docs.angularjs.org/api/ng.$controllerProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface IControllerService {\n        // Although the documentation doesn't state this, locals are optional\n        <T>(controllerConstructor: new (...args: any[]) => T, locals?: any, later?: boolean, ident?: string): T;\n        <T>(controllerConstructor: Function, locals?: any, later?: boolean, ident?: string): T;\n        <T>(controllerName: string, locals?: any, later?: boolean, ident?: string): T;\n    }\n\n    interface IControllerProvider extends IServiceProvider {\n        register(name: string, controllerConstructor: Function): void;\n        register(name: string, dependencyAnnotatedConstructor: any[]): void;\n        allowGlobals(): void;\n    }\n\n    /**\n     * xhrFactory\n     * Replace or decorate this service to create your own custom XMLHttpRequest objects.\n     * see https://docs.angularjs.org/api/ng/service/$xhrFactory\n     */\n    interface IXhrFactory<T> {\n        (method: string, url: string): T;\n    }\n\n    /**\n     * HttpService\n     * see http://docs.angularjs.org/api/ng/service/$http\n     */\n    interface IHttpService {\n        /**\n         * Object describing the request to be made and how it should be processed.\n         */\n        <T>(config: IRequestConfig): IHttpPromise<T>;\n\n        /**\n         * Shortcut method to perform GET request.\n         *\n         * @param url Relative or absolute URL specifying the destination of the request\n         * @param config Optional configuration object\n         */\n        get<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;\n\n        /**\n         * Shortcut method to perform DELETE request.\n         *\n         * @param url Relative or absolute URL specifying the destination of the request\n         * @param config Optional configuration object\n         */\n        delete<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;\n\n        /**\n         * Shortcut method to perform HEAD request.\n         *\n         * @param url Relative or absolute URL specifying the destination of the request\n         * @param config Optional configuration object\n         */\n        head<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;\n\n        /**\n         * Shortcut method to perform JSONP request.\n         *\n         * @param url Relative or absolute URL specifying the destination of the request\n         * @param config Optional configuration object\n         */\n        jsonp<T>(url: string, config?: IRequestShortcutConfig): IHttpPromise<T>;\n\n        /**\n         * Shortcut method to perform POST request.\n         *\n         * @param url Relative or absolute URL specifying the destination of the request\n         * @param data Request content\n         * @param config Optional configuration object\n         */\n        post<T>(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise<T>;\n\n        /**\n         * Shortcut method to perform PUT request.\n         *\n         * @param url Relative or absolute URL specifying the destination of the request\n         * @param data Request content\n         * @param config Optional configuration object\n         */\n        put<T>(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise<T>;\n\n        /**\n         * Shortcut method to perform PATCH request.\n         *\n         * @param url Relative or absolute URL specifying the destination of the request\n         * @param data Request content\n         * @param config Optional configuration object\n         */\n        patch<T>(url: string, data: any, config?: IRequestShortcutConfig): IHttpPromise<T>;\n\n        /**\n         * Runtime equivalent of the $httpProvider.defaults property. Allows configuration of default headers, withCredentials as well as request and response transformations.\n         */\n        defaults: IHttpProviderDefaults;\n\n        /**\n         * Array of config objects for currently pending requests. This is primarily meant to be used for debugging purposes.\n         */\n        pendingRequests: IRequestConfig[];\n    }\n\n    /**\n     * Object describing the request to be made and how it should be processed.\n     * see http://docs.angularjs.org/api/ng/service/$http#usage\n     */\n    interface IRequestShortcutConfig extends IHttpProviderDefaults {\n        /**\n         * {Object.<string|Object>}\n         * Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.\n         */\n        params?: any;\n\n        /**\n         * {string|Object}\n         * Data to be sent as the request message data.\n         */\n        data?: any;\n\n        /**\n         * Timeout in milliseconds, or promise that should abort the request when resolved.\n         */\n        timeout?: number|IPromise<any>;\n\n        /**\n         * See [XMLHttpRequest.responseType]https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype\n         */\n        responseType?: string;\n    }\n\n    /**\n     * Object describing the request to be made and how it should be processed.\n     * see http://docs.angularjs.org/api/ng/service/$http#usage\n     */\n    interface IRequestConfig extends IRequestShortcutConfig {\n        /**\n         * HTTP method (e.g. 'GET', 'POST', etc)\n         */\n        method: string;\n        /**\n         * Absolute or relative URL of the resource that is being requested.\n         */\n        url: string;\n    }\n\n    interface IHttpHeadersGetter {\n        (): { [name: string]: string; };\n        (headerName: string): string;\n    }\n\n    interface IHttpPromiseCallback<T> {\n        (data: T, status: number, headers: IHttpHeadersGetter, config: IRequestConfig): void;\n    }\n\n    interface IHttpPromiseCallbackArg<T> {\n        data?: T;\n        status?: number;\n        headers?: IHttpHeadersGetter;\n        config?: IRequestConfig;\n        statusText?: string;\n    }\n\n    interface IHttpPromise<T> extends IPromise<IHttpPromiseCallbackArg<T>> {\n        /**\n         * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.\n         * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.\n         * @deprecated\n         */\n        success?(callback: IHttpPromiseCallback<T>): IHttpPromise<T>;\n        /**\n         * The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.\n         * If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.\n         * @deprecated\n         */\n        error?(callback: IHttpPromiseCallback<any>): IHttpPromise<T>;\n    }\n\n    // See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228\n    interface IHttpRequestTransformer {\n        (data: any, headersGetter: IHttpHeadersGetter): any;\n    }\n\n    // The definition of fields are the same as IHttpPromiseCallbackArg\n    interface IHttpResponseTransformer {\n        (data: any, headersGetter: IHttpHeadersGetter, status: number): any;\n    }\n\n    type HttpHeaderType = {[requestType: string]:string|((config:IRequestConfig) => string)};\n\n    interface IHttpRequestConfigHeaders {\n        [requestType: string]: any;\n        common?: any;\n        get?: any;\n        post?: any;\n        put?: any;\n        patch?: any;\n    }\n\n    /**\n    * Object that controls the defaults for $http provider. Not all fields of IRequestShortcutConfig can be configured\n    * via defaults and the docs do not say which. The following is based on the inspection of the source code.\n    * https://docs.angularjs.org/api/ng/service/$http#defaults\n    * https://docs.angularjs.org/api/ng/service/$http#usage\n    * https://docs.angularjs.org/api/ng/provider/$httpProvider The properties section\n    */\n    interface IHttpProviderDefaults {\n        /**\n         * {boolean|Cache}\n         * If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.\n         */\n        cache?: any;\n\n        /**\n         * Transform function or an array of such functions. The transform function takes the http request body and\n         * headers and returns its transformed (typically serialized) version.\n         * @see {@link https://docs.angularjs.org/api/ng/service/$http#transforming-requests-and-responses}\n         */\n        transformRequest?: IHttpRequestTransformer |IHttpRequestTransformer[];\n\n        /**\n         * Transform function or an array of such functions. The transform function takes the http response body and\n         * headers and returns its transformed (typically deserialized) version.\n         */\n        transformResponse?: IHttpResponseTransformer | IHttpResponseTransformer[];\n\n        /**\n         * Map of strings or functions which return strings representing HTTP headers to send to the server. If the\n         * return value of a function is null, the header will not be sent.\n         * The key of the map is the request verb in lower case. The \"common\" key applies to all requests.\n         * @see {@link https://docs.angularjs.org/api/ng/service/$http#setting-http-headers}\n         */\n        headers?: IHttpRequestConfigHeaders;\n\n        /** Name of HTTP header to populate with the XSRF token. */\n        xsrfHeaderName?: string;\n\n        /** Name of cookie containing the XSRF token. */\n        xsrfCookieName?: string;\n\n        /**\n         * whether to to set the withCredentials flag on the XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5 for more information.\n         */\n        withCredentials?: boolean;\n\n        /**\n        * A function used to the prepare string representation of request parameters (specified as an object). If\n        * specified as string, it is interpreted as a function registered with the $injector. Defaults to\n        * $httpParamSerializer.\n        */\n        paramSerializer?: string | ((obj: any) => string);\n    }\n\n    interface IHttpInterceptor {\n        request?: (config: IRequestConfig) => IRequestConfig|IPromise<IRequestConfig>;\n        requestError?: (rejection: any) => any;\n        response?: <T>(response: IHttpPromiseCallbackArg<T>) => IPromise<IHttpPromiseCallbackArg<T>>|IHttpPromiseCallbackArg<T>;\n        responseError?: (rejection: any) => any;\n    }\n\n    interface IHttpInterceptorFactory {\n        (...args: any[]): IHttpInterceptor;\n    }\n\n    interface IHttpProvider extends IServiceProvider {\n        defaults: IHttpProviderDefaults;\n\n        /**\n         * Register service factories (names or implementations) for interceptors which are called before and after\n         * each request.\n         */\n        interceptors: (string|IHttpInterceptorFactory|(string|IHttpInterceptorFactory)[])[];\n        useApplyAsync(): boolean;\n        useApplyAsync(value: boolean): IHttpProvider;\n\n        /**\n         *\n         * @param {boolean=} value If true, `$http` will return a normal promise without the `success` and `error` methods.\n         * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.\n         *    otherwise, returns the current configured value.\n         */\n        useLegacyPromiseExtensions(value:boolean) : boolean | IHttpProvider;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // HttpBackendService\n    // see http://docs.angularjs.org/api/ng.$httpBackend\n    // You should never need to use this service directly.\n    ///////////////////////////////////////////////////////////////////////////\n    interface IHttpBackendService {\n        // XXX Perhaps define callback signature in the future\n        (method: string, url: string, post?: any, callback?: Function, headers?: any, timeout?: number, withCredentials?: boolean): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // InterpolateService\n    // see http://docs.angularjs.org/api/ng.$interpolate\n    // see http://docs.angularjs.org/api/ng.$interpolateProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface IInterpolateService {\n        (text: string, mustHaveExpression?: boolean, trustedContext?: string, allOrNothing?: boolean): IInterpolationFunction;\n        endSymbol(): string;\n        startSymbol(): string;\n    }\n\n    interface IInterpolationFunction {\n        (context: any): string;\n    }\n\n    interface IInterpolateProvider extends IServiceProvider {\n        startSymbol(): string;\n        startSymbol(value: string): IInterpolateProvider;\n        endSymbol(): string;\n        endSymbol(value: string): IInterpolateProvider;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // TemplateCacheService\n    // see http://docs.angularjs.org/api/ng.$templateCache\n    ///////////////////////////////////////////////////////////////////////////\n    interface ITemplateCacheService extends ICacheObject {}\n\n    ///////////////////////////////////////////////////////////////////////////\n    // SCEService\n    // see http://docs.angularjs.org/api/ng.$sce\n    ///////////////////////////////////////////////////////////////////////////\n    interface ISCEService {\n        getTrusted(type: string, mayBeTrusted: any): any;\n        getTrustedCss(value: any): any;\n        getTrustedHtml(value: any): any;\n        getTrustedJs(value: any): any;\n        getTrustedResourceUrl(value: any): any;\n        getTrustedUrl(value: any): any;\n        parse(type: string, expression: string): (context: any, locals: any) => any;\n        parseAsCss(expression: string): (context: any, locals: any) => any;\n        parseAsHtml(expression: string): (context: any, locals: any) => any;\n        parseAsJs(expression: string): (context: any, locals: any) => any;\n        parseAsResourceUrl(expression: string): (context: any, locals: any) => any;\n        parseAsUrl(expression: string): (context: any, locals: any) => any;\n        trustAs(type: string, value: any): any;\n        trustAsHtml(value: any): any;\n        trustAsJs(value: any): any;\n        trustAsResourceUrl(value: any): any;\n        trustAsUrl(value: any): any;\n        isEnabled(): boolean;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // SCEProvider\n    // see http://docs.angularjs.org/api/ng.$sceProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface ISCEProvider extends IServiceProvider {\n        enabled(value: boolean): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // SCEDelegateService\n    // see http://docs.angularjs.org/api/ng.$sceDelegate\n    ///////////////////////////////////////////////////////////////////////////\n    interface ISCEDelegateService {\n        getTrusted(type: string, mayBeTrusted: any): any;\n        trustAs(type: string, value: any): any;\n        valueOf(value: any): any;\n    }\n\n\n    ///////////////////////////////////////////////////////////////////////////\n    // SCEDelegateProvider\n    // see http://docs.angularjs.org/api/ng.$sceDelegateProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface ISCEDelegateProvider extends IServiceProvider {\n        resourceUrlBlacklist(blacklist: any[]): void;\n        resourceUrlWhitelist(whitelist: any[]): void;\n        resourceUrlBlacklist(): any[];\n        resourceUrlWhitelist(): any[];\n    }\n\n    /**\n     * $templateRequest service\n     * see http://docs.angularjs.org/api/ng/service/$templateRequest\n     */\n    interface ITemplateRequestService {\n        /**\n         * Downloads a template using $http and, upon success, stores the\n         * contents inside of $templateCache.\n         *\n         * If the HTTP request fails or the response data of the HTTP request is\n         * empty then a $compile error will be thrown (unless\n         * {ignoreRequestError} is set to true).\n         *\n         * @param tpl                  The template URL.\n         * @param ignoreRequestError   Whether or not to ignore the exception\n         *                             when the request fails or the template is\n         *                             empty.\n         *\n         * @return   A promise whose value is the template content.\n         */\n        (tpl: string, ignoreRequestError?: boolean): IPromise<string>;\n        /**\n         * total amount of pending template requests being downloaded.\n         * @type {number}\n         */\n        totalPendingRequests: number;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // Component\n    // see http://angularjs.blogspot.com.br/2015/11/angularjs-15-beta2-and-14-releases.html\n    // and http://toddmotto.com/exploring-the-angular-1-5-component-method/\n    ///////////////////////////////////////////////////////////////////////////\n    /**\n     * Component definition object (a simplified directive definition object)\n     */\n    interface IComponentOptions {\n        /**\n         * Controller constructor function that should be associated with newly created scope or the name of a registered\n         * controller if passed as a string. Empty function by default.\n         * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)\n         */\n        controller?: string | Function | (string | Function)[] | IComponentController;\n        /**\n         * An identifier name for a reference to the controller. If present, the controller will be published to scope under\n         * the controllerAs name. If not present, this will default to be the same as the component name.\n         * @default \"$ctrl\"\n         */\n        controllerAs?: string;\n        /**\n         * html template as a string or a function that returns an html template as a string which should be used as the\n         * contents of this component. Empty string by default.\n         * If template is a function, then it is injected with the following locals:\n         * $element - Current element\n         * $attrs - Current attributes object for the element\n         * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)\n         */\n        template?: string | Function | (string | Function)[];\n        /**\n         * path or function that returns a path to an html template that should be used as the contents of this component.\n         * If templateUrl is a function, then it is injected with the following locals:\n         * $element - Current element\n         * $attrs - Current attributes object for the element\n         * Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)\n         */\n        templateUrl?: string | Function | (string | Function)[];\n        /**\n         * Define DOM attribute binding to component properties. Component properties are always bound to the component\n         * controller and not to the scope.\n         */\n        bindings?: {[binding: string]: string};\n        /**\n         * Whether transclusion is enabled. Enabled by default.\n         */\n        transclude?: boolean | string | {[slot: string]: string};\n        require?: string | string[] | {[controller: string]: string};\n    }\n\n    interface IComponentTemplateFn {\n        ( $element?: JQuery, $attrs?: IAttributes ): string;\n    }\n    \n    /**\n     * Components have a well-defined lifecycle Each component can implement \"lifecycle hooks\". These are methods that\n     * will be called at certain points in the life of the component.\n     * @url https://docs.angularjs.org/guide/component\n     */\n    interface IComponentController {\n        /**\n         * Called on each controller after all the controllers on an element have been constructed and had their bindings\n         * initialized (and before the pre & post linking functions for the directives on this element). This is a good\n         * place to put initialization code for your controller.\n         */\n        $onInit?(): void;\n        /**\n         * Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound\n         * properties that have changed, and the values are an {@link IChangesObject} object  of the form\n         * { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as\n         * cloning the bound value to prevent accidental mutation of the outer value.\n         */\n        $onChanges?(changesObj: {[property:string]: IChangesObject}): void;\n        /**\n         * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources,\n         * watches and event handlers.\n         */\n        $onDestroy?(): void;\n        /**\n         * Called after this controller's element and its children have been linked. Similar to the post-link function this\n         * hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain\n         * templateUrl directives will not have been compiled and linked since they are waiting for their template to load\n         * asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered\n         * analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather\n         * different in Angular 1 there is no direct mapping and care should be taken when upgrading.\n         */\n        $postInit?(): void;\n    }\n\n    interface IChangesObject {\n        currentValue: any;\n        previousValue: any;\n        isFirstChange(): boolean;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // Directive\n    // see http://docs.angularjs.org/api/ng.$compileProvider#directive\n    // and http://docs.angularjs.org/guide/directive\n    ///////////////////////////////////////////////////////////////////////////\n\n    interface IDirectiveFactory {\n        (...args: any[]): IDirective;\n    }\n\n    interface IDirectiveLinkFn {\n        (\n            scope: IScope,\n            instanceElement: JQuery,\n            instanceAttributes: IAttributes,\n            controller: {},\n            transclude: ITranscludeFunction\n        ): void;\n    }\n\n    interface IDirectivePrePost {\n        pre?: IDirectiveLinkFn;\n        post?: IDirectiveLinkFn;\n    }\n\n    interface IDirectiveCompileFn {\n        (\n            templateElement: JQuery,\n            templateAttributes: IAttributes,\n            /**\n             * @deprecated\n             * Note: The transclude function that is passed to the compile function is deprecated,\n             * as it e.g. does not know about the right outer scope. Please use the transclude function\n             * that is passed to the link function instead.\n             */\n            transclude: ITranscludeFunction\n        ): IDirectivePrePost;\n    }\n\n    interface IDirective {\n        compile?: IDirectiveCompileFn;\n        controller?: any;\n        controllerAs?: string;\n        /**\n         * @deprecated\n         * Deprecation warning: although bindings for non-ES6 class controllers are currently bound to this before\n         * the controller constructor is called, this use is now deprecated. Please place initialization code that\n         * relies upon bindings inside a $onInit method on the controller, instead.\n         */\n        bindToController?: boolean | Object;\n        link?: IDirectiveLinkFn | IDirectivePrePost;\n        multiElement?: boolean;\n        name?: string;\n        priority?: number;\n        /**\n         * @deprecated\n         */\n        replace?: boolean;\n        require?: string | string[] | {[controller: string]: string};\n        restrict?: string;\n        scope?: boolean | Object;\n        template?: string | Function;\n        templateNamespace?: string;\n        templateUrl?: string | Function;\n        terminal?: boolean;\n        transclude?: boolean | string | {[slot: string]: string};\n    }\n\n    /**\n     * These interfaces are kept for compatibility with older versions of these type definitions.\n     * Actually, Angular doesn't create a special subclass of jQuery objects. It extends jQuery.prototype\n     * like jQuery plugins do, that's why all jQuery objects have these Angular-specific methods, not\n     * only those returned from angular.element.\n     * See: http://docs.angularjs.org/api/angular.element\n     */\n    interface IAugmentedJQueryStatic extends JQueryStatic {}\n    interface IAugmentedJQuery extends JQuery {}\n\n    ///////////////////////////////////////////////////////////////////////////\n    // AUTO module (angular.js)\n    ///////////////////////////////////////////////////////////////////////////\n    export module auto {\n\n        ///////////////////////////////////////////////////////////////////////\n        // InjectorService\n        // see http://docs.angularjs.org/api/AUTO.$injector\n        ///////////////////////////////////////////////////////////////////////\n        interface IInjectorService {\n            annotate(fn: Function, strictDi?: boolean): string[];\n            annotate(inlineAnnotatedFunction: any[]): string[];\n            get<T>(name: string, caller?: string): T;\n            get(name: '$anchorScroll'): IAnchorScrollService\n            get(name: '$cacheFactory'): ICacheFactoryService\n            get(name: '$compile'): ICompileService\n            get(name: '$controller'): IControllerService\n            get(name: '$document'): IDocumentService\n            get(name: '$exceptionHandler'): IExceptionHandlerService\n            get(name: '$filter'): IFilterService\n            get(name: '$http'): IHttpService\n            get(name: '$httpBackend'): IHttpBackendService\n            get(name: '$httpParamSerializer'): IHttpParamSerializer\n            get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer\n            get(name: '$interpolate'): IInterpolateService\n            get(name: '$interval'): IIntervalService\n            get(name: '$locale'): ILocaleService\n            get(name: '$location'): ILocationService\n            get(name: '$log'): ILogService\n            get(name: '$parse'): IParseService\n            get(name: '$q'): IQService\n            get(name: '$rootElement'): IRootElementService\n            get(name: '$rootScope'): IRootScopeService\n            get(name: '$sce'): ISCEService\n            get(name: '$sceDelegate'): ISCEDelegateService\n            get(name: '$templateCache'): ITemplateCacheService\n            get(name: '$templateRequest'): ITemplateRequestService\n            get(name: '$timeout'): ITimeoutService\n            get(name: '$window'): IWindowService\n            get<T>(name: '$xhrFactory'): IXhrFactory<T>\n            has(name: string): boolean;\n            instantiate<T>(typeConstructor: Function, locals?: any): T;\n            invoke(inlineAnnotatedFunction: any[]): any;\n            invoke(func: Function, context?: any, locals?: any): any;\n            strictDi: boolean;\n        }\n\n        ///////////////////////////////////////////////////////////////////////\n        // ProvideService\n        // see http://docs.angularjs.org/api/AUTO.$provide\n        ///////////////////////////////////////////////////////////////////////\n        interface IProvideService {\n            // Documentation says it returns the registered instance, but actual\n            // implementation does not return anything.\n            // constant(name: string, value: any): any;\n            /**\n             * Register a constant service, such as a string, a number, an array, an object or a function, with the $injector. Unlike value it can be injected into a module configuration function (see config) and it cannot be overridden by an Angular decorator.\n             *\n             * @param name The name of the constant.\n             * @param value The constant value.\n             */\n            constant(name: string, value: any): void;\n\n            /**\n             * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.\n             *\n             * @param name The name of the service to decorate.\n             * @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:\n             *\n             * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.\n             */\n            decorator(name: string, decorator: Function): void;\n            /**\n             * Register a service decorator with the $injector. A service decorator intercepts the creation of a service, allowing it to override or modify the behaviour of the service. The object returned by the decorator may be the original service, or a new service object which replaces or wraps and delegates to the original service.\n             *\n             * @param name The name of the service to decorate.\n             * @param inlineAnnotatedFunction This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments:\n             *\n             * $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.\n             */\n            decorator(name: string, inlineAnnotatedFunction: any[]): void;\n            factory(name: string, serviceFactoryFunction: Function): IServiceProvider;\n            factory(name: string, inlineAnnotatedFunction: any[]): IServiceProvider;\n            provider(name: string, provider: IServiceProvider): IServiceProvider;\n            provider(name: string, serviceProviderConstructor: Function): IServiceProvider;\n            service(name: string, constructor: Function): IServiceProvider;\n            service(name: string, inlineAnnotatedFunction: any[]): IServiceProvider;\n            value(name: string, value: any): IServiceProvider;\n        }\n\n    }\n\n    /**\n     * $http params serializer that converts objects to strings\n     * see https://docs.angularjs.org/api/ng/service/$httpParamSerializer\n     */\n    interface IHttpParamSerializer {\n        (obj: Object): string;\n    }\n}\n\ninterface JQuery {\n    // TODO: events, how to define?\n    //$destroy\n\n    find(element: any): JQuery;\n    find(obj: JQuery): JQuery;\n    controller(name?: string): any;\n    injector(): ng.auto.IInjectorService;\n    /** It's declared generic for custom scope interfaces */\n    scope<T extends ng.IScope>(): T;\n    isolateScope<T extends ng.IScope>(): T;\n\n    inheritedData(key: string, value: any): JQuery;\n    inheritedData(obj: { [key: string]: any; }): JQuery;\n    inheritedData(key?: string): any;\n}\n"
  },
  {
    "path": "typings/globals/angular/typings.json",
    "content": "{\n  \"resolution\": \"main\",\n  \"tree\": {\n    \"src\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/592a11f956f63a1028b76638f6aa47c8950ea705/angularjs/angular.d.ts\",\n    \"raw\": \"registry:dt/angular#1.5.0+20160614091201\",\n    \"typings\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/592a11f956f63a1028b76638f6aa47c8950ea705/angularjs/angular.d.ts\"\n  }\n}\n"
  },
  {
    "path": "typings/globals/angular-mocks/index.d.ts",
    "content": "// Generated by typings\n// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/0a23a2055d6f8f40fd39b5c1368ba6232842a057/angularjs/angular-mocks.d.ts\ndeclare module \"angular-mocks/ngMock\" {\n    var _: string;\n    export = _;\n}\n\ndeclare module \"angular-mocks/ngMockE2E\" {\n    var _: string;\n    export = _;\n}\n\ndeclare module \"angular-mocks/ngAnimateMock\" {\n    var _: string;\n    export = _;\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// ngMock module (angular-mocks.js)\n///////////////////////////////////////////////////////////////////////////////\ndeclare namespace angular {\n\n    ///////////////////////////////////////////////////////////////////////////\n    // AngularStatic\n    // We reopen it to add the MockStatic definition\n    ///////////////////////////////////////////////////////////////////////////\n    interface IAngularStatic {\n        mock: IMockStatic;\n    }\n\n    // see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject\n    interface IInjectStatic {\n        (...fns: Function[]): any;\n        (...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works\n        strictDi(val?: boolean): void;\n    }\n\n    interface IMockStatic {\n        // see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump\n        dump(obj: any): string;\n\n        inject: IInjectStatic\n\n        // see https://docs.angularjs.org/api/ngMock/function/angular.mock.module\n        module: {\n          (...modules: any[]): any;\n          sharedInjector(): void;\n        }\n\n        // see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate\n        TzDate(offset: number, timestamp: number): Date;\n        TzDate(offset: number, timestamp: string): Date;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // ExceptionHandlerService\n    // see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler\n    // see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider\n    ///////////////////////////////////////////////////////////////////////////\n    interface IExceptionHandlerProvider extends IServiceProvider {\n        mode(mode: string): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // TimeoutService\n    // see https://docs.angularjs.org/api/ngMock/service/$timeout\n    // Augments the original service\n    ///////////////////////////////////////////////////////////////////////////\n    interface ITimeoutService {\n        flush(delay?: number): void;\n        flushNext(expectedDelay?: number): void;\n        verifyNoPendingTasks(): void;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // IntervalService\n    // see https://docs.angularjs.org/api/ngMock/service/$interval\n    // Augments the original service\n    ///////////////////////////////////////////////////////////////////////////\n    interface IIntervalService {\n        flush(millis?: number): number;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // LogService\n    // see https://docs.angularjs.org/api/ngMock/service/$log\n    // Augments the original service\n    ///////////////////////////////////////////////////////////////////////////\n    interface ILogService {\n        assertEmpty(): void;\n        reset(): void;\n    }\n\n    interface ILogCall {\n        logs: string[];\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // ControllerService mock\n    // see https://docs.angularjs.org/api/ngMock/service/$controller\n    // This interface extends http://docs.angularjs.org/api/ng.$controller\n    ///////////////////////////////////////////////////////////////////////////\n    interface IControllerService {\n      // Although the documentation doesn't state this, locals are optional\n      <T>(controllerConstructor: new (...args: any[]) => T, locals?: any, bindings?: any): T;\n      <T>(controllerConstructor: Function, locals?: any, bindings?: any): T;\n      <T>(controllerName: string, locals?: any, bindings?: any): T;\n    }\n\n    ///////////////////////////////////////////////////////////////////////////\n    // ComponentControllerService\n    // see https://docs.angularjs.org/api/ngMock/service/$componentController\n    ///////////////////////////////////////////////////////////////////////////\n    interface IComponentControllerService {\n      // TBinding is an interface exposed by a component as per John Papa's style guide\n      // https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#accessible-members-up-top\n      <T, TBinding>(componentName: string, locals: { $scope: IScope, [key: string]: any }, bindings?: TBinding, ident?: string): T;\n    }\n\n\n    ///////////////////////////////////////////////////////////////////////////\n    // HttpBackendService\n    // see https://docs.angularjs.org/api/ngMock/service/$httpBackend\n    ///////////////////////////////////////////////////////////////////////////\n    interface IHttpBackendService {\n        /**\n          * Flushes all pending requests using the trained responses.\n          * @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.\n          */\n        flush(count?: number): void;\n\n        /**\n          * Resets all request expectations, but preserves all backend definitions.\n          */\n        resetExpectations(): void;\n\n        /**\n          * Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.\n          */\n        verifyNoOutstandingExpectation(): void;\n\n        /**\n          * Verifies that there are no outstanding requests that need to be flushed.\n          */\n        verifyNoOutstandingRequest(): void;\n\n        /**\n          * Creates a new request expectation.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param method HTTP method.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]) :mock.IRequestHandler;\n\n        /**\n          * Creates a new request expectation for DELETE requests.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.\n          * @param headers HTTP headers object to be compared with the HTTP headers in the request.\n          * @param keys Array of keys to assign to regex matches in the request url.\n        */\n        expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new request expectation for GET requests.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param headers HTTP headers object to be compared with the HTTP headers in the request.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new request expectation for HEAD requests.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param headers HTTP headers object to be compared with the HTTP headers in the request.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n\n        expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;\n        \n        /**\n          * Creates a new request expectation for JSONP requests.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */        \n        expectJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new request expectation for PATCH requests.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new request expectation for POST requests.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new request expectation for PUT requests.\n          * Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object, keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param method HTTP method.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition for DELETE requests.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition for GET requests.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in request url described above\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition for HEAD requests.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition for JSONP requests.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        whenJSONP(url: string | RegExp | ((url: string) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition for PATCH requests.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition for POST requests.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;\n\n        /**\n          * Creates a new backend definition for PUT requests.\n          * Returns an object with respond method that controls how a matched request is handled.\n          * @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.\n          * @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.\n          * @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.\n          * @param keys Array of keys to assign to regex matches in the request url.\n          */\n        whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean), keys?: Object[]): mock.IRequestHandler;\n    }\n\n    export module mock {\n        // returned interface by the the mocked HttpBackendService expect/when methods\n        interface IRequestHandler {\n\n            /**\n              * Controls the response for a matched request using a function to construct the response.\n              * Returns the RequestHandler object for possible overrides.\n              * @param func Function that receives the request HTTP method, url, data, headers, and an array of keys to regex matches in the request url and returns an array containing response status (number), data, headers, and status text.\n              */\n            respond(func: ((method: string, url: string, data: string | Object, headers: Object, params?: any) => [number, string | Object, Object, string])): IRequestHandler;\n\n            /**\n              * Controls the response for a matched request using supplied static data to construct the response.\n              * Returns the RequestHandler object for possible overrides.\n              * @param status HTTP status code to add to the response.\n              * @param data Data to add to the response.\n              * @param headers Headers object to add to the response.\n              * @param responseText Response text to add to the response.\n              */\n            respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;\n\n            /**\n              * Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.\n              * Returns the RequestHandler object for possible overrides.\n              * @param data Data to add to the response.\n              * @param headers Headers object to add to the response.\n              * @param responseText Response text to add to the response.\n              */\n            respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;\n\n            // Available when ngMockE2E is loaded\n            /**\n              * Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)\n              */\n            passThrough(): IRequestHandler;\n        }\n\n    }\n\n}\n\n///////////////////////////////////////////////////////////////////////////////\n// functions attached to global object (window)\n///////////////////////////////////////////////////////////////////////////////\n//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.\n//declare var module: (...modules: any[]) => any;\ndeclare var inject: angular.IInjectStatic;\n"
  },
  {
    "path": "typings/globals/angular-mocks/typings.json",
    "content": "{\n  \"resolution\": \"main\",\n  \"tree\": {\n    \"src\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/0a23a2055d6f8f40fd39b5c1368ba6232842a057/angularjs/angular-mocks.d.ts\",\n    \"raw\": \"registry:dt/angular-mocks#1.5.0+20160608104721\",\n    \"typings\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/0a23a2055d6f8f40fd39b5c1368ba6232842a057/angularjs/angular-mocks.d.ts\"\n  }\n}\n"
  },
  {
    "path": "typings/globals/es6-shim/index.d.ts",
    "content": "// Generated by typings\n// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/9807d9b701f58be068cb07833d2b24235351d052/es6-shim/es6-shim.d.ts\ndeclare type PropertyKey = string | number | symbol;\n\ninterface IteratorResult<T> {\n    done: boolean;\n    value?: T;\n}\n\ninterface IterableShim<T> {\n    /**\n      * Shim for an ES6 iterable. Not intended for direct use by user code.\n      */\n    \"_es6-shim iterator_\"(): Iterator<T>;\n}\n\ninterface Iterator<T> {\n    next(value?: any): IteratorResult<T>;\n    return?(value?: any): IteratorResult<T>;\n    throw?(e?: any): IteratorResult<T>;\n}\n\ninterface IterableIteratorShim<T> extends IterableShim<T>, Iterator<T> {\n    /**\n      * Shim for an ES6 iterable iterator. Not intended for direct use by user code.\n      */\n    \"_es6-shim iterator_\"(): IterableIteratorShim<T>;\n}\n\ninterface StringConstructor {\n    /**\n      * Return the String value whose elements are, in order, the elements in the List elements.\n      * If length is 0, the empty string is returned.\n      */\n    fromCodePoint(...codePoints: number[]): string;\n\n    /**\n      * String.raw is intended for use as a tag function of a Tagged Template String. When called\n      * as such the first argument will be a well formed template call site object and the rest\n      * parameter will contain the substitution values.\n      * @param template A well-formed template string call site representation.\n      * @param substitutions A set of substitution values.\n      */\n    raw(template: TemplateStringsArray, ...substitutions: any[]): string;\n}\n\ninterface String {\n    /**\n      * Returns a nonnegative integer Number less than 1114112 (0x110000) that is the code point\n      * value of the UTF-16 encoded code point starting at the string element at position pos in\n      * the String resulting from converting this object to a String.\n      * If there is no element at that position, the result is undefined.\n      * If a valid UTF-16 surrogate pair does not begin at pos, the result is the code unit at pos.\n      */\n    codePointAt(pos: number): number;\n\n    /**\n      * Returns true if searchString appears as a substring of the result of converting this\n      * object to a String, at one or more positions that are\n      * greater than or equal to position; otherwise, returns false.\n      * @param searchString search string\n      * @param position If position is undefined, 0 is assumed, so as to search all of the String.\n      */\n    includes(searchString: string, position?: number): boolean;\n\n    /**\n      * Returns true if the sequence of elements of searchString converted to a String is the\n      * same as the corresponding elements of this object (converted to a String) starting at\n      * endPosition – length(this). Otherwise returns false.\n      */\n    endsWith(searchString: string, endPosition?: number): boolean;\n\n    /**\n      * Returns a String value that is made from count copies appended together. If count is 0,\n      * T is the empty String is returned.\n      * @param count number of copies to append\n      */\n    repeat(count: number): string;\n\n    /**\n      * Returns true if the sequence of elements of searchString converted to a String is the\n      * same as the corresponding elements of this object (converted to a String) starting at\n      * position. Otherwise returns false.\n      */\n    startsWith(searchString: string, position?: number): boolean;\n\n    /**\n      * Returns an <a> HTML anchor element and sets the name attribute to the text value\n      * @param name\n      */\n    anchor(name: string): string;\n\n    /** Returns a <big> HTML element */\n    big(): string;\n\n    /** Returns a <blink> HTML element */\n    blink(): string;\n\n    /** Returns a <b> HTML element */\n    bold(): string;\n\n    /** Returns a <tt> HTML element */\n    fixed(): string\n\n    /** Returns a <font> HTML element and sets the color attribute value */\n    fontcolor(color: string): string\n\n    /** Returns a <font> HTML element and sets the size attribute value */\n    fontsize(size: number): string;\n\n    /** Returns a <font> HTML element and sets the size attribute value */\n    fontsize(size: string): string;\n\n    /** Returns an <i> HTML element */\n    italics(): string;\n\n    /** Returns an <a> HTML element and sets the href attribute value */\n    link(url: string): string;\n\n    /** Returns a <small> HTML element */\n    small(): string;\n\n    /** Returns a <strike> HTML element */\n    strike(): string;\n\n    /** Returns a <sub> HTML element */\n    sub(): string;\n\n    /** Returns a <sup> HTML element */\n    sup(): string;\n\n    /**\n      * Shim for an ES6 iterable. Not intended for direct use by user code.\n      */\n    \"_es6-shim iterator_\"(): IterableIteratorShim<string>;\n}\n\ninterface ArrayConstructor {\n    /**\n      * Creates an array from an array-like object.\n      * @param arrayLike An array-like object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    from<T, U>(arrayLike: ArrayLike<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;\n\n    /**\n      * Creates an array from an iterable object.\n      * @param iterable An iterable object to convert to an array.\n      * @param mapfn A mapping function to call on every element of the array.\n      * @param thisArg Value of 'this' used to invoke the mapfn.\n      */\n    from<T, U>(iterable: IterableShim<T>, mapfn: (v: T, k: number) => U, thisArg?: any): Array<U>;\n\n    /**\n      * Creates an array from an array-like object.\n      * @param arrayLike An array-like object to convert to an array.\n      */\n    from<T>(arrayLike: ArrayLike<T>): Array<T>;\n\n    /**\n      * Creates an array from an iterable object.\n      * @param iterable An iterable object to convert to an array.\n      */\n    from<T>(iterable: IterableShim<T>): Array<T>;\n\n    /**\n      * Returns a new array from a set of elements.\n      * @param items A set of elements to include in the new array object.\n      */\n    of<T>(...items: T[]): Array<T>;\n}\n\ninterface Array<T> {\n    /**\n      * Returns the value of the first element in the array where predicate is true, and undefined\n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending\n      * order, until it finds one where predicate returns true. If such an element is found, find\n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of\n      * predicate. If it is not provided, undefined is used instead.\n      */\n    find(predicate: (value: T, index: number, obj: Array<T>) => boolean, thisArg?: any): T;\n\n    /**\n      * Returns the index of the first element in the array where predicate is true, and undefined\n      * otherwise.\n      * @param predicate find calls predicate once for each element of the array, in ascending\n      * order, until it finds one where predicate returns true. If such an element is found, find\n      * immediately returns that element value. Otherwise, find returns undefined.\n      * @param thisArg If provided, it will be used as the this value for each invocation of\n      * predicate. If it is not provided, undefined is used instead.\n      */\n    findIndex(predicate: (value: T) => boolean, thisArg?: any): number;\n\n    /**\n      * Returns the this object after filling the section identified by start and end with value\n      * @param value value to fill array section with\n      * @param start index to start filling the array at. If start is negative, it is treated as\n      * length+start where length is the length of the array.\n      * @param end index to stop filling the array at. If end is negative, it is treated as\n      * length+end.\n      */\n    fill(value: T, start?: number, end?: number): T[];\n\n    /**\n      * Returns the this object after copying a section of the array identified by start and end\n      * to the same array starting at position target\n      * @param target If target is negative, it is treated as length+target where length is the\n      * length of the array.\n      * @param start If start is negative, it is treated as length+start. If end is negative, it\n      * is treated as length+end.\n      * @param end If not specified, length of the this object is used as its default value.\n      */\n    copyWithin(target: number, start: number, end?: number): T[];\n\n    /**\n      * Returns an array of key, value pairs for every entry in the array\n      */\n    entries(): IterableIteratorShim<[number, T]>;\n\n    /**\n      * Returns an list of keys in the array\n      */\n    keys(): IterableIteratorShim<number>;\n\n    /**\n      * Returns an list of values in the array\n      */\n    values(): IterableIteratorShim<T>;\n\n    /**\n      * Shim for an ES6 iterable. Not intended for direct use by user code.\n      */\n    \"_es6-shim iterator_\"(): IterableIteratorShim<T>;\n}\n\ninterface NumberConstructor {\n    /**\n      * The value of Number.EPSILON is the difference between 1 and the smallest value greater than 1\n      * that is representable as a Number value, which is approximately:\n      * 2.2204460492503130808472633361816 x 10‍−‍16.\n      */\n    EPSILON: number;\n\n    /**\n      * Returns true if passed value is finite.\n      * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a\n      * number. Only finite values of the type number, result in true.\n      * @param number A numeric value.\n      */\n    isFinite(number: number): boolean;\n\n    /**\n      * Returns true if the value passed is an integer, false otherwise.\n      * @param number A numeric value.\n      */\n    isInteger(number: number): boolean;\n\n    /**\n      * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a\n      * number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter\n      * to a number. Only values of the type number, that are also NaN, result in true.\n      * @param number A numeric value.\n      */\n    isNaN(number: number): boolean;\n\n    /**\n      * Returns true if the value passed is a safe integer.\n      * @param number A numeric value.\n      */\n    isSafeInteger(number: number): boolean;\n\n    /**\n      * The value of the largest integer n such that n and n + 1 are both exactly representable as\n      * a Number value.\n      * The value of Number.MIN_SAFE_INTEGER is 9007199254740991 2^53 − 1.\n      */\n    MAX_SAFE_INTEGER: number;\n\n    /**\n      * The value of the smallest integer n such that n and n − 1 are both exactly representable as\n      * a Number value.\n      * The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)).\n      */\n    MIN_SAFE_INTEGER: number;\n\n    /**\n      * Converts a string to a floating-point number.\n      * @param string A string that contains a floating-point number.\n      */\n    parseFloat(string: string): number;\n\n    /**\n      * Converts A string to an integer.\n      * @param s A string to convert into a number.\n      * @param radix A value between 2 and 36 that specifies the base of the number in numString.\n      * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal.\n      * All other strings are considered decimal.\n      */\n    parseInt(string: string, radix?: number): number;\n}\n\ninterface ObjectConstructor {\n    /**\n      * Copy the values of all of the enumerable own properties from one or more source objects to a\n      * target object. Returns the target object.\n      * @param target The target object to copy to.\n      * @param sources One or more source objects to copy properties from.\n      */\n    assign(target: any, ...sources: any[]): any;\n\n    /**\n      * Returns true if the values are the same value, false otherwise.\n      * @param value1 The first value.\n      * @param value2 The second value.\n      */\n    is(value1: any, value2: any): boolean;\n\n    /**\n      * Sets the prototype of a specified object o to  object proto or null. Returns the object o.\n      * @param o The object to change its prototype.\n      * @param proto The value of the new prototype or null.\n      * @remarks Requires `__proto__` support.\n      */\n    setPrototypeOf(o: any, proto: any): any;\n}\n\ninterface RegExp {\n    /**\n      * Returns a string indicating the flags of the regular expression in question. This field is read-only.\n      * The characters in this string are sequenced and concatenated in the following order:\n      *\n      *    - \"g\" for global\n      *    - \"i\" for ignoreCase\n      *    - \"m\" for multiline\n      *    - \"u\" for unicode\n      *    - \"y\" for sticky\n      *\n      * If no flags are set, the value is the empty string.\n      */\n    flags: string;\n}\n\ninterface Math {\n    /**\n      * Returns the number of leading zero bits in the 32-bit binary representation of a number.\n      * @param x A numeric expression.\n      */\n    clz32(x: number): number;\n\n    /**\n      * Returns the result of 32-bit multiplication of two numbers.\n      * @param x First number\n      * @param y Second number\n      */\n    imul(x: number, y: number): number;\n\n    /**\n      * Returns the sign of the x, indicating whether x is positive, negative or zero.\n      * @param x The numeric expression to test\n      */\n    sign(x: number): number;\n\n    /**\n      * Returns the base 10 logarithm of a number.\n      * @param x A numeric expression.\n      */\n    log10(x: number): number;\n\n    /**\n      * Returns the base 2 logarithm of a number.\n      * @param x A numeric expression.\n      */\n    log2(x: number): number;\n\n    /**\n      * Returns the natural logarithm of 1 + x.\n      * @param x A numeric expression.\n      */\n    log1p(x: number): number;\n\n    /**\n      * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of\n      * the natural logarithms).\n      * @param x A numeric expression.\n      */\n    expm1(x: number): number;\n\n    /**\n      * Returns the hyperbolic cosine of a number.\n      * @param x A numeric expression that contains an angle measured in radians.\n      */\n    cosh(x: number): number;\n\n    /**\n      * Returns the hyperbolic sine of a number.\n      * @param x A numeric expression that contains an angle measured in radians.\n      */\n    sinh(x: number): number;\n\n    /**\n      * Returns the hyperbolic tangent of a number.\n      * @param x A numeric expression that contains an angle measured in radians.\n      */\n    tanh(x: number): number;\n\n    /**\n      * Returns the inverse hyperbolic cosine of a number.\n      * @param x A numeric expression that contains an angle measured in radians.\n      */\n    acosh(x: number): number;\n\n    /**\n      * Returns the inverse hyperbolic sine of a number.\n      * @param x A numeric expression that contains an angle measured in radians.\n      */\n    asinh(x: number): number;\n\n    /**\n      * Returns the inverse hyperbolic tangent of a number.\n      * @param x A numeric expression that contains an angle measured in radians.\n      */\n    atanh(x: number): number;\n\n    /**\n      * Returns the square root of the sum of squares of its arguments.\n      * @param values Values to compute the square root for.\n      *     If no arguments are passed, the result is +0.\n      *     If there is only one argument, the result is the absolute value.\n      *     If any argument is +Infinity or -Infinity, the result is +Infinity.\n      *     If any argument is NaN, the result is NaN.\n      *     If all arguments are either +0 or −0, the result is +0.\n      */\n    hypot(...values: number[]): number;\n\n    /**\n      * Returns the integral part of the a numeric expression, x, removing any fractional digits.\n      * If x is already an integer, the result is x.\n      * @param x A numeric expression.\n      */\n    trunc(x: number): number;\n\n    /**\n      * Returns the nearest single precision float representation of a number.\n      * @param x A numeric expression.\n      */\n    fround(x: number): number;\n\n    /**\n      * Returns an implementation-dependent approximation to the cube root of number.\n      * @param x A numeric expression.\n      */\n    cbrt(x: number): number;\n}\n\ninterface PromiseLike<T> {\n    /**\n    * Attaches callbacks for the resolution and/or rejection of the Promise.\n    * @param onfulfilled The callback to execute when the Promise is resolved.\n    * @param onrejected The callback to execute when the Promise is rejected.\n    * @returns A Promise for the completion of which ever callback is executed.\n    */\n    then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): PromiseLike<TResult>;\n    then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): PromiseLike<TResult>;\n}\n\n/**\n * Represents the completion of an asynchronous operation\n */\ninterface Promise<T> {\n    /**\n    * Attaches callbacks for the resolution and/or rejection of the Promise.\n    * @param onfulfilled The callback to execute when the Promise is resolved.\n    * @param onrejected The callback to execute when the Promise is rejected.\n    * @returns A Promise for the completion of which ever callback is executed.\n    */\n    then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>): Promise<TResult>;\n    then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>;\n\n    /**\n     * Attaches a callback for only the rejection of the Promise.\n     * @param onrejected The callback to execute when the Promise is rejected.\n     * @returns A Promise for the completion of the callback.\n     */\n    catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;\n    catch(onrejected?: (reason: any) => void): Promise<T>;\n}\n\ninterface PromiseConstructor {\n    /**\n      * A reference to the prototype.\n      */\n    prototype: Promise<any>;\n\n    /**\n     * Creates a new Promise.\n     * @param executor A callback used to initialize the promise. This callback is passed two arguments:\n     * a resolve callback used resolve the promise with a value or the result of another promise,\n     * and a reject callback used to reject the promise with a provided reason or error.\n     */\n    new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;\n\n    /**\n     * Creates a Promise that is resolved with an array of results when all of the provided Promises\n     * resolve, or rejected when any Promise is rejected.\n     * @param values An array of Promises.\n     * @returns A new Promise.\n     */\n    all<T>(values: IterableShim<T | PromiseLike<T>>): Promise<T[]>;\n\n    /**\n     * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved\n     * or rejected.\n     * @param values An array of Promises.\n     * @returns A new Promise.\n     */\n    race<T>(values: IterableShim<T | PromiseLike<T>>): Promise<T>;\n\n    /**\n     * Creates a new rejected promise for the provided reason.\n     * @param reason The reason the promise was rejected.\n     * @returns A new rejected Promise.\n     */\n    reject(reason: any): Promise<void>;\n\n    /**\n     * Creates a new rejected promise for the provided reason.\n     * @param reason The reason the promise was rejected.\n     * @returns A new rejected Promise.\n     */\n    reject<T>(reason: any): Promise<T>;\n\n    /**\n      * Creates a new resolved promise for the provided value.\n      * @param value A promise.\n      * @returns A promise whose internal state matches the provided promise.\n      */\n    resolve<T>(value: T | PromiseLike<T>): Promise<T>;\n\n    /**\n     * Creates a new resolved promise .\n     * @returns A resolved promise.\n     */\n    resolve(): Promise<void>;\n}\n\ndeclare var Promise: PromiseConstructor;\n\ninterface Map<K, V> {\n    clear(): void;\n    delete(key: K): boolean;\n    forEach(callbackfn: (value: V, index: K, map: Map<K, V>) => void, thisArg?: any): void;\n    get(key: K): V;\n    has(key: K): boolean;\n    set(key: K, value?: V): Map<K, V>;\n    size: number;\n    entries(): IterableIteratorShim<[K, V]>;\n    keys(): IterableIteratorShim<K>;\n    values(): IterableIteratorShim<V>;\n}\n\ninterface MapConstructor {\n    new <K, V>(): Map<K, V>;\n    new <K, V>(iterable: IterableShim<[K, V]>): Map<K, V>;\n    prototype: Map<any, any>;\n}\n\ndeclare var Map: MapConstructor;\n\ninterface Set<T> {\n    add(value: T): Set<T>;\n    clear(): void;\n    delete(value: T): boolean;\n    forEach(callbackfn: (value: T, index: T, set: Set<T>) => void, thisArg?: any): void;\n    has(value: T): boolean;\n    size: number;\n    entries(): IterableIteratorShim<[T, T]>;\n    keys(): IterableIteratorShim<T>;\n    values(): IterableIteratorShim<T>;\n    '_es6-shim iterator_'(): IterableIteratorShim<T>;\n}\n\ninterface SetConstructor {\n    new <T>(): Set<T>;\n    new <T>(iterable: IterableShim<T>): Set<T>;\n    prototype: Set<any>;\n}\n\ndeclare var Set: SetConstructor;\n\ninterface WeakMap<K, V> {\n    delete(key: K): boolean;\n    get(key: K): V;\n    has(key: K): boolean;\n    set(key: K, value?: V): WeakMap<K, V>;\n}\n\ninterface WeakMapConstructor {\n    new <K, V>(): WeakMap<K, V>;\n    new <K, V>(iterable: IterableShim<[K, V]>): WeakMap<K, V>;\n    prototype: WeakMap<any, any>;\n}\n\ndeclare var WeakMap: WeakMapConstructor;\n\ninterface WeakSet<T> {\n    add(value: T): WeakSet<T>;\n    delete(value: T): boolean;\n    has(value: T): boolean;\n}\n\ninterface WeakSetConstructor {\n    new <T>(): WeakSet<T>;\n    new <T>(iterable: IterableShim<T>): WeakSet<T>;\n    prototype: WeakSet<any>;\n}\n\ndeclare var WeakSet: WeakSetConstructor;\n\ndeclare namespace Reflect {\n    function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;\n    function construct(target: Function, argumentsList: ArrayLike<any>): any;\n    function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;\n    function deleteProperty(target: any, propertyKey: PropertyKey): boolean;\n    function enumerate(target: any): IterableIteratorShim<any>;\n    function get(target: any, propertyKey: PropertyKey, receiver?: any): any;\n    function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;\n    function getPrototypeOf(target: any): any;\n    function has(target: any, propertyKey: PropertyKey): boolean;\n    function isExtensible(target: any): boolean;\n    function ownKeys(target: any): Array<PropertyKey>;\n    function preventExtensions(target: any): boolean;\n    function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;\n    function setPrototypeOf(target: any, proto: any): boolean;\n}\n\ndeclare module \"es6-shim\" {\n    var String: StringConstructor;\n    var Array: ArrayConstructor;\n    var Number: NumberConstructor;\n    var Math: Math;\n    var Object: ObjectConstructor;\n    var Map: MapConstructor;\n    var Set: SetConstructor;\n    var WeakMap: WeakMapConstructor;\n    var WeakSet: WeakSetConstructor;\n    var Promise: PromiseConstructor;\n    namespace Reflect {\n        function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;\n        function construct(target: Function, argumentsList: ArrayLike<any>): any;\n        function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;\n        function deleteProperty(target: any, propertyKey: PropertyKey): boolean;\n        function enumerate(target: any): Iterator<any>;\n        function get(target: any, propertyKey: PropertyKey, receiver?: any): any;\n        function getOwnPropertyDescriptor(target: any, propertyKey: PropertyKey): PropertyDescriptor;\n        function getPrototypeOf(target: any): any;\n        function has(target: any, propertyKey: PropertyKey): boolean;\n        function isExtensible(target: any): boolean;\n        function ownKeys(target: any): Array<PropertyKey>;\n        function preventExtensions(target: any): boolean;\n        function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;\n        function setPrototypeOf(target: any, proto: any): boolean;\n    }\n}\n"
  },
  {
    "path": "typings/globals/es6-shim/typings.json",
    "content": "{\n  \"resolution\": \"main\",\n  \"tree\": {\n    \"src\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/9807d9b701f58be068cb07833d2b24235351d052/es6-shim/es6-shim.d.ts\",\n    \"raw\": \"registry:dt/es6-shim#0.31.2+20160602141504\",\n    \"typings\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/9807d9b701f58be068cb07833d2b24235351d052/es6-shim/es6-shim.d.ts\"\n  }\n}\n"
  },
  {
    "path": "typings/globals/jasmine/index.d.ts",
    "content": "// Generated by typings\n// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/c49913aa9ea419ea46c1c684e488cf2a10303b1a/jasmine/jasmine.d.ts\ndeclare function describe(description: string, specDefinitions: () => void): void;\ndeclare function fdescribe(description: string, specDefinitions: () => void): void;\ndeclare function xdescribe(description: string, specDefinitions: () => void): void;\n\ndeclare function it(expectation: string, assertion?: () => void, timeout?: number): void;\ndeclare function it(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void;\ndeclare function fit(expectation: string, assertion?: () => void, timeout?: number): void;\ndeclare function fit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void;\ndeclare function xit(expectation: string, assertion?: () => void, timeout?: number): void;\ndeclare function xit(expectation: string, assertion?: (done: DoneFn) => void, timeout?: number): void;\n\n/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */\ndeclare function pending(reason?: string): void;\n\ndeclare function beforeEach(action: () => void, timeout?: number): void;\ndeclare function beforeEach(action: (done: DoneFn) => void, timeout?: number): void;\ndeclare function afterEach(action: () => void, timeout?: number): void;\ndeclare function afterEach(action: (done: DoneFn) => void, timeout?: number): void;\n\ndeclare function beforeAll(action: () => void, timeout?: number): void;\ndeclare function beforeAll(action: (done: DoneFn) => void, timeout?: number): void;\ndeclare function afterAll(action: () => void, timeout?: number): void;\ndeclare function afterAll(action: (done: DoneFn) => void, timeout?: number): void;\n\ndeclare function expect(spy: Function): jasmine.Matchers;\ndeclare function expect(actual: any): jasmine.Matchers;\n\ndeclare function fail(e?: any): void;\n/** Action method that should be called when the async work is complete */\ninterface DoneFn extends Function {\n    (): void;\n\n    /** fails the spec and indicates that it has completed. If the message is an Error, Error.message is used */\n    fail: (message?: Error|string) => void;\n}\n\ndeclare function spyOn(object: any, method: string): jasmine.Spy;\n\ndeclare function runs(asyncMethod: Function): void;\ndeclare function waitsFor(latchMethod: () => boolean, failureMessage?: string, timeout?: number): void;\ndeclare function waits(timeout?: number): void;\n\ndeclare namespace jasmine {\n\n    var clock: () => Clock;\n\n    function any(aclass: any): Any;\n    function anything(): Any;\n    function arrayContaining(sample: any[]): ArrayContaining;\n    function objectContaining(sample: any): ObjectContaining;\n    function createSpy(name: string, originalFn?: Function): Spy;\n    function createSpyObj(baseName: string, methodNames: any[]): any;\n    function createSpyObj<T>(baseName: string, methodNames: any[]): T;\n    function pp(value: any): string;\n    function getEnv(): Env;\n    function addCustomEqualityTester(equalityTester: CustomEqualityTester): void;\n    function addMatchers(matchers: CustomMatcherFactories): void;\n    function stringMatching(str: string): Any;\n    function stringMatching(str: RegExp): Any;\n\n    interface Any {\n\n        new (expectedClass: any): any;\n\n        jasmineMatches(other: any): boolean;\n        jasmineToString(): string;\n    }\n\n    // taken from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains()\n    interface ArrayLike<T> {\n        length: number;\n        [n: number]: T;\n    }\n\n    interface ArrayContaining {\n        new (sample: any[]): any;\n\n        asymmetricMatch(other: any): boolean;\n        jasmineToString(): string;\n    }\n\n    interface ObjectContaining {\n        new (sample: any): any;\n\n        jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean;\n        jasmineToString(): string;\n    }\n\n    interface Block {\n\n        new (env: Env, func: SpecFunction, spec: Spec): any;\n\n        execute(onComplete: () => void): void;\n    }\n\n    interface WaitsBlock extends Block {\n        new (env: Env, timeout: number, spec: Spec): any;\n    }\n\n    interface WaitsForBlock extends Block {\n        new (env: Env, timeout: number, latchFunction: SpecFunction, message: string, spec: Spec): any;\n    }\n\n    interface Clock {\n        install(): void;\n        uninstall(): void;\n        /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */\n        tick(ms: number): void;\n        mockDate(date?: Date): void;\n    }\n\n    interface CustomEqualityTester {\n        (first: any, second: any): boolean;\n    }\n\n    interface CustomMatcher {\n        compare<T>(actual: T, expected: T): CustomMatcherResult;\n        compare(actual: any, expected: any): CustomMatcherResult;\n    }\n\n    interface CustomMatcherFactory {\n        (util: MatchersUtil, customEqualityTesters: Array<CustomEqualityTester>): CustomMatcher;\n    }\n\n    interface CustomMatcherFactories {\n        [index: string]: CustomMatcherFactory;\n    }\n\n    interface CustomMatcherResult {\n        pass: boolean;\n        message?: string;\n    }\n\n    interface MatchersUtil {\n        equals(a: any, b: any, customTesters?: Array<CustomEqualityTester>): boolean;\n        contains<T>(haystack: ArrayLike<T> | string, needle: any, customTesters?: Array<CustomEqualityTester>): boolean;\n        buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array<any>): string;\n    }\n\n    interface Env {\n        setTimeout: any;\n        clearTimeout: void;\n        setInterval: any;\n        clearInterval: void;\n        updateInterval: number;\n\n        currentSpec: Spec;\n\n        matchersClass: Matchers;\n\n        version(): any;\n        versionString(): string;\n        nextSpecId(): number;\n        addReporter(reporter: Reporter): void;\n        execute(): void;\n        describe(description: string, specDefinitions: () => void): Suite;\n        // ddescribe(description: string, specDefinitions: () => void): Suite; Not a part of jasmine. Angular team adds these\n        beforeEach(beforeEachFunction: () => void): void;\n        beforeAll(beforeAllFunction: () => void): void;\n        currentRunner(): Runner;\n        afterEach(afterEachFunction: () => void): void;\n        afterAll(afterAllFunction: () => void): void;\n        xdescribe(desc: string, specDefinitions: () => void): XSuite;\n        it(description: string, func: () => void): Spec;\n        // iit(description: string, func: () => void): Spec; Not a part of jasmine. Angular team adds these\n        xit(desc: string, func: () => void): XSpec;\n        compareRegExps_(a: RegExp, b: RegExp, mismatchKeys: string[], mismatchValues: string[]): boolean;\n        compareObjects_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean;\n        equals_(a: any, b: any, mismatchKeys: string[], mismatchValues: string[]): boolean;\n        contains_(haystack: any, needle: any): boolean;\n        addCustomEqualityTester(equalityTester: CustomEqualityTester): void;\n        addMatchers(matchers: CustomMatcherFactories): void;\n        specFilter(spec: Spec): boolean;\n        throwOnExpectationFailure(value: boolean): void;\n    }\n\n    interface FakeTimer {\n\n        new (): any;\n\n        reset(): void;\n        tick(millis: number): void;\n        runFunctionsWithinRange(oldMillis: number, nowMillis: number): void;\n        scheduleFunction(timeoutKey: any, funcToCall: () => void, millis: number, recurring: boolean): void;\n    }\n\n    interface HtmlReporter {\n        new (): any;\n    }\n\n    interface HtmlSpecFilter {\n        new (): any;\n    }\n\n    interface Result {\n        type: string;\n    }\n\n    interface NestedResults extends Result {\n        description: string;\n\n        totalCount: number;\n        passedCount: number;\n        failedCount: number;\n\n        skipped: boolean;\n\n        rollupCounts(result: NestedResults): void;\n        log(values: any): void;\n        getItems(): Result[];\n        addResult(result: Result): void;\n        passed(): boolean;\n    }\n\n    interface MessageResult extends Result  {\n        values: any;\n        trace: Trace;\n    }\n\n    interface ExpectationResult extends Result  {\n        matcherName: string;\n        passed(): boolean;\n        expected: any;\n        actual: any;\n        message: string;\n        trace: Trace;\n    }\n\n    interface Trace {\n        name: string;\n        message: string;\n        stack: any;\n    }\n\n    interface PrettyPrinter {\n\n        new (): any;\n\n        format(value: any): void;\n        iterateObject(obj: any, fn: (property: string, isGetter: boolean) => void): void;\n        emitScalar(value: any): void;\n        emitString(value: string): void;\n        emitArray(array: any[]): void;\n        emitObject(obj: any): void;\n        append(value: any): void;\n    }\n\n    interface StringPrettyPrinter extends PrettyPrinter {\n    }\n\n    interface Queue {\n\n        new (env: any): any;\n\n        env: Env;\n        ensured: boolean[];\n        blocks: Block[];\n        running: boolean;\n        index: number;\n        offset: number;\n        abort: boolean;\n\n        addBefore(block: Block, ensure?: boolean): void;\n        add(block: any, ensure?: boolean): void;\n        insertNext(block: any, ensure?: boolean): void;\n        start(onComplete?: () => void): void;\n        isRunning(): boolean;\n        next_(): void;\n        results(): NestedResults;\n    }\n\n    interface Matchers {\n\n        new (env: Env, actual: any, spec: Env, isNot?: boolean): any;\n\n        env: Env;\n        actual: any;\n        spec: Env;\n        isNot?: boolean;\n        message(): any;\n\n        toBe(expected: any, expectationFailOutput?: any): boolean;\n        toEqual(expected: any, expectationFailOutput?: any): boolean;\n        toMatch(expected: string | RegExp, expectationFailOutput?: any): boolean;\n        toBeDefined(expectationFailOutput?: any): boolean;\n        toBeUndefined(expectationFailOutput?: any): boolean;\n        toBeNull(expectationFailOutput?: any): boolean;\n        toBeNaN(): boolean;\n        toBeTruthy(expectationFailOutput?: any): boolean;\n        toBeFalsy(expectationFailOutput?: any): boolean;\n        toHaveBeenCalled(): boolean;\n        toHaveBeenCalledWith(...params: any[]): boolean;\n        toHaveBeenCalledTimes(expected: number): boolean;\n        toContain(expected: any, expectationFailOutput?: any): boolean;\n        toBeLessThan(expected: number, expectationFailOutput?: any): boolean;\n        toBeGreaterThan(expected: number, expectationFailOutput?: any): boolean;\n        toBeCloseTo(expected: number, precision?: any, expectationFailOutput?: any): boolean;\n        toThrow(expected?: any): boolean;\n        toThrowError(message?: string | RegExp): boolean;\n        toThrowError(expected?: new (...args: any[]) => Error, message?: string | RegExp): boolean;\n        not: Matchers;\n\n        Any: Any;\n    }\n\n    interface Reporter {\n        reportRunnerStarting(runner: Runner): void;\n        reportRunnerResults(runner: Runner): void;\n        reportSuiteResults(suite: Suite): void;\n        reportSpecStarting(spec: Spec): void;\n        reportSpecResults(spec: Spec): void;\n        log(str: string): void;\n    }\n\n    interface MultiReporter extends Reporter {\n        addReporter(reporter: Reporter): void;\n    }\n\n    interface Runner {\n\n        new (env: Env): any;\n\n        execute(): void;\n        beforeEach(beforeEachFunction: SpecFunction): void;\n        afterEach(afterEachFunction: SpecFunction): void;\n        beforeAll(beforeAllFunction: SpecFunction): void;\n        afterAll(afterAllFunction: SpecFunction): void;\n        finishCallback(): void;\n        addSuite(suite: Suite): void;\n        add(block: Block): void;\n        specs(): Spec[];\n        suites(): Suite[];\n        topLevelSuites(): Suite[];\n        results(): NestedResults;\n    }\n\n    interface SpecFunction {\n        (spec?: Spec): void;\n    }\n\n    interface SuiteOrSpec {\n        id: number;\n        env: Env;\n        description: string;\n        queue: Queue;\n    }\n\n    interface Spec extends SuiteOrSpec {\n\n        new (env: Env, suite: Suite, description: string): any;\n\n        suite: Suite;\n\n        afterCallbacks: SpecFunction[];\n        spies_: Spy[];\n\n        results_: NestedResults;\n        matchersClass: Matchers;\n\n        getFullName(): string;\n        results(): NestedResults;\n        log(arguments: any): any;\n        runs(func: SpecFunction): Spec;\n        addToQueue(block: Block): void;\n        addMatcherResult(result: Result): void;\n        expect(actual: any): any;\n        waits(timeout: number): Spec;\n        waitsFor(latchFunction: SpecFunction, timeoutMessage?: string, timeout?: number): Spec;\n        fail(e?: any): void;\n        getMatchersClass_(): Matchers;\n        addMatchers(matchersPrototype: CustomMatcherFactories): void;\n        finishCallback(): void;\n        finish(onComplete?: () => void): void;\n        after(doAfter: SpecFunction): void;\n        execute(onComplete?: () => void): any;\n        addBeforesAndAftersToQueue(): void;\n        explodes(): void;\n        spyOn(obj: any, methodName: string, ignoreMethodDoesntExist: boolean): Spy;\n        removeAllSpies(): void;\n    }\n\n    interface XSpec {\n        id: number;\n        runs(): void;\n    }\n\n    interface Suite extends SuiteOrSpec {\n\n        new (env: Env, description: string, specDefinitions: () => void, parentSuite: Suite): any;\n\n        parentSuite: Suite;\n\n        getFullName(): string;\n        finish(onComplete?: () => void): void;\n        beforeEach(beforeEachFunction: SpecFunction): void;\n        afterEach(afterEachFunction: SpecFunction): void;\n        beforeAll(beforeAllFunction: SpecFunction): void;\n        afterAll(afterAllFunction: SpecFunction): void;\n        results(): NestedResults;\n        add(suiteOrSpec: SuiteOrSpec): void;\n        specs(): Spec[];\n        suites(): Suite[];\n        children(): any[];\n        execute(onComplete?: () => void): void;\n    }\n\n    interface XSuite {\n        execute(): void;\n    }\n\n    interface Spy {\n        (...params: any[]): any;\n\n        identity: string;\n        and: SpyAnd;\n        calls: Calls;\n        mostRecentCall: { args: any[]; };\n        argsForCall: any[];\n        wasCalled: boolean;\n    }\n\n    interface SpyAnd {\n        /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */\n        callThrough(): Spy;\n        /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */\n        returnValue(val: any): Spy;\n        /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */\n        returnValues(...values: any[]): Spy;\n        /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */\n        callFake(fn: Function): Spy;\n        /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */\n        throwError(msg: string): Spy;\n        /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */\n        stub(): Spy;\n    }\n\n    interface Calls {\n        /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. **/\n        any(): boolean;\n        /** By chaining the spy with calls.count(), will return the number of times the spy was called **/\n        count(): number;\n        /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index **/\n        argsFor(index: number): any[];\n        /** By chaining the spy with calls.allArgs(), will return the arguments to all calls **/\n        allArgs(): any[];\n        /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls **/\n        all(): CallInfo[];\n        /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call **/\n        mostRecent(): CallInfo;\n        /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call **/\n        first(): CallInfo;\n        /** By chaining the spy with calls.reset(), will clears all tracking for a spy **/\n        reset(): void;\n    }\n\n    interface CallInfo {\n        /** The context (the this) for the call */\n        object: any;\n        /** All arguments passed to the call */\n        args: any[];\n        /** The return value of the call */\n        returnValue: any;\n    }\n\n    interface Util {\n        inherit(childClass: Function, parentClass: Function): any;\n        formatException(e: any): any;\n        htmlEscape(str: string): string;\n        argsToArray(args: any): any;\n        extend(destination: any, source: any): any;\n    }\n\n    interface JsApiReporter extends Reporter {\n\n        started: boolean;\n        finished: boolean;\n        result: any;\n        messages: any;\n\n        new (): any;\n\n        suites(): Suite[];\n        summarize_(suiteOrSpec: SuiteOrSpec): any;\n        results(): any;\n        resultsForSpec(specId: any): any;\n        log(str: any): any;\n        resultsForSpecs(specIds: any): any;\n        summarizeResult_(result: any): any;\n    }\n\n    interface Jasmine {\n        Spec: Spec;\n        clock: Clock;\n        util: Util;\n    }\n\n    export var HtmlReporter: HtmlReporter;\n    export var HtmlSpecFilter: HtmlSpecFilter;\n    export var DEFAULT_TIMEOUT_INTERVAL: number;\n}\n"
  },
  {
    "path": "typings/globals/jasmine/typings.json",
    "content": "{\n  \"resolution\": \"main\",\n  \"tree\": {\n    \"src\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/c49913aa9ea419ea46c1c684e488cf2a10303b1a/jasmine/jasmine.d.ts\",\n    \"raw\": \"registry:dt/jasmine#2.2.0+20160621224255\",\n    \"typings\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/c49913aa9ea419ea46c1c684e488cf2a10303b1a/jasmine/jasmine.d.ts\"\n  }\n}\n"
  },
  {
    "path": "typings/globals/jquery/index.d.ts",
    "content": "// Generated by typings\n// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/4cdfbe96b666eec5e1defbb519a62abf04e96764/jquery/jquery.d.ts\ninterface JQueryAjaxSettings {\n    /**\n     * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method.\n     */\n    accepts?: any;\n    /**\n     * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: \"jsonp\" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().\n     */\n    async?: boolean;\n    /**\n     * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.\n     */\n    beforeSend? (jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any;\n    /**\n     * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending \"_={timestamp}\" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.\n     */\n    cache?: boolean;\n    /**\n     * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request (\"success\", \"notmodified\", \"error\", \"timeout\", \"abort\", or \"parsererror\"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.\n     */\n    complete? (jqXHR: JQueryXHR, textStatus: string): any;\n    /**\n     * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5)\n     */\n    contents?: { [key: string]: any; };\n    //According to jQuery.ajax source code, ajax's option actually allows contentType to set to \"false\"\n    // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/742\n    /**\n     * When sending data to the server, use this content type. Default is \"application/x-www-form-urlencoded; charset=UTF-8\", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.\n     */\n    contentType?: any;\n    /**\n     * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax).\n     */\n    context?: any;\n    /**\n     * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5)\n     */\n    converters?: { [key: string]: any; };\n    /**\n     * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5)\n     */\n    crossDomain?: boolean;\n    /**\n     * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).\n     */\n    data?: any;\n    /**\n     * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.\n     */\n    dataFilter? (data: any, ty: any): any;\n    /**\n     * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). \n     */\n    dataType?: string;\n    /**\n     * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are \"timeout\", \"error\", \"abort\", and \"parsererror\". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as \"Not Found\" or \"Internal Server Error.\" As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.\n     */\n    error? (jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any;\n    /**\n     * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events.\n     */\n    global?: boolean;\n    /**\n     * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5)\n     */\n    headers?: { [key: string]: any; };\n    /**\n     * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.\n     */\n    ifModified?: boolean;\n    /**\n     * Allow the current environment to be recognized as \"local,\" (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1)\n     */\n    isLocal?: boolean;\n    /**\n     * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the \"?callback\" string to the URL or attempting to use \"=?\" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: \"callbackName\" }\n     */\n    jsonp?: any;\n    /**\n     * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.\n     */\n    jsonpCallback?: any;\n    /**\n     * The HTTP method to use for the request (e.g. \"POST\", \"GET\", \"PUT\"). (version added: 1.9.0)\n     */\n    method?: string;\n    /**\n     * A mime type to override the XHR mime type. (version added: 1.5.1)\n     */\n    mimeType?: string;\n    /**\n     * A password to be used with XMLHttpRequest in response to an HTTP access authentication request.\n     */\n    password?: string;\n    /**\n     * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type \"application/x-www-form-urlencoded\". If you want to send a DOMDocument, or other non-processed data, set this option to false.\n     */\n    processData?: boolean;\n    /**\n     * Only applies when the \"script\" transport is used (e.g., cross-domain requests with \"jsonp\" or \"script\" dataType and \"GET\" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script.\n     */\n    scriptCharset?: string;\n    /**\n     * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5)\n     */\n    statusCode?: { [key: string]: any; };\n    /**\n     * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.\n     */\n    success? (data: any, textStatus: string, jqXHR: JQueryXHR): any;\n    /**\n     * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.\n     */\n    timeout?: number;\n    /**\n     * Set this to true if you wish to use the traditional style of param serialization.\n     */\n    traditional?: boolean;\n    /**\n     * The type of request to make (\"POST\" or \"GET\"), default is \"GET\". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.\n     */\n    type?: string;\n    /**\n     * A string containing the URL to which the request is sent.\n     */\n    url?: string;\n    /**\n     * A username to be used with XMLHttpRequest in response to an HTTP access authentication request.\n     */\n    username?: string;\n    /**\n     * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory.\n     */\n    xhr?: any;\n    /**\n     * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1)\n     */\n    xhrFields?: { [key: string]: any; };\n}\n\n/**\n * Interface for the jqXHR object\n */\ninterface JQueryXHR extends XMLHttpRequest, JQueryPromise<any> {\n    /**\n     * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). \n     */\n    overrideMimeType(mimeType: string): any;\n    /**\n     * Cancel the request. \n     *\n     * @param statusText A string passed as the textStatus parameter for the done callback. Default value: \"canceled\"\n     */\n    abort(statusText?: string): void;\n    /**\n     * Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.\n     */\n    then<R>(doneCallback: (data: any, textStatus: string, jqXHR: JQueryXHR) => R, failCallback?: (jqXHR: JQueryXHR, textStatus: string, errorThrown: any) => void): JQueryPromise<R>;\n    /**\n     * Property containing the parsed response if the response Content-Type is json\n     */\n    responseJSON?: any;\n    /**\n     * A function to be called if the request fails.\n     */\n    error(xhr: JQueryXHR, textStatus: string, errorThrown: string): void;\n}\n\n/**\n * Interface for the JQuery callback\n */\ninterface JQueryCallback {\n    /**\n     * Add a callback or a collection of callbacks to a callback list.\n     * \n     * @param callbacks A function, or array of functions, that are to be added to the callback list.\n     */\n    add(callbacks: Function): JQueryCallback;\n    /**\n     * Add a callback or a collection of callbacks to a callback list.\n     * \n     * @param callbacks A function, or array of functions, that are to be added to the callback list.\n     */\n    add(callbacks: Function[]): JQueryCallback;\n\n    /**\n     * Disable a callback list from doing anything more.\n     */\n    disable(): JQueryCallback;\n\n    /**\n     * Determine if the callbacks list has been disabled.\n     */\n    disabled(): boolean;\n\n    /**\n     * Remove all of the callbacks from a list.\n     */\n    empty(): JQueryCallback;\n\n    /**\n     * Call all of the callbacks with the given arguments\n     * \n     * @param arguments The argument or list of arguments to pass back to the callback list.\n     */\n    fire(...arguments: any[]): JQueryCallback;\n\n    /**\n     * Determine if the callbacks have already been called at least once.\n     */\n    fired(): boolean;\n\n    /**\n     * Call all callbacks in a list with the given context and arguments.\n     * \n     * @param context A reference to the context in which the callbacks in the list should be fired.\n     * @param arguments An argument, or array of arguments, to pass to the callbacks in the list.\n     */\n    fireWith(context?: any, args?: any[]): JQueryCallback;\n\n    /**\n     * Determine whether a supplied callback is in a list\n     * \n     * @param callback The callback to search for.\n     */\n    has(callback: Function): boolean;\n\n    /**\n     * Lock a callback list in its current state.\n     */\n    lock(): JQueryCallback;\n\n    /**\n     * Determine if the callbacks list has been locked.\n     */\n    locked(): boolean;\n\n    /**\n     * Remove a callback or a collection of callbacks from a callback list.\n     * \n     * @param callbacks A function, or array of functions, that are to be removed from the callback list.\n     */\n    remove(callbacks: Function): JQueryCallback;\n    /**\n     * Remove a callback or a collection of callbacks from a callback list.\n     * \n     * @param callbacks A function, or array of functions, that are to be removed from the callback list.\n     */\n    remove(callbacks: Function[]): JQueryCallback;\n}\n\n/**\n * Allows jQuery Promises to interop with non-jQuery promises\n */\ninterface JQueryGenericPromise<T> {\n    /**\n     * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.\n     * \n     * @param doneFilter A function that is called when the Deferred is resolved.\n     * @param failFilter An optional function that is called when the Deferred is rejected.\n     */\n    then<U>(doneFilter: (value?: T, ...values: any[]) => U|JQueryPromise<U>, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise<U>;\n\n    /**\n     * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress.\n     * \n     * @param doneFilter A function that is called when the Deferred is resolved.\n     * @param failFilter An optional function that is called when the Deferred is rejected.\n     */\n    then(doneFilter: (value?: T, ...values: any[]) => void, failFilter?: (...reasons: any[]) => any, progressFilter?: (...progression: any[]) => any): JQueryPromise<void>;\n}\n\n/**\n * Interface for the JQuery promise/deferred callbacks\n */\ninterface JQueryPromiseCallback<T> {\n    (value?: T, ...args: any[]): void;\n}\n\ninterface JQueryPromiseOperator<T, U> {\n    (callback1: JQueryPromiseCallback<T>|JQueryPromiseCallback<T>[], ...callbacksN: Array<JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[]>): JQueryPromise<U>;\n}\n\n/**\n * Interface for the JQuery promise, part of callbacks\n */\ninterface JQueryPromise<T> extends JQueryGenericPromise<T> {\n    /**\n     * Determine the current state of a Deferred object.\n     */\n    state(): string;\n    /**\n     * Add handlers to be called when the Deferred object is either resolved or rejected.\n     * \n     * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected.\n     * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected.\n     */\n    always(alwaysCallback1?: JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[], ...alwaysCallbacksN: Array<JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[]>): JQueryPromise<T>;\n    /**\n     * Add handlers to be called when the Deferred object is resolved.\n     * \n     * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved.\n     * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved.\n     */\n    done(doneCallback1?: JQueryPromiseCallback<T>|JQueryPromiseCallback<T>[], ...doneCallbackN: Array<JQueryPromiseCallback<T>|JQueryPromiseCallback<T>[]>): JQueryPromise<T>;\n    /**\n     * Add handlers to be called when the Deferred object is rejected.\n     * \n     * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected.\n     * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected.\n     */\n    fail(failCallback1?: JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[], ...failCallbacksN: Array<JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[]>): JQueryPromise<T>;\n    /**\n     * Add handlers to be called when the Deferred object generates progress notifications.\n     * \n     * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications.\n     */\n    progress(progressCallback1?: JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[], ...progressCallbackN: Array<JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[]>): JQueryPromise<T>;\n\n    // Deprecated - given no typings\n    pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise<any>;\n}\n\n/**\n * Interface for the JQuery deferred, part of callbacks\n */\ninterface JQueryDeferred<T> extends JQueryGenericPromise<T> {\n    /**\n     * Determine the current state of a Deferred object.\n     */\n    state(): string;\n    /**\n     * Add handlers to be called when the Deferred object is either resolved or rejected.\n     * \n     * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected.\n     * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected.\n     */\n    always(alwaysCallback1?: JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[], ...alwaysCallbacksN: Array<JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[]>): JQueryDeferred<T>;\n    /**\n     * Add handlers to be called when the Deferred object is resolved.\n     * \n     * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved.\n     * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved.\n     */\n    done(doneCallback1?: JQueryPromiseCallback<T>|JQueryPromiseCallback<T>[], ...doneCallbackN: Array<JQueryPromiseCallback<T>|JQueryPromiseCallback<T>[]>): JQueryDeferred<T>;\n    /**\n     * Add handlers to be called when the Deferred object is rejected.\n     * \n     * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected.\n     * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected.\n     */\n    fail(failCallback1?: JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[], ...failCallbacksN: Array<JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[]>): JQueryDeferred<T>;\n    /**\n     * Add handlers to be called when the Deferred object generates progress notifications.\n     * \n     * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications.\n     */\n    progress(progressCallback1?: JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[], ...progressCallbackN: Array<JQueryPromiseCallback<any>|JQueryPromiseCallback<any>[]>): JQueryDeferred<T>;\n\n    /**\n     * Call the progressCallbacks on a Deferred object with the given args.\n     * \n     * @param args Optional arguments that are passed to the progressCallbacks.\n     */\n    notify(value?: any, ...args: any[]): JQueryDeferred<T>;\n\n    /**\n     * Call the progressCallbacks on a Deferred object with the given context and args.\n     * \n     * @param context Context passed to the progressCallbacks as the this object.\n     * @param args Optional arguments that are passed to the progressCallbacks.\n     */\n    notifyWith(context: any, value?: any[]): JQueryDeferred<T>;\n\n    /**\n     * Reject a Deferred object and call any failCallbacks with the given args.\n     * \n     * @param args Optional arguments that are passed to the failCallbacks.\n     */\n    reject(value?: any, ...args: any[]): JQueryDeferred<T>;\n    /**\n     * Reject a Deferred object and call any failCallbacks with the given context and args.\n     * \n     * @param context Context passed to the failCallbacks as the this object.\n     * @param args An optional array of arguments that are passed to the failCallbacks.\n     */\n    rejectWith(context: any, value?: any[]): JQueryDeferred<T>;\n\n    /**\n     * Resolve a Deferred object and call any doneCallbacks with the given args.\n     * \n     * @param value First argument passed to doneCallbacks.\n     * @param args Optional subsequent arguments that are passed to the doneCallbacks.\n     */\n    resolve(value?: T, ...args: any[]): JQueryDeferred<T>;\n\n    /**\n     * Resolve a Deferred object and call any doneCallbacks with the given context and args.\n     * \n     * @param context Context passed to the doneCallbacks as the this object.\n     * @param args An optional array of arguments that are passed to the doneCallbacks.\n     */\n    resolveWith(context: any, value?: T[]): JQueryDeferred<T>;\n\n    /**\n     * Return a Deferred's Promise object.\n     * \n     * @param target Object onto which the promise methods have to be attached\n     */\n    promise(target?: any): JQueryPromise<T>;\n\n    // Deprecated - given no typings\n    pipe(doneFilter?: (x: any) => any, failFilter?: (x: any) => any, progressFilter?: (x: any) => any): JQueryPromise<any>;\n}\n\n/**\n * Interface of the JQuery extension of the W3C event object\n */\ninterface BaseJQueryEventObject extends Event {\n    data: any;\n    delegateTarget: Element;\n    isDefaultPrevented(): boolean;\n    isImmediatePropagationStopped(): boolean;\n    isPropagationStopped(): boolean;\n    namespace: string;\n    originalEvent: Event;\n    preventDefault(): any;\n    relatedTarget: Element;\n    result: any;\n    stopImmediatePropagation(): void;\n    stopPropagation(): void;\n    target: Element;\n    pageX: number;\n    pageY: number;\n    which: number;\n    metaKey: boolean;\n}\n\ninterface JQueryInputEventObject extends BaseJQueryEventObject {\n    altKey: boolean;\n    ctrlKey: boolean;\n    metaKey: boolean;\n    shiftKey: boolean;\n}\n\ninterface JQueryMouseEventObject extends JQueryInputEventObject {\n    button: number;\n    clientX: number;\n    clientY: number;\n    offsetX: number;\n    offsetY: number;\n    pageX: number;\n    pageY: number;\n    screenX: number;\n    screenY: number;\n}\n\ninterface JQueryKeyEventObject extends JQueryInputEventObject {\n    char: any;\n    charCode: number;\n    key: any;\n    keyCode: number;\n}\n\ninterface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject{\n}\n\n/*\n    Collection of properties of the current browser\n*/\n\ninterface JQuerySupport {\n    ajax?: boolean;\n    boxModel?: boolean;\n    changeBubbles?: boolean;\n    checkClone?: boolean;\n    checkOn?: boolean;\n    cors?: boolean;\n    cssFloat?: boolean;\n    hrefNormalized?: boolean;\n    htmlSerialize?: boolean;\n    leadingWhitespace?: boolean;\n    noCloneChecked?: boolean;\n    noCloneEvent?: boolean;\n    opacity?: boolean;\n    optDisabled?: boolean;\n    optSelected?: boolean;\n    scriptEval? (): boolean;\n    style?: boolean;\n    submitBubbles?: boolean;\n    tbody?: boolean;\n}\n\ninterface JQueryParam {\n    /**\n     * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.\n     * \n     * @param obj An array or object to serialize.\n     */\n    (obj: any): string;\n\n    /**\n     * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.\n     * \n     * @param obj An array or object to serialize.\n     * @param traditional A Boolean indicating whether to perform a traditional \"shallow\" serialization.\n     */\n    (obj: any, traditional: boolean): string;\n}\n\n/**\n * The interface used to construct jQuery events (with $.Event). It is\n * defined separately instead of inline in JQueryStatic to allow\n * overriding the construction function with specific strings\n * returning specific event objects.\n */\ninterface JQueryEventConstructor {\n    (name: string, eventProperties?: any): JQueryEventObject;\n    new (name: string, eventProperties?: any): JQueryEventObject;\n}\n\n/**\n * The interface used to specify coordinates.\n */\ninterface JQueryCoordinates {\n    left: number;\n    top: number;\n}\n\n/**\n * Elements in the array returned by serializeArray()\n */\ninterface JQuerySerializeArrayElement {\n    name: string;\n    value: string;\n}\n\ninterface JQueryAnimationOptions { \n    /**\n     * A string or number determining how long the animation will run.\n     */\n    duration?: any; \n    /**\n     * A string indicating which easing function to use for the transition.\n     */\n    easing?: string; \n    /**\n     * A function to call once the animation is complete.\n     */\n    complete?: Function; \n    /**\n     * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set.\n     */\n    step?: (now: number, tween: any) => any; \n    /**\n     * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8)\n     */\n    progress?: (animation: JQueryPromise<any>, progress: number, remainingMs: number) => any; \n    /**\n     * A function to call when the animation begins. (version added: 1.8)\n     */\n    start?: (animation: JQueryPromise<any>) => any; \n    /**\n     * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8)\n     */\n    done?: (animation: JQueryPromise<any>, jumpedToEnd: boolean) => any; \n    /**\n     * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8)\n     */\n    fail?: (animation: JQueryPromise<any>, jumpedToEnd: boolean) => any; \n    /**\n     * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8)\n     */\n    always?: (animation: JQueryPromise<any>, jumpedToEnd: boolean) => any; \n    /**\n     * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue(\"queuename\") to start it.\n     */\n    queue?: any; \n    /**\n     * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4)\n     */\n    specialEasing?: Object;\n}\n\ninterface JQueryEasingFunction {\n    ( percent: number ): number;\n}\n\ninterface JQueryEasingFunctions {\n    [ name: string ]: JQueryEasingFunction;\n    linear: JQueryEasingFunction;\n    swing: JQueryEasingFunction;\n}\n\n/**\n * Static members of jQuery (those on $ and jQuery themselves)\n */\ninterface JQueryStatic {\n\n    /**\n     * Perform an asynchronous HTTP (Ajax) request.\n     *\n     * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().\n     */\n    ajax(settings: JQueryAjaxSettings): JQueryXHR;\n    /**\n     * Perform an asynchronous HTTP (Ajax) request.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can be set for any option with $.ajaxSetup().\n     */\n    ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR;\n\n    /**\n     * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().\n     *\n     * @param dataTypes An optional string containing one or more space-separated dataTypes\n     * @param handler A handler to set default values for future Ajax requests.\n     */\n    ajaxPrefilter(dataTypes: string, handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void;\n    /**\n     * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().\n     *\n     * @param handler A handler to set default values for future Ajax requests.\n     */\n    ajaxPrefilter(handler: (opts: any, originalOpts: JQueryAjaxSettings, jqXHR: JQueryXHR) => any): void;\n\n    ajaxSettings: JQueryAjaxSettings;\n\n     /**\n      * Set default values for future Ajax requests. Its use is not recommended.\n      *\n      * @param options A set of key/value pairs that configure the default Ajax request. All options are optional.\n      */\n    ajaxSetup(options: JQueryAjaxSettings): void;\n\n    /**\n     * Load data from the server using a HTTP GET request.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param success A callback function that is executed if the request succeeds.\n     * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).\n     */\n    get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR;\n    /**\n     * Load data from the server using a HTTP GET request.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param data A plain object or string that is sent to the server with the request.\n     * @param success A callback function that is executed if the request succeeds.\n     * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).\n     */\n    get(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR;\n    /**\n     * Load data from the server using a HTTP GET request.\n     *\n     * @param settings The JQueryAjaxSettings to be used for the request\n     */\n    get(settings : JQueryAjaxSettings): JQueryXHR;\n    /**\n     * Load JSON-encoded data from the server using a GET HTTP request.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param success A callback function that is executed if the request succeeds.\n     */\n    getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR;\n    /**\n     * Load JSON-encoded data from the server using a GET HTTP request.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param data A plain object or string that is sent to the server with the request.\n     * @param success A callback function that is executed if the request succeeds.\n     */\n    getJSON(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR;\n    /**\n     * Load a JavaScript file from the server using a GET HTTP request, then execute it.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param success A callback function that is executed if the request succeeds.\n     */\n    getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR;\n\n    /**\n     * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request.\n     */\n    param: JQueryParam;\n\n    /**\n     * Load data from the server using a HTTP POST request.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case.\n     * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).\n     */\n    post(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR;\n    /**\n     * Load data from the server using a HTTP POST request.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param data A plain object or string that is sent to the server with the request.\n     * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but can be null in that case.\n     * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).\n     */\n    post(url: string, data?: Object|string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR;\n    /**\n     * Load data from the server using a HTTP POST request.\n     *\n     * @param settings The JQueryAjaxSettings to be used for the request\n     */\n    post(settings : JQueryAjaxSettings): JQueryXHR;\n    /**\n     * A multi-purpose callbacks list object that provides a powerful way to manage callback lists.\n     *\n     * @param flags An optional list of space-separated flags that change how the callback list behaves.\n     */\n    Callbacks(flags?: string): JQueryCallback;\n\n    /**\n     * Holds or releases the execution of jQuery's ready event.\n     *\n     * @param hold Indicates whether the ready hold is being requested or released\n     */\n    holdReady(hold: boolean): void;\n\n    /**\n     * Accepts a string containing a CSS selector which is then used to match a set of elements.\n     *\n     * @param selector A string containing a selector expression\n     * @param context A DOM Element, Document, or jQuery to use as context\n     */\n    (selector: string, context?: Element|JQuery): JQuery;\n\n    /**\n     * Accepts a string containing a CSS selector which is then used to match a set of elements.\n     *\n     * @param element A DOM element to wrap in a jQuery object.\n     */\n    (element: Element): JQuery;\n\n    /**\n     * Accepts a string containing a CSS selector which is then used to match a set of elements.\n     *\n     * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object.\n     */\n    (elementArray: Element[]): JQuery;\n\n    /**\n     * Binds a function to be executed when the DOM has finished loading.\n     *\n     * @param callback A function to execute after the DOM is ready.\n     */\n    (callback: (jQueryAlias?: JQueryStatic) => any): JQuery;\n\n    /**\n     * Accepts a string containing a CSS selector which is then used to match a set of elements.\n     *\n     * @param object A plain object to wrap in a jQuery object.\n     */\n    (object: {}): JQuery;\n\n    /**\n     * Accepts a string containing a CSS selector which is then used to match a set of elements.\n     *\n     * @param object An existing jQuery object to clone.\n     */\n    (object: JQuery): JQuery;\n\n    /**\n     * Specify a function to execute when the DOM is fully loaded.\n     */\n    (): JQuery;\n\n    /**\n     * Creates DOM elements on the fly from the provided string of raw HTML.\n     *\n     * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML.\n     * @param ownerDocument A document in which the new elements will be created.\n     */\n    (html: string, ownerDocument?: Document): JQuery;\n\n    /**\n     * Creates DOM elements on the fly from the provided string of raw HTML.\n     *\n     * @param html A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>).\n     * @param attributes An object of attributes, events, and methods to call on the newly-created element.\n     */\n    (html: string, attributes: Object): JQuery;\n\n    /**\n     * Relinquish jQuery's control of the $ variable.\n     *\n     * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself).\n     */\n    noConflict(removeAll?: boolean): JQueryStatic;\n\n    /**\n     * Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.\n     *\n     * @param deferreds One or more Deferred objects, or plain JavaScript objects.\n     */\n    when<T>(...deferreds: Array<T|JQueryPromise<T>/* as JQueryDeferred<T> */>): JQueryPromise<T>;\n\n    /**\n     * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties.\n     */\n    cssHooks: { [key: string]: any; };\n    cssNumber: any;\n\n    /**\n     * Store arbitrary data associated with the specified element. Returns the value that was set.\n     *\n     * @param element The DOM element to associate with the data.\n     * @param key A string naming the piece of data to set.\n     * @param value The new data value.\n     */\n    data<T>(element: Element, key: string, value: T): T;\n    /**\n     * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.\n     *\n     * @param element The DOM element to associate with the data.\n     * @param key A string naming the piece of data to set.\n     */\n    data(element: Element, key: string): any;\n    /**\n     * Returns value at named data store for the element, as set by jQuery.data(element, name, value), or the full data store for the element.\n     *\n     * @param element The DOM element to associate with the data.\n     */\n    data(element: Element): any;\n\n    /**\n     * Execute the next function on the queue for the matched element.\n     *\n     * @param element A DOM element from which to remove and execute a queued function.\n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     */\n    dequeue(element: Element, queueName?: string): void;\n\n    /**\n     * Determine whether an element has any jQuery data associated with it.\n     *\n     * @param element A DOM element to be checked for data.\n     */\n    hasData(element: Element): boolean;\n\n    /**\n     * Show the queue of functions to be executed on the matched element.\n     *\n     * @param element A DOM element to inspect for an attached queue.\n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     */\n    queue(element: Element, queueName?: string): any[];\n    /**\n     * Manipulate the queue of functions to be executed on the matched element.\n     *\n     * @param element A DOM element where the array of queued functions is attached.\n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     * @param newQueue An array of functions to replace the current queue contents.\n     */\n    queue(element: Element, queueName: string, newQueue: Function[]): JQuery;\n    /**\n     * Manipulate the queue of functions to be executed on the matched element.\n     *\n     * @param element A DOM element on which to add a queued function.\n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     * @param callback The new function to add to the queue.\n     */\n    queue(element: Element, queueName: string, callback: Function): JQuery;\n\n    /**\n     * Remove a previously-stored piece of data.\n     *\n     * @param element A DOM element from which to remove data.\n     * @param name A string naming the piece of data to remove.\n     */\n    removeData(element: Element, name?: string): JQuery;\n\n    /**\n     * A constructor function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.\n     *\n     * @param beforeStart A function that is called just before the constructor returns.\n     */\n    Deferred<T>(beforeStart?: (deferred: JQueryDeferred<T>) => any): JQueryDeferred<T>;\n\n    /**\n     * Effects\n     */\n\n    easing: JQueryEasingFunctions;\n\n    fx: {\n        tick: () => void;\n        /**\n         * The rate (in milliseconds) at which animations fire.\n         */\n        interval: number;\n        stop: () => void;\n        speeds: { slow: number; fast: number; };\n        /**\n         * Globally disable all animations.\n         */\n        off: boolean;\n        step: any;\n    };\n\n    /**\n     * Takes a function and returns a new one that will always have a particular context.\n     *\n     * @param fnction The function whose context will be changed.\n     * @param context The object to which the context (this) of the function should be set.\n     * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument.\n     */\n    proxy(fnction: (...args: any[]) => any, context: Object, ...additionalArguments: any[]): any;\n    /**\n     * Takes a function and returns a new one that will always have a particular context.\n     *\n     * @param context The object to which the context (this) of the function should be set.\n     * @param name The name of the function whose context will be changed (should be a property of the context object).\n     * @param additionalArguments Any number of arguments to be passed to the function named in the name argument.\n     */\n    proxy(context: Object, name: string, ...additionalArguments: any[]): any;\n\n    Event: JQueryEventConstructor;\n\n    /**\n     * Takes a string and throws an exception containing it.\n     *\n     * @param message The message to send out.\n     */\n    error(message: any): JQuery;\n\n    expr: any;\n    fn: any;  //TODO: Decide how we want to type this\n\n    isReady: boolean;\n\n    // Properties\n    support: JQuerySupport;\n\n    /**\n     * Check to see if a DOM element is a descendant of another DOM element.\n     * \n     * @param container The DOM element that may contain the other element.\n     * @param contained The DOM element that may be contained by (a descendant of) the other element.\n     */\n    contains(container: Element, contained: Element): boolean;\n\n    /**\n     * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.\n     * \n     * @param collection The object or array to iterate over.\n     * @param callback The function that will be executed on every object.\n     */\n    each<T>(\n        collection: T[],\n        callback: (indexInArray: number, valueOfElement: T) => any\n        ): any;\n\n    /**\n     * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.\n     * \n     * @param collection The object or array to iterate over.\n     * @param callback The function that will be executed on every object.\n     */\n    each(\n        collection: any,\n        callback: (indexInArray: any, valueOfElement: any) => any\n        ): any;\n\n    /**\n     * Merge the contents of two or more objects together into the first object.\n     *\n     * @param target An object that will receive the new properties if additional objects are passed in or that will extend the jQuery namespace if it is the sole argument.\n     * @param object1 An object containing additional properties to merge in.\n     * @param objectN Additional objects containing properties to merge in.\n     */\n    extend(target: any, object1?: any, ...objectN: any[]): any;\n    /**\n     * Merge the contents of two or more objects together into the first object.\n     *\n     * @param deep If true, the merge becomes recursive (aka. deep copy).\n     * @param target The object to extend. It will receive the new properties.\n     * @param object1 An object containing additional properties to merge in.\n     * @param objectN Additional objects containing properties to merge in.\n     */\n    extend(deep: boolean, target: any, object1?: any, ...objectN: any[]): any;\n\n    /**\n     * Execute some JavaScript code globally.\n     *\n     * @param code The JavaScript code to execute.\n     */\n    globalEval(code: string): any;\n\n    /**\n     * Finds the elements of an array which satisfy a filter function. The original array is not affected.\n     *\n     * @param array The array to search through.\n     * @param func The function to process each item against. The first argument to the function is the item, and the second argument is the index. The function should return a Boolean value.  this will be the global window object.\n     * @param invert If \"invert\" is false, or not provided, then the function returns an array consisting of all elements for which \"callback\" returns true. If \"invert\" is true, then the function returns an array consisting of all elements for which \"callback\" returns false.\n     */\n    grep<T>(array: T[], func: (elementOfArray: T, indexInArray: number) => boolean, invert?: boolean): T[];\n\n    /**\n     * Search for a specified value within an array and return its index (or -1 if not found).\n     *\n     * @param value The value to search for.\n     * @param array An array through which to search.\n     * @param fromIndex he index of the array at which to begin the search. The default is 0, which will search the whole array.\n     */\n    inArray<T>(value: T, array: T[], fromIndex?: number): number;\n\n    /**\n     * Determine whether the argument is an array.\n     *\n     * @param obj Object to test whether or not it is an array.\n     */\n    isArray(obj: any): boolean;\n    /**\n     * Check to see if an object is empty (contains no enumerable properties).\n     *\n     * @param obj The object that will be checked to see if it's empty.\n     */\n    isEmptyObject(obj: any): boolean;\n    /**\n     * Determine if the argument passed is a Javascript function object.\n     *\n     * @param obj Object to test whether or not it is a function.\n     */\n    isFunction(obj: any): boolean;\n    /**\n     * Determines whether its argument is a number.\n     *\n     * @param obj The value to be tested.\n     */\n    isNumeric(value: any): boolean;\n    /**\n     * Check to see if an object is a plain object (created using \"{}\" or \"new Object\").\n     *\n     * @param obj The object that will be checked to see if it's a plain object.\n     */\n    isPlainObject(obj: any): boolean;\n    /**\n     * Determine whether the argument is a window.\n     *\n     * @param obj Object to test whether or not it is a window.\n     */\n    isWindow(obj: any): boolean;\n    /**\n     * Check to see if a DOM node is within an XML document (or is an XML document).\n     *\n     * @param node he DOM node that will be checked to see if it's in an XML document.\n     */\n    isXMLDoc(node: Node): boolean;\n\n    /**\n     * Convert an array-like object into a true JavaScript array.\n     * \n     * @param obj Any object to turn into a native Array.\n     */\n    makeArray(obj: any): any[];\n\n    /**\n     * Translate all items in an array or object to new array of items.\n     * \n     * @param array The Array to translate.\n     * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object.\n     */\n    map<T, U>(array: T[], callback: (elementOfArray: T, indexInArray: number) => U): U[];\n    /**\n     * Translate all items in an array or object to new array of items.\n     * \n     * @param arrayOrObject The Array or Object to translate.\n     * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object.\n     */\n    map(arrayOrObject: any, callback: (value: any, indexOrKey: any) => any): any;\n\n    /**\n     * Merge the contents of two arrays together into the first array.\n     * \n     * @param first The first array to merge, the elements of second added.\n     * @param second The second array to merge into the first, unaltered.\n     */\n    merge<T>(first: T[], second: T[]): T[];\n\n    /**\n     * An empty function.\n     */\n    noop(): any;\n\n    /**\n     * Return a number representing the current time.\n     */\n    now(): number;\n\n    /**\n     * Takes a well-formed JSON string and returns the resulting JavaScript object.\n     * \n     * @param json The JSON string to parse.\n     */\n    parseJSON(json: string): any;\n\n    /**\n     * Parses a string into an XML document.\n     *\n     * @param data a well-formed XML string to be parsed\n     */\n    parseXML(data: string): XMLDocument;\n\n    /**\n     * Remove the whitespace from the beginning and end of a string.\n     * \n     * @param str Remove the whitespace from the beginning and end of a string.\n     */\n    trim(str: string): string;\n\n    /**\n     * Determine the internal JavaScript [[Class]] of an object.\n     * \n     * @param obj Object to get the internal JavaScript [[Class]] of.\n     */\n    type(obj: any): string;\n\n    /**\n     * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.\n     * \n     * @param array The Array of DOM elements.\n     */\n    unique(array: Element[]): Element[];\n\n    /**\n     * Parses a string into an array of DOM nodes.\n     *\n     * @param data HTML string to be parsed\n     * @param context DOM element to serve as the context in which the HTML fragment will be created\n     * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string\n     */\n    parseHTML(data: string, context?: HTMLElement, keepScripts?: boolean): any[];\n\n    /**\n     * Parses a string into an array of DOM nodes.\n     *\n     * @param data HTML string to be parsed\n     * @param context DOM element to serve as the context in which the HTML fragment will be created\n     * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string\n     */\n    parseHTML(data: string, context?: Document, keepScripts?: boolean): any[];\n}\n\n/**\n * The jQuery instance members\n */\ninterface JQuery {\n    /**\n     * Register a handler to be called when Ajax requests complete. This is an AjaxEvent.\n     *\n     * @param handler The function to be invoked.\n     */\n    ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery;\n    /**\n     * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event.\n     *\n     * @param handler The function to be invoked.\n     */\n    ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery;\n    /**\n     * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event.\n     *\n     * @param handler The function to be invoked.\n     */\n    ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery;\n    /**\n     * Register a handler to be called when the first Ajax request begins. This is an Ajax Event.\n     *\n     * @param handler The function to be invoked.\n     */\n    ajaxStart(handler: () => any): JQuery;\n    /**\n     * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event.\n     *\n     * @param handler The function to be invoked.\n     */\n    ajaxStop(handler: () => any): JQuery;\n    /**\n     * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event.\n     *\n     * @param handler The function to be invoked.\n     */\n    ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery;\n\n    /**\n     * Load data from the server and place the returned HTML into the matched element.\n     *\n     * @param url A string containing the URL to which the request is sent.\n     * @param data A plain object or string that is sent to the server with the request.\n     * @param complete A callback function that is executed when the request completes.\n     */\n    load(url: string, data?: string|Object, complete?: (responseText: string, textStatus: string, XMLHttpRequest: XMLHttpRequest) => any): JQuery;\n\n    /**\n     * Encode a set of form elements as a string for submission.\n     */\n    serialize(): string;\n    /**\n     * Encode a set of form elements as an array of names and values.\n     */\n    serializeArray(): JQuerySerializeArrayElement[];\n\n    /**\n     * Adds the specified class(es) to each of the set of matched elements.\n     *\n     * @param className One or more space-separated classes to be added to the class attribute of each matched element.\n     */\n    addClass(className: string): JQuery;\n    /**\n     * Adds the specified class(es) to each of the set of matched elements.\n     *\n     * @param function A function returning one or more space-separated class names to be added to the existing class name(s). Receives the index position of the element in the set and the existing class name(s) as arguments. Within the function, this refers to the current element in the set.\n     */\n    addClass(func: (index: number, className: string) => string): JQuery;\n\n    /**\n     * Add the previous set of elements on the stack to the current set, optionally filtered by a selector.\n     */\n    addBack(selector?: string): JQuery;\n\n    /**\n     * Get the value of an attribute for the first element in the set of matched elements.\n     *\n     * @param attributeName The name of the attribute to get.\n     */\n    attr(attributeName: string): string;\n    /**\n     * Set one or more attributes for the set of matched elements.\n     *\n     * @param attributeName The name of the attribute to set.\n     * @param value A value to set for the attribute.\n     */\n    attr(attributeName: string, value: string|number): JQuery;\n    /**\n     * Set one or more attributes for the set of matched elements.\n     *\n     * @param attributeName The name of the attribute to set.\n     * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old attribute value as arguments.\n     */\n    attr(attributeName: string, func: (index: number, attr: string) => string|number): JQuery;\n    /**\n     * Set one or more attributes for the set of matched elements.\n     *\n     * @param attributes An object of attribute-value pairs to set.\n     */\n    attr(attributes: Object): JQuery;\n    \n    /**\n     * Determine whether any of the matched elements are assigned the given class.\n     *\n     * @param className The class name to search for.\n     */\n    hasClass(className: string): boolean;\n\n    /**\n     * Get the HTML contents of the first element in the set of matched elements.\n     */\n    html(): string;\n    /**\n     * Set the HTML contents of each element in the set of matched elements.\n     *\n     * @param htmlString A string of HTML to set as the content of each matched element.\n     */\n    html(htmlString: string): JQuery;\n    /**\n     * Set the HTML contents of each element in the set of matched elements.\n     *\n     * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.\n     */\n    html(func: (index: number, oldhtml: string) => string): JQuery;\n    /**\n     * Set the HTML contents of each element in the set of matched elements.\n     *\n     * @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.\n     */\n\n    /**\n     * Get the value of a property for the first element in the set of matched elements.\n     *\n     * @param propertyName The name of the property to get.\n     */\n    prop(propertyName: string): any;\n    /**\n     * Set one or more properties for the set of matched elements.\n     *\n     * @param propertyName The name of the property to set.\n     * @param value A value to set for the property.\n     */\n    prop(propertyName: string, value: string|number|boolean): JQuery;\n    /**\n     * Set one or more properties for the set of matched elements.\n     *\n     * @param properties An object of property-value pairs to set.\n     */\n    prop(properties: Object): JQuery;\n    /**\n     * Set one or more properties for the set of matched elements.\n     *\n     * @param propertyName The name of the property to set.\n     * @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.\n     */\n    prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery;\n\n    /**\n     * Remove an attribute from each element in the set of matched elements.\n     *\n     * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.\n     */\n    removeAttr(attributeName: string): JQuery;\n\n    /**\n     * Remove a single class, multiple classes, or all classes from each element in the set of matched elements.\n     *\n     * @param className One or more space-separated classes to be removed from the class attribute of each matched element.\n     */\n    removeClass(className?: string): JQuery;\n    /**\n     * Remove a single class, multiple classes, or all classes from each element in the set of matched elements.\n     *\n     * @param function A function returning one or more space-separated class names to be removed. Receives the index position of the element in the set and the old class value as arguments.\n     */\n    removeClass(func: (index: number, className: string) => string): JQuery;\n\n    /**\n     * Remove a property for the set of matched elements.\n     *\n     * @param propertyName The name of the property to remove.\n     */\n    removeProp(propertyName: string): JQuery;\n\n    /**\n     * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.\n     *\n     * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set.\n     * @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.\n     */\n    toggleClass(className: string, swtch?: boolean): JQuery;\n    /**\n     * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.\n     *\n     * @param swtch A boolean value to determine whether the class should be added or removed.\n     */\n    toggleClass(swtch?: boolean): JQuery;\n    /**\n     * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.\n     *\n     * @param func A function that returns class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the switch as arguments.\n     * @param swtch A boolean value to determine whether the class should be added or removed.\n     */\n    toggleClass(func: (index: number, className: string, swtch: boolean) => string, swtch?: boolean): JQuery;\n\n    /**\n     * Get the current value of the first element in the set of matched elements.\n     */\n    val(): any;\n    /**\n     * Set the value of each element in the set of matched elements.\n     *\n     * @param value A string of text, an array of strings or number corresponding to the value of each matched element to set as selected/checked.\n     */\n    val(value: string|string[]|number): JQuery;\n    /**\n     * Set the value of each element in the set of matched elements.\n     *\n     * @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.\n     */\n    val(func: (index: number, value: string) => string): JQuery;\n\n\n    /**\n     * Get the value of style properties for the first element in the set of matched elements.\n     *\n     * @param propertyName A CSS property.\n     */\n    css(propertyName: string): string;\n    /**\n     * Set one or more CSS properties for the set of matched elements.\n     *\n     * @param propertyName A CSS property name.\n     * @param value A value to set for the property.\n     */\n    css(propertyName: string, value: string|number): JQuery;\n    /**\n     * Set one or more CSS properties for the set of matched elements.\n     *\n     * @param propertyName A CSS property name.\n     * @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.\n     */\n    css(propertyName: string, value: (index: number, value: string) => string|number): JQuery;\n    /**\n     * Set one or more CSS properties for the set of matched elements.\n     *\n     * @param properties An object of property-value pairs to set.\n     */\n    css(properties: Object): JQuery;\n\n    /**\n     * Get the current computed height for the first element in the set of matched elements.\n     */\n    height(): number;\n    /**\n     * Set the CSS height of every matched element.\n     *\n     * @param value An integer representing the number of pixels, or an integer with an optional unit of measure appended (as a string).\n     */\n    height(value: number|string): JQuery;\n    /**\n     * Set the CSS height of every matched element.\n     *\n     * @param func A function returning the height to set. Receives the index position of the element in the set and the old height as arguments. Within the function, this refers to the current element in the set.\n     */\n    height(func: (index: number, height: number) => number|string): JQuery;\n\n    /**\n     * Get the current computed height for the first element in the set of matched elements, including padding but not border.\n     */\n    innerHeight(): number;\n\n    /**\n     * Sets the inner height on elements in the set of matched elements, including padding but not border.\n     *\n     * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).\n     */\n    innerHeight(height: number|string): JQuery;\n    \n    /**\n     * Get the current computed width for the first element in the set of matched elements, including padding but not border.\n     */\n    innerWidth(): number;\n\n    /**\n     * Sets the inner width on elements in the set of matched elements, including padding but not border.\n     *\n     * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).\n     */\n    innerWidth(width: number|string): JQuery;\n    \n    /**\n     * Get the current coordinates of the first element in the set of matched elements, relative to the document.\n     */\n    offset(): JQueryCoordinates;\n    /**\n     * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.\n     *\n     * @param coordinates An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.\n     */\n    offset(coordinates: JQueryCoordinates): JQuery;\n    /**\n     * An object containing the properties top and left, which are integers indicating the new top and left coordinates for the elements.\n     *\n     * @param func A function to return the coordinates to set. Receives the index of the element in the collection as the first argument and the current coordinates as the second argument. The function should return an object with the new top and left properties.\n     */\n    offset(func: (index: number, coords: JQueryCoordinates) => JQueryCoordinates): JQuery;\n\n    /**\n     * Get the current computed height for the first element in the set of matched elements, including padding, border, and optionally margin. Returns an integer (without \"px\") representation of the value or null if called on an empty set of elements.\n     *\n     * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation.\n     */\n    outerHeight(includeMargin?: boolean): number;\n\n    /**\n     * Sets the outer height on elements in the set of matched elements, including padding and border.\n     *\n     * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).\n     */\n    outerHeight(height: number|string): JQuery;\n\n    /**\n     * Get the current computed width for the first element in the set of matched elements, including padding and border.\n     *\n     * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation.\n     */\n    outerWidth(includeMargin?: boolean): number;\n\n    /**\n     * Sets the outer width on elements in the set of matched elements, including padding and border.\n     *\n     * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).\n     */\n    outerWidth(width: number|string): JQuery;\n\n    /**\n     * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.\n     */\n    position(): JQueryCoordinates;\n\n    /**\n     * Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element.\n     */\n    scrollLeft(): number;\n    /**\n     * Set the current horizontal position of the scroll bar for each of the set of matched elements.\n     *\n     * @param value An integer indicating the new position to set the scroll bar to.\n     */\n    scrollLeft(value: number): JQuery;\n\n    /**\n     * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.\n     */\n    scrollTop(): number;\n    /**\n     * Set the current vertical position of the scroll bar for each of the set of matched elements.\n     *\n     * @param value An integer indicating the new position to set the scroll bar to.\n     */\n    scrollTop(value: number): JQuery;\n\n    /**\n     * Get the current computed width for the first element in the set of matched elements.\n     */\n    width(): number;\n    /**\n     * Set the CSS width of each element in the set of matched elements.\n     *\n     * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string).\n     */\n    width(value: number|string): JQuery;\n    /**\n     * Set the CSS width of each element in the set of matched elements.\n     *\n     * @param func A function returning the width to set. Receives the index position of the element in the set and the old width as arguments. Within the function, this refers to the current element in the set.\n     */\n    width(func: (index: number, width: number) => number|string): JQuery;\n\n    /**\n     * Remove from the queue all items that have not yet been run.\n     *\n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     */\n    clearQueue(queueName?: string): JQuery;\n\n    /**\n     * Store arbitrary data associated with the matched elements.\n     *\n     * @param key A string naming the piece of data to set.\n     * @param value The new data value; it can be any Javascript type including Array or Object.\n     */\n    data(key: string, value: any): JQuery;\n    /**\n     * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.\n     *\n     * @param key Name of the data stored.\n     */\n    data(key: string): any;\n    /**\n     * Store arbitrary data associated with the matched elements.\n     *\n     * @param obj An object of key-value pairs of data to update.\n     */\n    data(obj: { [key: string]: any; }): JQuery;\n    /**\n     * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.\n     */\n    data(): any;\n\n    /**\n     * Execute the next function on the queue for the matched elements.\n     *\n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     */\n    dequeue(queueName?: string): JQuery;\n\n    /**\n     * Remove a previously-stored piece of data.\n     *\n     * @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete.\n     */\n    removeData(name: string): JQuery;\n    /**\n     * Remove a previously-stored piece of data.\n     *\n     * @param list An array of strings naming the pieces of data to delete.\n     */\n    removeData(list: string[]): JQuery;\n    /**\n     * Remove all previously-stored piece of data.\n     */\n    removeData(): JQuery;\n\n    /**\n     * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished.\n     *\n     * @param type The type of queue that needs to be observed. (default: fx)\n     * @param target Object onto which the promise methods have to be attached\n     */\n    promise(type?: string, target?: Object): JQueryPromise<any>;\n\n    /**\n     * Perform a custom animation of a set of CSS properties.\n     *\n     * @param properties An object of CSS properties and values that the animation will move toward.\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    animate(properties: Object, duration?: string|number, complete?: Function): JQuery;\n    /**\n     * Perform a custom animation of a set of CSS properties.\n     *\n     * @param properties An object of CSS properties and values that the animation will move toward.\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition. (default: swing)\n     * @param complete A function to call once the animation is complete.\n     */\n    animate(properties: Object, duration?: string|number, easing?: string, complete?: Function): JQuery;\n    /**\n     * Perform a custom animation of a set of CSS properties.\n     *\n     * @param properties An object of CSS properties and values that the animation will move toward.\n     * @param options A map of additional options to pass to the method.\n     */\n    animate(properties: Object, options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Set a timer to delay execution of subsequent items in the queue.\n     *\n     * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue.\n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     */\n    delay(duration: number, queueName?: string): JQuery;\n\n    /**\n     * Display the matched elements by fading them to opaque.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeIn(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Display the matched elements by fading them to opaque.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeIn(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Display the matched elements by fading them to opaque.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    fadeIn(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Hide the matched elements by fading them to transparent.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeOut(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Hide the matched elements by fading them to transparent.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeOut(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Hide the matched elements by fading them to transparent.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    fadeOut(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Adjust the opacity of the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param opacity A number between 0 and 1 denoting the target opacity.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeTo(duration: string|number, opacity: number, complete?: Function): JQuery;\n    /**\n     * Adjust the opacity of the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param opacity A number between 0 and 1 denoting the target opacity.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeTo(duration: string|number, opacity: number, easing?: string, complete?: Function): JQuery;\n\n    /**\n     * Display or hide the matched elements by animating their opacity.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeToggle(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Display or hide the matched elements by animating their opacity.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    fadeToggle(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Display or hide the matched elements by animating their opacity.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    fadeToggle(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements.\n     *\n     * @param queue The name of the queue in which to stop animations.\n     */\n    finish(queue?: string): JQuery;\n\n    /**\n     * Hide the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    hide(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Hide the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    hide(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Hide the matched elements.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    hide(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Display the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    show(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Display the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    show(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Display the matched elements.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    show(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Display the matched elements with a sliding motion.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    slideDown(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Display the matched elements with a sliding motion.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    slideDown(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Display the matched elements with a sliding motion.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    slideDown(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Display or hide the matched elements with a sliding motion.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    slideToggle(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Display or hide the matched elements with a sliding motion.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    slideToggle(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Display or hide the matched elements with a sliding motion.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    slideToggle(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Hide the matched elements with a sliding motion.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    slideUp(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Hide the matched elements with a sliding motion.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    slideUp(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Hide the matched elements with a sliding motion.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    slideUp(options: JQueryAnimationOptions): JQuery;\n\n    /**\n     * Stop the currently-running animation on the matched elements.\n     *\n     * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false.\n     * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false.\n     */\n    stop(clearQueue?: boolean, jumpToEnd?: boolean): JQuery;\n    /**\n     * Stop the currently-running animation on the matched elements.\n     *\n     * @param queue The name of the queue in which to stop animations.\n     * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false.\n     * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false.\n     */\n    stop(queue?: string, clearQueue?: boolean, jumpToEnd?: boolean): JQuery;\n\n    /**\n     * Display or hide the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param complete A function to call once the animation is complete.\n     */\n    toggle(duration?: number|string, complete?: Function): JQuery;\n    /**\n     * Display or hide the matched elements.\n     *\n     * @param duration A string or number determining how long the animation will run.\n     * @param easing A string indicating which easing function to use for the transition.\n     * @param complete A function to call once the animation is complete.\n     */\n    toggle(duration?: number|string, easing?: string, complete?: Function): JQuery;\n    /**\n     * Display or hide the matched elements.\n     *\n     * @param options A map of additional options to pass to the method.\n     */\n    toggle(options: JQueryAnimationOptions): JQuery;\n    /**\n     * Display or hide the matched elements.\n     *\n     * @param showOrHide A Boolean indicating whether to show or hide the elements.\n     */\n    toggle(showOrHide: boolean): JQuery;\n\n    /**\n     * Attach a handler to an event for the elements.\n     * \n     * @param eventType A string containing one or more DOM event types, such as \"click\" or \"submit,\" or custom event names.\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Attach a handler to an event for the elements.\n     * \n     * @param eventType A string containing one or more DOM event types, such as \"click\" or \"submit,\" or custom event names.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Attach a handler to an event for the elements.\n     * \n     * @param eventType A string containing one or more DOM event types, such as \"click\" or \"submit,\" or custom event names.\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.\n     */\n    bind(eventType: string, eventData: any, preventBubble: boolean): JQuery;\n    /**\n     * Attach a handler to an event for the elements.\n     * \n     * @param eventType A string containing one or more DOM event types, such as \"click\" or \"submit,\" or custom event names.\n     * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.\n     */\n    bind(eventType: string, preventBubble: boolean): JQuery;\n    /**\n     * Attach a handler to an event for the elements.\n     * \n     * @param events An object containing one or more DOM event types and functions to execute for them.\n     */\n    bind(events: any): JQuery;\n\n    /**\n     * Trigger the \"blur\" event on an element\n     */\n    blur(): JQuery;\n    /**\n     * Bind an event handler to the \"blur\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    blur(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"blur\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    blur(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"change\" event on an element.\n     */\n    change(): JQuery;\n    /**\n     * Bind an event handler to the \"change\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    change(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"change\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    change(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"click\" event on an element.\n     */\n    click(): JQuery;\n    /**\n     * Bind an event handler to the \"click\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     */\n    click(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"click\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    click(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"dblclick\" event on an element.\n     */\n    dblclick(): JQuery;\n    /**\n     * Bind an event handler to the \"dblclick\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    dblclick(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"dblclick\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    dblclick(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    delegate(selector: any, eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery;\n    delegate(selector: any, eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"focus\" event on an element.\n     */\n    focus(): JQuery;\n    /**\n     * Bind an event handler to the \"focus\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    focus(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"focus\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    focus(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"focusin\" event on an element.\n     */\n    focusin(): JQuery;\n    /**\n     * Bind an event handler to the \"focusin\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    focusin(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"focusin\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    focusin(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"focusout\" event on an element.\n     */\n    focusout(): JQuery;\n    /**\n     * Bind an event handler to the \"focusout\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    focusout(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"focusout\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    focusout(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.\n     *\n     * @param handlerIn A function to execute when the mouse pointer enters the element.\n     * @param handlerOut A function to execute when the mouse pointer leaves the element.\n     */\n    hover(handlerIn: (eventObject: JQueryEventObject) => any, handlerOut: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements.\n     *\n     * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element.\n     */\n    hover(handlerInOut: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"keydown\" event on an element.\n     */\n    keydown(): JQuery;\n    /**\n     * Bind an event handler to the \"keydown\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    keydown(handler: (eventObject: JQueryKeyEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"keydown\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    keydown(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"keypress\" event on an element.\n     */\n    keypress(): JQuery;\n    /**\n     * Bind an event handler to the \"keypress\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    keypress(handler: (eventObject: JQueryKeyEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"keypress\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    keypress(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"keyup\" event on an element.\n     */\n    keyup(): JQuery;\n    /**\n     * Bind an event handler to the \"keyup\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    keyup(handler: (eventObject: JQueryKeyEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"keyup\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    keyup(eventData?: any, handler?: (eventObject: JQueryKeyEventObject) => any): JQuery;\n\n    /**\n     * Bind an event handler to the \"load\" JavaScript event.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    load(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"load\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    load(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"mousedown\" event on an element.\n     */\n    mousedown(): JQuery;\n    /**\n     * Bind an event handler to the \"mousedown\" JavaScript event.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    mousedown(handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"mousedown\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    mousedown(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"mouseenter\" event on an element.\n     */\n    mouseenter(): JQuery;\n    /**\n     * Bind an event handler to be fired when the mouse enters an element.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseenter(handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to be fired when the mouse enters an element.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseenter(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"mouseleave\" event on an element.\n     */\n    mouseleave(): JQuery;\n    /**\n     * Bind an event handler to be fired when the mouse leaves an element.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseleave(handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to be fired when the mouse leaves an element.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseleave(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"mousemove\" event on an element.\n     */\n    mousemove(): JQuery;\n    /**\n     * Bind an event handler to the \"mousemove\" JavaScript event.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    mousemove(handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"mousemove\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    mousemove(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"mouseout\" event on an element.\n     */\n    mouseout(): JQuery;\n    /**\n     * Bind an event handler to the \"mouseout\" JavaScript event.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseout(handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"mouseout\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseout(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"mouseover\" event on an element.\n     */\n    mouseover(): JQuery;\n    /**\n     * Bind an event handler to the \"mouseover\" JavaScript event.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseover(handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"mouseover\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseover(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"mouseup\" event on an element.\n     */\n    mouseup(): JQuery;\n    /**\n     * Bind an event handler to the \"mouseup\" JavaScript event.\n     *\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseup(handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"mouseup\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    mouseup(eventData: Object, handler: (eventObject: JQueryMouseEventObject) => any): JQuery;\n\n    /**\n     * Remove an event handler.\n     */\n    off(): JQuery;\n    /**\n     * Remove an event handler.\n     *\n     * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as \"click\", \"keydown.myPlugin\", or \".myPlugin\".\n     * @param selector A selector which should match the one originally passed to .on() when attaching event handlers.\n     * @param handler A handler function previously attached for the event(s), or the special value false.\n     */\n    off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Remove an event handler.\n     *\n     * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as \"click\", \"keydown.myPlugin\", or \".myPlugin\".\n     * @param handler A handler function previously attached for the event(s), or the special value false. Takes handler with extra args that can be attached with on().\n     */\n    off(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;\n    /**\n     * Remove an event handler.\n     *\n     * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as \"click\", \"keydown.myPlugin\", or \".myPlugin\".\n     * @param handler A handler function previously attached for the event(s), or the special value false.\n     */\n    off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Remove an event handler.\n     *\n     * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s).\n     * @param selector A selector which should match the one originally passed to .on() when attaching event handlers.\n     */\n    off(events: { [key: string]: any; }, selector?: string): JQuery;\n\n    /**\n     * Attach an event handler function for one or more events to the selected elements.\n     *\n     * @param events One or more space-separated event types and optional namespaces, such as \"click\" or \"keydown.myPlugin\".\n     * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax).\n     */\n    on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;\n    /**\n     * Attach an event handler function for one or more events to the selected elements.\n     *\n     * @param events One or more space-separated event types and optional namespaces, such as \"click\" or \"keydown.myPlugin\".\n     * @param data Data to be passed to the handler in event.data when an event is triggered.\n     * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.\n    */\n    on(events: string, data : any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;\n    /**\n     * Attach an event handler function for one or more events to the selected elements.\n     *\n     * @param events One or more space-separated event types and optional namespaces, such as \"click\" or \"keydown.myPlugin\".\n     * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.\n     * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.\n     */\n    on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;\n    /**\n     * Attach an event handler function for one or more events to the selected elements.\n     *\n     * @param events One or more space-separated event types and optional namespaces, such as \"click\" or \"keydown.myPlugin\".\n     * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.\n     * @param data Data to be passed to the handler in event.data when an event is triggered.\n     * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.\n     */\n    on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;\n    /**\n     * Attach an event handler function for one or more events to the selected elements.\n     *\n     * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).\n     * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.\n     * @param data Data to be passed to the handler in event.data when an event occurs.\n     */\n    on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery;\n    /**\n     * Attach an event handler function for one or more events to the selected elements.\n     *\n     * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).\n     * @param data Data to be passed to the handler in event.data when an event occurs.\n     */\n    on(events: { [key: string]: any; }, data?: any): JQuery;\n\n    /**\n     * Attach a handler to an event for the elements. The handler is executed at most once per element per event type.\n     *\n     * @param events A string containing one or more JavaScript event types, such as \"click\" or \"submit,\" or custom event names.\n     * @param handler A function to execute at the time the event is triggered.\n     */\n    one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Attach a handler to an event for the elements. The handler is executed at most once per element per event type.\n     *\n     * @param events A string containing one or more JavaScript event types, such as \"click\" or \"submit,\" or custom event names.\n     * @param data An object containing data that will be passed to the event handler.\n     * @param handler A function to execute at the time the event is triggered.\n     */\n    one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Attach a handler to an event for the elements. The handler is executed at most once per element per event type.\n     *\n     * @param events One or more space-separated event types and optional namespaces, such as \"click\" or \"keydown.myPlugin\".\n     * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.\n     * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.\n     */\n    one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Attach a handler to an event for the elements. The handler is executed at most once per element per event type.\n     *\n     * @param events One or more space-separated event types and optional namespaces, such as \"click\" or \"keydown.myPlugin\".\n     * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.\n     * @param data Data to be passed to the handler in event.data when an event is triggered.\n     * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.\n     */\n    one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Attach a handler to an event for the elements. The handler is executed at most once per element per event type.\n     *\n     * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).\n     * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.\n     * @param data Data to be passed to the handler in event.data when an event occurs.\n     */\n    one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery;\n\n    /**\n     * Attach a handler to an event for the elements. The handler is executed at most once per element per event type.\n     *\n     * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).\n     * @param data Data to be passed to the handler in event.data when an event occurs.\n     */\n    one(events: { [key: string]: any; }, data?: any): JQuery;\n\n\n    /**\n     * Specify a function to execute when the DOM is fully loaded.\n     *\n     * @param handler A function to execute after the DOM is ready.\n     */\n    ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery;\n\n    /**\n     * Trigger the \"resize\" event on an element.\n     */\n    resize(): JQuery;\n    /**\n     * Bind an event handler to the \"resize\" JavaScript event.\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    resize(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"resize\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    resize(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"scroll\" event on an element.\n     */\n    scroll(): JQuery;\n    /**\n     * Bind an event handler to the \"scroll\" JavaScript event.\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    scroll(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"scroll\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    scroll(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"select\" event on an element.\n     */\n    select(): JQuery;\n    /**\n     * Bind an event handler to the \"select\" JavaScript event.\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    select(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"select\" JavaScript event.\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    select(eventData: Object, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Trigger the \"submit\" event on an element.\n     */\n    submit(): JQuery;\n    /**\n     * Bind an event handler to the \"submit\" JavaScript event\n     *\n     * @param handler A function to execute each time the event is triggered.\n     */\n    submit(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"submit\" JavaScript event\n     *\n     * @param eventData An object containing data that will be passed to the event handler.\n     * @param handler A function to execute each time the event is triggered.\n     */\n    submit(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Execute all handlers and behaviors attached to the matched elements for the given event type.\n     * \n     * @param eventType A string containing a JavaScript event type, such as click or submit.\n     * @param extraParameters Additional parameters to pass along to the event handler.\n     */\n    trigger(eventType: string, extraParameters?: any[]|Object): JQuery;\n    /**\n     * Execute all handlers and behaviors attached to the matched elements for the given event type.\n     * \n     * @param event A jQuery.Event object.\n     * @param extraParameters Additional parameters to pass along to the event handler.\n     */\n    trigger(event: JQueryEventObject, extraParameters?: any[]|Object): JQuery;\n\n    /**\n     * Execute all handlers attached to an element for an event.\n     * \n     * @param eventType A string containing a JavaScript event type, such as click or submit.\n     * @param extraParameters An array of additional parameters to pass along to the event handler.\n     */\n    triggerHandler(eventType: string, ...extraParameters: any[]): Object;\n\n    /**\n     * Execute all handlers attached to an element for an event.\n     * \n     * @param event A jQuery.Event object.\n     * @param extraParameters An array of additional parameters to pass along to the event handler.\n     */\n    triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object;\n\n    /**\n     * Remove a previously-attached event handler from the elements.\n     * \n     * @param eventType A string containing a JavaScript event type, such as click or submit.\n     * @param handler The function that is to be no longer executed.\n     */\n    unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Remove a previously-attached event handler from the elements.\n     * \n     * @param eventType A string containing a JavaScript event type, such as click or submit.\n     * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ).\n     */\n    unbind(eventType: string, fls: boolean): JQuery;\n    /**\n     * Remove a previously-attached event handler from the elements.\n     * \n     * @param evt A JavaScript event object as passed to an event handler.\n     */\n    unbind(evt: any): JQuery;\n\n    /**\n     * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.\n     */\n    undelegate(): JQuery;\n    /**\n     * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.\n     * \n     * @param selector A selector which will be used to filter the event results.\n     * @param eventType A string containing a JavaScript event type, such as \"click\" or \"keydown\"\n     * @param handler A function to execute at the time the event is triggered.\n     */\n    undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.\n     * \n     * @param selector A selector which will be used to filter the event results.\n     * @param events An object of one or more event types and previously bound functions to unbind from them.\n     */\n    undelegate(selector: string, events: Object): JQuery;\n    /**\n     * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements.\n     * \n     * @param namespace A string containing a namespace to unbind all events from.\n     */\n    undelegate(namespace: string): JQuery;\n\n    /**\n     * Bind an event handler to the \"unload\" JavaScript event. (DEPRECATED from v1.8)\n     * \n     * @param handler A function to execute when the event is triggered.\n     */\n    unload(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"unload\" JavaScript event. (DEPRECATED from v1.8)\n     * \n     * @param eventData A plain object of data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    unload(eventData?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * The DOM node context originally passed to jQuery(); if none was passed then context will likely be the document. (DEPRECATED from v1.10)\n     */\n    context: Element;\n\n    jquery: string;\n\n    /**\n     * Bind an event handler to the \"error\" JavaScript event. (DEPRECATED from v1.8)\n     * \n     * @param handler A function to execute when the event is triggered.\n     */\n    error(handler: (eventObject: JQueryEventObject) => any): JQuery;\n    /**\n     * Bind an event handler to the \"error\" JavaScript event. (DEPRECATED from v1.8)\n     * \n     * @param eventData A plain object of data that will be passed to the event handler.\n     * @param handler A function to execute when the event is triggered.\n     */\n    error(eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery;\n\n    /**\n     * Add a collection of DOM elements onto the jQuery stack.\n     * \n     * @param elements An array of elements to push onto the stack and make into a new jQuery object.\n     */\n    pushStack(elements: any[]): JQuery;\n    /**\n     * Add a collection of DOM elements onto the jQuery stack.\n     * \n     * @param elements An array of elements to push onto the stack and make into a new jQuery object.\n     * @param name The name of a jQuery method that generated the array of elements.\n     * @param arguments The arguments that were passed in to the jQuery method (for serialization).\n     */\n    pushStack(elements: any[], name: string, arguments: any[]): JQuery;\n\n    /**\n     * Insert content, specified by the parameter, after each element in the set of matched elements.\n     * \n     * param content1 HTML string, DOM element, array of elements, or jQuery object to insert after each element in the set of matched elements.\n     * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.\n     */\n    after(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery;\n    /**\n     * Insert content, specified by the parameter, after each element in the set of matched elements.\n     * \n     * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.\n     */\n    after(func: (index: number, html: string) => string|Element|JQuery): JQuery;\n\n    /**\n     * Insert content, specified by the parameter, to the end of each element in the set of matched elements.\n     * \n     * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.\n     * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.\n     */\n    append(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery;\n    /**\n     * Insert content, specified by the parameter, to the end of each element in the set of matched elements.\n     * \n     * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.\n     */\n    append(func: (index: number, html: string) => string|Element|JQuery): JQuery;\n\n    /**\n     * Insert every element in the set of matched elements to the end of the target.\n     * \n     * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter.\n     */\n    appendTo(target: JQuery|any[]|Element|string): JQuery;\n\n    /**\n     * Insert content, specified by the parameter, before each element in the set of matched elements.\n     * \n     * param content1 HTML string, DOM element, array of elements, or jQuery object to insert before each element in the set of matched elements.\n     * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements.\n     */\n    before(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery;\n    /**\n     * Insert content, specified by the parameter, before each element in the set of matched elements.\n     * \n     * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.\n     */\n    before(func: (index: number, html: string) => string|Element|JQuery): JQuery;\n\n    /**\n     * Create a deep copy of the set of matched elements.\n     * \n     * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false.\n     * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).\n     */\n    clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery;\n\n    /**\n     * Remove the set of matched elements from the DOM.\n     * \n     * param selector A selector expression that filters the set of matched elements to be removed.\n     */\n    detach(selector?: string): JQuery;\n\n    /**\n     * Remove all child nodes of the set of matched elements from the DOM.\n     */\n    empty(): JQuery;\n\n    /**\n     * Insert every element in the set of matched elements after the target.\n     * \n     * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter.\n     */\n    insertAfter(target: JQuery|any[]|Element|Text|string): JQuery;\n\n    /**\n     * Insert every element in the set of matched elements before the target.\n     * \n     * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter.\n     */\n    insertBefore(target: JQuery|any[]|Element|Text|string): JQuery;\n\n    /**\n     * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.\n     * \n     * param content1 DOM element, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.\n     * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.\n     */\n    prepend(content1: JQuery|any[]|Element|Text|string, ...content2: any[]): JQuery;\n    /**\n     * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.\n     * \n     * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.\n     */\n    prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery;\n\n    /**\n     * Insert every element in the set of matched elements to the beginning of the target.\n     * \n     * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter.\n     */\n    prependTo(target: JQuery|any[]|Element|string): JQuery;\n\n    /**\n     * Remove the set of matched elements from the DOM.\n     * \n     * @param selector A selector expression that filters the set of matched elements to be removed.\n     */\n    remove(selector?: string): JQuery;\n\n    /**\n     * Replace each target element with the set of matched elements.\n     * \n     * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace.\n     */\n    replaceAll(target: JQuery|any[]|Element|string): JQuery;\n\n    /**\n     * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.\n     * \n     * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object.\n     */\n    replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery;\n    /**\n     * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.\n     * \n     * param func A function that returns content with which to replace the set of matched elements.\n     */\n    replaceWith(func: () => Element|JQuery): JQuery;\n\n    /**\n     * Get the combined text contents of each element in the set of matched elements, including their descendants.\n     */\n    text(): string;\n    /**\n     * Set the content of each element in the set of matched elements to the specified text.\n     * \n     * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation.\n     */\n    text(text: string|number|boolean): JQuery;\n    /**\n     * Set the content of each element in the set of matched elements to the specified text.\n     * \n     * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.\n     */\n    text(func: (index: number, text: string) => string): JQuery;\n\n    /**\n     * Retrieve all the elements contained in the jQuery set, as an array.\n     */\n    toArray(): any[];\n\n    /**\n     * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.\n     */\n    unwrap(): JQuery;\n\n    /**\n     * Wrap an HTML structure around each element in the set of matched elements.\n     * \n     * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements.\n     */\n    wrap(wrappingElement: JQuery|Element|string): JQuery;\n    /**\n     * Wrap an HTML structure around each element in the set of matched elements.\n     * \n     * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.\n     */\n    wrap(func: (index: number) => string|JQuery): JQuery;\n\n    /**\n     * Wrap an HTML structure around all elements in the set of matched elements.\n     * \n     * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements.\n     */\n    wrapAll(wrappingElement: JQuery|Element|string): JQuery;\n    wrapAll(func: (index: number) => string): JQuery;\n\n    /**\n     * Wrap an HTML structure around the content of each element in the set of matched elements.\n     * \n     * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements.\n     */\n    wrapInner(wrappingElement: JQuery|Element|string): JQuery;\n    /**\n     * Wrap an HTML structure around the content of each element in the set of matched elements.\n     * \n     * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.\n     */\n    wrapInner(func: (index: number) => string): JQuery;\n\n    /**\n     * Iterate over a jQuery object, executing a function for each matched element.\n     * \n     * @param func A function to execute for each matched element.\n     */\n    each(func: (index: number, elem: Element) => any): JQuery;\n\n    /**\n     * Retrieve one of the elements matched by the jQuery object.\n     * \n     * @param index A zero-based integer indicating which element to retrieve.\n     */\n    get(index: number): HTMLElement;\n    /**\n     * Retrieve the elements matched by the jQuery object.\n     */\n    get(): any[];\n\n    /**\n     * Search for a given element from among the matched elements.\n     */\n    index(): number;\n    /**\n     * Search for a given element from among the matched elements.\n     * \n     * @param selector A selector representing a jQuery collection in which to look for an element.\n     */\n    index(selector: string|JQuery|Element): number;\n\n    /**\n     * The number of elements in the jQuery object.\n     */\n    length: number;\n    /**\n     * A selector representing selector passed to jQuery(), if any, when creating the original set.\n     * version deprecated: 1.7, removed: 1.9\n     */\n    selector: string;\n    [index: string]: any;\n    [index: number]: HTMLElement;\n\n    /**\n     * Add elements to the set of matched elements.\n     * \n     * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements.\n     * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method.\n     */\n    add(selector: string, context?: Element): JQuery;\n    /**\n     * Add elements to the set of matched elements.\n     * \n     * @param elements One or more elements to add to the set of matched elements.\n     */\n    add(...elements: Element[]): JQuery;\n    /**\n     * Add elements to the set of matched elements.\n     * \n     * @param html An HTML fragment to add to the set of matched elements.\n     */\n    add(html: string): JQuery;\n    /**\n     * Add elements to the set of matched elements.\n     * \n     * @param obj An existing jQuery object to add to the set of matched elements.\n     */\n    add(obj: JQuery): JQuery;\n\n    /**\n     * Get the children of each element in the set of matched elements, optionally filtered by a selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    children(selector?: string): JQuery;\n\n    /**\n     * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    closest(selector: string): JQuery;\n    /**\n     * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.\n     */\n    closest(selector: string, context?: Element): JQuery;\n    /**\n     * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.\n     * \n     * @param obj A jQuery object to match elements against.\n     */\n    closest(obj: JQuery): JQuery;\n    /**\n     * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.\n     * \n     * @param element An element to match elements against.\n     */\n    closest(element: Element): JQuery;\n\n    /**\n     * Get an array of all the elements and selectors matched against the current element up through the DOM tree.\n     * \n     * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object).\n     * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.\n     */\n    closest(selectors: any, context?: Element): any[];\n\n    /**\n     * Get the children of each element in the set of matched elements, including text and comment nodes.\n     */\n    contents(): JQuery;\n\n    /**\n     * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state.\n     */\n    end(): JQuery;\n\n    /**\n     * Reduce the set of matched elements to the one at the specified index.\n     * \n     * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set.\n     *  \n     */\n    eq(index: number): JQuery;\n\n    /**\n     * Reduce the set of matched elements to those that match the selector or pass the function's test.\n     * \n     * @param selector A string containing a selector expression to match the current set of elements against.\n     */\n    filter(selector: string): JQuery;\n    /**\n     * Reduce the set of matched elements to those that match the selector or pass the function's test.\n     * \n     * @param func A function used as a test for each element in the set. this is the current DOM element.\n     */\n    filter(func: (index: number, element: Element) => any): JQuery;\n    /**\n     * Reduce the set of matched elements to those that match the selector or pass the function's test.\n     * \n     * @param element An element to match the current set of elements against.\n     */\n    filter(element: Element): JQuery;\n    /**\n     * Reduce the set of matched elements to those that match the selector or pass the function's test.\n     * \n     * @param obj An existing jQuery object to match the current set of elements against.\n     */\n    filter(obj: JQuery): JQuery;\n\n    /**\n     * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    find(selector: string): JQuery;\n    /**\n     * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.\n     * \n     * @param element An element to match elements against.\n     */\n    find(element: Element): JQuery;\n    /**\n     * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.\n     * \n     * @param obj A jQuery object to match elements against.\n     */\n    find(obj: JQuery): JQuery;\n\n    /**\n     * Reduce the set of matched elements to the first in the set.\n     */\n    first(): JQuery;\n\n    /**\n     * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    has(selector: string): JQuery;\n    /**\n     * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.\n     * \n     * @param contained A DOM element to match elements against.\n     */\n    has(contained: Element): JQuery;\n\n    /**\n     * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    is(selector: string): boolean;\n    /**\n     * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.\n     * \n     * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element.\n     */\n    is(func: (index: number, element: Element) => boolean): boolean;\n    /**\n     * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.\n     * \n     * @param obj An existing jQuery object to match the current set of elements against.\n     */\n    is(obj: JQuery): boolean;\n    /**\n     * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.\n     * \n     * @param elements One or more elements to match the current set of elements against.\n     */\n    is(elements: any): boolean;\n\n    /**\n     * Reduce the set of matched elements to the final one in the set.\n     */\n    last(): JQuery;\n\n    /**\n     * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.\n     * \n     * @param callback A function object that will be invoked for each element in the current set.\n     */\n    map(callback: (index: number, domElement: Element) => any): JQuery;\n\n    /**\n     * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    next(selector?: string): JQuery;\n\n    /**\n     * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    nextAll(selector?: string): JQuery;\n\n    /**\n     * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.\n     * \n     * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    nextUntil(selector?: string, filter?: string): JQuery;\n    /**\n     * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.\n     * \n     * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    nextUntil(element?: Element, filter?: string): JQuery;\n    /**\n     * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed.\n     * \n     * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    nextUntil(obj?: JQuery, filter?: string): JQuery;\n\n    /**\n     * Remove elements from the set of matched elements.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    not(selector: string): JQuery;\n    /**\n     * Remove elements from the set of matched elements.\n     * \n     * @param func A function used as a test for each element in the set. this is the current DOM element.\n     */\n    not(func: (index: number, element: Element) => boolean): JQuery;\n    /**\n     * Remove elements from the set of matched elements.\n     * \n     * @param elements One or more DOM elements to remove from the matched set.\n     */\n    not(elements: Element|Element[]): JQuery;\n    /**\n     * Remove elements from the set of matched elements.\n     * \n     * @param obj An existing jQuery object to match the current set of elements against.\n     */\n    not(obj: JQuery): JQuery;\n\n    /**\n     * Get the closest ancestor element that is positioned.\n     */\n    offsetParent(): JQuery;\n\n    /**\n     * Get the parent of each element in the current set of matched elements, optionally filtered by a selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    parent(selector?: string): JQuery;\n\n    /**\n     * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    parents(selector?: string): JQuery;\n\n    /**\n     * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.\n     * \n     * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    parentsUntil(selector?: string, filter?: string): JQuery;\n    /**\n     * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.\n     * \n     * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    parentsUntil(element?: Element, filter?: string): JQuery;\n    /**\n     * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object.\n     * \n     * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    parentsUntil(obj?: JQuery, filter?: string): JQuery;\n\n    /**\n     * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    prev(selector?: string): JQuery;\n\n    /**\n     * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    prevAll(selector?: string): JQuery;\n\n    /**\n     * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.\n     * \n     * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    prevUntil(selector?: string, filter?: string): JQuery;\n    /**\n     * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.\n     * \n     * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    prevUntil(element?: Element, filter?: string): JQuery;\n    /**\n     * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object.\n     * \n     * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements.\n     * @param filter A string containing a selector expression to match elements against.\n     */\n    prevUntil(obj?: JQuery, filter?: string): JQuery;\n\n    /**\n     * Get the siblings of each element in the set of matched elements, optionally filtered by a selector.\n     * \n     * @param selector A string containing a selector expression to match elements against.\n     */\n    siblings(selector?: string): JQuery;\n\n    /**\n     * Reduce the set of matched elements to a subset specified by a range of indices.\n     * \n     * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set.\n     * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set.\n     */\n    slice(start: number, end?: number): JQuery;\n\n    /**\n     * Show the queue of functions to be executed on the matched elements.\n     * \n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     */\n    queue(queueName?: string): any[];\n    /**\n     * Manipulate the queue of functions to be executed, once for each matched element.\n     * \n     * @param newQueue An array of functions to replace the current queue contents.\n     */\n    queue(newQueue: Function[]): JQuery;\n    /**\n     * Manipulate the queue of functions to be executed, once for each matched element.\n     * \n     * @param callback The new function to add to the queue, with a function to call that will dequeue the next item.\n     */\n    queue(callback: Function): JQuery;\n    /**\n     * Manipulate the queue of functions to be executed, once for each matched element.\n     * \n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     * @param newQueue An array of functions to replace the current queue contents.\n     */\n    queue(queueName: string, newQueue: Function[]): JQuery;\n    /**\n     * Manipulate the queue of functions to be executed, once for each matched element.\n     * \n     * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue.\n     * @param callback The new function to add to the queue, with a function to call that will dequeue the next item.\n     */\n    queue(queueName: string, callback: Function): JQuery;\n}\ndeclare module \"jquery\" {\n    export = $;\n}\ndeclare var jQuery: JQueryStatic;\ndeclare var $: JQueryStatic;\n"
  },
  {
    "path": "typings/globals/jquery/typings.json",
    "content": "{\n  \"resolution\": \"main\",\n  \"tree\": {\n    \"src\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/4cdfbe96b666eec5e1defbb519a62abf04e96764/jquery/jquery.d.ts\",\n    \"raw\": \"registry:dt/jquery#1.10.0+20160417213236\",\n    \"typings\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/4cdfbe96b666eec5e1defbb519a62abf04e96764/jquery/jquery.d.ts\"\n  }\n}\n"
  },
  {
    "path": "typings/globals/node/index.d.ts",
    "content": "// Generated by typings\n// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6abf99dda133ff859e16e3520b0b00b6b1239341/node/node.d.ts\ninterface Error {\n    stack?: string;\n}\n\ninterface ErrorConstructor {\n    captureStackTrace(targetObject: Object, constructorOpt?: Function): void;\n    stackTraceLimit: number;\n}\n\n// compat for TypeScript 1.8\n// if you use with --target es3 or --target es5 and use below definitions,\n// use the lib.es6.d.ts that is bundled with TypeScript 1.8.\ninterface MapConstructor {}\ninterface WeakMapConstructor {}\ninterface SetConstructor {}\ninterface WeakSetConstructor {}\n\n/************************************************\n*                                               *\n*                   GLOBAL                      *\n*                                               *\n************************************************/\ndeclare var process: NodeJS.Process;\ndeclare var global: NodeJS.Global;\n\ndeclare var __filename: string;\ndeclare var __dirname: string;\n\ndeclare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;\ndeclare function clearTimeout(timeoutId: NodeJS.Timer): void;\ndeclare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer;\ndeclare function clearInterval(intervalId: NodeJS.Timer): void;\ndeclare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any;\ndeclare function clearImmediate(immediateId: any): void;\n\ninterface NodeRequireFunction {\n    (id: string): any;\n}\n\ninterface NodeRequire extends NodeRequireFunction {\n    resolve(id:string): string;\n    cache: any;\n    extensions: any;\n    main: any;\n}\n\ndeclare var require: NodeRequire;\n\ninterface NodeModule {\n    exports: any;\n    require: NodeRequireFunction;\n    id: string;\n    filename: string;\n    loaded: boolean;\n    parent: any;\n    children: any[];\n}\n\ndeclare var module: NodeModule;\n\n// Same as module.exports\ndeclare var exports: any;\ndeclare var SlowBuffer: {\n    new (str: string, encoding?: string): Buffer;\n    new (size: number): Buffer;\n    new (size: Uint8Array): Buffer;\n    new (array: any[]): Buffer;\n    prototype: Buffer;\n    isBuffer(obj: any): boolean;\n    byteLength(string: string, encoding?: string): number;\n    concat(list: Buffer[], totalLength?: number): Buffer;\n};\n\n\n// Buffer class\ntype BufferEncoding = \"ascii\" | \"utf8\" | \"utf16le\" | \"ucs2\" | \"binary\" | \"hex\";\ninterface Buffer extends NodeBuffer {}\n\n/**\n * Raw data is stored in instances of the Buffer class.\n * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap.  A Buffer cannot be resized.\n * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'\n */\ndeclare var Buffer: {\n    /**\n     * Allocates a new buffer containing the given {str}.\n     *\n     * @param str String to store in buffer.\n     * @param encoding encoding to use, optional.  Default is 'utf8'\n     */\n    new (str: string, encoding?: string): Buffer;\n    /**\n     * Allocates a new buffer of {size} octets.\n     *\n     * @param size count of octets to allocate.\n     */\n    new (size: number): Buffer;\n    /**\n     * Allocates a new buffer containing the given {array} of octets.\n     *\n     * @param array The octets to store.\n     */\n    new (array: Uint8Array): Buffer;\n    /**\n     * Produces a Buffer backed by the same allocated memory as\n     * the given {ArrayBuffer}.\n     *\n     *\n     * @param arrayBuffer The ArrayBuffer with which to share memory.\n     */\n    new (arrayBuffer: ArrayBuffer): Buffer;\n    /**\n     * Allocates a new buffer containing the given {array} of octets.\n     *\n     * @param array The octets to store.\n     */\n    new (array: any[]): Buffer;\n    /**\n     * Copies the passed {buffer} data onto a new {Buffer} instance.\n     *\n     * @param buffer The buffer to copy.\n     */\n    new (buffer: Buffer): Buffer;\n    prototype: Buffer;\n    /**\n     * Allocates a new Buffer using an {array} of octets.\n     *\n     * @param array\n     */\n    from(array: any[]): Buffer;\n    /**\n     * When passed a reference to the .buffer property of a TypedArray instance,\n     * the newly created Buffer will share the same allocated memory as the TypedArray.\n     * The optional {byteOffset} and {length} arguments specify a memory range\n     * within the {arrayBuffer} that will be shared by the Buffer.\n     *\n     * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()\n     * @param byteOffset\n     * @param length\n     */\n    from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer;\n    /**\n     * Copies the passed {buffer} data onto a new Buffer instance.\n     *\n     * @param buffer\n     */\n    from(buffer: Buffer): Buffer;\n    /**\n     * Creates a new Buffer containing the given JavaScript string {str}.\n     * If provided, the {encoding} parameter identifies the character encoding.\n     * If not provided, {encoding} defaults to 'utf8'.\n     *\n     * @param str\n     */\n    from(str: string, encoding?: string): Buffer;\n    /**\n     * Returns true if {obj} is a Buffer\n     *\n     * @param obj object to test.\n     */\n    isBuffer(obj: any): obj is Buffer;\n    /**\n     * Returns true if {encoding} is a valid encoding argument.\n     * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'\n     *\n     * @param encoding string to test.\n     */\n    isEncoding(encoding: string): boolean;\n    /**\n     * Gives the actual byte length of a string. encoding defaults to 'utf8'.\n     * This is not the same as String.prototype.length since that returns the number of characters in a string.\n     *\n     * @param string string to test.\n     * @param encoding encoding used to evaluate (defaults to 'utf8')\n     */\n    byteLength(string: string, encoding?: string): number;\n    /**\n     * Returns a buffer which is the result of concatenating all the buffers in the list together.\n     *\n     * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.\n     * If the list has exactly one item, then the first item of the list is returned.\n     * If the list has more than one item, then a new Buffer is created.\n     *\n     * @param list An array of Buffer objects to concatenate\n     * @param totalLength Total length of the buffers when concatenated.\n     *   If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.\n     */\n    concat(list: Buffer[], totalLength?: number): Buffer;\n    /**\n     * The same as buf1.compare(buf2).\n     */\n    compare(buf1: Buffer, buf2: Buffer): number;\n    /**\n     * Allocates a new buffer of {size} octets.\n     *\n     * @param size count of octets to allocate.\n     * @param fill if specified, buffer will be initialized by calling buf.fill(fill).\n     *    If parameter is omitted, buffer will be filled with zeros.\n     * @param encoding encoding used for call to buf.fill while initalizing\n     */\n    alloc(size: number, fill?: string|Buffer|number, encoding?: string): Buffer;\n     /**\n      * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents\n      * of the newly created Buffer are unknown and may contain sensitive data.\n      *\n      * @param size count of octets to allocate\n      */\n    allocUnsafe(size: number): Buffer;\n     /**\n      * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents\n      * of the newly created Buffer are unknown and may contain sensitive data.\n      *\n      * @param size count of octets to allocate\n      */\n    allocUnsafeSlow(size: number): Buffer;\n};\n\n/************************************************\n*                                               *\n*               GLOBAL INTERFACES               *\n*                                               *\n************************************************/\ndeclare namespace NodeJS {\n    export interface ErrnoException extends Error {\n        errno?: number;\n        code?: string;\n        path?: string;\n        syscall?: string;\n        stack?: string;\n    }\n\n    export interface EventEmitter {\n        addListener(event: string, listener: Function): this;\n        on(event: string, listener: Function): this;\n        once(event: string, listener: Function): this;\n        removeListener(event: string, listener: Function): this;\n        removeAllListeners(event?: string): this;\n        setMaxListeners(n: number): this;\n        getMaxListeners(): number;\n        listeners(event: string): Function[];\n        emit(event: string, ...args: any[]): boolean;\n        listenerCount(type: string): number;\n    }\n\n    export interface ReadableStream extends EventEmitter {\n        readable: boolean;\n        read(size?: number): string|Buffer;\n        setEncoding(encoding: string): void;\n        pause(): void;\n        resume(): void;\n        pipe<T extends WritableStream>(destination: T, options?: { end?: boolean; }): T;\n        unpipe<T extends WritableStream>(destination?: T): void;\n        unshift(chunk: string): void;\n        unshift(chunk: Buffer): void;\n        wrap(oldStream: ReadableStream): ReadableStream;\n    }\n\n    export interface WritableStream extends EventEmitter {\n        writable: boolean;\n        write(buffer: Buffer|string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n    }\n\n    export interface ReadWriteStream extends ReadableStream, WritableStream {}\n\n    export interface Events extends EventEmitter { }\n\n    export interface Domain extends Events {\n        run(fn: Function): void;\n        add(emitter: Events): void;\n        remove(emitter: Events): void;\n        bind(cb: (err: Error, data: any) => any): any;\n        intercept(cb: (data: any) => any): any;\n        dispose(): void;\n\n        addListener(event: string, listener: Function): this;\n        on(event: string, listener: Function): this;\n        once(event: string, listener: Function): this;\n        removeListener(event: string, listener: Function): this;\n        removeAllListeners(event?: string): this;\n    }\n\n    export interface MemoryUsage {\n        rss: number;\n        heapTotal: number;\n        heapUsed: number;\n    }\n\n    export interface Process extends EventEmitter {\n        stdout: WritableStream;\n        stderr: WritableStream;\n        stdin: ReadableStream;\n        argv: string[];\n        execArgv: string[];\n        execPath: string;\n        abort(): void;\n        chdir(directory: string): void;\n        cwd(): string;\n        env: any;\n        exit(code?: number): void;\n        getgid(): number;\n        setgid(id: number): void;\n        setgid(id: string): void;\n        getuid(): number;\n        setuid(id: number): void;\n        setuid(id: string): void;\n        version: string;\n        versions: {\n            http_parser: string;\n            node: string;\n            v8: string;\n            ares: string;\n            uv: string;\n            zlib: string;\n            modules: string;\n            openssl: string;\n        };\n        config: {\n            target_defaults: {\n                cflags: any[];\n                default_configuration: string;\n                defines: string[];\n                include_dirs: string[];\n                libraries: string[];\n            };\n            variables: {\n                clang: number;\n                host_arch: string;\n                node_install_npm: boolean;\n                node_install_waf: boolean;\n                node_prefix: string;\n                node_shared_openssl: boolean;\n                node_shared_v8: boolean;\n                node_shared_zlib: boolean;\n                node_use_dtrace: boolean;\n                node_use_etw: boolean;\n                node_use_openssl: boolean;\n                target_arch: string;\n                v8_no_strict_aliasing: number;\n                v8_use_snapshot: boolean;\n                visibility: string;\n            };\n        };\n        kill(pid:number, signal?: string|number): void;\n        pid: number;\n        title: string;\n        arch: string;\n        platform: string;\n        memoryUsage(): MemoryUsage;\n        nextTick(callback: Function): void;\n        umask(mask?: number): number;\n        uptime(): number;\n        hrtime(time?:number[]): number[];\n        domain: Domain;\n\n        // Worker\n        send?(message: any, sendHandle?: any): void;\n        disconnect(): void;\n        connected: boolean;\n    }\n\n    export interface Global {\n        Array: typeof Array;\n        ArrayBuffer: typeof ArrayBuffer;\n        Boolean: typeof Boolean;\n        Buffer: typeof Buffer;\n        DataView: typeof DataView;\n        Date: typeof Date;\n        Error: typeof Error;\n        EvalError: typeof EvalError;\n        Float32Array: typeof Float32Array;\n        Float64Array: typeof Float64Array;\n        Function: typeof Function;\n        GLOBAL: Global;\n        Infinity: typeof Infinity;\n        Int16Array: typeof Int16Array;\n        Int32Array: typeof Int32Array;\n        Int8Array: typeof Int8Array;\n        Intl: typeof Intl;\n        JSON: typeof JSON;\n        Map: MapConstructor;\n        Math: typeof Math;\n        NaN: typeof NaN;\n        Number: typeof Number;\n        Object: typeof Object;\n        Promise: Function;\n        RangeError: typeof RangeError;\n        ReferenceError: typeof ReferenceError;\n        RegExp: typeof RegExp;\n        Set: SetConstructor;\n        String: typeof String;\n        Symbol: Function;\n        SyntaxError: typeof SyntaxError;\n        TypeError: typeof TypeError;\n        URIError: typeof URIError;\n        Uint16Array: typeof Uint16Array;\n        Uint32Array: typeof Uint32Array;\n        Uint8Array: typeof Uint8Array;\n        Uint8ClampedArray: Function;\n        WeakMap: WeakMapConstructor;\n        WeakSet: WeakSetConstructor;\n        clearImmediate: (immediateId: any) => void;\n        clearInterval: (intervalId: NodeJS.Timer) => void;\n        clearTimeout: (timeoutId: NodeJS.Timer) => void;\n        console: typeof console;\n        decodeURI: typeof decodeURI;\n        decodeURIComponent: typeof decodeURIComponent;\n        encodeURI: typeof encodeURI;\n        encodeURIComponent: typeof encodeURIComponent;\n        escape: (str: string) => string;\n        eval: typeof eval;\n        global: Global;\n        isFinite: typeof isFinite;\n        isNaN: typeof isNaN;\n        parseFloat: typeof parseFloat;\n        parseInt: typeof parseInt;\n        process: Process;\n        root: Global;\n        setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any;\n        setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;\n        setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => NodeJS.Timer;\n        undefined: typeof undefined;\n        unescape: (str: string) => string;\n        gc: () => void;\n        v8debug?: any;\n    }\n\n    export interface Timer {\n        ref() : void;\n        unref() : void;\n    }\n}\n\n/**\n * @deprecated\n */\ninterface NodeBuffer extends Uint8Array {\n    write(string: string, offset?: number, length?: number, encoding?: string): number;\n    toString(encoding?: string, start?: number, end?: number): string;\n    toJSON(): any;\n    equals(otherBuffer: Buffer): boolean;\n    compare(otherBuffer: Buffer): number;\n    copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;\n    slice(start?: number, end?: number): Buffer;\n    writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;\n    readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;\n    readUInt8(offset: number, noAssert?: boolean): number;\n    readUInt16LE(offset: number, noAssert?: boolean): number;\n    readUInt16BE(offset: number, noAssert?: boolean): number;\n    readUInt32LE(offset: number, noAssert?: boolean): number;\n    readUInt32BE(offset: number, noAssert?: boolean): number;\n    readInt8(offset: number, noAssert?: boolean): number;\n    readInt16LE(offset: number, noAssert?: boolean): number;\n    readInt16BE(offset: number, noAssert?: boolean): number;\n    readInt32LE(offset: number, noAssert?: boolean): number;\n    readInt32BE(offset: number, noAssert?: boolean): number;\n    readFloatLE(offset: number, noAssert?: boolean): number;\n    readFloatBE(offset: number, noAssert?: boolean): number;\n    readDoubleLE(offset: number, noAssert?: boolean): number;\n    readDoubleBE(offset: number, noAssert?: boolean): number;\n    writeUInt8(value: number, offset: number, noAssert?: boolean): number;\n    writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;\n    writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;\n    writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;\n    writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;\n    writeInt8(value: number, offset: number, noAssert?: boolean): number;\n    writeInt16LE(value: number, offset: number, noAssert?: boolean): number;\n    writeInt16BE(value: number, offset: number, noAssert?: boolean): number;\n    writeInt32LE(value: number, offset: number, noAssert?: boolean): number;\n    writeInt32BE(value: number, offset: number, noAssert?: boolean): number;\n    writeFloatLE(value: number, offset: number, noAssert?: boolean): number;\n    writeFloatBE(value: number, offset: number, noAssert?: boolean): number;\n    writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;\n    writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;\n    fill(value: any, offset?: number, end?: number): this;\n    // TODO: encoding param\n    indexOf(value: string | number | Buffer, byteOffset?: number): number;\n    // TODO: entries\n    // TODO: includes\n    // TODO: keys\n    // TODO: values\n}\n\n/************************************************\n*                                               *\n*                   MODULES                     *\n*                                               *\n************************************************/\ndeclare module \"buffer\" {\n    export var INSPECT_MAX_BYTES: number;\n    var BuffType: typeof Buffer;\n    var SlowBuffType: typeof SlowBuffer;\n    export { BuffType as Buffer, SlowBuffType as SlowBuffer };\n}\n\ndeclare module \"querystring\" {\n    export interface StringifyOptions {\n        encodeURIComponent?: Function;\n    }\n\n    export interface ParseOptions {\n        maxKeys?: number;\n        decodeURIComponent?: Function;\n    }\n\n    export function stringify<T>(obj: T, sep?: string, eq?: string, options?: StringifyOptions): string;\n    export function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): any;\n    export function parse<T extends {}>(str: string, sep?: string, eq?: string, options?: ParseOptions): T;\n    export function escape(str: string): string;\n    export function unescape(str: string): string;\n}\n\ndeclare module \"events\" {\n    export class EventEmitter implements NodeJS.EventEmitter {\n        static EventEmitter: EventEmitter;\n        static listenerCount(emitter: EventEmitter, event: string): number; // deprecated\n        static defaultMaxListeners: number;\n\n        addListener(event: string, listener: Function): this;\n        on(event: string, listener: Function): this;\n        once(event: string, listener: Function): this;\n        prependListener(event: string, listener: Function): this;\n        prependOnceListener(event: string, listener: Function): this;\n        removeListener(event: string, listener: Function): this;\n        removeAllListeners(event?: string): this;\n        setMaxListeners(n: number): this;\n        getMaxListeners(): number;\n        listeners(event: string): Function[];\n        emit(event: string, ...args: any[]): boolean;\n        eventNames(): string[];\n        listenerCount(type: string): number;\n    }\n}\n\ndeclare module \"http\" {\n    import * as events from \"events\";\n    import * as net from \"net\";\n    import * as stream from \"stream\";\n\n    export interface RequestOptions {\n        protocol?: string;\n        host?: string;\n        hostname?: string;\n        family?: number;\n        port?: number;\n        localAddress?: string;\n        socketPath?: string;\n        method?: string;\n        path?: string;\n        headers?: { [key: string]: any };\n        auth?: string;\n        agent?: Agent|boolean;\n    }\n\n    export interface Server extends events.EventEmitter, net.Server {\n        setTimeout(msecs: number, callback: Function): void;\n        maxHeadersCount: number;\n        timeout: number;\n    }\n    /**\n     * @deprecated Use IncomingMessage\n     */\n    export interface ServerRequest extends IncomingMessage {\n        connection: net.Socket;\n    }\n    export interface ServerResponse extends events.EventEmitter, stream.Writable {\n        // Extended base methods\n        write(buffer: Buffer): boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, fd?: string): boolean;\n\n        writeContinue(): void;\n        writeHead(statusCode: number, reasonPhrase?: string, headers?: any): void;\n        writeHead(statusCode: number, headers?: any): void;\n        statusCode: number;\n        statusMessage: string;\n        headersSent: boolean;\n        setHeader(name: string, value: string | string[]): void;\n        sendDate: boolean;\n        getHeader(name: string): string;\n        removeHeader(name: string): void;\n        write(chunk: any, encoding?: string): any;\n        addTrailers(headers: any): void;\n\n        // Extended base methods\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n        end(data?: any, encoding?: string): void;\n    }\n    export interface ClientRequest extends events.EventEmitter, stream.Writable {\n        // Extended base methods\n        write(buffer: Buffer): boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, fd?: string): boolean;\n\n        write(chunk: any, encoding?: string): void;\n        abort(): void;\n        setTimeout(timeout: number, callback?: Function): void;\n        setNoDelay(noDelay?: boolean): void;\n        setSocketKeepAlive(enable?: boolean, initialDelay?: number): void;\n\n        setHeader(name: string, value: string | string[]): void;\n        getHeader(name: string): string;\n        removeHeader(name: string): void;\n        addTrailers(headers: any): void;\n\n        // Extended base methods\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n        end(data?: any, encoding?: string): void;\n    }\n    export interface IncomingMessage extends events.EventEmitter, stream.Readable {\n        httpVersion: string;\n        headers: any;\n        rawHeaders: string[];\n        trailers: any;\n        rawTrailers: any;\n        setTimeout(msecs: number, callback: Function): NodeJS.Timer;\n        /**\n         * Only valid for request obtained from http.Server.\n         */\n        method?: string;\n        /**\n         * Only valid for request obtained from http.Server.\n         */\n        url?: string;\n        /**\n         * Only valid for response obtained from http.ClientRequest.\n         */\n        statusCode?: number;\n        /**\n         * Only valid for response obtained from http.ClientRequest.\n         */\n        statusMessage?: string;\n        socket: net.Socket;\n    }\n    /**\n     * @deprecated Use IncomingMessage\n     */\n    export interface ClientResponse extends IncomingMessage { }\n\n    export interface AgentOptions {\n        /**\n         * Keep sockets around in a pool to be used by other requests in the future. Default = false\n         */\n        keepAlive?: boolean;\n        /**\n         * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.\n         * Only relevant if keepAlive is set to true.\n         */\n        keepAliveMsecs?: number;\n        /**\n         * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity\n         */\n        maxSockets?: number;\n        /**\n         * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.\n         */\n        maxFreeSockets?: number;\n    }\n\n    export class Agent {\n        maxSockets: number;\n        sockets: any;\n        requests: any;\n\n        constructor(opts?: AgentOptions);\n\n        /**\n         * Destroy any sockets that are currently in use by the agent.\n         * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled,\n         * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise,\n         * sockets may hang open for quite a long time before the server terminates them.\n         */\n        destroy(): void;\n    }\n\n    export var METHODS: string[];\n\n    export var STATUS_CODES: {\n        [errorCode: number]: string;\n        [errorCode: string]: string;\n    };\n    export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server;\n    export function createClient(port?: number, host?: string): any;\n    export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest;\n    export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest;\n    export var globalAgent: Agent;\n}\n\ndeclare module \"cluster\" {\n    import * as child from \"child_process\";\n    import * as events from \"events\";\n\n    export interface ClusterSettings {\n        exec?: string;\n        args?: string[];\n        silent?: boolean;\n    }\n\n    export interface Address {\n        address: string;\n        port: number;\n        addressType: string;\n    }\n\n    export class Worker extends events.EventEmitter {\n        id: string;\n        process: child.ChildProcess;\n        suicide: boolean;\n        send(message: any, sendHandle?: any): void;\n        kill(signal?: string): void;\n        destroy(signal?: string): void;\n        disconnect(): void;\n        isConnected(): boolean;\n        isDead(): boolean;\n    }\n\n    export var settings: ClusterSettings;\n    export var isMaster: boolean;\n    export var isWorker: boolean;\n    export function setupMaster(settings?: ClusterSettings): void;\n    export function fork(env?: any): Worker;\n    export function disconnect(callback?: Function): void;\n    export var worker: Worker;\n    export var workers: {\n        [index: string]: Worker\n    };\n\n    // Event emitter\n    export function addListener(event: string, listener: Function): void;\n    export function on(event: \"disconnect\", listener: (worker: Worker) => void): void;\n    export function on(event: \"exit\", listener: (worker: Worker, code: number, signal: string) => void): void;\n    export function on(event: \"fork\", listener: (worker: Worker) => void): void;\n    export function on(event: \"listening\", listener: (worker: Worker, address: any) => void): void;\n    export function on(event: \"message\", listener: (worker: Worker, message: any) => void): void;\n    export function on(event: \"online\", listener: (worker: Worker) => void): void;\n    export function on(event: \"setup\", listener: (settings: any) => void): void;\n    export function on(event: string, listener: Function): any;\n    export function once(event: string, listener: Function): void;\n    export function removeListener(event: string, listener: Function): void;\n    export function removeAllListeners(event?: string): void;\n    export function setMaxListeners(n: number): void;\n    export function listeners(event: string): Function[];\n    export function emit(event: string, ...args: any[]): boolean;\n}\n\ndeclare module \"zlib\" {\n    import * as stream from \"stream\";\n    export interface ZlibOptions { chunkSize?: number; windowBits?: number; level?: number; memLevel?: number; strategy?: number; dictionary?: any; }\n\n    export interface Gzip extends stream.Transform { }\n    export interface Gunzip extends stream.Transform { }\n    export interface Deflate extends stream.Transform { }\n    export interface Inflate extends stream.Transform { }\n    export interface DeflateRaw extends stream.Transform { }\n    export interface InflateRaw extends stream.Transform { }\n    export interface Unzip extends stream.Transform { }\n\n    export function createGzip(options?: ZlibOptions): Gzip;\n    export function createGunzip(options?: ZlibOptions): Gunzip;\n    export function createDeflate(options?: ZlibOptions): Deflate;\n    export function createInflate(options?: ZlibOptions): Inflate;\n    export function createDeflateRaw(options?: ZlibOptions): DeflateRaw;\n    export function createInflateRaw(options?: ZlibOptions): InflateRaw;\n    export function createUnzip(options?: ZlibOptions): Unzip;\n\n    export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function deflateSync(buf: Buffer, options?: ZlibOptions): any;\n    export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any;\n    export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function gzipSync(buf: Buffer, options?: ZlibOptions): any;\n    export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function gunzipSync(buf: Buffer, options?: ZlibOptions): any;\n    export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function inflateSync(buf: Buffer, options?: ZlibOptions): any;\n    export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any;\n    export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void;\n    export function unzipSync(buf: Buffer, options?: ZlibOptions): any;\n\n    // Constants\n    export var Z_NO_FLUSH: number;\n    export var Z_PARTIAL_FLUSH: number;\n    export var Z_SYNC_FLUSH: number;\n    export var Z_FULL_FLUSH: number;\n    export var Z_FINISH: number;\n    export var Z_BLOCK: number;\n    export var Z_TREES: number;\n    export var Z_OK: number;\n    export var Z_STREAM_END: number;\n    export var Z_NEED_DICT: number;\n    export var Z_ERRNO: number;\n    export var Z_STREAM_ERROR: number;\n    export var Z_DATA_ERROR: number;\n    export var Z_MEM_ERROR: number;\n    export var Z_BUF_ERROR: number;\n    export var Z_VERSION_ERROR: number;\n    export var Z_NO_COMPRESSION: number;\n    export var Z_BEST_SPEED: number;\n    export var Z_BEST_COMPRESSION: number;\n    export var Z_DEFAULT_COMPRESSION: number;\n    export var Z_FILTERED: number;\n    export var Z_HUFFMAN_ONLY: number;\n    export var Z_RLE: number;\n    export var Z_FIXED: number;\n    export var Z_DEFAULT_STRATEGY: number;\n    export var Z_BINARY: number;\n    export var Z_TEXT: number;\n    export var Z_ASCII: number;\n    export var Z_UNKNOWN: number;\n    export var Z_DEFLATED: number;\n    export var Z_NULL: number;\n}\n\ndeclare module \"os\" {\n    export interface CpuInfo {\n        model: string;\n        speed: number;\n        times: {\n            user: number;\n            nice: number;\n            sys: number;\n            idle: number;\n            irq: number;\n        };\n    }\n\n    export interface NetworkInterfaceInfo {\n        address: string;\n        netmask: string;\n        family: string;\n        mac: string;\n        internal: boolean;\n    }\n\n    export function tmpdir(): string;\n    export function homedir(): string;\n    export function endianness(): \"BE\" | \"LE\";\n    export function hostname(): string;\n    export function type(): string;\n    export function platform(): string;\n    export function arch(): string;\n    export function release(): string;\n    export function uptime(): number;\n    export function loadavg(): number[];\n    export function totalmem(): number;\n    export function freemem(): number;\n    export function cpus(): CpuInfo[];\n    export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]};\n    export var EOL: string;\n}\n\ndeclare module \"https\" {\n    import * as tls from \"tls\";\n    import * as events from \"events\";\n    import * as http from \"http\";\n\n    export interface ServerOptions {\n        pfx?: any;\n        key?: any;\n        passphrase?: string;\n        cert?: any;\n        ca?: any;\n        crl?: any;\n        ciphers?: string;\n        honorCipherOrder?: boolean;\n        requestCert?: boolean;\n        rejectUnauthorized?: boolean;\n        NPNProtocols?: any;\n        SNICallback?: (servername: string) => any;\n    }\n\n    export interface RequestOptions extends http.RequestOptions {\n        pfx?: any;\n        key?: any;\n        passphrase?: string;\n        cert?: any;\n        ca?: any;\n        ciphers?: string;\n        rejectUnauthorized?: boolean;\n        secureProtocol?: string;\n    }\n\n    export interface Agent extends http.Agent { }\n\n    export interface AgentOptions extends http.AgentOptions {\n        maxCachedSessions?: number;\n    }\n\n    export var Agent: {\n        new (options?: AgentOptions): Agent;\n    };\n    export interface Server extends tls.Server { }\n    export function createServer(options: ServerOptions, requestListener?: Function): Server;\n    export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;\n    export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest;\n    export var globalAgent: Agent;\n}\n\ndeclare module \"punycode\" {\n    export function decode(string: string): string;\n    export function encode(string: string): string;\n    export function toUnicode(domain: string): string;\n    export function toASCII(domain: string): string;\n    export var ucs2: ucs2;\n    interface ucs2 {\n        decode(string: string): number[];\n        encode(codePoints: number[]): string;\n    }\n    export var version: any;\n}\n\ndeclare module \"repl\" {\n    import * as stream from \"stream\";\n    import * as events from \"events\";\n\n    export interface ReplOptions {\n        prompt?: string;\n        input?: NodeJS.ReadableStream;\n        output?: NodeJS.WritableStream;\n        terminal?: boolean;\n        eval?: Function;\n        useColors?: boolean;\n        useGlobal?: boolean;\n        ignoreUndefined?: boolean;\n        writer?: Function;\n    }\n    export function start(options: ReplOptions): events.EventEmitter;\n}\n\ndeclare module \"readline\" {\n    import * as events from \"events\";\n    import * as stream from \"stream\";\n\n    export interface Key {\n        sequence?: string;\n        name?: string;\n        ctrl?: boolean;\n        meta?: boolean;\n        shift?: boolean;\n    }\n\n    export interface ReadLine extends events.EventEmitter {\n        setPrompt(prompt: string): void;\n        prompt(preserveCursor?: boolean): void;\n        question(query: string, callback: (answer: string) => void): void;\n        pause(): ReadLine;\n        resume(): ReadLine;\n        close(): void;\n        write(data: string|Buffer, key?: Key): void;\n    }\n\n    export interface Completer {\n        (line: string): CompleterResult;\n        (line: string, callback: (err: any, result: CompleterResult) => void): any;\n    }\n\n    export interface CompleterResult {\n        completions: string[];\n        line: string;\n    }\n\n    export interface ReadLineOptions {\n        input: NodeJS.ReadableStream;\n        output?: NodeJS.WritableStream;\n        completer?: Completer;\n        terminal?: boolean;\n        historySize?: number;\n    }\n\n    export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): ReadLine;\n    export function createInterface(options: ReadLineOptions): ReadLine;\n\n    export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void;\n    export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void;\n    export function clearLine(stream: NodeJS.WritableStream, dir: number): void;\n    export function clearScreenDown(stream: NodeJS.WritableStream): void;\n}\n\ndeclare module \"vm\" {\n    export interface Context { }\n    export interface ScriptOptions {\n        filename?: string;\n        lineOffset?: number;\n        columnOffset?: number;\n        displayErrors?: boolean;\n        timeout?: number;\n        cachedData?: Buffer;\n        produceCachedData?: boolean;\n    }\n    export interface RunningScriptOptions {\n        filename?: string;\n        lineOffset?: number;\n        columnOffset?: number;\n        displayErrors?: boolean;\n        timeout?: number;\n    }\n    export class Script {\n        constructor(code: string, options?: ScriptOptions);\n        runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any;\n        runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any;\n        runInThisContext(options?: RunningScriptOptions): any;\n    }\n    export function createContext(sandbox?: Context): Context;\n    export function isContext(sandbox: Context): boolean;\n    export function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions): any;\n    export function runInDebugContext(code: string): any;\n    export function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions): any;\n    export function runInThisContext(code: string, options?: RunningScriptOptions): any;\n}\n\ndeclare module \"child_process\" {\n    import * as events from \"events\";\n    import * as stream from \"stream\";\n\n    export interface ChildProcess extends events.EventEmitter {\n        stdin:  stream.Writable;\n        stdout: stream.Readable;\n        stderr: stream.Readable;\n        stdio: [stream.Writable, stream.Readable, stream.Readable];\n        pid: number;\n        kill(signal?: string): void;\n        send(message: any, sendHandle?: any): void;\n        connected: boolean;\n        disconnect(): void;\n        unref(): void;\n    }\n\n    export interface SpawnOptions {\n        cwd?: string;\n        env?: any;\n        stdio?: any;\n        detached?: boolean;\n        uid?: number;\n        gid?: number;\n        shell?: boolean | string;\n    }\n    export function spawn(command: string, args?: string[], options?: SpawnOptions): ChildProcess;\n\n    export interface ExecOptions {\n        cwd?: string;\n        env?: any;\n        shell?: string;\n        timeout?: number;\n        maxBuffer?: number;\n        killSignal?: string;\n        uid?: number;\n        gid?: number;\n    }\n    export interface ExecOptionsWithStringEncoding extends ExecOptions {\n        encoding: BufferEncoding;\n    }\n    export interface ExecOptionsWithBufferEncoding extends ExecOptions {\n        encoding: string; // specify `null`.\n    }\n    export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n    export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n    // usage. child_process.exec(\"tsc\", {encoding: null as string}, (err, stdout, stderr) => {});\n    export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n\n    export interface ExecFileOptions {\n        cwd?: string;\n        env?: any;\n        timeout?: number;\n        maxBuffer?: number;\n        killSignal?: string;\n        uid?: number;\n        gid?: number;\n    }\n    export interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {\n        encoding: BufferEncoding;\n    }\n    export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions {\n        encoding: string; // specify `null`.\n    }\n    export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n    export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n    // usage. child_process.execFile(\"file.sh\", {encoding: null as string}, (err, stdout, stderr) => {});\n    export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n    export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n    export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n    // usage. child_process.execFile(\"file.sh\", [\"foo\"], {encoding: null as string}, (err, stdout, stderr) => {});\n    export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess;\n    export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess;\n\n    export interface ForkOptions {\n        cwd?: string;\n        env?: any;\n        execPath?: string;\n        execArgv?: string[];\n        silent?: boolean;\n        uid?: number;\n        gid?: number;\n    }\n    export function fork(modulePath: string, args?: string[], options?: ForkOptions): ChildProcess;\n\n    export interface SpawnSyncOptions {\n        cwd?: string;\n        input?: string | Buffer;\n        stdio?: any;\n        env?: any;\n        uid?: number;\n        gid?: number;\n        timeout?: number;\n        killSignal?: string;\n        maxBuffer?: number;\n        encoding?: string;\n        shell?: boolean | string;\n    }\n    export interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions {\n        encoding: BufferEncoding;\n    }\n    export interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions {\n        encoding: string; // specify `null`.\n    }\n    export interface SpawnSyncReturns<T> {\n        pid: number;\n        output: string[];\n        stdout: T;\n        stderr: T;\n        status: number;\n        signal: string;\n        error: Error;\n    }\n    export function spawnSync(command: string): SpawnSyncReturns<Buffer>;\n    export function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;\n    export function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;\n    export function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;\n    export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;\n    export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>;\n    export function spawnSync(command: string, args?: string[], options?: SpawnSyncOptions): SpawnSyncReturns<Buffer>;\n\n    export interface ExecSyncOptions {\n        cwd?: string;\n        input?: string | Buffer;\n        stdio?: any;\n        env?: any;\n        shell?: string;\n        uid?: number;\n        gid?: number;\n        timeout?: number;\n        killSignal?: string;\n        maxBuffer?: number;\n        encoding?: string;\n    }\n    export interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions {\n        encoding: BufferEncoding;\n    }\n    export interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions {\n        encoding: string; // specify `null`.\n    }\n    export function execSync(command: string): Buffer;\n    export function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string;\n    export function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer;\n    export function execSync(command: string, options?: ExecSyncOptions): Buffer;\n\n    export interface ExecFileSyncOptions {\n        cwd?: string;\n        input?: string | Buffer;\n        stdio?: any;\n        env?: any;\n        uid?: number;\n        gid?: number;\n        timeout?: number;\n        killSignal?: string;\n        maxBuffer?: number;\n        encoding?: string;\n    }\n    export interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions {\n        encoding: BufferEncoding;\n    }\n    export interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions {\n        encoding: string; // specify `null`.\n    }\n    export function execFileSync(command: string): Buffer;\n    export function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string;\n    export function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;\n    export function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer;\n    export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithStringEncoding): string;\n    export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptionsWithBufferEncoding): Buffer;\n    export function execFileSync(command: string, args?: string[], options?: ExecFileSyncOptions): Buffer;\n}\n\ndeclare module \"url\" {\n    export interface Url {\n        href?: string;\n        protocol?: string;\n        auth?: string;\n        hostname?: string;\n        port?: string;\n        host?: string;\n        pathname?: string;\n        search?: string;\n        query?: string | any;\n        slashes?: boolean;\n        hash?: string;\n        path?: string;\n    }\n\n    export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url;\n    export function format(url: Url): string;\n    export function resolve(from: string, to: string): string;\n}\n\ndeclare module \"dns\" {\n    export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string;\n    export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string;\n    export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[];\n    export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[];\n}\n\ndeclare module \"net\" {\n    import * as stream from \"stream\";\n\n    export interface Socket extends stream.Duplex {\n        // Extended base methods\n        write(buffer: Buffer): boolean;\n        write(buffer: Buffer, cb?: Function): boolean;\n        write(str: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, cb?: Function): boolean;\n        write(str: string, encoding?: string, fd?: string): boolean;\n\n        connect(port: number, host?: string, connectionListener?: Function): void;\n        connect(path: string, connectionListener?: Function): void;\n        bufferSize: number;\n        setEncoding(encoding?: string): void;\n        write(data: any, encoding?: string, callback?: Function): void;\n        destroy(): void;\n        pause(): void;\n        resume(): void;\n        setTimeout(timeout: number, callback?: Function): void;\n        setNoDelay(noDelay?: boolean): void;\n        setKeepAlive(enable?: boolean, initialDelay?: number): void;\n        address(): { port: number; family: string; address: string; };\n        unref(): void;\n        ref(): void;\n\n        remoteAddress: string;\n        remoteFamily: string;\n        remotePort: number;\n        localAddress: string;\n        localPort: number;\n        bytesRead: number;\n        bytesWritten: number;\n\n        // Extended base methods\n        end(): void;\n        end(buffer: Buffer, cb?: Function): void;\n        end(str: string, cb?: Function): void;\n        end(str: string, encoding?: string, cb?: Function): void;\n        end(data?: any, encoding?: string): void;\n    }\n\n    export var Socket: {\n        new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket;\n    };\n\n    export interface ListenOptions {\n        port?: number;\n        host?: string;\n        backlog?: number;\n        path?: string;\n        exclusive?: boolean;\n    }\n\n    export interface Server extends Socket {\n        listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server;\n        listen(port: number, hostname?: string, listeningListener?: Function): Server;\n        listen(port: number, backlog?: number, listeningListener?: Function): Server;\n        listen(port: number, listeningListener?: Function): Server;\n        listen(path: string, backlog?: number, listeningListener?: Function): Server;\n        listen(path: string, listeningListener?: Function): Server;\n        listen(handle: any, backlog?: number, listeningListener?: Function): Server;\n        listen(handle: any, listeningListener?: Function): Server;\n        listen(options: ListenOptions, listeningListener?: Function): Server;\n        close(callback?: Function): Server;\n        address(): { port: number; family: string; address: string; };\n        getConnections(cb: (error: Error, count: number) => void): void;\n        ref(): Server;\n        unref(): Server;\n        maxConnections: number;\n        connections: number;\n    }\n    export function createServer(connectionListener?: (socket: Socket) =>void ): Server;\n    export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server;\n    export function connect(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;\n    export function connect(port: number, host?: string, connectionListener?: Function): Socket;\n    export function connect(path: string, connectionListener?: Function): Socket;\n    export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket;\n    export function createConnection(port: number, host?: string, connectionListener?: Function): Socket;\n    export function createConnection(path: string, connectionListener?: Function): Socket;\n    export function isIP(input: string): number;\n    export function isIPv4(input: string): boolean;\n    export function isIPv6(input: string): boolean;\n}\n\ndeclare module \"dgram\" {\n    import * as events from \"events\";\n\n    interface RemoteInfo {\n        address: string;\n        port: number;\n        size: number;\n    }\n\n    interface AddressInfo {\n        address: string;\n        family: string;\n        port: number;\n    }\n\n    export function createSocket(type: string, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket;\n\n    interface Socket extends events.EventEmitter {\n        send(buf: Buffer, offset: number, length: number, port: number, address: string, callback?: (error: Error, bytes: number) => void): void;\n        bind(port: number, address?: string, callback?: () => void): void;\n        close(): void;\n        address(): AddressInfo;\n        setBroadcast(flag: boolean): void;\n        setMulticastTTL(ttl: number): void;\n        setMulticastLoopback(flag: boolean): void;\n        addMembership(multicastAddress: string, multicastInterface?: string): void;\n        dropMembership(multicastAddress: string, multicastInterface?: string): void;\n    }\n}\n\ndeclare module \"fs\" {\n    import * as stream from \"stream\";\n    import * as events from \"events\";\n\n    interface Stats {\n        isFile(): boolean;\n        isDirectory(): boolean;\n        isBlockDevice(): boolean;\n        isCharacterDevice(): boolean;\n        isSymbolicLink(): boolean;\n        isFIFO(): boolean;\n        isSocket(): boolean;\n        dev: number;\n        ino: number;\n        mode: number;\n        nlink: number;\n        uid: number;\n        gid: number;\n        rdev: number;\n        size: number;\n        blksize: number;\n        blocks: number;\n        atime: Date;\n        mtime: Date;\n        ctime: Date;\n        birthtime: Date;\n    }\n\n    interface FSWatcher extends events.EventEmitter {\n        close(): void;\n    }\n\n    export interface ReadStream extends stream.Readable {\n        close(): void;\n    }\n    export interface WriteStream extends stream.Writable {\n        close(): void;\n        bytesWritten: number;\n    }\n\n    /**\n     * Asynchronous rename.\n     * @param oldPath\n     * @param newPath\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /**\n     * Synchronous rename\n     * @param oldPath\n     * @param newPath\n     */\n    export function renameSync(oldPath: string, newPath: string): void;\n    export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function truncateSync(path: string | Buffer, len?: number): void;\n    export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function ftruncateSync(fd: number, len?: number): void;\n    export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function chownSync(path: string | Buffer, uid: number, gid: number): void;\n    export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fchownSync(fd: number, uid: number, gid: number): void;\n    export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function lchownSync(path: string | Buffer, uid: number, gid: number): void;\n    export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function chmodSync(path: string | Buffer, mode: number): void;\n    export function chmodSync(path: string | Buffer, mode: string): void;\n    export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fchmodSync(fd: number, mode: number): void;\n    export function fchmodSync(fd: number, mode: string): void;\n    export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function lchmodSync(path: string | Buffer, mode: number): void;\n    export function lchmodSync(path: string | Buffer, mode: string): void;\n    export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;\n    export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;\n    export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void;\n    export function statSync(path: string | Buffer): Stats;\n    export function lstatSync(path: string | Buffer): Stats;\n    export function fstatSync(fd: number): Stats;\n    export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void;\n    export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void;\n    export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void;\n    export function readlinkSync(path: string | Buffer): string;\n    export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void;\n    export function realpath(path: string | Buffer, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void;\n    export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string;\n    /*\n     * Asynchronous unlink - deletes the file specified in {path}\n     *\n     * @param path\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Synchronous unlink - deletes the file specified in {path}\n     *\n     * @param path\n     */\n    export function unlinkSync(path: string | Buffer): void;\n    /*\n     * Asynchronous rmdir - removes the directory specified in {path}\n     *\n     * @param path\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Synchronous rmdir - removes the directory specified in {path}\n     *\n     * @param path\n     */\n    export function rmdirSync(path: string | Buffer): void;\n    /*\n     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Asynchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    /*\n     * Synchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdirSync(path: string | Buffer, mode?: number): void;\n    /*\n     * Synchronous mkdir - creates the directory specified in {path}.  Parameter {mode} defaults to 0777.\n     *\n     * @param path\n     * @param mode\n     * @param callback No arguments other than a possible exception are given to the completion callback.\n     */\n    export function mkdirSync(path: string | Buffer, mode?: string): void;\n    /*\n     * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.\n     *\n     * @param prefix\n     * @param callback The created folder path is passed as a string to the callback's second parameter.\n     */\n    export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void;\n    /*\n     * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.\n     *\n     * @param prefix\n     * @returns Returns the created folder path.\n     */\n    export function mkdtempSync(prefix: string): string;\n    export function readdir(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, files: string[]) => void): void;\n    export function readdirSync(path: string | Buffer): string[];\n    export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function closeSync(fd: number): void;\n    export function open(path: string | Buffer, flags: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;\n    export function open(path: string | Buffer, flags: string, mode: number, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;\n    export function open(path: string | Buffer, flags: string, mode: string, callback?: (err: NodeJS.ErrnoException, fd: number) => any): void;\n    export function openSync(path: string | Buffer, flags: string, mode?: number): number;\n    export function openSync(path: string | Buffer, flags: string, mode?: string): number;\n    export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function utimesSync(path: string | Buffer, atime: number, mtime: number): void;\n    export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void;\n    export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function futimesSync(fd: number, atime: number, mtime: number): void;\n    export function futimesSync(fd: number, atime: Date, mtime: Date): void;\n    export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void;\n    export function fsyncSync(fd: number): void;\n    export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void;\n    export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void;\n    export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void;\n    export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void;\n    export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void;\n    export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number): number;\n    export function writeSync(fd: number, data: any, position?: number, enconding?: string): number;\n    export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void;\n    export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number): number;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param encoding\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer.\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;\n    /*\n     * Asynchronous readFile - Asynchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file.\n     */\n    export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void;\n    /*\n     * Synchronous readFile - Synchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param encoding\n     */\n    export function readFileSync(filename: string, encoding: string): string;\n    /*\n     * Synchronous readFile - Synchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.\n     */\n    export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string;\n    /*\n     * Synchronous readFile - Synchronously reads the entire contents of a file.\n     *\n     * @param fileName\n     * @param options An object with optional {encoding} and {flag} properties.  If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer.\n     */\n    export function readFileSync(filename: string, options?: { flag?: string; }): Buffer;\n    export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;\n    export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;\n    export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void;\n    export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void;\n    export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void;\n    export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void;\n    export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void;\n    export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void;\n    export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher;\n    export function watch(filename: string, encoding: string, listener?: (event: string, filename: string) => any): FSWatcher;\n    export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string) => any): FSWatcher;\n    export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void;\n    export function existsSync(path: string | Buffer): boolean;\n    /** Constant for fs.access(). File is visible to the calling process. */\n    export var F_OK: number;\n    /** Constant for fs.access(). File can be read by the calling process. */\n    export var R_OK: number;\n    /** Constant for fs.access(). File can be written by the calling process. */\n    export var W_OK: number;\n    /** Constant for fs.access(). File can be executed by the calling process. */\n    export var X_OK: number;\n    /** Tests a user's permissions for the file specified by path. */\n    export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void;\n    export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void;\n    /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */\n    export function accessSync(path: string | Buffer, mode ?: number): void;\n    export function createReadStream(path: string | Buffer, options?: {\n        flags?: string;\n        encoding?: string;\n        fd?: number;\n        mode?: number;\n        autoClose?: boolean;\n        start?: number;\n        end?: number;\n    }): ReadStream;\n    export function createWriteStream(path: string | Buffer, options?: {\n        flags?: string;\n        encoding?: string;\n        fd?: number;\n        mode?: number;\n    }): WriteStream;\n}\n\ndeclare module \"path\" {\n\n    /**\n     * A parsed path object generated by path.parse() or consumed by path.format().\n     */\n    export interface ParsedPath {\n        /**\n         * The root of the path such as '/' or 'c:\\'\n         */\n        root: string;\n        /**\n         * The full directory path such as '/home/user/dir' or 'c:\\path\\dir'\n         */\n        dir: string;\n        /**\n         * The file name including extension (if any) such as 'index.html'\n         */\n        base: string;\n        /**\n         * The file extension (if any) such as '.html'\n         */\n        ext: string;\n        /**\n         * The file name without extension (if any) such as 'index'\n         */\n        name: string;\n    }\n\n    /**\n     * Normalize a string path, reducing '..' and '.' parts.\n     * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used.\n     *\n     * @param p string path to normalize.\n     */\n    export function normalize(p: string): string;\n    /**\n     * Join all arguments together and normalize the resulting path.\n     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n     *\n     * @param paths string paths to join.\n     */\n    export function join(...paths: any[]): string;\n    /**\n     * Join all arguments together and normalize the resulting path.\n     * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown.\n     *\n     * @param paths string paths to join.\n     */\n    export function join(...paths: string[]): string;\n    /**\n     * The right-most parameter is considered {to}.  Other parameters are considered an array of {from}.\n     *\n     * Starting from leftmost {from} paramter, resolves {to} to an absolute path.\n     *\n     * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory.\n     *\n     * @param pathSegments string paths to join.  Non-string arguments are ignored.\n     */\n    export function resolve(...pathSegments: any[]): string;\n    /**\n     * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory.\n     *\n     * @param path path to test.\n     */\n    export function isAbsolute(path: string): boolean;\n    /**\n     * Solve the relative path from {from} to {to}.\n     * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve.\n     *\n     * @param from\n     * @param to\n     */\n    export function relative(from: string, to: string): string;\n    /**\n     * Return the directory name of a path. Similar to the Unix dirname command.\n     *\n     * @param p the path to evaluate.\n     */\n    export function dirname(p: string): string;\n    /**\n     * Return the last portion of a path. Similar to the Unix basename command.\n     * Often used to extract the file name from a fully qualified path.\n     *\n     * @param p the path to evaluate.\n     * @param ext optionally, an extension to remove from the result.\n     */\n    export function basename(p: string, ext?: string): string;\n    /**\n     * Return the extension of the path, from the last '.' to end of string in the last portion of the path.\n     * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string\n     *\n     * @param p the path to evaluate.\n     */\n    export function extname(p: string): string;\n    /**\n     * The platform-specific file separator. '\\\\' or '/'.\n     */\n    export var sep: string;\n    /**\n     * The platform-specific file delimiter. ';' or ':'.\n     */\n    export var delimiter: string;\n    /**\n     * Returns an object from a path string - the opposite of format().\n     *\n     * @param pathString path to evaluate.\n     */\n    export function parse(pathString: string): ParsedPath;\n    /**\n     * Returns a path string from an object - the opposite of parse().\n     *\n     * @param pathString path to evaluate.\n     */\n    export function format(pathObject: ParsedPath): string;\n\n    export module posix {\n      export function normalize(p: string): string;\n      export function join(...paths: any[]): string;\n      export function resolve(...pathSegments: any[]): string;\n      export function isAbsolute(p: string): boolean;\n      export function relative(from: string, to: string): string;\n      export function dirname(p: string): string;\n      export function basename(p: string, ext?: string): string;\n      export function extname(p: string): string;\n      export var sep: string;\n      export var delimiter: string;\n      export function parse(p: string): ParsedPath;\n      export function format(pP: ParsedPath): string;\n    }\n\n    export module win32 {\n      export function normalize(p: string): string;\n      export function join(...paths: any[]): string;\n      export function resolve(...pathSegments: any[]): string;\n      export function isAbsolute(p: string): boolean;\n      export function relative(from: string, to: string): string;\n      export function dirname(p: string): string;\n      export function basename(p: string, ext?: string): string;\n      export function extname(p: string): string;\n      export var sep: string;\n      export var delimiter: string;\n      export function parse(p: string): ParsedPath;\n      export function format(pP: ParsedPath): string;\n    }\n}\n\ndeclare module \"string_decoder\" {\n    export interface NodeStringDecoder {\n        write(buffer: Buffer): string;\n        detectIncompleteChar(buffer: Buffer): number;\n    }\n    export var StringDecoder: {\n        new (encoding: string): NodeStringDecoder;\n    };\n}\n\ndeclare module \"tls\" {\n    import * as crypto from \"crypto\";\n    import * as net from \"net\";\n    import * as stream from \"stream\";\n\n    var CLIENT_RENEG_LIMIT: number;\n    var CLIENT_RENEG_WINDOW: number;\n\n    export interface TlsOptions {\n        host?: string;\n        port?: number;\n        pfx?: any;   //string or buffer\n        key?: any;   //string or buffer\n        passphrase?: string;\n        cert?: any;\n        ca?: any;    //string or buffer\n        crl?: any;   //string or string array\n        ciphers?: string;\n        honorCipherOrder?: any;\n        requestCert?: boolean;\n        rejectUnauthorized?: boolean;\n        NPNProtocols?: any;  //array or Buffer;\n        SNICallback?: (servername: string) => any;\n    }\n\n    export interface ConnectionOptions {\n        host?: string;\n        port?: number;\n        socket?: net.Socket;\n        pfx?: string | Buffer\n        key?: string | Buffer\n        passphrase?: string;\n        cert?: string | Buffer\n        ca?: (string | Buffer)[];\n        rejectUnauthorized?: boolean;\n        NPNProtocols?: (string | Buffer)[];\n        servername?: string;\n    }\n\n    export interface Server extends net.Server {\n        close(): Server;\n        address(): { port: number; family: string; address: string; };\n        addContext(hostName: string, credentials: {\n            key: string;\n            cert: string;\n            ca: string;\n        }): void;\n        maxConnections: number;\n        connections: number;\n    }\n\n    export interface ClearTextStream extends stream.Duplex {\n        authorized: boolean;\n        authorizationError: Error;\n        getPeerCertificate(): any;\n        getCipher: {\n            name: string;\n            version: string;\n        };\n        address: {\n            port: number;\n            family: string;\n            address: string;\n        };\n        remoteAddress: string;\n        remotePort: number;\n    }\n\n    export interface SecurePair {\n        encrypted: any;\n        cleartext: any;\n    }\n\n    export interface SecureContextOptions {\n        pfx?: string | Buffer;\n        key?: string | Buffer;\n        passphrase?: string;\n        cert?: string | Buffer;\n        ca?: string | Buffer;\n        crl?: string | string[]\n        ciphers?: string;\n        honorCipherOrder?: boolean;\n    }\n\n    export interface SecureContext {\n        context: any;\n    }\n\n    export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server;\n    export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream;\n    export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;\n    export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream;\n    export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair;\n    export function createSecureContext(details: SecureContextOptions): SecureContext;\n}\n\ndeclare module \"crypto\" {\n    export interface CredentialDetails {\n        pfx: string;\n        key: string;\n        passphrase: string;\n        cert: string;\n        ca: string | string[];\n        crl: string | string[];\n        ciphers: string;\n    }\n    export interface Credentials { context?: any; }\n    export function createCredentials(details: CredentialDetails): Credentials;\n    export function createHash(algorithm: string): Hash;\n    export function createHmac(algorithm: string, key: string): Hmac;\n    export function createHmac(algorithm: string, key: Buffer): Hmac;\n    export interface Hash {\n        update(data: any, input_encoding?: string): Hash;\n        digest(encoding: 'buffer'): Buffer;\n        digest(encoding: string): any;\n        digest(): Buffer;\n    }\n    export interface Hmac extends NodeJS.ReadWriteStream {\n        update(data: any, input_encoding?: string): Hmac;\n        digest(encoding: 'buffer'): Buffer;\n        digest(encoding: string): any;\n        digest(): Buffer;\n    }\n    export function createCipher(algorithm: string, password: any): Cipher;\n    export function createCipheriv(algorithm: string, key: any, iv: any): Cipher;\n    export interface Cipher extends NodeJS.ReadWriteStream {\n        update(data: Buffer): Buffer;\n        update(data: string, input_encoding: \"utf8\"|\"ascii\"|\"binary\"): Buffer;\n        update(data: Buffer, input_encoding: any, output_encoding: \"binary\"|\"base64\"|\"hex\"): string;\n        update(data: string, input_encoding: \"utf8\"|\"ascii\"|\"binary\", output_encoding: \"binary\"|\"base64\"|\"hex\"): string;\n        final(): Buffer;\n        final(output_encoding: string): string;\n        setAutoPadding(auto_padding: boolean): void;\n        getAuthTag(): Buffer;\n    }\n    export function createDecipher(algorithm: string, password: any): Decipher;\n    export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher;\n    export interface Decipher extends NodeJS.ReadWriteStream {\n        update(data: Buffer): Buffer;\n        update(data: string, input_encoding: \"binary\"|\"base64\"|\"hex\"): Buffer;\n        update(data: Buffer, input_encoding: any, output_encoding: \"utf8\"|\"ascii\"|\"binary\"): string;\n        update(data: string, input_encoding: \"binary\"|\"base64\"|\"hex\", output_encoding: \"utf8\"|\"ascii\"|\"binary\"): string;\n        final(): Buffer;\n        final(output_encoding: string): string;\n        setAutoPadding(auto_padding: boolean): void;\n        setAuthTag(tag: Buffer): void;\n    }\n    export function createSign(algorithm: string): Signer;\n    export interface Signer extends NodeJS.WritableStream {\n        update(data: any): void;\n        sign(private_key: string, output_format: string): string;\n    }\n    export function createVerify(algorith: string): Verify;\n    export interface Verify extends NodeJS.WritableStream {\n        update(data: any): void;\n        verify(object: string, signature: string, signature_format?: string): boolean;\n    }\n    export function createDiffieHellman(prime_length: number): DiffieHellman;\n    export function createDiffieHellman(prime: number, encoding?: string): DiffieHellman;\n    export interface DiffieHellman {\n        generateKeys(encoding?: string): string;\n        computeSecret(other_public_key: string, input_encoding?: string, output_encoding?: string): string;\n        getPrime(encoding?: string): string;\n        getGenerator(encoding: string): string;\n        getPublicKey(encoding?: string): string;\n        getPrivateKey(encoding?: string): string;\n        setPublicKey(public_key: string, encoding?: string): void;\n        setPrivateKey(public_key: string, encoding?: string): void;\n    }\n    export function getDiffieHellman(group_name: string): DiffieHellman;\n    export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void;\n    export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void;\n    export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer;\n    export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer;\n    export function randomBytes(size: number): Buffer;\n    export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;\n    export function pseudoRandomBytes(size: number): Buffer;\n    export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void;\n    export interface RsaPublicKey {\n        key: string;\n        padding?: any;\n    }\n    export interface RsaPrivateKey {\n        key: string;\n        passphrase?: string,\n        padding?: any;\n    }\n    export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer\n    export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer\n}\n\ndeclare module \"stream\" {\n    import * as events from \"events\";\n\n    export class Stream extends events.EventEmitter {\n        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;\n    }\n\n    export interface ReadableOptions {\n        highWaterMark?: number;\n        encoding?: string;\n        objectMode?: boolean;\n    }\n\n    export class Readable extends events.EventEmitter implements NodeJS.ReadableStream {\n        readable: boolean;\n        constructor(opts?: ReadableOptions);\n        _read(size: number): void;\n        read(size?: number): any;\n        setEncoding(encoding: string): void;\n        pause(): void;\n        resume(): void;\n        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;\n        unpipe<T extends NodeJS.WritableStream>(destination?: T): void;\n        unshift(chunk: any): void;\n        wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;\n        push(chunk: any, encoding?: string): boolean;\n    }\n\n    export interface WritableOptions {\n        highWaterMark?: number;\n        decodeStrings?: boolean;\n        objectMode?: boolean;\n    }\n\n    export class Writable extends events.EventEmitter implements NodeJS.WritableStream {\n        writable: boolean;\n        constructor(opts?: WritableOptions);\n        _write(chunk: any, encoding: string, callback: Function): void;\n        write(chunk: any, cb?: Function): boolean;\n        write(chunk: any, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(chunk: any, cb?: Function): void;\n        end(chunk: any, encoding?: string, cb?: Function): void;\n    }\n\n    export interface DuplexOptions extends ReadableOptions, WritableOptions {\n        allowHalfOpen?: boolean;\n    }\n\n    // Note: Duplex extends both Readable and Writable.\n    export class Duplex extends Readable implements NodeJS.ReadWriteStream {\n        writable: boolean;\n        constructor(opts?: DuplexOptions);\n        _write(chunk: any, encoding: string, callback: Function): void;\n        write(chunk: any, cb?: Function): boolean;\n        write(chunk: any, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(chunk: any, cb?: Function): void;\n        end(chunk: any, encoding?: string, cb?: Function): void;\n    }\n\n    export interface TransformOptions extends ReadableOptions, WritableOptions {}\n\n    // Note: Transform lacks the _read and _write methods of Readable/Writable.\n    export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream {\n        readable: boolean;\n        writable: boolean;\n        constructor(opts?: TransformOptions);\n        _transform(chunk: any, encoding: string, callback: Function): void;\n        _flush(callback: Function): void;\n        read(size?: number): any;\n        setEncoding(encoding: string): void;\n        pause(): void;\n        resume(): void;\n        pipe<T extends NodeJS.WritableStream>(destination: T, options?: { end?: boolean; }): T;\n        unpipe<T extends NodeJS.WritableStream>(destination?: T): void;\n        unshift(chunk: any): void;\n        wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream;\n        push(chunk: any, encoding?: string): boolean;\n        write(chunk: any, cb?: Function): boolean;\n        write(chunk: any, encoding?: string, cb?: Function): boolean;\n        end(): void;\n        end(chunk: any, cb?: Function): void;\n        end(chunk: any, encoding?: string, cb?: Function): void;\n    }\n\n    export class PassThrough extends Transform {}\n}\n\ndeclare module \"util\" {\n    export interface InspectOptions {\n        showHidden?: boolean;\n        depth?: number;\n        colors?: boolean;\n        customInspect?: boolean;\n    }\n\n    export function format(format: any, ...param: any[]): string;\n    export function debug(string: string): void;\n    export function error(...param: any[]): void;\n    export function puts(...param: any[]): void;\n    export function print(...param: any[]): void;\n    export function log(string: string): void;\n    export function inspect(object: any, showHidden?: boolean, depth?: number, color?: boolean): string;\n    export function inspect(object: any, options: InspectOptions): string;\n    export function isArray(object: any): boolean;\n    export function isRegExp(object: any): boolean;\n    export function isDate(object: any): boolean;\n    export function isError(object: any): boolean;\n    export function inherits(constructor: any, superConstructor: any): void;\n    export function debuglog(key:string): (msg:string,...param: any[])=>void;\n}\n\ndeclare module \"assert\" {\n    function internal (value: any, message?: string): void;\n    namespace internal {\n        export class AssertionError implements Error {\n            name: string;\n            message: string;\n            actual: any;\n            expected: any;\n            operator: string;\n            generatedMessage: boolean;\n\n            constructor(options?: {message?: string; actual?: any; expected?: any;\n                                  operator?: string; stackStartFunction?: Function});\n        }\n\n        export function fail(actual?: any, expected?: any, message?: string, operator?: string): void;\n        export function ok(value: any, message?: string): void;\n        export function equal(actual: any, expected: any, message?: string): void;\n        export function notEqual(actual: any, expected: any, message?: string): void;\n        export function deepEqual(actual: any, expected: any, message?: string): void;\n        export function notDeepEqual(acutal: any, expected: any, message?: string): void;\n        export function strictEqual(actual: any, expected: any, message?: string): void;\n        export function notStrictEqual(actual: any, expected: any, message?: string): void;\n        export function deepStrictEqual(actual: any, expected: any, message?: string): void;\n        export function notDeepStrictEqual(actual: any, expected: any, message?: string): void;\n        export var throws: {\n            (block: Function, message?: string): void;\n            (block: Function, error: Function, message?: string): void;\n            (block: Function, error: RegExp, message?: string): void;\n            (block: Function, error: (err: any) => boolean, message?: string): void;\n        };\n\n        export var doesNotThrow: {\n            (block: Function, message?: string): void;\n            (block: Function, error: Function, message?: string): void;\n            (block: Function, error: RegExp, message?: string): void;\n            (block: Function, error: (err: any) => boolean, message?: string): void;\n        };\n\n        export function ifError(value: any): void;\n    }\n\n    export = internal;\n}\n\ndeclare module \"tty\" {\n    import * as net from \"net\";\n\n    export function isatty(fd: number): boolean;\n    export interface ReadStream extends net.Socket {\n        isRaw: boolean;\n        setRawMode(mode: boolean): void;\n        isTTY: boolean;\n    }\n    export interface WriteStream extends net.Socket {\n        columns: number;\n        rows: number;\n        isTTY: boolean;\n    }\n}\n\ndeclare module \"domain\" {\n    import * as events from \"events\";\n\n    export class Domain extends events.EventEmitter implements NodeJS.Domain {\n        run(fn: Function): void;\n        add(emitter: events.EventEmitter): void;\n        remove(emitter: events.EventEmitter): void;\n        bind(cb: (err: Error, data: any) => any): any;\n        intercept(cb: (data: any) => any): any;\n        dispose(): void;\n    }\n\n    export function create(): Domain;\n}\n\ndeclare module \"constants\" {\n    export var E2BIG: number;\n    export var EACCES: number;\n    export var EADDRINUSE: number;\n    export var EADDRNOTAVAIL: number;\n    export var EAFNOSUPPORT: number;\n    export var EAGAIN: number;\n    export var EALREADY: number;\n    export var EBADF: number;\n    export var EBADMSG: number;\n    export var EBUSY: number;\n    export var ECANCELED: number;\n    export var ECHILD: number;\n    export var ECONNABORTED: number;\n    export var ECONNREFUSED: number;\n    export var ECONNRESET: number;\n    export var EDEADLK: number;\n    export var EDESTADDRREQ: number;\n    export var EDOM: number;\n    export var EEXIST: number;\n    export var EFAULT: number;\n    export var EFBIG: number;\n    export var EHOSTUNREACH: number;\n    export var EIDRM: number;\n    export var EILSEQ: number;\n    export var EINPROGRESS: number;\n    export var EINTR: number;\n    export var EINVAL: number;\n    export var EIO: number;\n    export var EISCONN: number;\n    export var EISDIR: number;\n    export var ELOOP: number;\n    export var EMFILE: number;\n    export var EMLINK: number;\n    export var EMSGSIZE: number;\n    export var ENAMETOOLONG: number;\n    export var ENETDOWN: number;\n    export var ENETRESET: number;\n    export var ENETUNREACH: number;\n    export var ENFILE: number;\n    export var ENOBUFS: number;\n    export var ENODATA: number;\n    export var ENODEV: number;\n    export var ENOENT: number;\n    export var ENOEXEC: number;\n    export var ENOLCK: number;\n    export var ENOLINK: number;\n    export var ENOMEM: number;\n    export var ENOMSG: number;\n    export var ENOPROTOOPT: number;\n    export var ENOSPC: number;\n    export var ENOSR: number;\n    export var ENOSTR: number;\n    export var ENOSYS: number;\n    export var ENOTCONN: number;\n    export var ENOTDIR: number;\n    export var ENOTEMPTY: number;\n    export var ENOTSOCK: number;\n    export var ENOTSUP: number;\n    export var ENOTTY: number;\n    export var ENXIO: number;\n    export var EOPNOTSUPP: number;\n    export var EOVERFLOW: number;\n    export var EPERM: number;\n    export var EPIPE: number;\n    export var EPROTO: number;\n    export var EPROTONOSUPPORT: number;\n    export var EPROTOTYPE: number;\n    export var ERANGE: number;\n    export var EROFS: number;\n    export var ESPIPE: number;\n    export var ESRCH: number;\n    export var ETIME: number;\n    export var ETIMEDOUT: number;\n    export var ETXTBSY: number;\n    export var EWOULDBLOCK: number;\n    export var EXDEV: number;\n    export var WSAEINTR: number;\n    export var WSAEBADF: number;\n    export var WSAEACCES: number;\n    export var WSAEFAULT: number;\n    export var WSAEINVAL: number;\n    export var WSAEMFILE: number;\n    export var WSAEWOULDBLOCK: number;\n    export var WSAEINPROGRESS: number;\n    export var WSAEALREADY: number;\n    export var WSAENOTSOCK: number;\n    export var WSAEDESTADDRREQ: number;\n    export var WSAEMSGSIZE: number;\n    export var WSAEPROTOTYPE: number;\n    export var WSAENOPROTOOPT: number;\n    export var WSAEPROTONOSUPPORT: number;\n    export var WSAESOCKTNOSUPPORT: number;\n    export var WSAEOPNOTSUPP: number;\n    export var WSAEPFNOSUPPORT: number;\n    export var WSAEAFNOSUPPORT: number;\n    export var WSAEADDRINUSE: number;\n    export var WSAEADDRNOTAVAIL: number;\n    export var WSAENETDOWN: number;\n    export var WSAENETUNREACH: number;\n    export var WSAENETRESET: number;\n    export var WSAECONNABORTED: number;\n    export var WSAECONNRESET: number;\n    export var WSAENOBUFS: number;\n    export var WSAEISCONN: number;\n    export var WSAENOTCONN: number;\n    export var WSAESHUTDOWN: number;\n    export var WSAETOOMANYREFS: number;\n    export var WSAETIMEDOUT: number;\n    export var WSAECONNREFUSED: number;\n    export var WSAELOOP: number;\n    export var WSAENAMETOOLONG: number;\n    export var WSAEHOSTDOWN: number;\n    export var WSAEHOSTUNREACH: number;\n    export var WSAENOTEMPTY: number;\n    export var WSAEPROCLIM: number;\n    export var WSAEUSERS: number;\n    export var WSAEDQUOT: number;\n    export var WSAESTALE: number;\n    export var WSAEREMOTE: number;\n    export var WSASYSNOTREADY: number;\n    export var WSAVERNOTSUPPORTED: number;\n    export var WSANOTINITIALISED: number;\n    export var WSAEDISCON: number;\n    export var WSAENOMORE: number;\n    export var WSAECANCELLED: number;\n    export var WSAEINVALIDPROCTABLE: number;\n    export var WSAEINVALIDPROVIDER: number;\n    export var WSAEPROVIDERFAILEDINIT: number;\n    export var WSASYSCALLFAILURE: number;\n    export var WSASERVICE_NOT_FOUND: number;\n    export var WSATYPE_NOT_FOUND: number;\n    export var WSA_E_NO_MORE: number;\n    export var WSA_E_CANCELLED: number;\n    export var WSAEREFUSED: number;\n    export var SIGHUP: number;\n    export var SIGINT: number;\n    export var SIGILL: number;\n    export var SIGABRT: number;\n    export var SIGFPE: number;\n    export var SIGKILL: number;\n    export var SIGSEGV: number;\n    export var SIGTERM: number;\n    export var SIGBREAK: number;\n    export var SIGWINCH: number;\n    export var SSL_OP_ALL: number;\n    export var SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;\n    export var SSL_OP_CIPHER_SERVER_PREFERENCE: number;\n    export var SSL_OP_CISCO_ANYCONNECT: number;\n    export var SSL_OP_COOKIE_EXCHANGE: number;\n    export var SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;\n    export var SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;\n    export var SSL_OP_EPHEMERAL_RSA: number;\n    export var SSL_OP_LEGACY_SERVER_CONNECT: number;\n    export var SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;\n    export var SSL_OP_MICROSOFT_SESS_ID_BUG: number;\n    export var SSL_OP_MSIE_SSLV2_RSA_PADDING: number;\n    export var SSL_OP_NETSCAPE_CA_DN_BUG: number;\n    export var SSL_OP_NETSCAPE_CHALLENGE_BUG: number;\n    export var SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;\n    export var SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;\n    export var SSL_OP_NO_COMPRESSION: number;\n    export var SSL_OP_NO_QUERY_MTU: number;\n    export var SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;\n    export var SSL_OP_NO_SSLv2: number;\n    export var SSL_OP_NO_SSLv3: number;\n    export var SSL_OP_NO_TICKET: number;\n    export var SSL_OP_NO_TLSv1: number;\n    export var SSL_OP_NO_TLSv1_1: number;\n    export var SSL_OP_NO_TLSv1_2: number;\n    export var SSL_OP_PKCS1_CHECK_1: number;\n    export var SSL_OP_PKCS1_CHECK_2: number;\n    export var SSL_OP_SINGLE_DH_USE: number;\n    export var SSL_OP_SINGLE_ECDH_USE: number;\n    export var SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;\n    export var SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;\n    export var SSL_OP_TLS_BLOCK_PADDING_BUG: number;\n    export var SSL_OP_TLS_D5_BUG: number;\n    export var SSL_OP_TLS_ROLLBACK_BUG: number;\n    export var ENGINE_METHOD_DSA: number;\n    export var ENGINE_METHOD_DH: number;\n    export var ENGINE_METHOD_RAND: number;\n    export var ENGINE_METHOD_ECDH: number;\n    export var ENGINE_METHOD_ECDSA: number;\n    export var ENGINE_METHOD_CIPHERS: number;\n    export var ENGINE_METHOD_DIGESTS: number;\n    export var ENGINE_METHOD_STORE: number;\n    export var ENGINE_METHOD_PKEY_METHS: number;\n    export var ENGINE_METHOD_PKEY_ASN1_METHS: number;\n    export var ENGINE_METHOD_ALL: number;\n    export var ENGINE_METHOD_NONE: number;\n    export var DH_CHECK_P_NOT_SAFE_PRIME: number;\n    export var DH_CHECK_P_NOT_PRIME: number;\n    export var DH_UNABLE_TO_CHECK_GENERATOR: number;\n    export var DH_NOT_SUITABLE_GENERATOR: number;\n    export var NPN_ENABLED: number;\n    export var RSA_PKCS1_PADDING: number;\n    export var RSA_SSLV23_PADDING: number;\n    export var RSA_NO_PADDING: number;\n    export var RSA_PKCS1_OAEP_PADDING: number;\n    export var RSA_X931_PADDING: number;\n    export var RSA_PKCS1_PSS_PADDING: number;\n    export var POINT_CONVERSION_COMPRESSED: number;\n    export var POINT_CONVERSION_UNCOMPRESSED: number;\n    export var POINT_CONVERSION_HYBRID: number;\n    export var O_RDONLY: number;\n    export var O_WRONLY: number;\n    export var O_RDWR: number;\n    export var S_IFMT: number;\n    export var S_IFREG: number;\n    export var S_IFDIR: number;\n    export var S_IFCHR: number;\n    export var S_IFLNK: number;\n    export var O_CREAT: number;\n    export var O_EXCL: number;\n    export var O_TRUNC: number;\n    export var O_APPEND: number;\n    export var F_OK: number;\n    export var R_OK: number;\n    export var W_OK: number;\n    export var X_OK: number;\n    export var UV_UDP_REUSEADDR: number;\n}\n"
  },
  {
    "path": "typings/globals/node/typings.json",
    "content": "{\n  \"resolution\": \"main\",\n  \"tree\": {\n    \"src\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6abf99dda133ff859e16e3520b0b00b6b1239341/node/node.d.ts\",\n    \"raw\": \"registry:dt/node#6.0.0+20160613154055\",\n    \"typings\": \"https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/6abf99dda133ff859e16e3520b0b00b6b1239341/node/node.d.ts\"\n  }\n}\n"
  },
  {
    "path": "typings/index.d.ts",
    "content": "/// <reference path=\"../satellizer.d.ts\" />\n/// <reference path=\"globals/angular-mocks/index.d.ts\" />\n/// <reference path=\"globals/angular-route/index.d.ts\" />\n/// <reference path=\"globals/angular/index.d.ts\" />\n/// <reference path=\"globals/es6-shim/index.d.ts\" />\n/// <reference path=\"globals/jasmine/index.d.ts\" />\n/// <reference path=\"globals/jquery/index.d.ts\" />\n/// <reference path=\"globals/node/index.d.ts\" />\n"
  },
  {
    "path": "typings.json",
    "content": "{\n  \"name\": \"satellizer\",\n  \"globalDependencies\": {\n    \"angular\": \"registry:dt/angular#1.5.0+20160614091201\",\n    \"angular-mocks\": \"registry:dt/angular-mocks#1.5.0+20160608104721\",\n    \"es6-shim\": \"registry:dt/es6-shim#0.31.2+20160602141504\",\n    \"jquery\": \"registry:dt/jquery#1.10.0+20160417213236\",\n    \"node\": \"registry:dt/node#6.0.0+20160613154055\"\n  },\n  \"globalDevDependencies\": {\n    \"jasmine\": \"registry:dt/jasmine#2.2.0+20160621224255\"\n  }\n}\n"
  }
]